Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/agent_comms/registry/thread_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...]:
Expand Down
91 changes: 91 additions & 0 deletions src/agent_comms/registry/thread_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""

Expand All @@ -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."""
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions src/agent_comms/registry/threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)

Expand Down
1 change: 1 addition & 0 deletions src/agent_comms/transport/served_tools/served.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)


Expand Down
1 change: 1 addition & 0 deletions src/agent_comms/transport/tools/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading