From f9ff5cb10e3b037f79c9f2706705b104bfe7f75f Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 09:15:38 -0500 Subject: [PATCH] Convert cross-provider model switches into thread forks and expose generic provider catalog --- src/agent_comms/registry/thread_management.py | 53 +++++ src/agent_comms/registry/thread_model.py | 91 +++++++ src/agent_comms/registry/threads.py | 8 + .../transport/served_tools/served.py | 1 + src/agent_comms/transport/tools/commands.py | 1 + tests/test_cross_provider_model_fork.py | 224 ++++++++++++++++++ 6 files changed, 378 insertions(+) create mode 100644 tests/test_cross_provider_model_fork.py diff --git a/src/agent_comms/registry/thread_management.py b/src/agent_comms/registry/thread_management.py index d295f3ba51..44e9be5940 100644 --- a/src/agent_comms/registry/thread_management.py +++ b/src/agent_comms/registry/thread_management.py @@ -564,6 +564,59 @@ def configure(thread: NativeThread) -> Thread: ThreadCatalog.publish(updated, self.root) return updated + def fork_for_model_switch( + self, original: Thread, configuration: NextTurnConfiguration, + ) -> NativeThread: + """Convert a cross-provider model switch into a forked child thread. + + Preserves the parent thread's original provider, model, and session file + untouched, while declaring a forked child ``NativeThread`` carrying + ``ForkedParent(original.name)``, inherited child tags, the target provider's + backend, and a fresh session location. + """ + if not original.independent_threads(): + raise RelationViolationError( + f"Thread {original.name!r} is a subagent; only independent threads can fork " + "on cross-provider model switch." + ) + target_provider = configuration.model.provider_name() + if target_provider is None: + raise ValueError( + "Cross-provider model fork requires a provider-qualified model selection." + ) + base_slug = RegistryNames.thread_slug(f"{original.name}-{target_provider}") + with self.registry.store.editing() as edit: + current = edit.document.require(original.name) + if current.incarnation != original.incarnation: + raise RelationViolationError( + f"Thread {original.name!r} changed while forking for model switch." + ) + fork_name = base_slug + suffix = 2 + while fork_name in edit.document: + fork_name = f"{base_slug}-{suffix}" + suffix += 1 + seed = NativeThread( + name=fork_name, + tags=DeclaredTag.for_child(current.tags), + worktree=current.worktree, + parent=ForkedParent(current.name), + model=UndeclaredModel(), + thinking_level=current.thinking_level, + service_tier=current.service_tier, + context_edit_policy=current.context_edit_policy, + ) + configured = configuration.configured(seed) + fresh = configured.backend.new_location(self.root, configured.worktree.path) + saved = RegistrySessionLocation.from_path(fresh.read_key, self.root) + child = replace(configured, session_file=saved) + self.registry.require_declaration_available(child, StoppedThreadStatus()) + forked = NativeThread.stored( + self.registry._declare_in(edit, child, StoppedThreadStatus()) + ) + ThreadCatalog.publish(forked, self.root) + return forked + def native_launch_arguments( self, thread: Thread, arguments: NativeArguments, package: Path, ) -> tuple[str, ...]: diff --git a/src/agent_comms/registry/thread_model.py b/src/agent_comms/registry/thread_model.py index 1ea2aed262..a95aa01a2a 100644 --- a/src/agent_comms/registry/thread_model.py +++ b/src/agent_comms/registry/thread_model.py @@ -5,6 +5,7 @@ abstractmethod, ) from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass from pathlib import Path from typing import Annotated, ClassVar, Self @@ -32,6 +33,16 @@ from agent_comms.registry.thread_text import AbsentText, TextChoice +@dataclass(frozen=True, slots=True) +class ProviderCatalogChoice: + """One model choice declared by a ``ModelProvider`` or registered catalog source.""" + + value: str + name: str + description: str | None = None + provider: str = "" + + class ModelSelection(TextChoice): """A model's spelling and native arguments, shared by saved values and requests.""" @@ -48,6 +59,81 @@ def __deepcopy__(self, memo: object) -> Self: @abstractmethod def native(self, arguments: NativeArguments) -> NativeArguments: ... + def provider_name(self) -> str | None: + """Normalized provider identifier for a provider-qualified model, or ``None``.""" + return None + + def crosses_provider_from(self, current: ModelSelection) -> bool: + """True when both selections declare concrete providers and those providers differ.""" + current_provider = current.provider_name() + target_provider = self.provider_name() + return ( + current_provider is not None + and target_provider is not None + and current_provider != target_provider + ) + + @classmethod + def crosses_provider_values(cls, current_wire: str, target_wire: str) -> bool: + """Decide whether switching from ``current_wire`` to ``target_wire`` crosses providers.""" + if ( + not current_wire + or not target_wire + or current_wire == CliInboxSelection.wire_value + or target_wire == CliInboxSelection.wire_value + or "/" not in current_wire + or "/" not in target_wire + ): + return False + return ( + SelectedModel.decode(current_wire).provider + != SelectedModel.decode(target_wire).provider + ) + + @classmethod + def provider_catalog_choices(cls) -> tuple[ProviderCatalogChoice, ...]: + """Generic provider-driven model catalog across every declared ``ModelProvider``.""" + seen: dict[str, ProviderCatalogChoice] = {} + for source in ThreadModelChoices._sources: + for label, model in source(): + wire = model.to_wire() if isinstance(model, WireValue) else str(model) + if not wire: + continue + seen.setdefault( + wire, + ProviderCatalogChoice( + value=wire, + name=label, + description=None, + provider=model.provider_name() or "", + ), + ) + for provider in ModelProvider.members_with(ModelProvider): + provider_name = provider.declared_name + if not provider_name: + continue + for model_id, display_label, description in provider.catalog_models(): + qualified = f"{provider_name}/{model_id}" + seen.setdefault( + qualified, + ProviderCatalogChoice( + value=qualified, + name=display_label, + description=description, + provider=provider_name, + ), + ) + seen.setdefault( + CliInboxSelection.wire_value, + ProviderCatalogChoice( + value=CliInboxSelection.wire_value, + name=CliInboxSelection.choice_label, + description=CliInboxSelection.choice_description, + provider="", + ), + ) + return tuple(seen.values()) + class CliInboxSelection(ExternalField, WireValue, ModelSelection): """Selects external CLI-inbox execution instead of a native Pi provider/model.""" @@ -143,6 +229,11 @@ def texts(self) -> tuple[str, ...]: def native(self, arguments: NativeArguments) -> NativeArguments: return arguments.with_model(self.text) + def provider_name(self) -> str | None: + if "/" not in self.text: + return None + return SelectedModel.decode(self.text).provider + @classmethod def wire_structure(cls, structural: DecoderPlan) -> DecoderPlan: return compile_decoder(str) diff --git a/src/agent_comms/registry/threads.py b/src/agent_comms/registry/threads.py index bbc16469bb..a6c95b90e8 100644 --- a/src/agent_comms/registry/threads.py +++ b/src/agent_comms/registry/threads.py @@ -268,6 +268,10 @@ def set_thread_configuration( self, original: Thread, configuration: NextTurnConfiguration, ) -> Thread: ... + def fork_for_model_switch( + self, original: Thread, configuration: NextTurnConfiguration, + ) -> NativeThread: ... + def switch_to_cli_inbox(self, name: str) -> ExternalThread: ... def switch_to_native(self, name: str) -> NativeThread: ... @@ -1061,6 +1065,8 @@ def catalog_model(self, observed: ThreadModel) -> ThreadModel: def apply_chosen_model( self, threads: ThreadConfigurationTarget, configuration: NextTurnConfiguration, ) -> Thread: + if configuration.model.crosses_provider_from(self.model): + return threads.fork_for_model_switch(self, configuration) return threads.set_thread_configuration(self, configuration) def apply_kept_model( @@ -1182,6 +1188,8 @@ def catalog_model(self, observed: ThreadModel) -> ThreadModel: def apply_chosen_model( self, threads: ThreadConfigurationTarget, configuration: NextTurnConfiguration, ) -> Thread: + if configuration.model.crosses_provider_from(self.model): + return threads.fork_for_model_switch(self, configuration) native = threads.switch_to_native(self.name) return threads.set_thread_configuration(native, configuration) diff --git a/src/agent_comms/transport/served_tools/served.py b/src/agent_comms/transport/served_tools/served.py index 124b363a4c..c56f6131a9 100644 --- a/src/agent_comms/transport/served_tools/served.py +++ b/src/agent_comms/transport/served_tools/served.py @@ -614,6 +614,7 @@ def apply(self, comms: Comms, caller: ToolCaller) -> ModelChanged: model=thread.catalog_model(UndeclaredModel()), thinking_level=thread.thinking_level, service_tier=thread.service_tier, + forked_from=original.name if thread.name != original.name else None, ) diff --git a/src/agent_comms/transport/tools/commands.py b/src/agent_comms/transport/tools/commands.py index 0703b50800..a29a450dce 100644 --- a/src/agent_comms/transport/tools/commands.py +++ b/src/agent_comms/transport/tools/commands.py @@ -76,6 +76,7 @@ class ModelChanged(ToolResult): model: ThreadModel thinking_level: ThinkingLevelField service_tier: ServiceTier + forked_from: Annotated[str | None, WireOmitDefault()] = None @dataclass(frozen=True) diff --git a/tests/test_cross_provider_model_fork.py b/tests/test_cross_provider_model_fork.py new file mode 100644 index 0000000000..c1ff578f32 --- /dev/null +++ b/tests/test_cross_provider_model_fork.py @@ -0,0 +1,224 @@ +"""Tests for generic provider-driven model catalog and cross-provider switch -> fork.""" + +from __future__ import annotations + +import socket +import threading +import time +from pathlib import Path + +from zmqruntime import TransportMode + +from agent_comms.execution.antigravity_backend import AntigravityAcpBackend +from agent_comms.execution.pi_vocabulary import HighThinkingLevel, LowThinkingLevel +from agent_comms.execution.session_file import RegistrySessionLocation +from agent_comms.pi_native_backend import PiNativeBackend +from agent_comms.projects.checkouts import Checkout +from agent_comms.registry.thread_model import ( + CliInboxSelection, + CliInboxThreadModel, + DeclaredModel, + ModelSelection, + UndeclaredModel, +) +from agent_comms.registry.thread_status import NoBridgeThreadStatus, StoppedThreadStatus +from agent_comms.registry.thread_text import ForkedParent +from agent_comms.registry.threads import ChosenModel, ExternalThread, NativeThread +from agent_comms.transport.served_tools.served import invoke_tool +from agent_comms.transport.tool_caller import HumanCaller +from agent_comms.transport.tools.commands import CommsModelTool, ModelChanged, NamedSubject +from agent_comms.transport.zmq_comms_server import ( + CommsZMQClient, + CommsZMQConfig, + CommsZMQServer, +) +from conftest import installed_comms + + +def test_cross_provider_detection_and_generic_provider_catalog() -> None: + anthropic_sonnet = DeclaredModel("anthropic/claude-sonnet-4-5") + anthropic_opus = ChosenModel("anthropic/claude-opus-4-6") + codex_gpt = ChosenModel("openai-codex/gpt-5.6-sol") + agy_gemini = ChosenModel("antigravity/gemini-4-neon") + + assert not anthropic_opus.crosses_provider_from(anthropic_sonnet) + assert not anthropic_opus.crosses_provider_from(UndeclaredModel()) + assert not anthropic_opus.crosses_provider_from(CliInboxThreadModel()) + assert codex_gpt.crosses_provider_from(anthropic_sonnet) + assert agy_gemini.crosses_provider_from(anthropic_sonnet) + assert agy_gemini.crosses_provider_from(codex_gpt) + + assert ModelSelection.crosses_provider_values( + "anthropic/claude-opus-4-6", "openai-codex/gpt-5.6-sol" + ) + assert not ModelSelection.crosses_provider_values( + "anthropic/claude-sonnet-4-5", "anthropic/claude-opus-4-6" + ) + assert not ModelSelection.crosses_provider_values( + "anthropic/claude-opus-4-6", CliInboxSelection.wire_value + ) + assert not ModelSelection.crosses_provider_values("", "anthropic/claude-opus-4-6") + + catalog = ModelSelection.provider_catalog_choices() + values = {choice.value for choice in catalog} + assert "antigravity/gemini-4-neon" in values + assert CliInboxSelection.wire_value in values + + +def test_cross_provider_model_switch_forks_preserving_parent(tmp_path: Path) -> None: + comms = installed_comms(tmp_path / "wire") + session_path = comms.root / "native-sessions" / "designer.jsonl" + session_path.parent.mkdir(parents=True, exist_ok=True) + session_path.write_text('{"type":"session","id":"designer-orig"}\n') + original = comms.registry.declare( + NativeThread( + "designer", + frozenset({"comms", "ux"}), + Checkout(tmp_path), + model=DeclaredModel("anthropic/claude-sonnet-4-5"), + thinking_level=HighThinkingLevel, + session_file=RegistrySessionLocation.from_path(session_path, comms.root), + ), + StoppedThreadStatus(), + ) + + # 1. Same-provider switch updates in place with no forked_from field. + same_reply = invoke_tool( + comms, + "comms_model", + {"thread": "designer", "model": "anthropic/claude-opus-4-6"}, + caller=HumanCaller(), + ) + assert same_reply["thread"] == "designer" + assert same_reply["model"] == "anthropic/claude-opus-4-6" + assert "forked_from" not in same_reply + after_same = comms.registry.require("designer") + assert after_same.model == DeclaredModel("anthropic/claude-opus-4-6") + assert after_same.session_file == original.session_file + + # 2. Cross-provider switch (anthropic -> openai-codex) automatically forks a child thread. + forked_reply = invoke_tool( + comms, + "comms_model", + { + "thread": "designer", + "model": "openai-codex/gpt-5.6-sol", + "thinking_level": "low", + }, + caller=HumanCaller(), + ) + assert forked_reply["thread"] == "designer-openai-codex" + assert forked_reply["forked_from"] == "designer" + assert forked_reply["model"] == "openai-codex/gpt-5.6-sol" + assert forked_reply["thinking_level"] == "low" + + # Parent thread stays completely intact (original provider, model, and session file). + parent_after = comms.registry.require("designer") + assert parent_after.model == DeclaredModel("anthropic/claude-opus-4-6") + assert parent_after.session_file == original.session_file + assert parent_after.thinking_level is HighThinkingLevel + + # Child thread carries ForkedParent, inherited tags, target model, and fresh session file. + child = comms.registry.require("designer-openai-codex") + assert isinstance(child, NativeThread) + assert child.parent == ForkedParent("designer") + assert child.tags == frozenset({"comms", "ux"}) + assert child.model == DeclaredModel("openai-codex/gpt-5.6-sol") + assert child.thinking_level is LowThinkingLevel + assert child.backend is PiNativeBackend + assert child.session_file != original.session_file + + # 3. Switching to another provider with a distinct backend forks onto AntigravityAcpBackend. + agy_reply = invoke_tool( + comms, + "comms_model", + {"thread": "designer", "model": "antigravity/gemini-4-neon"}, + caller=HumanCaller(), + ) + assert agy_reply["thread"] == "designer-antigravity" + assert agy_reply["forked_from"] == "designer" + agy_child = comms.registry.require("designer-antigravity") + assert agy_child.backend is AntigravityAcpBackend + assert agy_child.parent == ForkedParent("designer") + + # 4. Repeating the same cross-provider switch allocates a collision-free -2 fork name. + second_agy = invoke_tool( + comms, + "comms_model", + {"thread": "designer", "model": "antigravity/claude-opus-5-5"}, + caller=HumanCaller(), + ) + assert second_agy["thread"] == "designer-antigravity-2" + assert second_agy["forked_from"] == "designer" + + +def test_external_thread_switch_and_zmq_roundtrip(tmp_path: Path) -> None: + comms = installed_comms(tmp_path / "wire") + # ExternalThread with no prior model switches to native in place. + comms.registry.declare( + ExternalThread("cli-plain", frozenset({"comms"}), Checkout(tmp_path)), + NoBridgeThreadStatus(), + ) + switched = invoke_tool( + comms, + "comms_model", + {"thread": "cli-plain", "model": "anthropic/claude-opus-4-6"}, + caller=HumanCaller(), + ) + assert switched["thread"] == "cli-plain" + assert "forked_from" not in switched + assert isinstance(comms.registry.require("cli-plain"), NativeThread) + + # ExternalThread carrying a saved provider model forks on cross-provider switch over ZMQ. + comms.registry.declare( + ExternalThread( + "cli-with-model", + frozenset({"comms"}), + Checkout(tmp_path), + model=DeclaredModel("anthropic/claude-opus-4-6"), + ), + NoBridgeThreadStatus(), + ) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + port = port if port < 60000 else 17795 + config = CommsZMQConfig.for_root(comms.root, port=port) + server = CommsZMQServer( + comms, port=port, transport_mode=TransportMode.IPC, config=config + ) + stop = threading.Event() + started = threading.Event() + + def _run() -> None: + server.start() + started.set() + try: + while server.is_running() and not stop.is_set(): + server.process_messages() + time.sleep(0.005) + finally: + server.stop() + + thread = threading.Thread(target=_run, daemon=True) + thread.start() + assert started.wait(timeout=5.0) + client = CommsZMQClient( + comms.root, port=port, transport_mode=TransportMode.IPC, config=config + ) + try: + assert client.connect_existing(timeout=3.0) is True + result = client.call( + CommsModelTool( + thread=NamedSubject("cli-with-model"), + model=ChosenModel("openai-codex/gpt-5.6-sol"), + ) + ) + assert isinstance(result, ModelChanged) + assert result.thread == "cli-with-model-openai-codex" + assert result.forked_from == "cli-with-model" + assert result.model == DeclaredModel("openai-codex/gpt-5.6-sol") + finally: + client.disconnect() + stop.set() + thread.join(timeout=3.0)