Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(model-hub): add automatic and API-key passthrough routing (#1897)

Call White6bddf6617c52
diff --git a/config/v2_config.py b/config/v2_config.py
index 179aa3d7a..cb86d73eb 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -281,58 +281,6 @@ def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:
)
-def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:
- """Adapt fixed-menu route keys to the current bundled catalog on reload.
-
- Newly introduced menu ids receive empty routes. Legacy route keys remain
- intact so the canonical agent loader can preserve them as manual catalog
- rows; matching and placement never run here.
- """
-
- model_hub = payload.get("model_hub")
- if not isinstance(model_hub, dict):
- return payload
- agents = model_hub.get("agents")
- if not isinstance(agents, dict):
- return payload
-
- migrated_agents = dict(agents)
- changed = False
- for backend in ("claude", "codex"):
- raw_agent = agents.get(backend)
- if not isinstance(raw_agent, dict):
- continue
- if "models" in raw_agent:
- continue
- routes = raw_agent.get("routes")
- expected_menu_ids = model_hub_fixed_menu_ids(backend)
- if not isinstance(routes, dict) or not expected_menu_ids:
- continue
- migrated_routes = {
- model_id: routes.get(model_id, {"hops": []})
- for model_id in expected_menu_ids
- }
- migrated_routes.update(
- (model_id, route)
- for model_id, route in routes.items()
- if model_id not in migrated_routes
- )
- if migrated_routes == routes:
- continue
- migrated_agent = dict(raw_agent)
- migrated_agent["routes"] = migrated_routes
- migrated_agents[backend] = migrated_agent
- changed = True
-
- if not changed:
- return payload
- migrated_model_hub = dict(model_hub)
- migrated_model_hub["agents"] = migrated_agents
- migrated_payload = dict(payload)
- migrated_payload["model_hub"] = migrated_model_hub
- return migrated_payload
-
-
def _legacy_source_eligible_for_backend(source: object, backend: str) -> bool:
if not isinstance(source, dict):
return False
@@ -456,8 +404,8 @@ def _legacy_claude_matching_model_id(source: dict, requested_model: str) -> str
Claude's old native CLI resolver treated ``opus``/``sonnet``/``haiku`` as
family selectors and persisted the newest concrete model it observed. Keep
- that behavior at the disk migration boundary; the current runtime resolver
- intentionally only follows persisted exact hops.
+ that behavior at the disk migration boundary so the resulting override
+ retains its exact historical target independently of automatic routing.
"""
if source.get("vendor") != "anthropic":
@@ -811,7 +759,6 @@ def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:
def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)
- migrated = _migrate_fixed_menu_routes_on_load(migrated)
model_hub_changed = changed or migrated.get("model_hub") != payload.get("model_hub")
migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)
return migrated, model_hub_changed, warnings
@@ -3051,10 +2998,7 @@ class ModelHubRouteHopConfig:
or _contains_model_hub_credential_material(model_id)
):
raise ValueError("Config 'model_hub.agents.routes.hops.model_id' is invalid")
- # A hop names a model in some source's inventory, and membership is decided
- # by an exact comparison against that inventory. So the reference has to be
- # spelled by whatever spells the thing it refers to: normalizing one side
- # only would turn a working chain into `model_unsupported` on upgrade.
+ # Keep saved targets in the same canonical namespace as inventory evidence.
from core.handlers.model_hub.identifiers import normalized_model_id
return cls(source_id=source_id, model_id=normalized_model_id(model_id))
@@ -3375,7 +3319,6 @@ class ModelHubAgentSupplyConfig:
backend=backend,
mode=mode,
menu_kind="fixed",
- routes={model_id: ModelHubRouteConfig() for model_id in model_hub_fixed_menu_ids(backend)},
models=_default_backend_models(backend),
)
@@ -3629,14 +3572,6 @@ class ModelHubConfig:
expected_menu_ids = tuple(
model.id for model in agents[backend].models
)
- missing_route = next(
- (model_id for model_id in expected_menu_ids if model_id not in agents[backend].routes),
- None,
- )
- if missing_route is not None:
- raise ValueError(
- f"Config 'model_hub.agents.{backend}.routes' is missing menu model '{missing_route}'"
- )
extra_route = next(
(
model_id
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index b419333a9..3b459a289 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v8 (2026-09-05).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v9 (2026-09-06).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
@@ -12,7 +12,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
from .stream_wire import ProtocolSSEState, ProtocolUsageReport
@@ -73,12 +73,14 @@ class SourceBinding:
# source. Empty tuple = unrestricted (api_key default). Subscription
# sources MUST be non-empty (README invariant 3); L2 populates, L1
# enforces as backstop.
- model_ids: tuple[str, ...] # declared supply list (discovered + manual
- # custom entries); required by the engine's generic/API-key config. Bare
- # model ids, no provider prefix.
+ model_ids: tuple[str, ...] # truthful inventory evidence (discovered + manual).
+ # May be empty; API-key invocation need not be listed. Bare ids, no prefix.
model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()
# Per-model levels declared by the Source. CLIProxyAPI needs these on its
# model registration or it removes an otherwise valid reasoning effort.
+ route_model_ids: tuple[str, ...] = ()
+ # Sorted API-key transport targets derived from effective routes, never
+ # inventory or capability evidence. Independent of live health and mode.
class OriginNotAllowedError(Exception):
@@ -535,8 +537,18 @@ class EngineAdapter(Protocol):
request: Mapping[str, Any],
stream: bool,
origin: str,
+ *,
+ on_admitted: Callable[[], None] | None = None,
) -> InvokeHandle:
"""``origin`` = requesting agent name ("claude"|"codex"|"opencode"|...).
Raises ``OriginNotAllowedError`` when the binding's ``allowed_origins``
- excludes it (backstop; L2 must have filtered already)."""
+ excludes it (backstop; L2 must have filtered already). ``model_id`` is
+ the chosen canonical route target. API-key targets need not be listed;
+ subscriptions retain their existing exact inventory admission.
+ The adapter must keep exact source isolation without inventing inventory.
+ After validating source/origin, acquire the transport lease and call
+ ``on_admitted`` exactly once before any network wait. Callback failure
+ releases the lease without invoking upstream. Transport completion,
+ close, or cancellation releases the lease independently of settlement.
+ """
...
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 9cc58097f..465966260 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -23,7 +23,12 @@ from core.run_settlement import (
from vibe.i18n import t as i18n_t
from .adapter import RawCallOutcome
-from .classification import ResolutionDecision, ResolutionReason
+from .classification import (
+ UPSTREAM_MACHINE_ERROR_CODES,
+ ResolutionDecision,
+ ResolutionReason,
+ machine_error_codes,
+)
from .events import (
EVENT_REASON_AUTHORITY,
RETIRED_PERSISTED_REASON_DEGRADATIONS,
@@ -816,6 +821,18 @@ class BoundedProvenanceStore:
None,
)
+ def latest_for_model(self, backend: str, model_id: str) -> Optional[dict]:
+ with self._lock:
+ return next(
+ (
+ dict(record)
+ for record in reversed(self._read())
+ if record.get("agent") == backend
+ and record.get("requested_model_id") == model_id
+ ),
+ None,
+ )
+
class TurnCorrelationRegistry:
"""Correlate process credentials to the existing Workbench turn token."""
@@ -1549,10 +1566,22 @@ class TurnCorrelationRegistry:
)
return
if decision.action == "surface":
+ observed_codes = machine_error_codes(outcome)
+ diagnostic_code = (
+ "model_not_found"
+ if decision.error_code == "upstream_request_invalid" and "model_not_found" in observed_codes
+ else next((code for code in observed_codes if code in UPSTREAM_MACHINE_ERROR_CODES), None)
+ )
trace.terminal_error = {
**identity.payload(),
"reason": _terminal_reason(decision),
"stream_started": outcome.stream_started,
+ "http_status": (
+ outcome.http_status
+ if type(outcome.http_status) is int and 100 <= outcome.http_status <= 599
+ else None
+ ),
+ "upstream_error_code": diagnostic_code,
}
def settle(self, turn_id: str, *, settled_by: Optional[str], ts: Optional[str] = None) -> None:
@@ -1661,7 +1690,7 @@ class TurnCorrelationRegistry:
self.store.put(
{
- "contract_version": 8,
+ "contract_version": 9,
"turn_id": normalized_turn_id,
"ts": ts or _utc_now_iso(),
"agent": trace.agent,
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
index f6651d239..4de90ba1d 100644
--- a/core/handlers/model_hub/resolver.py
+++ b/core/handlers/model_hub/resolver.py
@@ -1,4 +1,4 @@
-"""Pure Model Hub resolution over the persisted per-model route."""
+"""Pure Model Hub routing from explicit overrides and backend defaults."""
from __future__ import annotations
@@ -10,6 +10,7 @@ from typing import Literal
from config.v2_config import (
MODEL_HUB_BACKENDS,
ModelHubConfig,
+ ModelHubRouteConfig,
ModelHubRouteHopConfig,
ModelHubSourceConfig,
)
@@ -18,11 +19,19 @@ from config.v2_config import (
BackendName = Literal["claude", "codex", "opencode"]
ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]
SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]
+RouteOrigin = Literal["automatic", "manual", "passthrough"]
+
+
+@dataclass(frozen=True)
+class EffectiveModelRoute:
+ manual_override: ModelHubRouteConfig | None
+ route_origin: RouteOrigin | None
+ hops: tuple[ModelHubRouteHopConfig, ...]
@dataclass(frozen=True)
class ExactHopInspection:
- """Canonical identity and live eligibility for one persisted Route hop."""
+ """Canonical identity and live eligibility for one effective Route hop."""
backend: BackendName
menu_model: str
@@ -49,6 +58,8 @@ class ModelHubTurnResolution:
requested_model: str
target_model: str
source: ModelHubSourceConfig | None
+ manual_override: ModelHubRouteConfig | None = None
+ route_origin: RouteOrigin | None = None
matching_sources: tuple[ModelHubSourceConfig, ...] = ()
candidates: tuple[ModelHubSourceConfig, ...] = ()
candidate_hops: tuple[ExactHopInspection, ...] = ()
@@ -165,7 +176,7 @@ def matching_v1_model_id(
source: ModelHubSourceConfig,
include_manual: bool = False,
) -> str | None:
- """Return one concrete observed model for the frozen add-time matching-v1."""
+ """Match one inventory id using the established literal/native Claude policy."""
observed_models = tuple(
model
@@ -208,6 +219,53 @@ def matching_v1_model_id(
)
+def source_model_retired(source: ModelHubSourceConfig, model_id: str) -> bool:
+ return any(model.id == model_id and model.retired for model in source.models)
+
+
+def source_supports_passthrough(source: ModelHubSourceConfig) -> bool:
+ return source.kind == "api_key" and source.supply_channel == "hub"
+
+
+def effective_model_route(
+ config: ModelHubConfig,
+ backend: BackendName,
+ requested_model: str,
+) -> EffectiveModelRoute:
+ """Choose one route tier before live health or transport restriction."""
+
+ agent = config.agents[backend]
+ if requested_model in agent.routes:
+ override = agent.routes[requested_model]
+ return EffectiveModelRoute(override, "manual" if override.hops else None, override.hops)
+ if not requested_model or not any(model.id == requested_model for model in agent.models):
+ return EffectiveModelRoute(None, None, ())
+ by_id = {source.id: source for source in config.sources}
+ sources = [
+ by_id[source_id]
+ for source_id in agent.sources.order
+ if source_id in by_id and source_eligible_for_backend(by_id[source_id], backend)
+ ]
+ matches = tuple(
+ ModelHubRouteHopConfig(source.id, matched)
+ for source in sources
+ if (matched := matching_v1_model_id(
+ backend=backend,
+ requested_model=requested_model,
+ source=source,
+ include_manual=True,
+ )) is not None
+ )
+ if matches:
+ return EffectiveModelRoute(None, "automatic", matches)
+ hops = tuple(
+ ModelHubRouteHopConfig(source.id, requested_model)
+ for source in sources
+ if source_supports_passthrough(source) and not source_model_retired(source, requested_model)
+ )
+ return EffectiveModelRoute(None, "passthrough" if hops else None, hops)
+
+
def inspect_exact_hop(
config: ModelHubConfig,
backend: BackendName,
@@ -218,7 +276,7 @@ def inspect_exact_hop(
unavailable_source_ids: frozenset[str] = frozenset(),
supply_channel: Literal["hub"] | None = None,
) -> ExactHopInspection:
- """Inspect one stored hop without matching, substituting, or reordering it."""
+ """Inspect one exact hop without matching, substituting, or reordering it."""
if hop is None:
return ExactHopInspection(
@@ -259,16 +317,19 @@ def inspect_exact_hop(
for model in source.models
)
channel_eligible = supply_channel is None or source.supply_channel == supply_channel
- supply_eligible = configuration_eligible and inventory_member and channel_eligible
+ model_supported = inventory_member or (
+ source_supports_passthrough(source) and not source_model_retired(source, hop.model_id)
+ )
+ supply_eligible = configuration_eligible and model_supported and channel_eligible
runnable = supply_eligible and source_runnable(
source,
now=now,
unavailable_source_ids=unavailable_source_ids,
- model_supported=inventory_member,
+ model_supported=model_supported,
)
reason: str | None = None
structural_blocker = False
- if not inventory_member or not configuration_eligible:
+ if not model_supported or not configuration_eligible:
reason = "model_unsupported"
structural_blocker = True
elif source.id in unavailable_source_ids:
@@ -327,12 +388,7 @@ def resolve_model_hub_turn(
unavailable_source_ids: frozenset[str] = frozenset(),
supply_channel: Literal["hub"] | None = None,
) -> ModelHubTurnResolution:
- """Resolve a turn by walking the route persisted for ``requested_model``.
-
- This function deliberately does not inspect source inventory, vendor names,
- or source order to create a route. Those decisions belong to source-add and
- explicit chain-edit operations.
- """
+ """Annotate the effective route without changing its membership or tier."""
requested_model = str(requested_model or "").strip()
agent = config.agents[backend]
@@ -356,18 +412,7 @@ def resolve_model_hub_turn(
supply_status="interrupted",
)
- route = agent.routes.get(requested_model)
- if route is None:
- return ModelHubTurnResolution(
- backend=backend,
- channel="unavailable",
- requested_model=requested_model,
- target_model=requested_model,
- source=None,
- supply_status="interrupted",
- route_unconfigured=True,
- route_reason="route_unconfigured",
- )
+ route = effective_model_route(config, backend, requested_model)
inspected_hops = tuple(
inspect_exact_hop(
@@ -460,6 +505,8 @@ def resolve_model_hub_turn(
requested_model=requested_model,
target_model=target_model or requested_model,
source=first,
+ manual_override=route.manual_override,
+ route_origin=route.route_origin,
matching_sources=matching_sources,
candidates=candidates,
candidate_hops=runnable_inspections,
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 771ed13c1..2d25703c8 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -136,6 +136,9 @@ async def dispatch_model_hub_rpc(
return await service.reorder_agent_chains(
payload.get("backend"),
payload.get("order"),
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
return await service.reorder_agent_chains(payload.get("backend"))
if operation == "set_agent_mode":
@@ -164,6 +167,14 @@ async def dispatch_model_hub_rpc(
payload.get("model_id"),
payload.get("chain"),
)
+ if operation == "delete_agent_chain":
+ return await service.delete_agent_chain(
+ payload.get("backend"), payload.get("model_id"), payload.get("chain"),
+ )
+ if operation == "preview_agent_chain":
+ return service.preview_agent_chain(
+ payload.get("backend"), payload.get("model_id"), payload.get("chain"),
+ )
if operation == "add_custom_model":
return await service.add_custom_model(payload.get("source_id"), payload.get("model"))
if operation == "update_model_reasoning_efforts":
@@ -203,6 +214,8 @@ async def dispatch_model_hub_rpc(
)
if operation == "get_turn_provenance":
return service.get_turn_provenance(payload.get("turn_id"))
+ if operation == "get_model_provenance":
+ return await asyncio.to_thread(service.get_model_provenance, payload.get("backend"), payload.get("model_id"))
if operation == "oauth_start":
return await service.oauth_start(payload.get("oauth"))
if operation == "oauth_status":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 9871e0c08..0e7860761 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -88,7 +88,7 @@ from .events import (
redact_credential_material,
)
from .errors import ModelDiscoveryError
-from .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_id
+from .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_id, normalized_model_id
from .migration import (
MigrationConflictError,
apply_native_migration,
@@ -119,17 +119,20 @@ from .resolver import (
BackendName,
ModelHubTurnResolution,
allowed_origins,
+ effective_model_route,
inspect_exact_hop,
matching_v1_model_id as _matching_v1_model_id,
resolve_model_hub_turn,
source_after_cooldown_recovery,
source_eligible_for_backend,
+ source_model_retired,
+ source_supports_passthrough,
source_runnable,
)
from .revocations import CredentialRevocationJournal
from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter
-CONTRACT_VERSION = 8
+CONTRACT_VERSION = 9
def _storable_backend_model_metadata(
@@ -152,8 +155,8 @@ def _storable_backend_model_metadata(
return proposed_display_name, proposed_efforts
-AGENT_CHAIN_CONTRACT_VERSION = 8
-PROBE_RESULT_CONTRACT_VERSION = 8
+AGENT_CHAIN_CONTRACT_VERSION = 9
+PROBE_RESULT_CONTRACT_VERSION = 9
_REORDER_ORDER_UNSET = object()
_REASONING_EFFORT_TELEMETRY_MAX_BYTES = 256
# Settlement generations are minted per attempt start and live only in this
@@ -370,10 +373,16 @@ class UnavailableEngineAdapter:
request: Mapping[str, Any],
stream: bool,
origin: str,
+ *,
+ on_admitted: Callable[[], None] | None = None,
) -> InvokeHandle:
raise EngineUnavailableError
+class _InvocationPlanChanged(Exception):
+ """No transport was admitted; recompute the remaining effective route."""
+
+
@dataclass(frozen=True)
class ResolvedInvocation:
backend: BackendName
@@ -710,7 +719,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
manager = EngineRuntimeManager()
return {
- "contract_version": 8,
+ "contract_version": 9,
"enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
@@ -971,28 +980,19 @@ class ModelHubService:
raise ModelHubError("engine_down", status=503) from None
def _bindings(self, config: ModelHubConfig) -> list[SourceBinding]:
- ineligible_source_ids = {
- inspection.source_id
- for backend_name in MODEL_HUB_BACKENDS
- for menu_model, route in config.agents[backend_name].routes.items()
- for hop in route.hops
- for inspection in (
- inspect_exact_hop(
- config,
- cast(BackendName, backend_name),
- menu_model,
- hop,
- ),
- )
- if inspection.source_id is not None
- and not inspection.configuration_eligible
- }
+ route_targets: dict[str, set[str]] = {}
+ sources = {source.id: source for source in config.sources}
+ for backend, agent in config.agents.items():
+ for model_id in self._agent_model_ids(agent, ""):
+ for hop in effective_model_route(config, cast(BackendName, backend), model_id).hops:
+ source = sources.get(hop.source_id)
+ if source is not None and source_supports_passthrough(source) and not source_model_retired(source, hop.model_id):
+ route_targets.setdefault(source.id, set()).add(hop.model_id)
return [
- _binding(source)
+ replace(_binding(source), route_model_ids=tuple(sorted(route_targets.get(source.id, ()))))
for source in config.sources
if source.supply_channel == "hub"
- and any(not model.retired for model in source.models)
- and source.id not in ineligible_source_ids
+ and (source_supports_passthrough(source) or any(not model.retired for model in source.models))
]
@staticmethod
@@ -1090,7 +1090,7 @@ class ModelHubService:
previous_bindings = self._bindings(previous)
updated_bindings = self._bindings(updated)
# SourceBinding order is the engine-config serialization order. Agent
- # Route hop order is not part of this projection, so a pure chain reorder
+ # Route target order is not part of this projection, so a pure chain reorder
# compares equal and does not restart a healthy engine.
if previous_bindings == updated_bindings:
self._save_config(updated)
@@ -1866,25 +1866,12 @@ class ModelHubService:
config: ModelHubConfig,
source: ModelHubSourceConfig,
) -> None:
- """Apply matching-v1 and placement-v1 to one newly added Source."""
+ """Add a new Source to eligible backend defaults without editing overrides."""
for backend in MODEL_HUB_BACKENDS:
agent = config.agents[backend]
if self._eligible_for_agent(source, backend) and source.id not in agent.sources.order:
agent.sources.order.append(source.id)
- menu_ids = self._agent_menu_model_ids(agent)
- for menu_model in menu_ids:
- route = agent.routes.setdefault(menu_model, ModelHubRouteConfig())
- if not self._eligible_for_agent(source, backend):
- continue
- matched_model = _matching_v1_model_id(
- backend=cast(BackendName, backend),
- requested_model=menu_model,
- source=source,
- )
- if matched_model is None or any(hop.source_id == source.id for hop in route.hops):
- continue
- route.hops = (*route.hops, ModelHubRouteHopConfig(source.id, matched_model))
def _matching_menu_model_hops(
self,
@@ -1892,36 +1879,18 @@ class ModelHubService:
backend: BackendName,
menu_model: str,
) -> tuple[ModelHubRouteHopConfig, ...]:
- """Project matching-v1 in placement-v1 order for one menu model."""
+ """Expose matching inventory evidence for a prospective catalog row."""
- agent = config.agents[backend]
- source_by_id = {source.id: source for source in config.sources}
- hops: list[ModelHubRouteHopConfig] = []
- for source_id in agent.sources.order:
- source = source_by_id.get(source_id)
- if source is None or not self._eligible_for_agent(source, backend):
- continue
- matched_model = _matching_v1_model_id(
- backend=backend,
- requested_model=menu_model,
- source=source,
- include_manual=True,
- )
- if matched_model is not None:
- hops.append(ModelHubRouteHopConfig(source.id, matched_model))
- return tuple(hops)
-
- def _seed_menu_model_route(
- self,
- config: ModelHubConfig,
- backend: BackendName,
- menu_model: str,
- ) -> None:
- """Apply matching-v1 and placement-v1 once for a newly added menu row."""
-
- config.agents[backend].routes[menu_model] = ModelHubRouteConfig(
- hops=self._matching_menu_model_hops(config, backend, menu_model)
+ automatic = replace(
+ config,
+ agents={**config.agents, backend: replace(
+ config.agents[backend],
+ routes={},
+ models=[ModelHubBackendModelConfig(id=menu_model, origin="manual")],
+ )},
)
+ route = effective_model_route(automatic, backend, menu_model)
+ return route.hops if route.route_origin == "automatic" else ()
@staticmethod
def _agent_menu_model_ids(agent: ModelHubAgentSupplyConfig) -> tuple[str, ...]:
@@ -1931,8 +1900,9 @@ class ModelHubService:
config = self.store.load()
result: list[dict] = []
for backend in MODEL_HUB_BACKENDS:
- routes = config.agents[backend].routes
- for menu_model, route in routes.items():
+ agent = config.agents[backend]
+ for menu_model in self._agent_model_ids(agent, self._requested_model(agent)):
+ route = effective_model_route(config, cast(BackendName, backend), menu_model)
for position, hop in enumerate(route.hops, start=1):
if hop.source_id == source_id:
result.append(
@@ -1956,8 +1926,11 @@ class ModelHubService:
{"backend": backend, "menu_model": menu_model}
for backend in MODEL_HUB_BACKENDS
if config.agents[backend].mode == "hub"
- for menu_model, route in config.agents[backend].routes.items()
- if any(hop.source_id == source_id for hop in route.hops)
+ for menu_model in self._agent_model_ids(config.agents[backend], self._requested_model(config.agents[backend]))
+ if any(
+ hop.source_id == source_id
+ for hop in effective_model_route(config, cast(BackendName, backend), menu_model).hops
+ )
]
result.sort(key=lambda item: (item["backend"], item["menu_model"]))
return result
@@ -3230,19 +3203,14 @@ class ModelHubService:
self,
config: ModelHubConfig,
*,
- newly_empty_routes: frozenset[tuple[str, str]] = frozenset(),
+ include_unconfigured: bool = False,
) -> list[dict]:
gaps: list[dict] = []
for backend_name in MODEL_HUB_BACKENDS:
backend = cast(BackendName, backend_name)
unavailable_source_ids = self._unavailable_native_sources(config, backend)
- for model_id, agents in self._protected_menu_models(config, backend).items():
- route = config.agents[backend].routes.get(model_id)
- if (
- (route is None or not route.hops)
- and (backend, model_id) not in newly_empty_routes
- ):
- continue
+ protected = self._protected_menu_models(config, backend)
+ for model_id, agents in protected.items():
resolution = resolve_model_hub_turn(
config,
backend,
@@ -3252,6 +3220,8 @@ class ModelHubService:
)
if resolution.candidates:
continue
+ if not include_unconfigured and not agents and not resolution.inspected_hops:
+ continue
gaps.append(
{
"backend": backend,
@@ -3265,22 +3235,61 @@ class ModelHubService:
self,
previous: ModelHubConfig,
updated: ModelHubConfig,
- *,
- newly_empty_routes: frozenset[tuple[str, str]] = frozenset(),
) -> list[dict]:
baseline = {
(item["backend"], item["model_id"])
- for item in self._would_interrupt(previous)
+ for item in self._would_interrupt(previous, include_unconfigured=True)
}
return [
item
for item in self._would_interrupt(
updated,
- newly_empty_routes=newly_empty_routes,
+ include_unconfigured=True,
)
if (item["backend"], item["model_id"]) not in baseline
]
+ def _effective_hop_refs(self, config: ModelHubConfig, backend: str | None = None) -> list[dict]:
+ refs: list[dict] = []
+ for backend_name in MODEL_HUB_BACKENDS:
+ if backend is not None and backend_name != backend:
+ continue
+ agent = config.agents[backend_name]
+ model_ids = dict.fromkeys((
+ *self._agent_model_ids(agent, self._requested_model(agent)),
+ *self._protected_menu_models(config, cast(BackendName, backend_name)),
+ ))
+ for model_id in model_ids:
+ route = effective_model_route(config, cast(BackendName, backend_name), model_id)
+ refs.extend(
+ {
+ "backend": backend_name,
+ "menu_model": model_id,
+ "source_id": hop.source_id,
+ "model_id": hop.model_id,
+ "position": position,
+ }
+ for position, hop in enumerate(route.hops, start=1)
+ )
+ return refs
+
+ def _removed_effective_hops(
+ self,
+ previous: ModelHubConfig,
+ updated: ModelHubConfig,
+ *,
+ backend: str | None = None,
+ model_id: str | None = None,
+ ) -> list[dict]:
+ def identity(item: dict) -> tuple[str, str, str, str]:
+ return item["backend"], item["menu_model"], item["source_id"], item["model_id"]
+
+ remaining = {identity(item) for item in self._effective_hop_refs(updated, backend)}
+ return [
+ item for item in self._effective_hop_refs(previous, backend)
+ if (model_id is None or item["menu_model"] == model_id) and identity(item) not in remaining
+ ]
+
def _invalidated_route_hops(
self,
config: ModelHubConfig,
@@ -3345,7 +3354,9 @@ class ModelHubService:
confirmed_remove_hops: object,
confirmed_interruptions: object,
) -> tuple[list[dict], list[dict]]:
- would_remove_hops = self._invalidated_route_hops(updated, source_id)
+ invalidated = self._invalidated_route_hops(updated, source_id)
+ would_remove_hops = self._removed_effective_hops(previous, updated)
+ would_remove_hops.extend(item for item in invalidated if item not in would_remove_hops)
would_interrupt = self._introduced_interruptions(previous, updated)
self._require_guard_plan(
force=force,
@@ -3359,8 +3370,8 @@ class ModelHubService:
else "source_last_supplier"
),
)
- if would_remove_hops:
- self._prune_invalidated_route_hops(updated, would_remove_hops)
+ if invalidated:
+ self._prune_invalidated_route_hops(updated, invalidated)
return would_remove_hops, would_interrupt
@staticmethod
@@ -3402,34 +3413,16 @@ class ModelHubService:
previous = self.store.load()
config = self._clone_config(previous)
source = self._source(config, source_id)
- removed_hops = [
- {
- "backend": backend,
- "menu_model": model_id,
- "source_id": source_id,
- "model_id": hop.model_id,
- "position": position,
- }
- for backend in MODEL_HUB_BACKENDS
- for model_id, route in config.agents[backend].routes.items()
- for position, hop in enumerate(route.hops, start=1)
- if hop.source_id == source_id
- ]
+ removed_hops = [item for item in self._effective_hop_refs(previous) if item["source_id"] == source_id]
config.sources = [item for item in config.sources if item.id != source_id]
for agent in config.agents.values():
agent.sources.order = [item for item in agent.sources.order if item != source_id]
for model_id, route in list(agent.routes.items()):
route.hops = tuple(hop for hop in route.hops if hop.source_id != source_id)
agent.routes[model_id] = route
- newly_empty_routes = frozenset(
- (item["backend"], item["menu_model"])
- for item in removed_hops
- if not config.agents[item["backend"]].routes[item["menu_model"]].hops
- )
would_interrupt = self._introduced_interruptions(
previous,
config,
- newly_empty_routes=newly_empty_routes,
)
self._require_guard_plan(
force=force,
@@ -3443,7 +3436,6 @@ class ModelHubService:
else "source_last_supplier"
),
)
- self._prune_unavailable_agent_references(config)
if source.credential_ref:
self.revocations.add(source.id, source.credential_ref)
try:
@@ -3592,8 +3584,11 @@ class ModelHubService:
async def set_agent_sources(self, backend: str, payload: object) -> dict:
if backend not in MODEL_HUB_BACKENDS or not isinstance(payload, dict):
raise self._invalid_source_order()
- if set(payload) != {"order"}:
- rejected = sorted(set(payload) - {"order"})
+ allowed = {"order", "force", "would_remove_hops", "would_interrupt"}
+ if "order" not in payload or set(payload) - allowed or (
+ "force" in payload and not isinstance(payload["force"], bool)
+ ):
+ rejected = sorted(set(payload) - allowed)
raise self._invalid_source_order(rejected_keys=rejected)
async with self._mutation_lock:
@@ -3605,6 +3600,16 @@ class ModelHubService:
backend,
payload.get("order"),
)
+ removed = self._removed_effective_hops(previous, config, backend=backend)
+ interrupted = self._introduced_interruptions(previous, config)
+ self._require_guard_plan(
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
+ would_remove_hops=removed,
+ would_interrupt=interrupted,
+ error="source_in_route_chain" if removed else "source_last_supplier",
+ )
await self._commit_synced(previous, config)
return self._agent_payload(config, agent)
@@ -3616,7 +3621,7 @@ class ModelHubService:
if (
backend not in MODEL_HUB_BACKENDS
or not isinstance(model_id, str)
- or not model_id.strip()
+ or normalized_model_id(model_id) != model_id
or not isinstance(payload, dict)
or set(payload)
- {"hops", "force", "would_remove_hops", "would_interrupt"}
@@ -3626,73 +3631,105 @@ class ModelHubService:
raise ModelHubError("mapping_target_unavailable", status=409)
try:
route = ModelHubRouteConfig.from_payload({"hops": payload["hops"]})
+ if any(normalized_model_id(hop["model_id"]) != hop["model_id"] for hop in payload["hops"]):
+ raise ValueError("noncanonical model")
except (TypeError, ValueError):
raise ModelHubError("mapping_target_unavailable", status=409) from None
+ return await self._write_agent_chain(backend, model_id, route, payload)
- async with self._mutation_lock:
- previous = self.store.load()
- config = self._clone_config(previous)
- agent = self._agent(config, backend)
- if agent.mode == "direct":
- raise self._direct_mode_error()
- if model_id not in self._agent_menu_model_ids(agent):
+ def _validate_route_override(
+ self,
+ config: ModelHubConfig,
+ backend: str,
+ model_id: object,
+ route: ModelHubRouteConfig | None,
+ ) -> ModelHubAgentSupplyConfig:
+ agent = self._agent(config, backend)
+ if agent.mode == "direct":
+ raise self._direct_mode_error()
+ if not isinstance(model_id, str) or normalized_model_id(model_id) != model_id or (
+ model_id not in self._agent_menu_model_ids(agent)
+ ):
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ by_id = {source.id: source for source in config.sources}
+ old_pairs = {
+ (hop.source_id, hop.model_id)
+ for hop in agent.routes.get(model_id, ModelHubRouteConfig()).hops
+ }
+ for hop in route.hops if route is not None else ():
+ source = by_id.get(hop.source_id)
+ if source is None or not self._eligible_for_agent(source, backend):
raise ModelHubError("mapping_target_unavailable", status=409)
- by_id = {source.id: source for source in config.sources}
- old_route = agent.routes.get(model_id, ModelHubRouteConfig())
- old_pairs = {(hop.source_id, hop.model_id) for hop in old_route.hops}
- for hop in route.hops:
- source = by_id.get(hop.source_id)
- if source is None or not self._eligible_for_agent(source, backend):
- raise ModelHubError("mapping_target_unavailable", status=409)
- if (hop.source_id, hop.model_id) not in old_pairs and not any(
- model.id == hop.model_id and not model.retired
- for model in source.models
- ):
- raise ModelHubError("mapping_target_unavailable", status=409)
- new_pairs = {
- (item.source_id, item.model_id)
- for item in route.hops
- }
- removed_hops = [
- {
- "backend": backend,
- "menu_model": model_id,
- "source_id": hop.source_id,
- "model_id": hop.model_id,
- "position": position,
- }
- for position, hop in enumerate(old_route.hops, start=1)
- if (hop.source_id, hop.model_id) not in new_pairs
- ]
- agent.routes[model_id] = route
- interrupted = self._introduced_interruptions(
- previous,
- config,
- newly_empty_routes=(
- frozenset({(backend, model_id)})
- if old_route.hops and not route.hops
- else frozenset()
- ),
+ # Existing exact targets keep their load-time identity; only a new
+ # source/target identity is subject to the current admission bound.
+ persisted_target = (hop.source_id, hop.model_id) in old_pairs or any(
+ model.id == hop.model_id for model in source.models
)
- confirmed = (
- payload.get("force") is True
- and _same_json_value(
- payload.get("would_remove_hops"),
- removed_hops,
- )
- and _same_json_value(
- payload.get("would_interrupt"),
- interrupted,
+ if not persisted_target and canonical_model_id(hop.model_id) != hop.model_id:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ if source_supports_passthrough(source):
+ valid = not source_model_retired(source, hop.model_id)
+ else:
+ valid = (hop.source_id, hop.model_id) in old_pairs or any(
+ model.id == hop.model_id and not model.retired for model in source.models
)
- )
- if interrupted and not confirmed:
- raise ModelHubError(
- "source_last_supplier",
- status=409,
- data={
- "would_remove_hops": removed_hops,
- "would_interrupt": interrupted,
- },
+ if not valid:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return agent
+
+ def preview_agent_chain(self, backend: str, model_id: object, payload: object) -> dict:
+ if not isinstance(payload, dict) or set(payload) != {"manual_override"}:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ raw = payload["manual_override"]
+ try:
+ route = ModelHubRouteConfig.from_payload(raw) if raw is not None else None
+ if raw is not None and any(normalized_model_id(hop["model_id"]) != hop["model_id"] for hop in raw["hops"]):
+ raise ValueError("noncanonical model")
+ except (TypeError, ValueError):
+ raise ModelHubError("mapping_target_unavailable", status=409) from None
+ config = self._clone_config(self.store.load())
+ agent = self._validate_route_override(config, backend, model_id, route)
+ if route is None:
+ agent.routes.pop(model_id, None)
+ else:
+ agent.routes[model_id] = route
+ return self._agent_chain(config, backend, model_id)
+
+ async def delete_agent_chain(self, backend: str, model_id: object, payload: object = None) -> dict:
+ if payload is None:
+ payload = {}
+ if not isinstance(payload, dict) or set(payload) - {"force", "would_remove_hops", "would_interrupt"} or (
+ "force" in payload and not isinstance(payload["force"], bool)
+ ):
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return await self._write_agent_chain(backend, model_id, None, payload)
+
+ async def _write_agent_chain(
+ self,
+ backend: str,
+ model_id: object,
+ route: ModelHubRouteConfig | None,
+ payload: dict,
+ ) -> dict:
+
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ agent = self._validate_route_override(config, backend, model_id, route)
+ if route is None:
+ agent.routes.pop(model_id, None)
+ else:
+ agent.routes[model_id] = route
+ removed_hops = self._removed_effective_hops(previous, config, backend=backend, model_id=model_id)
+ interrupted = self._introduced_interruptions(previous, config)
+ if interrupted or (route is None and removed_hops):
+ self._require_guard_plan(
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
+ would_remove_hops=removed_hops,
+ would_interrupt=interrupted,
+ error="source_last_supplier" if interrupted else "source_in_route_chain",
)
await self._commit_synced(previous, config)
return {
@@ -3701,11 +3738,6 @@ class ModelHubService:
"interrupted": interrupted,
}
- def _prune_unavailable_agent_references(self, config: ModelHubConfig) -> None:
- # Route membership is user configuration. Inventory refresh and source
- # deletion may annotate or remove exact hops, but never re-match menus.
- return
-
@staticmethod
def _catalog_model_payload(model: ModelHubBackendModelConfig) -> dict:
return {
@@ -3769,19 +3801,14 @@ class ModelHubService:
model_supply = [
{
"model_id": model_id,
- "chain_length": len(agent.routes.get(model_id, ModelHubRouteConfig()).hops),
- "has_runnable_hop": any(
- inspection.runnable
- for inspection in resolve_model_hub_turn(
- config,
- backend,
- model_id,
- now=now,
- unavailable_source_ids=unavailable_source_ids,
- ).inspected_hops
- ),
+ "chain_length": len(model_resolution.inspected_hops),
+ "route_origin": model_resolution.route_origin,
+ "has_runnable_hop": bool(model_resolution.candidate_hops),
}
for model_id in menu_model_ids
+ for model_resolution in (resolve_model_hub_turn(
+ config, backend, model_id, now=now, unavailable_source_ids=unavailable_source_ids,
+ ),)
]
selected_model_id = (
(resolution.requested_model or None)
@@ -4121,39 +4148,19 @@ class ModelHubService:
self,
backend: str,
order: object = _REORDER_ORDER_UNSET,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
) -> dict:
- async with self._mutation_lock:
- previous = self.store.load()
- config = self._clone_config(previous)
- agent = self._agent(config, backend)
- if order is not _REORDER_ORDER_UNSET:
- # The optional order lets the UI commit the persisted priority and
- # its application to existing routes in one mutation.
- agent.sources.order = self._validate_agent_source_order(
- config,
- backend,
- order,
- )
- source_positions = {
- source_id: position
- for position, source_id in enumerate(agent.sources.order)
- }
- for route in agent.routes.values():
- indexed_hops = list(enumerate(route.hops))
- indexed_hops.sort(
- key=lambda entry: (
- (
- 0,
- source_positions[entry[1].source_id],
- entry[0],
- )
- if entry[1].source_id in source_positions
- else (1, entry[0], entry[0])
- )
- )
- route.hops = tuple(hop for _, hop in indexed_hops)
- await self._commit_synced(previous, config)
- return self._agent_payload(config, agent)
+ if order is _REORDER_ORDER_UNSET:
+ return self.get_agent_sources(backend)
+ return await self.set_agent_sources(backend, {
+ "order": order,
+ "force": force,
+ "would_remove_hops": confirmed_remove_hops,
+ "would_interrupt": confirmed_interruptions,
+ })
@classmethod
def _parse_backend_catalog_models(
@@ -4358,11 +4365,6 @@ class ModelHubService:
builtin_order,
)
present.add(model_id)
- self._seed_menu_model_route(
- config,
- cast(BackendName, backend),
- model_id,
- )
added = True
if added:
changed.append(cast(BackendName, backend))
@@ -4574,11 +4576,11 @@ class ModelHubService:
]
removed_model_id_set = set(removed_model_ids)
for model_id in removed_model_ids:
- route = agent.routes.get(model_id)
+ route = effective_model_route(config, agent_backend, model_id)
current = current_by_id.get(model_id)
if current is not None and current != baseline_by_id[model_id]:
raise ModelHubError("backend_model_conflict", status=409)
- if route is not None:
+ if route.hops:
removed_hops.extend(
{
"backend": backend,
@@ -4589,7 +4591,6 @@ class ModelHubService:
}
for position, hop in enumerate(route.hops, start=1)
)
- route.hops = ()
merged_by_id.pop(model_id, None)
agent.routes.pop(model_id, None)
if model_id not in agent.removed_model_ids:
@@ -4601,14 +4602,9 @@ class ModelHubService:
if model.id not in removed_model_id_set
]
- newly_empty_routes = frozenset(
- (backend, item["menu_model"])
- for item in removed_hops
- )
interrupted = self._introduced_interruptions(
previous,
config,
- newly_empty_routes=newly_empty_routes,
)
self._require_guard_plan(
force=force,
@@ -4626,7 +4622,6 @@ class ModelHubService:
if current is not None and current != desired:
raise ModelHubError("backend_model_conflict", status=409)
merged_by_id[model_id] = desired
- agent.routes.setdefault(model_id, ModelHubRouteConfig())
continue
if current is None:
if desired != baseline_model:
@@ -4689,12 +4684,6 @@ class ModelHubService:
for removed_id in agent.removed_model_ids
if removed_id != model_id
]
- if model_id not in current_by_id and model_id in merged_by_id:
- self._seed_menu_model_route(
- config,
- agent_backend,
- model_id,
- )
if agent.backend == "opencode":
agent.menu = ModelHubMenuConfig(
view=agent.menu.view if agent.menu else "featured",
@@ -4865,18 +4854,9 @@ class ModelHubService:
model = next((item for item in source.models if item.id == model_id), None)
if model is None:
raise ModelHubError("mapping_target_unavailable", status=404)
- removed_hops = [
- {
- "backend": backend,
- "menu_model": menu_model,
- "source_id": source.id,
- "model_id": model_id,
- "position": position,
- }
- for backend in MODEL_HUB_BACKENDS
- for menu_model, route in config.agents[backend].routes.items()
- for position, hop in enumerate(route.hops, start=1)
- if hop.source_id == source.id and hop.model_id == model_id
+ retired_hops = [
+ item for item in self._effective_hop_refs(previous)
+ if model.provenance == "discovered" and item["source_id"] == source.id and item["model_id"] == model_id
]
if model.provenance == "discovered":
model.retired = True
@@ -4886,6 +4866,14 @@ class ModelHubService:
for item in source.models
if item.id != model_id
]
+ removed_hops = self._removed_effective_hops(previous, config)
+ removed_hops.extend(item for item in retired_hops if item not in removed_hops)
+ invalidated = (
+ self._invalidated_route_hops(config, source.id)
+ if not source_supports_passthrough(source)
+ else []
+ )
+ removed_hops.extend(item for item in invalidated if item not in removed_hops)
would_interrupt = self._introduced_interruptions(previous, config)
self._require_guard_plan(
force=force,
@@ -4899,7 +4887,7 @@ class ModelHubService:
else "source_last_supplier"
),
)
- if force and removed_hops:
+ if force and retired_hops:
for agent in config.agents.values():
for route in agent.routes.values():
route.hops = tuple(
@@ -4907,6 +4895,8 @@ class ModelHubService:
for hop in route.hops
if not (hop.source_id == source.id and hop.model_id == model_id)
)
+ if invalidated:
+ self._prune_invalidated_route_hops(config, invalidated)
await self._commit_synced(previous, config)
return {
"source": self._source_payload(source),
@@ -5047,6 +5037,8 @@ class ModelHubService:
"contract_version": AGENT_CHAIN_CONTRACT_VERSION,
"backend": backend,
"model_id": resolution.requested_model or model_id,
+ "manual_override": resolution.manual_override.to_payload() if resolution.manual_override is not None else None,
+ "route_origin": resolution.route_origin,
"chain": chain,
"current": current,
"supply_state": self._chain_supply_state(chain),
@@ -5199,18 +5191,26 @@ class ModelHubService:
return persisted
async def probe_agent(self, backend: str, model_id: object = None) -> dict:
+ while True:
+ try:
+ return await self._probe_agent_once(backend, model_id)
+ except _InvocationPlanChanged:
+ continue
+
+ async def _probe_agent_once(self, backend: str, model_id: object) -> dict:
if backend not in MODEL_HUB_BACKENDS:
raise ModelHubError("mapping_target_unavailable", status=409)
- config = self.store.load()
- agent = self._agent(config, backend)
- if agent.mode == "direct":
- raise self._direct_mode_error()
- requested_model = (
- str(model_id).strip()
- if isinstance(model_id, str) and model_id.strip()
- else self._requested_model(agent)
- )
- chain_payload = self._agent_chain(config, backend, requested_model)
+ async with self._mutation_lock:
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ if agent.mode == "direct":
+ raise self._direct_mode_error()
+ requested_model = (
+ str(model_id).strip()
+ if isinstance(model_id, str) and model_id.strip()
+ else self._requested_model(agent)
+ )
+ chain_payload = self._agent_chain(config, backend, requested_model)
candidate_payload = next(
(item for item in chain_payload["chain"] if item["runnable"]),
None,
@@ -5260,15 +5260,21 @@ class ModelHubService:
await self._prepare_engine_for_demand()
started_at = time.monotonic()
- settlement_generation = self._reserve_settlement_generation(source.id)
- handle = await self._engine_call(
- self.adapter.invoke(
- source.id,
- resolved_model,
- self._probe_request(source, resolved_model, backend),
- False,
- backend,
- )
+ settlement_generation = None
+
+ def admitted() -> None:
+ nonlocal settlement_generation
+ settlement_generation = self._reserve_settlement_generation(source.id)
+
+ handle = await self._invoke_admitted(
+ source=source,
+ model_id=resolved_model,
+ requested_model_id=chain_payload["model_id"],
+ request=self._probe_request(source, resolved_model, backend),
+ stream=False,
+ backend=cast(BackendName, backend),
+ excluded_source_ids=set(),
+ on_admitted=admitted,
)
if handle.stream is not None:
async for _chunk in handle.stream:
@@ -5276,14 +5282,16 @@ class ModelHubService:
outcome = await self._engine_call(handle.outcome())
decision = await self._classify_source_outcome(source, outcome)
if decision.action == "refresh":
- handle = await self._engine_call(
- self.adapter.invoke(
- source.id,
- resolved_model,
- self._probe_request(source, resolved_model, backend),
- False,
- backend,
- )
+ handle = await self._invoke_admitted(
+ source=source,
+ model_id=resolved_model,
+ requested_model_id=chain_payload["model_id"],
+ request=self._probe_request(source, resolved_model, backend),
+ stream=False,
+ backend=cast(BackendName, backend),
+ excluded_source_ids=set(),
+ exact_retry=True,
+ on_admitted=admitted,
)
if handle.stream is not None:
async for _chunk in handle.stream:
@@ -5410,6 +5418,14 @@ class ModelHubService:
detail=detail,
)
+ def get_model_provenance(self, backend: str, model_id: object) -> dict | None:
+ if backend not in MODEL_HUB_BACKENDS or not isinstance(model_id, str) or normalized_model_id(model_id) != model_id:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ agent = self.store.load().agents[backend]
+ if model_id not in self._agent_menu_model_ids(agent):
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return self.provenance.latest_for_model(backend, model_id)
+
async def reauth_source(self, source_id: str, payload: object) -> dict:
if (
not isinstance(payload, dict)
@@ -6111,7 +6127,7 @@ class ModelHubService:
backend: BackendName,
model_id: str,
) -> tuple[ModelHubConfig, ModelHubTurnResolution]:
- """Inspect the complete persisted chain used by the next turn."""
+ """Inspect the complete effective chain used by the next turn."""
config = self.store.load()
resolution = resolve_model_hub_turn(
@@ -6316,6 +6332,88 @@ class ModelHubService:
now=self.now(),
)
+ def _invocation_resolution(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ model_id: str,
+ supply_channel: Literal["hub"] | None = None,
+ ) -> ModelHubTurnResolution:
+ if config.agents[backend].mode != "hub":
+ raise ModelHubError("mode_switch_blocked", status=409)
+ resolution = resolve_model_hub_turn(
+ config,
+ backend,
+ model_id,
+ now=self.now(),
+ unavailable_source_ids=self._unavailable_native_sources(config, backend),
+ supply_channel=supply_channel,
+ )
+ if resolution.channel == "direct":
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return resolution
+
+ async def _invoke_admitted(
+ self,
+ *,
+ source: ModelHubSourceConfig,
+ model_id: str,
+ requested_model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ backend: BackendName,
+ excluded_source_ids: set[str],
+ supply_channel: Literal["hub"] | None = None,
+ exact_retry: bool = False,
+ on_admitted: Callable[[], None] | None = None,
+ ) -> InvokeHandle:
+ while True:
+ await self._mutation_lock.acquire()
+ held = True
+
+ def release_exclusion() -> None:
+ nonlocal held
+ if held:
+ held = False
+ self._mutation_lock.release()
+
+ def admitted() -> None:
+ release_exclusion()
+ if on_admitted is not None:
+ on_admitted()
+
+ try:
+ config = self.store.load()
+ resolution = self._invocation_resolution(config, backend, requested_model_id, supply_channel)
+ candidates = [
+ hop for hop in resolution.candidate_hops
+ if hop.source_id not in excluded_source_ids
+ ]
+ candidate = next(
+ (
+ hop for hop in candidates
+ if not exact_retry or (hop.source_id, hop.model_id) == (source.id, model_id)
+ ),
+ None,
+ )
+ if (
+ candidate is None
+ or candidate.source != source
+ or candidate.model_id != model_id
+ ):
+ raise _InvocationPlanChanged
+ if self._engine_synced:
+ # Lock order matches config sync. The adapter hands exclusion
+ # back only after owning the transport that sync must drain.
+ return await self._engine_call(self.adapter.invoke(
+ source.id, model_id, request, stream, backend, on_admitted=admitted,
+ ))
+ finally:
+ release_exclusion()
+ # A canceled configuration transaction left reconciliation pending.
+ # Use its existing owner outside the lock, then revalidate the plan.
+ await self._prepare_engine_for_demand()
+
async def _invoke(
self,
*,
@@ -6324,7 +6422,20 @@ class ModelHubService:
request: Mapping[str, Any],
stream: bool,
backend: str,
+ requested_model_id: str,
+ excluded_source_ids: set[str],
+ supply_channel: Literal["hub"] | None = None,
+ exact_retry: bool = False,
+ on_admitted: Callable[[], None] | None = None,
) -> tuple[InvokeHandle, Optional[RawCallOutcome], asyncio.CancelledError | None]:
+ transport_admitted = False
+
+ def admitted() -> None:
+ nonlocal transport_admitted
+ transport_admitted = True
+ if on_admitted is not None:
+ on_admitted()
+
async def meter_handle(
handle: InvokeHandle,
outcome: RawCallOutcome | None,
@@ -6346,8 +6457,17 @@ class ModelHubService:
return outcome
async def invoke_and_meter_bodyless() -> tuple[InvokeHandle, Optional[RawCallOutcome]]:
- handle = await self._engine_call(
- self.adapter.invoke(source.id, model_id, request, stream, backend)
+ handle = await self._invoke_admitted(
+ source=source,
+ model_id=model_id,
+ requested_model_id=requested_model_id,
+ request=request,
+ stream=stream,
+ backend=cast(BackendName, backend),
+ excluded_source_ids=excluded_source_ids,
+ supply_channel=supply_channel,
+ exact_retry=exact_retry,
+ on_admitted=admitted,
)
if handle.stream is not None:
# The body is the gateway's to forward, so the tokens in it are the
@@ -6363,6 +6483,8 @@ class ModelHubService:
handle, outcome = await asyncio.shield(attempt_task)
except asyncio.CancelledError as caught:
cancelled = caught
+ if not transport_admitted:
+ attempt_task.cancel()
try:
handle, outcome = await await_owned_task(attempt_task)
except BaseException:
@@ -6608,36 +6730,18 @@ class ModelHubService:
pass
else:
engine_prepared = True
- config = self.store.load()
- resolution = resolve_model_hub_turn(
- config,
- cast(BackendName, backend),
- model_id,
- now=self.now(),
- unavailable_source_ids=self._unavailable_native_sources(
- config,
- cast(BackendName, backend),
- ),
- supply_channel=supply_channel,
- )
- if config.agents[backend].mode != "hub":
- raise ModelHubError("mode_switch_blocked", status=409)
- if resolution.channel == "direct":
- raise ModelHubError("mapping_target_unavailable", status=409)
- if resolution.recoverable_source_ids:
- await self._recover_resolution_sources(resolution)
+ async with self._mutation_lock:
config = self.store.load()
- resolution = resolve_model_hub_turn(
- config,
- cast(BackendName, backend),
- model_id,
- now=self.now(),
- unavailable_source_ids=self._unavailable_native_sources(
- config,
- cast(BackendName, backend),
- ),
- supply_channel=supply_channel,
+ resolution = self._invocation_resolution(
+ config, cast(BackendName, backend), model_id, supply_channel,
)
+ if resolution.recoverable_source_ids:
+ await self._recover_resolution_sources(resolution)
+ async with self._mutation_lock:
+ config = self.store.load()
+ resolution = self._invocation_resolution(
+ config, cast(BackendName, backend), model_id, supply_channel,
+ )
event_agent = cast(EventAgent, backend)
candidate_hops = list(resolution.candidate_hops)
if not candidate_hops:
@@ -6665,13 +6769,22 @@ class ModelHubService:
failed_source: Optional[ModelHubSourceConfig] = None
failed_reason: Optional[EventReason] = None
globally_blocked_source_ids: set[str] = set()
- for inspection in candidate_hops:
+ while True:
+ async with self._mutation_lock:
+ config = self.store.load()
+ resolution = self._invocation_resolution(
+ config, cast(BackendName, backend), model_id, supply_channel,
+ )
+ inspection = next(
+ (hop for hop in resolution.candidate_hops if hop.source_id not in globally_blocked_source_ids),
+ None,
+ )
+ if inspection is None:
+ break
source = inspection.source
target_model = inspection.model_id
if source is None or target_model is None:
raise AssertionError("runnable hop must have an exact identity")
- if source.id in globally_blocked_source_ids:
- continue
exact_reasoning_request = self._request_for_exact_reasoning_effort(
request,
source,
@@ -6698,25 +6811,37 @@ class ModelHubService:
)
await self._prepare_engine_for_demand(already_synced=engine_prepared)
engine_prepared = True
- settlement_generation = self._reserve_settlement_generation(source.id)
- if attempt_observer is not None:
- attempt_observer(
- source.id,
- target_model,
- "hub",
- False,
- None,
- None,
- exact_reasoning_request.stripped_efforts,
- exact_reasoning_request.declared_efforts,
+ settlement_generation = None
+
+ def admitted() -> None:
+ nonlocal settlement_generation
+ settlement_generation = self._reserve_settlement_generation(source.id)
+ if attempt_observer is not None:
+ attempt_observer(
+ source.id,
+ target_model,
+ "hub",
+ False,
+ None,
+ None,
+ exact_reasoning_request.stripped_efforts,
+ exact_reasoning_request.declared_efforts,
+ )
+
+ try:
+ handle, outcome, cancelled = await self._invoke(
+ source=source,
+ model_id=target_model,
+ request=exact_request,
+ stream=stream,
+ backend=backend,
+ requested_model_id=model_id,
+ excluded_source_ids=globally_blocked_source_ids,
+ supply_channel=supply_channel,
+ on_admitted=admitted,
)
- handle, outcome, cancelled = await self._invoke(
- source=source,
- model_id=target_model,
- request=exact_request,
- stream=stream,
- backend=backend,
- )
+ except _InvocationPlanChanged:
+ continue
if outcome is None:
if cancelled is not None:
raise cancelled
@@ -6754,13 +6879,23 @@ class ModelHubService:
if decision.action == "refresh":
# The engine refreshes its credential internally; L2 retries the
# exact same source once and never falls through on a second 401.
- handle, outcome, cancelled = await self._invoke(
- source=source,
- model_id=target_model,
- request=exact_request,
- stream=stream,
- backend=backend,
- )
+ try:
+ handle, outcome, cancelled = await self._invoke(
+ source=source,
+ model_id=target_model,
+ request=exact_request,
+ stream=stream,
+ backend=backend,
+ requested_model_id=model_id,
+ excluded_source_ids=globally_blocked_source_ids,
+ supply_channel=supply_channel,
+ exact_retry=True,
+ on_admitted=admitted,
+ )
+ except _InvocationPlanChanged:
+ if attempt_observer is not None:
+ attempt_observer(source.id, target_model, "hub", False, outcome, decision, (), ())
+ continue
if outcome is None:
if cancelled is not None:
raise cancelled
@@ -6795,7 +6930,7 @@ class ModelHubService:
attempt_observer=attempt_observer,
)
raise cancelled
- if attempt_observer is not None:
+ if attempt_observer is not None and settlement_generation is not None:
attempt_observer(
source.id,
target_model,
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 36b9c62d2..056254fda 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,27 +1,18 @@
# Model Hub contracts
-Status: **FINAL shape, implementation-gated. `contract_version` is 8 (2026-09-05
-OpenCode bare ids and per-protocol overlay); 7 defined 2026-09-03 for
-backend-catalog composition and reasoning-tier provenance; 6 published 2026-08-19
-usage metering; 5 published the 2026-08-11 contract completion.**
-
-These files describe the terminal contract for Model Hub before first release. No bump
-carries a data migration, compatibility reader, conversion transaction, or version
-discriminator: Model Hub has not shipped, so republishing the shape converts nothing.
-`contract_version` is 8 wherever a versioned object exists. The owner-approved
-pre-release correction adds OpenCode bare ids, server-owned native protocols, and
-per-protocol runtime providers while deleting the prefixed-id compatibility paths.
-
-`v5` is still written throughout these files and stays: it names the contract-completion
-generation they were authored in, and sentences such as "Minimum v5 set" or
-`adapter-interface.py`'s dated header describe what that generation said. Only
-`contract_version` — the value a consumer reads and the closure below guards — moves.
-
-Which of the two a sentence means is not left to the reader. A claim about the current
-value spells `contract_version`, which is the token the closure guard matches, so a bare
-`vN` is a generation name by construction. Prose that restated the number in its own
-words is exactly how `api.md` came to advertise one value in its envelopes and another
-in its own declarations.
+Status: **contract_version 9**, 2026-09-06: sparse manual overrides, shared effective
+planning and guarded Restore/default membership. The approved routing contract is
+`../model-hub-routing-modes.md`, frozen at `2db273891` before implementation, amended by owner decision `c1d398d5f`.
+
+Supported persisted configuration shapes remain readable under the repository's
+persisted-shape rule. Existing explicit arrays, including empty, stale and dormant
+OpenCode routes, retain their exact intent. Do not infer old authorship from array
+contents or Source order. Ephemeral envelopes use the terminal version; persisted
+TurnProvenance accepts historical versions through the terminal one without new
+required route fields. Existing persistence readers normalize retired reason values
+before current-schema validation without changing the writer generation; raw historical
+bytes need not already use today's reason vocabulary. Generation names in older implementation history are not a
+current version declaration.
The contracts and their consumers must coexist on one tested PR head before Model Hub
can be enabled. CI evaluates that head, not individual commits. A green intermediate
@@ -30,13 +21,14 @@ commit is not evidence that the complete final protocol has landed.
## Product model
- Sources are upstream assets. A Source never owns ordering.
-- Gateway stores one explicit Source order per backend and one exact ordered Route chain
- per menu model. Neither has a `follow | custom` or other policy discriminator.
-- Add Source, a menu-model add, and a built-in reconcile add each run the same matching
- and placement policies once and persist the accepted hops. Runtime never repeats
- placement, model matching, vendor matching, or substitution.
-- Runtime walks the stored Route hops verbatim, rechecking only whether each exact hop is
- runnable now and whether a failure permits fallthrough.
+- Gateway stores one default Source membership/order per backend and sparse manual
+ overrides per model. Absence inherits; presence overrides, including an empty array.
+- The shared pure planner returns manual hops verbatim, otherwise all accepted matches
+ in default order, otherwise unchanged-id passthrough on eligible non-retired Hub API-key defaults.
+- Reads, previews, summaries, guards, adoption, probes, launches and execution use that
+ effective plan. Health and process readiness annotate it without changing its origin.
+- New catalog rows have no override; Source creation appends defaults but never writes
+ manual hops. Restoring automatic deletes the key; saving equal hops remains manual.
- A hop whose upstream `model_id` differs from its menu model is an explicit configured
mapping. There is no separate mapping object or runtime mapping event.
- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat`.
@@ -48,11 +40,14 @@ commit is not evidence that the complete final protocol has landed.
- Supply state is pull-oriented. Successful fallback is silent; Gateway and Usage are
the user-visible inspection surfaces.
-Normative routing behavior lives only in `docs/plans/model-hub.md`: §4.2 owns one-time
-matching and placement, §4.3 owns exact-chain execution and credential failures, §4.5 owns state,
+Normative routing behavior lives only in `docs/plans/model-hub.md`: §4.2 owns effective planning and default placement, §4.3 owns effective-chain execution and credential failures, §4.5 owns state,
turn copy, and guarded mutation envelopes, and §6 owns native-config import actions.
Contract prose points to those authorities and does not add branches.
+API-key passthrough is the delivery scope. Subscriptions continue automatic matching and
+known-model manual routes; an unmatched subscription-only default set is Unconfigured.
+No underlying engine expansion or OAuth alias substitution is part of this change.
+
## Invariants
1. Plaintext upstream credentials never appear in config, API payloads, events, logs,
@@ -68,13 +63,17 @@ Contract prose points to those authorities and does not add branches.
still require reachability and authentication; they never bypass those failures.
3. Every Source/model reference is canonical and referentially valid at write time.
Unchanged stale Route hops may be retained or reordered, but new or changed pairs
- must validate.
+ must validate Source existence/eligibility, canonical identifiers and explicit retirement.
+ Missing API-key inventory alone is not an invocation or manual-write rejection.
+ Subscription Sources retain existing model admission and stale-hop retention.
+ Normalized persisted catalog/target identities do not lose edit, preview, restore
+ or history-read capability when a later new-identifier length bound is shorter.
4. Source deletion atomically removes its id from every backend Source order and every
exact Route chain, preserving survivor order. Serialization and reload reject a
dangling Source id.
-5. Given the same stored configuration and request, the selected Route hops are stable
- across time, quota, and health changes. Live runnability and current execution
- position may change; Route membership and order may not.
+5. Manual Route membership and order survive unrelated state changes. Automatic routes
+ follow current defaults and matching evidence. For the same planning inputs, health,
+ quota and process readiness may change runnability/current but never tier or origin.
6. Every Source model id is unique within that Source. The final model item shape is
`{id, origin, reasoning_efforts, reasoning_efforts_source, retired?, display_name?,
discovered_at?}`. The tier source is `upstream | catalog | user | null`; only `user`
@@ -104,7 +103,7 @@ comparison. A gate may not report success by comparing stale input with itself.
## Version closure
-`contract_version` 8 must coexist in all registered version locations on the same tested head:
+`contract_version` 9 must coexist in all registered version locations on the same tested head:
- `mirror-registry.json`
- `agent-chain.schema.json`
@@ -152,10 +151,10 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| --- | --- |
| `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. |
| `source-create.schema.json` | API-key Source creation request, transient credential boundary, optional single-protocol constraint, and lost-response correlation. |
-| `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |
+| `agent-supply.schema.json` | Backend mode, default Source membership/order and sparse manual intent, configuration eligibility, model-supply and backend-health projections. |
| `backend-model.schema.json` | Backend Agent model identity, editable capability metadata, and server-owned lock/routeability projection. |
-| `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, live connection backoff, retry metadata, and model supply state. |
-| `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops, including the live connection-backoff reason without persistent network health. |
+| `agent-chain.schema.json` | Effective route, manual override and origin projection plus current execution position, runnability, blockers, live connection backoff, retry metadata, and model supply state. |
+| `probe-result.schema.json` | Saved recovery probes and route probes over the shared effective plan, including the live connection-backoff reason without persistent network health. |
| `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, protocol-establishment, and inventory observation. |
| `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. The one versioned object persisted to disk, so it accepts every released version. |
| `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns. A report only: no consumer may feed it back into resolution, admission, or cooldown. |
@@ -164,9 +163,9 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `migration-scan.schema.json` | Copy-only import of existing native CLI/provider configuration; not an internal contract migration. |
| `runtime-dependency.schema.json` | Managed local Gateway asset, persisted enablement intent, lifecycle, and health. |
| `guard-refusal.schema.json` | Shared guarded-mutation refusal whose two arrays are the exact plan echoed by a confirmed retry. |
-| `api.md` | Routes, envelopes, exact Source order and Route-chain writes, guards, OAuth/import results, provenance, usage, and runtime status. |
+| `api.md` | Routes, envelopes, default Source order and manual Route writes/Restore/preview, guards, OAuth/import results, provenance, usage, and runtime status. |
| `api-response.schema.json` | Machine-readable response contract and real-response exercise for every route in `api.md`, at exact route-table parity. |
-| `opencode-overlay.md` | Stable OpenCode provider/model identifiers and exact configured-hop overlay behavior. |
+| `opencode-overlay.md` | Stable OpenCode provider/model identifiers and effective-hop overlay behavior. |
| `adapter-interface.py` | Adapter protocol, observation, credential, discovery, invocation, cleanup, and classification boundary. |
| `mirror-registry.json` | Executable authority/mirror registry and terminal contract version. |
| `README.md` | This ownership, version-closure, and contract-index document. |
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index b419333a9..3b459a289 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v8 (2026-09-05).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v9 (2026-09-06).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
@@ -12,7 +12,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
-from typing import Any, AsyncIterator, Final, Literal, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
from .stream_wire import ProtocolSSEState, ProtocolUsageReport
@@ -73,12 +73,14 @@ class SourceBinding:
# source. Empty tuple = unrestricted (api_key default). Subscription
# sources MUST be non-empty (README invariant 3); L2 populates, L1
# enforces as backstop.
- model_ids: tuple[str, ...] # declared supply list (discovered + manual
- # custom entries); required by the engine's generic/API-key config. Bare
- # model ids, no provider prefix.
+ model_ids: tuple[str, ...] # truthful inventory evidence (discovered + manual).
+ # May be empty; API-key invocation need not be listed. Bare ids, no prefix.
model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()
# Per-model levels declared by the Source. CLIProxyAPI needs these on its
# model registration or it removes an otherwise valid reasoning effort.
+ route_model_ids: tuple[str, ...] = ()
+ # Sorted API-key transport targets derived from effective routes, never
+ # inventory or capability evidence. Independent of live health and mode.
class OriginNotAllowedError(Exception):
@@ -535,8 +537,18 @@ class EngineAdapter(Protocol):
request: Mapping[str, Any],
stream: bool,
origin: str,
+ *,
+ on_admitted: Callable[[], None] | None = None,
) -> InvokeHandle:
"""``origin`` = requesting agent name ("claude"|"codex"|"opencode"|...).
Raises ``OriginNotAllowedError`` when the binding's ``allowed_origins``
- excludes it (backstop; L2 must have filtered already)."""
+ excludes it (backstop; L2 must have filtered already). ``model_id`` is
+ the chosen canonical route target. API-key targets need not be listed;
+ subscriptions retain their existing exact inventory admission.
+ The adapter must keep exact source isolation without inventing inventory.
+ After validating source/origin, acquire the transport lease and call
+ ``on_admitted`` exactly once before any network wait. Callback failure
+ releases the lease without invoking upstream. Transport completion,
+ close, or cancellation releases the lease independently of settlement.
+ """
...
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index a32565293..39ed29677 100644
--- a/docs/plans/model-hub-contracts/agent-chain.schema.json
+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json
@@ -2,14 +2,43 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/agent-chain.schema.json",
"title": "AgentChain",
- "description": "Read projection of one stored per-model Route chain. Items preserve exact configured Source/model pairs and order; runtime adds only live health, runnability, blocker, retry annotations, and the current execution position. Runtime never derives membership, resolves aliases, or substitutes a model.",
+ "description": "Read projection of the shared effective route plan. A sparse manual override wins verbatim; otherwise the planner selects matching evidence or exact-id passthrough on Hub API-key sources in backend default order. Live inspection adds health, runnability, blocker, retry annotations, and current position without changing plan membership or origin.",
"type": "object",
- "required": ["contract_version", "backend", "model_id", "chain", "current", "supply_state"],
+ "required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 8 },
+ "contract_version": { "const": 9 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"model_id": { "type": "string" },
+ "manual_override": {
+ "description": "Actual persisted override, or the draft override on preview. Null means absent and automatic; an object with empty hops is an explicit empty override. Equality with generated hops never determines intent.",
+ "anyOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["hops"],
+ "additionalProperties": false,
+ "properties": {
+ "hops": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["source_id", "model_id"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "model_id": { "type": "string", "minLength": 1 }
+ }
+ }
+ }
+ }
+ }
+ ]
+ },
+ "route_origin": {
+ "enum": ["automatic", "manual", "passthrough", null],
+ "description": "Origin of the nonempty effective plan, independent of health and native process readiness. Passthrough is restricted to Hub API-key Sources; unmatched subscription-only defaults yield an empty plan. Null exactly when chain is empty, including an explicit empty manual override."
+ },
"current": {
"anyOf": [
{ "type": "null" },
@@ -23,11 +52,11 @@
}
}
],
- "description": "The live execution position, identified by one exact stored hop. It is null when no hop is current. Recovery may change this projection on the next turn without changing the stored chain."
+ "description": "The live execution position, identified by one exact effective hop. It is null when no hop is current. Recovery may change this projection on the next turn without changing the effective plan."
},
"chain": {
"type": "array",
- "description": "Exact stored hops in configured order. Empty is a first-class unconfigured route.",
+ "description": "Effective hops in planner order. Manual hops retain the exact saved order; generated hops follow matching evidence or passthrough defaults. Empty is a first-class unconfigured route.",
"items": {
"type": "object",
"required": ["source_id", "model_id", "channel", "health", "runnable", "reason", "retry_at"],
@@ -38,7 +67,7 @@
"channel": { "enum": ["hub", "native_cli"] },
"health": {
"enum": ["healthy", "cooldown", "backoff", "needs_action", "error"],
- "description": "Source-global health mapped to this hop, plus live backoff. backoff is an in-memory connection throttle before the first user-visible model-output byte and is never persisted on Source or configuration. It is projected only over an otherwise healthy hop whose exact Source/model capability is present; every durable Source/capability blocker suppresses it."
+ "description": "Source-global health mapped to this hop, plus live backoff. backoff is an in-memory connection throttle before the first user-visible model-output byte and is never persisted on Source or configuration. It is projected only over an otherwise healthy hop whose exact Source/model pair is eligible and not explicitly retired; API-key inventory absence is not a blocker; subscriptions retain existing model membership admission; every durable Source/capability blocker suppresses it."
},
"runnable": { "type": "boolean" },
"reason": {
@@ -109,6 +138,24 @@
}
},
"allOf": [
+ {
+ "if": { "properties": { "manual_override": { "type": "object" } }, "required": ["manual_override"] },
+ "then": {
+ "if": { "properties": { "manual_override": { "properties": { "hops": { "maxItems": 0 } }, "required": ["hops"] } } },
+ "then": { "properties": { "chain": { "maxItems": 0 } } },
+ "else": { "properties": { "chain": { "minItems": 1 } } }
+ }
+ },
+ {
+ "if": { "properties": { "chain": { "maxItems": 0 } }, "required": ["chain"] },
+ "then": { "properties": { "route_origin": { "type": "null" }, "current": { "type": "null" } } },
+ "else": {
+ "properties": { "route_origin": { "enum": ["automatic", "manual", "passthrough"] } },
+ "if": { "properties": { "manual_override": { "type": "object" } }, "required": ["manual_override"] },
+ "then": { "properties": { "route_origin": { "const": "manual" } } },
+ "else": { "properties": { "route_origin": { "enum": ["automatic", "passthrough"] } } }
+ }
+ },
{
"if": { "properties": { "supply_state": { "const": "ok" } }, "required": ["supply_state"] },
"then": { "properties": { "chain": { "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] } } } }
@@ -161,41 +208,71 @@
],
"examples": [
{
- "contract_version": 8,
+ "contract_version": 9,
+ "backend": "codex",
+ "model_id": "unlisted-model",
+ "manual_override": null,
+ "route_origin": "passthrough",
+ "chain": [{ "source_id": "src_relay9c1x", "model_id": "unlisted-model", "channel": "hub", "health": "healthy", "runnable": true, "reason": null, "retry_at": null }],
+ "current": { "source_id": "src_relay9c1x", "model_id": "unlisted-model" },
+ "supply_state": "ok"
+ },
+ {
+ "contract_version": 9,
+ "backend": "codex",
+ "model_id": "gpt-5.6",
+ "manual_override": { "hops": [] },
+ "route_origin": null,
+ "chain": [],
+ "current": null,
+ "supply_state": "interrupted"
+ },
+ {
+ "contract_version": 9,
"backend": "claude",
"model_id": "claude-opus-4-6",
+ "manual_override": null,
+ "route_origin": "automatic",
"chain": [{ "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "channel": "native_cli", "health": "cooldown", "runnable": false, "reason": null, "retry_at": "2026-07-29T04:00:00Z" }],
"current": null,
"supply_state": "waiting"
},
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "opencode",
- "model_id": "custom/glm-5.2",
+ "model_id": "glm-5.2",
+ "manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },
+ "route_origin": "manual",
"chain": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2", "channel": "hub", "health": "backoff", "runnable": false, "reason": "models.source.backoff.connection_failed", "retry_at": "2026-08-11T11:55:08Z" }],
"current": null,
"supply_state": "waiting"
},
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"model_id": "gpt-5.6",
+ "manual_override": null,
+ "route_origin": "automatic",
"chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "healthy", "runnable": false, "reason": "native_cli_unavailable", "retry_at": null }],
"current": null,
"supply_state": "interrupted"
},
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"model_id": "gpt-5.6",
+ "manual_override": null,
+ "route_origin": "automatic",
"chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "backoff", "runnable": false, "reason": "native_cli_unavailable", "retry_at": "2026-08-11T11:55:08Z" }],
"current": null,
"supply_state": "interrupted"
},
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "claude",
"model_id": "claude-haiku-4-5",
+ "manual_override": null,
+ "route_origin": null,
"chain": [],
"current": null,
"supply_state": "interrupted"
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index 264d330f1..d4719a874 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/agent-supply.schema.json",
"title": "AgentSupply",
- "description": "Per-backend Gateway configuration and live supply projection. It exposes explicit Source order, menu metadata, model-supply state, and enabled named-Agent attribution without deriving Route membership.",
+ "description": "Per-backend Gateway configuration and live supply projection. It exposes explicit Source order, menu metadata, model-supply state, and enabled named-Agent attribution from the shared effective route planner.",
"type": "object",
"required": ["backend", "mode", "menu_kind"],
"additionalProperties": false,
@@ -35,19 +35,19 @@
"selected_model_explicit": { "type": "boolean", "description": "TRUE iff `selected_model_id` originates from the user's explicit configuration request; FALSE means no explicit model selection, including a resolver-picked value or no selected model." },
"sources": {
"type": ["object", "null"],
- "description": "This backend's explicit Gateway Source order. It is stored configuration and an Add-time placement input; runtime model execution reads the exact per-model Route chain instead of deriving one from this order. There is no follow/custom or other policy discriminator. It is non-null in Gateway mode and null in Direct mode.",
+ "description": "This backend's default Gateway Source membership and priority. The shared planner uses this order only when a model has no manual override. No second persisted policy discriminator exists. It is non-null in Gateway mode and null in Direct mode.",
"required": ["order"],
"additionalProperties": false,
"properties": {
"order": {
"type": "array",
- "description": "Configured Source ids, position 0 first. A subset, not a permutation: configuration-ineligible Sources or Sources the user removed are absent. The server re-echoes the full canonical order after mutation; clients never compute a partial reorder. Add-time placement is owned only by model-hub.md §4.2 and never reruns during a request.",
+ "description": "Configured Source ids, position 0 first. A subset, not a permutation: configuration-ineligible Sources or Sources the user removed are absent. The server re-echoes the full canonical order after mutation; clients never compute a partial reorder. Source creation appends eligible defaults once; effective routing consumes the latest saved order. Manual overrides may reference eligible Sources outside this subset.",
"items": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
"uniqueItems": true
},
"eligibility": {
"type": ["array", "null"],
- "description": "Server-authoritative configuration eligibility, one row per existing Source. It makes UI eligibility a projection rather than a second compatibility matrix. `in_current_model_chain` reports whether the selected model's stored Route references the Source; `process_availability_reason` reports native CLI readiness independently of Source health. Required and non-null whenever sources is an object.",
+ "description": "Server-authoritative configuration eligibility, one row per existing Source. It makes UI eligibility a projection rather than a second compatibility matrix. `in_current_model_chain` reports whether the selected model's effective Route references the Source; `process_availability_reason` reports native CLI readiness independently of Source health. Required and non-null whenever sources is an object.",
"items": {
"type": "object",
"required": ["source_id", "eligible"],
@@ -94,7 +94,7 @@
},
"in_current_model_chain": {
"type": ["boolean", "null"],
- "description": "Whether the selected model's stored Route references this Source. true includes blocked hops because availability does not rewrite configuration; false keeps non-members visible; null exactly when selected_model_id is null."
+ "description": "Whether the selected model's effective Route references this Source. true includes blocked hops because availability does not rewrite configuration; false keeps non-members visible; null exactly when selected_model_id is null."
},
"process_availability_reason": {
"enum": ["native_cli_unavailable", null],
@@ -108,7 +108,7 @@
},
"routes": {
"type": ["object", "null"],
- "description": "The persisted exact Route for every menu model. Keys are caller-facing menu ids; each value is an ordered hops array and may be empty. Runtime reads this projection verbatim.",
+ "description": "Sparse persisted manual overrides keyed by caller-facing canonical menu ids. Key absence means automatic. Key presence preserves exact hops, including empty, stale and dormant arrays. Saving equal-to-automatic hops remains manual; Restore deletes the key. New catalog rows receive no key.",
"additionalProperties": {
"type": "object",
"required": ["hops"],
@@ -152,25 +152,29 @@
},
"model_supply": {
"type": ["array", "null"],
- "description": "Per-menu-item configured Route summary so the model menu can flag an empty chain without one chain query per row. Read-only projection; the authoritative chain is GET /api/models/agents/<backend>/chain.",
+ "description": "Per-menu-item effective Route summary so the model menu can flag an empty chain without one chain query per row. Read-only projection; the authoritative chain is GET /api/models/agents/<backend>/chain.",
"items": {
"type": "object",
- "required": ["model_id", "chain_length"],
+ "required": ["model_id", "chain_length", "route_origin"],
"additionalProperties": false,
"properties": {
"model_id": {
"type": "string",
"description": "The exact canonical identifier this backend's menu uses."
},
+ "route_origin": {
+ "enum": ["automatic", "manual", "passthrough", null],
+ "description": "Shared planner origin, independent of transient health. Passthrough uses Hub API-key defaults only; subscriptions remain subject to known-model admission. Null exactly when chain_length is zero."
+ },
"chain_length": {
"type": "integer",
"minimum": 0,
- "$comment": "Configuration visibility is not candidate availability. Every stored hop remains counted regardless of live runnability.",
- "description": "Length of the exact configured Route chain, including cooling, live-connection-backoff, and process-unavailable native CLI hops. It is not a count of currently runnable candidates. Zero marks a structurally empty Route; live blockers appear through supply_status."
+ "$comment": "Configuration visibility is not candidate availability. Every effective hop remains counted regardless of live runnability.",
+ "description": "Length of the effective Route chain, including cooling, live-connection-backoff, and process-unavailable native CLI hops. It is not a count of currently runnable candidates. Zero marks a structurally empty Route; live blockers appear through supply_status."
},
"has_runnable_hop": {
"type": "boolean",
- "description": "True exactly when at least one exact stored hop is runnable under the same source-health AND process-availability axiom as AgentChain. False distinguishes an all-stale or empty Route from a Route with live supply without changing chain_length. OPTIONAL in the reusable schema and REQUIRED on AgentSupply API payloads."
+ "description": "True exactly when at least one exact effective hop is runnable under the same source-health AND process-availability axiom as AgentChain. False distinguishes an all-stale or empty Route from a Route with live supply without changing chain_length. OPTIONAL in the reusable schema and REQUIRED on AgentSupply API payloads."
}
},
"allOf": [
@@ -180,7 +184,10 @@
"required": ["chain_length"]
},
"then": {
- "properties": { "has_runnable_hop": { "const": false } }
+ "properties": { "has_runnable_hop": { "const": false }, "route_origin": { "type": "null" } }
+ },
+ "else": {
+ "properties": { "route_origin": { "enum": ["automatic", "manual", "passthrough"] } }
}
}
]
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 8ccb21bae..6f017b2b3 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -28,7 +28,10 @@
{"method": "GET", "path": "/api/models/agents/<backend>/chains", "response_schema": "ChainListResponse", "exercise": {"path": "/api/models/agents/claude/chains", "status": 200}},
{"method": "GET", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200}},
{"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}},
+ {"method": "DELETE", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {}}},
+ {"method": "POST", "path": "/api/models/agents/<backend>/chain/preview?model=<id>", "response_schema": "ChainResponse", "exercises": [{"path": "/api/models/agents/claude/chain/preview?model=claude-opus-4-6", "status": 200, "json": {"manual_override": null}}, {"path": "/api/models/agents/claude/chain/preview?model=claude-opus-4-6", "status": 200, "json": {"manual_override": {"hops": []}}}]},
{"method": "POST", "path": "/api/models/agents/<backend>/probe", "response_schema": "ProbeResponse", "exercise": {"path": "/api/models/agents/claude/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},
+ {"method": "GET", "path": "/api/models/agents/<backend>/provenance?model=<id>", "response_schema": "LatestProvenanceResponse", "exercises": [{"path": "/api/models/agents/claude/provenance?model=claude-opus-4-6", "status": 200}, {"path": "/api/models/agents/claude/provenance?model=claude-sonnet-4-6", "status": 200}]},
{"method": "GET", "path": "/api/models/events?limit=<n>&before=<id>", "response_schema": "EventsResponse", "exercise": {"path": "/api/models/events?limit=20", "status": 200}},
{"method": "GET", "path": "/api/models/usage?days=<n>", "response_schema": "UsageResponse", "exercise": {"path": "/api/models/usage?days=30", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/start", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/oauth/start", "status": 200, "json": {"vendor": "anthropic", "channel": "hub"}}},
@@ -85,7 +88,7 @@
{"type": "null"},
{
"type": "array",
- "items": {"required": ["model_id", "chain_length", "has_runnable_hop"]}
+ "items": {"required": ["model_id", "chain_length", "has_runnable_hop", "route_origin"]}
}
]
}
@@ -139,7 +142,7 @@
"SuccessCore": {
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8}
+ "contract_version": {"const": 9}
}
},
"SourceListResponse": {
@@ -148,7 +151,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}
}
},
@@ -158,7 +161,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"observation": {"$ref": "model-hub/observation-result.schema.json"}
}
},
@@ -168,7 +171,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"source": {"$ref": "#/definitions/SourceApi"},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},
"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}
@@ -180,7 +183,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"source": {"$ref": "#/definitions/SourceApi"}
}
},
@@ -190,7 +193,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"source": {"$ref": "#/definitions/SourceApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -202,7 +205,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
}
@@ -213,7 +216,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}
}
},
@@ -223,7 +226,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
@@ -236,7 +239,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"agent": {"$ref": "#/definitions/AgentSupplyApi"},
"removed_hops": {"type": "array", "minItems": 1, "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}
@@ -261,7 +264,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": false},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"error": {"const": "candidate_suppliers_changed"},
"detail": {"type": "string", "minLength": 1},
"changed": {
@@ -281,7 +284,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"agent": {
"type": "object",
"required": ["backend", "mode", "catalog_models"],
@@ -362,7 +365,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"candidates": {
"type": "object",
"required": ["builtin", "providers", "in_list"],
@@ -381,7 +384,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"matches": {
"type": "array",
"maxItems": 8,
@@ -415,7 +418,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
@@ -425,7 +428,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
}
},
@@ -435,7 +438,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"chain": {"$ref": "model-hub/agent-chain.schema.json"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -447,7 +450,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"probe": {"$ref": "model-hub/probe-result.schema.json"}
}
},
@@ -457,7 +460,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
@@ -467,7 +470,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
@@ -477,7 +480,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -499,7 +502,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -522,7 +525,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -547,7 +550,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8}
+ "contract_version": {"const": 9}
}
},
"RuntimeApi": {
@@ -569,7 +572,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"scan": {"$ref": "model-hub/migration-scan.schema.json"}
}
},
@@ -579,7 +582,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"applied": {"type": "integer", "minimum": 0},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}
@@ -591,17 +594,33 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}
}
},
+ "LatestProvenanceResponse": {
+ "description": "On-demand latest persisted retained turn for the exact backend and requested catalog model, regardless of outcome. Null means no retained match. The existing turn-id response remains non-nullable.",
+ "type": "object",
+ "required": ["ok", "contract_version", "provenance"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 9},
+ "provenance": {
+ "anyOf": [
+ {"$ref": "model-hub/turn-provenance.schema.json"},
+ {"type": "null"}
+ ]
+ }
+ }
+ },
"RuntimeResponse": {
"type": "object",
"required": ["ok", "contract_version", "runtime"],
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 8},
+ "contract_version": {"const": 9},
"runtime": {"$ref": "#/definitions/RuntimeApi"}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index fd69145c2..ec6c93e03 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1,10 +1,10 @@
# Model Hub — REST API contract
-Status: **Normative, `contract_version` 8** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
+Status: **Normative, `contract_version` 9** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
-Success envelope: `{ok: true, contract_version: 8, ...}`.
+Success envelope: `{ok: true, contract_version: 9, ...}`.
Failure envelope:
-`{ok: false, contract_version: 8, error: <machine_code>, detail?: <i18n_key>}`.
+`{ok: false, contract_version: 9, error: <machine_code>, detail?: <i18n_key>}`.
`detail` is always a string. Structured error data lives in a named sibling.
Guarded mutation refusals specialize that envelope through
`guard-refusal.schema.json`; both report arrays are required and together form the plan
@@ -16,9 +16,9 @@ table. The contract guard requires the two endpoint sets to be identical, requir
exercised HTTP response for every registry entry, and validates that response against
the route's named schema.
-The shared envelope and every versioned nested contract carry `contract_version` 8, the
-terminal value. Model Hub has not shipped, so there is no internal contract migration or
-compatibility path.
+The shared envelope and every versioned nested contract carry `contract_version` 9, the
+terminal value. Supported persisted config shapes and historical TurnProvenance
+remain readable; ephemeral envelopes use only the terminal version.
## Route table
@@ -26,7 +26,7 @@ compatibility path.
| --- | --- | --- |
| GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Every Source carries server-derived `adopted_by` and any persisted `client_nonce`; array order is never a spend order. |
| POST `/api/models/sources/observe` | `{vendor, base_url?, key, protocol?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. On `custom`, omitted `protocol` auto-detects and still requires matching response proof. A shipped vendor catalog pin collapses omission to that one protocol. A supplied value restricts observation to one interface and is established when authentication succeeds and either `vendor` has a shipped catalog pin, the client declared the protocol on `custom`, or a matching protocol-shaped response proves it. No credential reference is returned. |
-| POST `/api/models/sources` | `source-create.schema.json` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. Optional `accept_unavailable_inventory` is the sole explicit consent for a repeated observation that established a protocol owner but whose inventory discovery fails. An optional `client_nonce` is reserved only in process before work and persisted only on the committed Source for list-based lost-response reconciliation. |
+| POST `/api/models/sources` | `source-create.schema.json` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Default placement is committed before effective adoption is projected; manual overrides are unchanged. Optional `accept_unavailable_inventory` is the sole explicit consent for a repeated observation that established a protocol owner but whose inventory discovery fails. An optional `client_nonce` is reserved only in process before work and persisted only on the committed Source for list-based lost-response reconciliation. |
| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. A forced retry confirms only an exact echo of the refusal plan. |
| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | API-key replacement. Confirmation fields are JSON body fields. Success is exactly `{source, removed_hops, interrupted}`; the OAuth-only repair tail never appears here. |
| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | Both Hub OAuth and `native_cli` Sources require the acknowledgement before OAuth starts. Missing or false acknowledgement returns `reauth_confirmation_required` before any adapter call. See repair rules. |
@@ -37,17 +37,20 @@ compatibility path.
| DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or Source-mutation success | Deletes a manual entry; for a discovered entry it persists `retired: true` without deleting the row. Both outcomes use the same exact-hop and supply guards. |
| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. The default read returns the current presence snapshot; `?refresh_cli_presence=1` first refreshes deep npm-only discovery and returns the resulting snapshot. |
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
-| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. |
-| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. |
+| PUT `/api/models/agents/<backend>/sources` | `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Atomically replaces default membership/order, preserves manual overrides, and guards effective hop removal or protected-supply loss. Pure reordering needs no guard. |
+| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Compatibility default-order entry point with the same guards as Sources PUT. Never reorders manual arrays. Without order, returns the current projection. New UI uses Sources PUT. |
| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |
| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |
| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. |
-| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list is matched once against complete non-retired inventory in stored eligible Source order. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
+| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list starts automatic without a route key. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, derive `native_protocol` from the model id's last path segment through the vendor map, cap results at 8, and never persist automatically. |
| GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. |
| GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |
-| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |
+| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Saves an explicit manual override, including equal-to-automatic and empty arrays. New pairs validate canonical ids, Source eligibility/existence and retirement; API-key pairs do not require inventory membership, while subscriptions retain existing membership admission/stale-hop retention. `mutation.route_replace` retains its protected-supply-only guard for visible edits. |
+| DELETE `/api/models/agents/<backend>/chain?model=<id>` | optional `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | `mutation.route_restore` removes the key and recomputes defaults; absent key is idempotent. Guard actual effective removals and supply loss. |
+| POST `/api/models/agents/<backend>/chain/preview?model=<id>` | `{manual_override: null \| {hops: RouteHop[]}}` → `{chain: AgentChain}` | Shared planner over an isolated draft config. No persistence, events, engine startup/sync, credentials or egress, including when runtime is stopped. |
| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |
+| GET `/api/models/agents/<backend>/provenance?model=<id>` | → `{provenance: TurnProvenance \| null}` | On-demand read of the most recently persisted retained record for this exact backend and canonical catalog model, regardless of outcome. Validates backend/model; absent history is null. Uses only the existing bounded store and never starts or syncs the engine. No history field is added to AgentChain. |
| GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |
| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary}` | Bounded metered token report over a trailing local-day window. `days` is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. |
| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |
@@ -55,17 +58,17 @@ compatibility path.
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |
| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. |
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
-| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. |
+| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same default placement and effective adoption as Add Source; original files remain byte-identical. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 8 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 9 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
-The removed product-global route `PUT /api/models/priority` has no replacement. Backend
-Source order has two explicit operations: the sources route stores it without touching
-Routes, while `chains/reorder` can store the same order and apply it to existing Routes
-atomically. Exact per-model order is explicit configuration through the chain route.
+The removed product-global route `PUT /api/models/priority` has no replacement. Sources
+PUT and compatibility chains/reorder share backend-default semantics and effective guards,
+preserving all manual arrays. Exact manual order is saved through the chain resource;
+DELETE restores automatic and POST preview evaluates the draft without a write.
## Unsaved Source observation
@@ -231,7 +234,7 @@ non-empty user list with a managed declaration emits exactly one redacted
emitted or accepted. JSON Schema can validate format, not cross-document existence.
- Claude and Codex requests use fixed-menu built-in ids.
- OpenCode requests use the bare canonical menu id (spec §4.8 v4). The overlay provider
- is a function of the row's `native_protocol`; the resolver sends the exact stored hop's
+ is a function of the row's `native_protocol`; the resolver sends the exact effective hop's
model id upstream.
- Add-time matching may suggest a sanctioned alias or mapping, but it materializes the
accepted result as an exact `{source_id, model_id}` hop before commit. Runtime neither
@@ -392,47 +395,28 @@ its process availability but carries `in_current_model_chain: null`.
## Per-backend source order
-The storage-only PUT requires, and the atomic reorder POST may accept, the same total
-order body:
+Sources PUT requires `order`; compatibility chains/reorder POST accepts optional order.
+Both accept optional `force`, `would_remove_hops`, and `would_interrupt` fields.
```json
{"order": ["src_anthkey01", "src_relay9c1x"]}
```
-- `order` is the complete desired ordered subset. The empty subset is legal.
-- Every id is unique, exists, and is eligible for the backend. Otherwise the route
- returns `invalid_source_order`.
-- Add Source and native import invoke `placement-v1` once and persist its chosen
- position. Refresh, restart, health changes, and turns never recompute this order.
-
-The storage-only PUT is intentionally outside the §4.5 Source-mutation envelope matrix.
-It stores only `sources.order`, never reads or writes a Route chain, and therefore never
-returns a guarded `409`. This is the G-9 tombstone: adding a guard branch would imply
-that this storage-only route can remove supply, which violates S-1.
-
-`POST /api/models/agents/<backend>/chains/reorder` is the only server-side post-creation
-operation that implicitly reads and applies the stored Source order to existing Routes.
-When the optional `order` body is present, storing that complete order and applying it
-to existing Routes happen under the same mutation lock and persistence boundary; an
-omitted body preserves the stored-order-only form for internal callers.
-For each Route, give every hop its original zero-based index `i` and sort by this total key:
-
-```text
-source_id in sources.order -> (0, sources.order.index(source_id), i)
-source_id not in the order -> (1, i, i)
-```
+The order is the complete desired default subset, including an empty subset. Every id
+is unique, existing and configuration-eligible; invalid input returns
+`invalid_source_order`. Manual routes can name other eligible Sources and are never
+rewritten by either operation. Source creation/native import append eligible defaults;
+refresh, health and turns do not rewrite order.
-Thus ordered Sources come first in Source-order sequence; hops of the same Source keep
-their prior order; every unlisted hop follows and all unlisted hops keep their relative
-order. The operation changes only hop order. It preserves the multiset of exact
-`(source_id, model_id)` pairs byte-for-byte, never runs matching, and never adds,
-removes, or remaps a hop. It is idempotent and has no `force`, guarded refusal, removed-
-hop, or interruption branch: changing a preferred first hop is an explicit non-
-destructive configuration edit, not loss of supply. This route is the first consumer of
-the Source-order sequence under the current `placement-v1` policy.
+`mutation.default_sources` stages the order under the mutation lock and compares
+before/after effective plans. Existing exact-plan guards cover effective hop removal
+or protected-supply loss; pure reordering without removal has no guard. A confirmed
+retry must echo both refusal arrays exactly. Success remains `{agent: AgentSupply}`.
+An omitted POST order returns the current projection without a write.
-Eligibility is server-authoritative. An ineligible row carries exactly one closed
-`reason_key` from `agent-supply.schema.json`; an eligible row carries null.
+Eligibility remains server-authoritative. Ineligible rows carry the closed reason key;
+eligible rows carry null. The frontend never matches inventory or infers intent from
+array equality. Default changes affect only the chosen backend.
### Direct-to-Gateway native adoption
@@ -440,33 +424,53 @@ For `PATCH /api/models/agents/<backend>/mode`, a transition from `direct` to `hu
reuses the same sanctioned native-login recognition and response-backed observation
boundary as native import. If that backend has a recognized CLI login and has no
`native_cli` Source, the mode change, creation of the backend's singleton native Source,
-`placement-v1` Source-order insertion, and every accepted add-time exact match commit in
+default Source-order insertion commit in
one transaction. The returned `AgentSupply` is assembled after that commit and exposes
-the resulting order, eligibility, Routes, and supply summaries.
+the resulting order, eligibility, sparse manual Routes, and effective supply summaries.
An existing native Source, an unrecognized or absent CLI login, or any transition other
than `direct` → `hub` creates nothing. The mode switch itself remains legal in those
cases. Repeating the request never creates a second native Source. `cli_present` alone
does not satisfy the recognition predicate.
-### Exact Route-chain configuration
-
-Every menu model stores one `hops` array. Each hop is an exact
-`{source_id, model_id}` pair; a differing upstream id is the mapping itself, not a
-separate mapping object. A write validates only newly introduced or changed pairs.
-The per-model PUT persists the explicit submitted order and never reads `sources.order`.
-An editor may sort its local draft from the Source-order projection already on the page,
-but the request still carries only explicit `hops`, with no stored-order instruction.
-The whole-array PUT uses `force` plus the optional echoed `would_remove_hops` and
-`would_interrupt` arrays in the JSON body only when the submitted edit would interrupt
-protected supply. A successful write returns `{chain, removed_hops, interrupted}`.
-Removing a hop while leaving protected supply runnable is the user's visible direct edit
-and succeeds without a guard round trip; a non-forced write that would interrupt
-protected supply returns the shared `GuardRefusal` envelope with
-`error: source_last_supplier`.
-An unchanged stale pair may be retained or reordered so a user can add a working
-fallback without discarding a temporarily unavailable configured hop. Runtime walks
-the stored array verbatim and annotates only live runnability.
+### Manual Route configuration and preview
+
+Owner decision `c1d398d5f` scopes unknown-model passthrough and inventory-independent
+manual invocation to Hub API-key Sources. Subscriptions retain known-model admission and
+automatic matching; unmatched subscription-only defaults yield an empty/null-origin plan.
+
+`AgentSupply.routes` is a sparse map of `{hops: RouteHop[]}` overrides. No key means
+automatic; a present empty array is deliberately empty. PUT creates a manual key even
+when submitted hops equal the automatic result. DELETE removes that key. Manual arrays
+are exact and can use an eligible Source outside default membership. New or changed
+pairs require canonical nonempty ids, Source existence/eligibility and no explicit
+retirement. API-key targets do not require inventory membership; subscription targets
+retain existing known-model admission and stale-hop retention. Retained stale hops remain
+editable without inventing inventory.
+
+The new-identifier length bound is not a read or mutation bound for persisted
+identities. Existing normalized catalog ids and retained exact target/source-inventory
+identities remain usable across PUT, preview, DELETE and model-provenance reads even
+when a later admission bound is shorter. Newly introduced identifiers still pass
+admission; padding aliases remain rejected, and existing source, channel, retirement
+and stale-hop policies are unchanged.
+
+PUT uses `mutation.route_replace`: visible noninterrupting removals are ordinary
+success; protected-supply interruption returns the existing exact-plan refusal. DELETE
+uses `mutation.route_restore`: guard actual effective removals and supply loss, then
+remove the key and recompute. Both return `{chain, removed_hops, interrupted}` and
+preserve the existing error family and confirmation arrays. DELETE is idempotent if
+there is no key.
+
+Preview requires `manual_override`, whose value is null for automatic or an object
+with the draft hops. It uses the same pure planner with isolated draft configuration,
+returns the existing chain success envelope, and performs no persistent mutation,
+event, runtime startup/sync, credential access or upstream request. The returned
+`manual_override` describes the draft, not persisted intent. Preview is available
+while runtime is stopped. Save responses remain authoritative, and failed/ambiguous
+writes follow existing reconciliation using intent as well as effective hops.
+
+<!-- authority-consumer: route_plan.manual route_plan.automatic route_plan.passthrough route_plan.empty -->
## Source creation outcome
@@ -476,14 +480,14 @@ the stored array verbatim and annotates only live runnability.
{"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_anthkey01", "model_id": "claude-opus-4-6", "position": 2}
```
-`position` is one-based in the persisted Route chain after commit. `AdoptedBy` is the
-stable Source-card projection of persisted references:
+`position` is one-based in the effective Route chain after commit. `AdoptedBy` is the
+Source-card projection of effective references:
```json
{"backend": "claude", "menu_model": "claude-opus-4-6"}
```
-Neither array carries a policy field. A Source with no accepted automatic match returns
+Neither array carries a policy field. A Source with no effective adoption returns
empty arrays and remains available for explicit Route editing; there is no skipped-order
reason or “not enabled” state.
@@ -492,7 +496,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 8,
+ "contract_version": 9,
"source": {
"id": "src_anthkey01",
"kind": "api_key",
@@ -560,7 +564,7 @@ The protected model set for a backend is the union of:
3. every menu model with a persisted Route row, including an empty `hops` array.
The guard evaluates each protected `(backend, model)` against the post-mutation
-state. It counts only runnable exact hops in that model's stored Route chain, never
+state. It counts only runnable exact hops in that model's effective Route chain, never
eligible inventory or the backend Source order by itself. A pair with no runnable hop
appears once in `would_interrupt` or `interrupted`.
@@ -570,7 +574,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c
```json
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [
@@ -595,7 +599,7 @@ mutation with `force: true` and byte-for-byte equivalent JSON values for the ref
server-side confirmation state exists.
The shared layer recomputes the current guarded-impact plan and then applies this total
-decision matrix. For Source and inventory mutations, a plan is nonempty when the staged
+decision matrix. For Source, inventory, default-membership and Restore mutations, a plan is nonempty when the staged
mutation has at least one `would_remove_hops` or `would_interrupt` item. For
`mutation.route_replace`, only a nonempty `would_interrupt` activates the plan; its
refusal also reports every submitted removal in `would_remove_hops`, while a
@@ -702,7 +706,7 @@ API-key success:
```json
{
"ok": true,
- "contract_version": 8,
+ "contract_version": 9,
"source": {
"id": "src_relay9c1x",
"kind": "api_key",
@@ -793,7 +797,7 @@ Status and submit return the same terminal shape:
```json
{
"ok": true,
- "contract_version": 8,
+ "contract_version": 9,
"flow": {
"flow_id": "oaf_claude01",
"client_nonce": "ofn_01j5w8z7p4n6q2rt",
@@ -822,13 +826,15 @@ reference is created.
## Chain and probe
-In Hub mode, `AgentChain.chain` is the exact stored per-model Route chain in the same
-order. Runtime does not filter or rebuild it: cooling, missing, model-unsupported,
-source-blocked, live connection-backoff, and process-unavailable native CLI hops stay at their configured
+In Hub mode, `AgentChain.chain` is the shared effective per-model route in planner
+order. `manual_override` reports actual key presence and `route_origin` reports
+`automatic | manual | passthrough | null`, independently of live health. Empty chains
+have null origin, even with `{hops: []}` manual intent. Live inspection annotates it: cooling, missing, model-unsupported,
+source-blocked, live connection-backoff, and process-unavailable native CLI hops stay at their effective-plan
positions with live annotations.
`AgentChain.current` is either null or the exact `{source_id, model_id}` identity of
the hop that is current for the next execution. Recovery changes `current` on the next
-turn without changing the stored `chain` array.
+turn without changing the effective plan or origin.
Each item carries `channel`, Source-global health or the distinct live `backoff`
overlay, process-aware `runnable`, and nullable `reason`. The complete axiom is:
@@ -839,7 +845,7 @@ configuration knob for it. For `native_cli`, `reason: "native_cli_unavailable"`
orthogonal process fact legal at every health and always forces `runnable: false`. The
item stays visible and dimmed, and makes a fully blocked chain `interrupted`, even when
its health is `cooldown` or `backoff`. A short connection throttle overlays only an
-otherwise healthy, capability-present Hub or process-available native hop. Source
+otherwise healthy, eligible non-retired Hub or process-available native hop. Source
cooldown, `needs_action`, `error`, `source_missing`, and `model_unsupported` suppress
that overlay and retain their established health/reason/retry projection. An eligible
throttled hop carries `health: backoff`,
@@ -853,11 +859,13 @@ a valid `interrupted` chain.
```json
{
"ok": true,
- "contract_version": 8,
+ "contract_version": 9,
"chain": {
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"model_id": "gpt-5.6",
+ "manual_override": null,
+ "route_origin": "automatic",
"chain": [
{
"source_id": "src_chatgptplus",
@@ -880,7 +888,7 @@ In Direct mode both chain and probe refuse with:
```json
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "direct_mode",
"detail": "models.hub.direct_mode"
}
@@ -894,9 +902,9 @@ A successful probe nests its result:
```json
{
"ok": true,
- "contract_version": 8,
+ "contract_version": 9,
"probe": {
- "contract_version": 8,
+ "contract_version": 9,
"backend": "claude",
"channel": "hub",
"reachable": false,
@@ -919,7 +927,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"channel": "native_cli",
"reachable": true,
@@ -932,7 +940,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"channel": "native_cli",
"reachable": false,
@@ -948,7 +956,7 @@ No candidate is an API error with a typed model-scoped state:
```json
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
"supply": {
@@ -987,7 +995,7 @@ Projection precedence while a deadline is live is total:
| Underlying hop fact | Backoff overlay | Emitted facts | Fully blocked rollup |
| --- | --- | --- | --- |
-| healthy + exact capability present + process available | apply | `backoff`, `connection_failed`, future deadline | `waiting` when all hops are cooldown/ordinary backoff |
+| healthy + exact admitted non-retired pair + process available | apply | `backoff`, `connection_failed`, future deadline | `waiting` when all hops are cooldown/ordinary backoff |
| cooldown | suppress | existing cooldown health/reason/deadline | `waiting` when all hops are cooldown/ordinary backoff |
| `needs_action` or `error` | suppress | existing Source health/reason/retry facts | `interrupted` |
| `source_missing` or `model_unsupported` | suppress | existing capability-blocker health/reason/retry facts | `interrupted` |
@@ -999,15 +1007,58 @@ closed live key and validates only as `channel: hub`, `reachable: false`, and
`latency_ms: null`; native probes and Hub probes with measured latency cannot carry it.
It never reports the removed persistent network/timeout cooldown keys.
+## Latest recorded turn
+
+The Recorded Error Detail Closure in `model-hub-routing-modes.md` (`0de3d2f47`,
+envelope/diagnostic correction `9cb9ebb53`)
+binds GET `/api/models/agents/<backend>/provenance?model=<id>` to the existing
+`BoundedProvenanceStore`. Select the latest persisted retained record matching both
+`agent` and `requested_model_id`, not the latest failure or the current route's Source.
+The store retains at most 500 exactly attributed settled turns with its existing atomic
+writes. Ambiguous attribution remains excluded; this is not a log of every upstream
+request. Null means no matching retained record, including eviction. A newer served,
+canceled or other record without a terminal error supersedes older error display.
+Success uses exactly `{ok: true, contract_version: 9, provenance: TurnProvenance | null}`;
+there is no `success` field or envelope exception.
+
+New `terminal_error` records may contain `http_status` (integer 100-599 or null) and
+`upstream_error_code` (a recognized upstream machine code or null). The existing
+`UPSTREAM_MACHINE_ERROR_CODES` authority owns code membership. When `model_not_found`
+was observed and classification returned `upstream_request_invalid`, retain it over a
+co-occurring generic `invalid_request_error` type; otherwise use existing specificity
+order. This is diagnostic selection, not a classifier rank/decision change. Never infer
+`model_not_found` from `invalid_parameter`, the requested model, or today's route.
+Unknown upstream strings, raw bodies, messages, headers and credentials are not
+retained. These optional observations do not change classification, fallback or Source
+health. Historical records may omit both fields and keep their existing read behavior.
+
+The dialog independently reads this projection on demand and labels it "Latest recorded
+turn" / "最近已记录回合". Its error panel and details action use the same structured record,
+recorded timestamp and exact historical Source/model identifiers. Deleted Sources keep
+their historical ids. Missing machine codes use generic reason-based copy. Retrieval
+failure has an explicit retry state; model changes and dialog close invalidate pending
+reads. Cancel, Restore and Save never rewrite history. The pure effective planner and
+chain-list response do not acquire history reads or fields.
+
+Diagnostic selection follows the Recorded-error diagnostic selection authority in
+`model-hub.md`. D28 mirrors its decisions; the schema code enum is independently
+compared with production `UPSTREAM_MACHINE_ERROR_CODES` by
+`tests/test_model_hub_provenance.py::test_terminal_diagnostic_schema_uses_the_production_machine_code_authority`.
+
+<!-- authority-consumer: recorded_error.specific_model_not_found recorded_error.known_code recorded_error.no_safe_code -->
+
## Turn provenance absence
+This section applies only to the existing turn-id endpoint; the backend/model latest
+projection above returns successful null for absent retained history.
+
`TurnProvenance` is returned only for an exactly attributed Hub turn. Direct and
ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "provenance_unavailable",
"detail": "models.provenance.direct_mode"
}
@@ -1016,7 +1067,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "provenance_unavailable",
"detail": "models.provenance.attribution_ambiguous"
}
@@ -1177,7 +1228,7 @@ contract harness and API-boundary tests enforce:
<!-- authority-consumer: credential.refresh_once credential.refresh_failed credential.refresh_rejected credential.static_unauthorized credential.account_classified credential.request_nonfallback -->
<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.blocked turn.canceled -->
-<!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace -->
+<!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace mutation.route_restore mutation.default_sources -->
<!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled -->
<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->
<!-- authority-consumer: observation.outcome observed ambiguous unreachable authentication_failed adapter_error timeout -->
@@ -1200,15 +1251,15 @@ contract harness and API-boundary tests enforce:
| authority registry and mirror relations are generated from live files in the same test run; every registered closed branch has a consumer and every registered consumer resolves to one authority | `mirror-registry.json` harness |
| every non-null `then` constraint has matching `required` | contract harness |
| every `sources.order` id exists, is unique, and is eligible | config loader + source-order route |
-| the per-model Route PUT accepts only explicit `hops` and its server path never reads or implicitly applies `sources.order`; only the all-chain reorder operation does so after creation | API route negative fixture |
+| the per-model Route PUT accepts only explicit `hops` and its server path never reads or implicitly applies `sources.order`; the shared planner consumes defaults for inherited routes, while default writes preserve manual arrays | API route negative fixture |
| eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler |
| every AgentSupply eligibility row carries `in_current_model_chain` and `process_availability_reason`; membership nullability follows `selected_model_id`, and only a native source may carry `native_cli_unavailable` | AgentSupply assembler |
-| `AgentChain.chain` re-echoes the stored exact hops in the same order, including missing, model-unsupported, and process-unavailable native CLI items; `AgentChain.current` is null or identifies one exact hop in that array | chain assembler |
+| `AgentChain.chain` returns the shared effective hops in planner order, including missing, model-unsupported, and process-unavailable native CLI items; `AgentChain.current` is null or identifies one exact hop in that array | chain assembler |
| `model_supply` has one row per menu model with unique ids | AgentSupply assembler |
| probe `source_id` names an existing source | probe assembler |
| non-null event endpoints name existing sources at emission time | event emitter |
| `channel_switch.from_source == channel_switch.to_source` | event emitter |
-| API AgentSupply includes `cli_present`, `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply[].has_runnable_hop`, and `named_agents[].route_reason`; every Source includes persisted `last_discovered_at`, optional persisted `client_nonce`, derived `adopted_by`, model retirement tombstones, and every model's `reasoning_efforts_source`; source creation returns `added_to` and top-level `adopted_by` equal to `source.adopted_by`; saved refresh and discovered-model retirement use the guarded Source envelope | API payload test |
+| API AgentSupply includes `cli_present`, `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, default `sources.order`, sparse `routes`, `supply_status`, `model_supply[].route_origin`, `model_supply[].has_runnable_hop`, and `named_agents[].route_reason`; every Source includes persisted `last_discovered_at`, optional persisted `client_nonce`, derived `adopted_by`, model retirement tombstones, and every model's `reasoning_efforts_source`; source creation returns `added_to` and top-level `adopted_by` equal to `source.adopted_by`; saved refresh and discovered-model retirement use the guarded Source envelope | API payload test |
| every OAuthFlow response includes `intent` | API payload test |
| Hub OAuth and native CLI `POST /sources/<id>/reauth` requests with missing or false `acknowledge_irreversible` return `reauth_confirmation_required` before the OAuth adapter is called; true acknowledgement is the only start path, while transactional API-key PUT is unaffected | API route negative/positive fixtures |
| OAuth start claims `(client_nonce, vendor, channel)` before provider work; a blocked first call plus concurrent same-tuple retry coalesces to one pending result and exactly one provider start; pending-start failure/task cancellation releases after cleanup; success atomically exposes one echoed-nonce flow; explicit cancellation retains that nonce-bearing flow as `cancelled` so a same-tuple retry starts no provider, while existing expiry releases it for exactly one fresh start; no-nonce cancellation forgets | OAuth registry totality, clocked expiry, API payload, and auth-setup closed-loop tests |
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index d8d6c1710..60d6bfc6a 100644
--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json
+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json
@@ -62,7 +62,7 @@
],
"properties": {
"ok": { "const": false },
- "contract_version": { "const": 8 },
+ "contract_version": { "const": 9 },
"error": {
"enum": [
"source_last_supplier",
@@ -117,7 +117,7 @@
"examples": [
{
"ok": false,
- "contract_version": 8,
+ "contract_version": 9,
"error": "source_model_in_route_chain",
"detail": "modelHub.errors.source_model_in_route_chain",
"would_remove_hops": [
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index a9dc16ec6..d516bee8d 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -1,5 +1,5 @@
{
- "contract_version": 8,
+ "contract_version": 9,
"input_generation": {
"mode": "same_run_live_files",
"external_snapshot": "content_fingerprint_required"
@@ -395,6 +395,76 @@
}
],
"decision_tables": [
+ {
+ "id": "D28",
+ "domain": "recorded-error diagnostic selection",
+ "authority": {
+ "kind": "markdown_table",
+ "file": "docs/plans/model-hub.md",
+ "heading": "Recorded-error diagnostic selection",
+ "column": "Decision"
+ },
+ "consumers": [
+ {
+ "kind": "marker",
+ "file": "docs/plans/model-hub-contracts/api.md",
+ "prefix": "recorded_error."
+ }
+ ]
+ },
+ {
+ "id": "D26",
+ "domain": "effective route origin",
+ "authority": {
+ "kind": "schema_vocabulary",
+ "schema": "agent-chain.schema.json",
+ "paths": [
+ "/properties/route_origin"
+ ],
+ "exclude": [
+ null
+ ]
+ },
+ "consumers": [
+ {
+ "kind": "schema_vocabulary",
+ "schema": "agent-supply.schema.json",
+ "paths": [
+ "/properties/model_supply/items/properties/route_origin"
+ ],
+ "exclude": [
+ null
+ ]
+ },
+ {
+ "kind": "python_string_assignment",
+ "file": "core/handlers/model_hub/resolver.py",
+ "name": "RouteOrigin"
+ },
+ {
+ "kind": "typescript_string_union",
+ "file": "ui/src/components/settings/models/types.ts",
+ "name": "RouteOrigin"
+ }
+ ]
+ },
+ {
+ "id": "D27",
+ "domain": "effective route planning",
+ "authority": {
+ "kind": "markdown_table",
+ "file": "docs/plans/model-hub.md",
+ "heading": "Effective-route decision matrix",
+ "column": "Decision"
+ },
+ "consumers": [
+ {
+ "kind": "marker",
+ "file": "docs/plans/model-hub-contracts/api.md",
+ "prefix": "route_plan."
+ }
+ ]
+ },
{
"id": "D1",
"domain": "credential failure handling",
diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.json
index 716e83d92..131270d1e 100644
--- a/docs/plans/model-hub-contracts/observation-result.schema.json
+++ b/docs/plans/model-hub-contracts/observation-result.schema.json
@@ -16,7 +16,7 @@
],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 8 },
+ "contract_version": { "const": 9 },
"outcome": {
"enum": [
"observed",
@@ -150,7 +150,7 @@
],
"examples": [
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "observed",
"reachable": true,
"authenticated": "authenticated",
@@ -165,7 +165,7 @@
]
},
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "authentication_failed",
"reachable": true,
"authenticated": "rejected",
@@ -175,7 +175,7 @@
"model_metadata": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "ambiguous",
"reachable": true,
"authenticated": "unknown",
@@ -185,7 +185,7 @@
"model_metadata": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "unreachable",
"reachable": false,
"authenticated": "unknown",
@@ -195,7 +195,7 @@
"model_metadata": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "adapter_error",
"reachable": null,
"authenticated": "unknown",
@@ -205,7 +205,7 @@
"model_metadata": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "timeout",
"reachable": null,
"authenticated": "unknown",
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
index 28131e496..3e28a5ed5 100644
--- a/docs/plans/model-hub-contracts/opencode-overlay.md
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -69,11 +69,11 @@ contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that s
`thinking.budgetTokens` shape is not used: the engine folds it into a bucketed effort, and
`thinking: {type, effort}` silently becomes a 1024-token budget. A row with
`supports_reasoning: false` has no variants.
-- The invocation selects the exact stored `(source_id, model_id)` hop. Runtime never
- normalizes a provider, matches inventory, or substitutes a model. The same-protocol
+- The invocation selects the exact effective `(source_id, model_id)` hop. Invocation never
+ normalizes a provider or chooses a different plan tier. The same-protocol
guarantee is protocol-specific: **Anthropic** — when the hop's Source protocol is
`anthropic`, the request body reaches the upstream unchanged apart from the `model` field,
- which the Gateway rewrites to the stored hop's model id (a user-configured substitution,
+ which the Gateway rewrites to the effective hop's model id (a user-configured substitution,
`model-hub.md` §4.5, is invoked as written); **Responses** — when the hop's Source protocol
is `openai_responses`, `input`, `reasoning`, and `prompt_cache_key` reach the upstream intact
while the engine's Codex executor edits the envelope (below). The Anthropic guarantee is
@@ -92,28 +92,31 @@ contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that s
Anthropic-frontend `output_config.effort` is dropped on the way to an `openai_chat` upstream
(a second reason models are grouped by native protocol, not by supplier).
-## Add-time matching (`matching-v1`)
+## Effective route planning
-OpenCode matching occurs once while adding a Source or a menu model, using the inventory
-owned by that write. An exact model id wins; there is no prefix to strip or repair. The stored
-Route carries the concrete upstream model id and this normalization is never repeated by
-runtime or refresh.
+The shared resolver owns OpenCode matching over complete non-retired inventory.
+A manual key returns exact saved hops. Otherwise literal canonical model equality
+selects the matching tier in default order; if none matches, eligible non-retired
+Hub API-key defaults receive the original id unchanged. Subscriptions retain existing
+known-model admission and are never speculative unknown-model candidates. No vendor-prefix repair or fuzzy matching
+exists. Live health and protocol transport inspection annotate that chosen plan without
+creating another tier. The overlay never duplicates this planning algorithm.
## Stability invariant (test requirement, L7)
For a fixed set of checked rows with fixed `native_protocol` values, the generated overlay is
byte-identical across: Source-order edits, Source cooldown/failover, route-chain edits,
engine restarts, and gateway token rotation apart from
-`options.apiKey`. Adding/removing a Source without changing the stored Route chains also
+`options.apiKey`. Adding/removing a Source without changing the effective Route targets also
leaves it byte-identical. A scenario test asserts this by diffing generated overlays under
each perturbation.
-## Upgrade — none
+## Persisted compatibility
-Model Hub is pre-release (owner, 2026-09-05; `README.md`: no bump carries a migration,
-compatibility reader, conversion, or version discriminator). A stored OpenCode section in the
-pre-v4 shape is invalid input under the v4 schema and is handled by the existing invalid-config
-path; nothing converts it.
+Supported saved shapes use the existing safe loader. Preserve sparse manual intent,
+including empty, stale and dormant OpenCode entries; do not infer old authorship or
+automatic intent from array equality/default order. Legacy shapes outside supported
+conversion use documented safe degradation, never a blanket pre-release waiver.
## Spike record (S1–S6; evidence captured 2026-09-04 on OpenCode 1.18.18 and CLIProxyAPI 7.2.105 `4a2eb54d`, the binary Avibe's manifest pins, with the repo mock upstream recording path/headers/body)
diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.json
index ecab2f5b7..fce82d385 100644
--- a/docs/plans/model-hub-contracts/probe-result.schema.json
+++ b/docs/plans/model-hub-contracts/probe-result.schema.json
@@ -2,17 +2,17 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/probe-result.schema.json",
"title": "ProbeResult",
- "description": "Outcome of probing the first runnable exact configured hop. Runtime never performs model matching or substitution.",
+ "description": "Outcome of probing the first runnable exact hop from the shared effective route plan. Probes use the same manual, automatic or passthrough tier as reads and execution; live restrictions never create another tier. Unknown-model passthrough is Hub API-key-only; subscriptions retain existing model admission.",
"type": "object",
"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 8 },
+ "contract_version": { "const": 9 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"channel": { "enum": ["hub", "native_cli"] },
"reachable": { "type": "boolean" },
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
- "model_id": { "type": "string", "minLength": 1, "description": "The exact upstream model id stored in the selected hop." },
+ "model_id": { "type": "string", "minLength": 1, "description": "The exact upstream model id selected by the effective planner." },
"latency_ms": { "type": ["integer", "null"], "minimum": 0 },
"error": {
"type": ["string", "null"],
@@ -62,10 +62,10 @@
}
],
"examples": [
- { "contract_version": 8, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
- { "contract_version": 8, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
- { "contract_version": 8, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
- { "contract_version": 8, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
- { "contract_version": 8, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
+ { "contract_version": 9, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
+ { "contract_version": 9, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
+ { "contract_version": 9, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
+ { "contract_version": 9, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
+ { "contract_version": 9, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
]
}
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index 3aa983482..4a30cf111 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 8 },
+ "contract_version": { "const": 9 },
"enabled": {
"type": "boolean",
"description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."
@@ -131,7 +131,7 @@
},
"examples": [
{
- "contract_version": 8,
+ "contract_version": 9,
"host_platform": "darwin-arm64",
"manifest": {
"name": "cliproxyapi",
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 638ee9f6d..da7be7ace 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -439,7 +439,7 @@
},
"adopted_by": {
"type": "array",
- "description": "Server-derived Source-card projection of persisted Route references, sorted by backend then menu_model. It is returned on every current Source read and creation payload, is never persisted on the Source record, and must not be reconstructed by clients from live chains.",
+ "description": "Server-derived Source-card projection of effective Route references, sorted by backend then menu_model. It is returned on every current Source read and creation payload, is never persisted on the Source record, and must not be reconstructed by clients from live chains.",
"uniqueItems": true,
"items": {
"type": "object",
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index 74a054b48..d381262cd 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/turn-provenance.schema.json",
"title": "TurnProvenance",
- "description": "Persisted debug record for one exactly attributed Gateway turn. It records exact configured Source/model attempts in stored order and one terminal outcome. No route-policy or runtime-mapping discriminator exists; ambiguous attempts produce no record.",
+ "description": "Persisted debug record for one exactly attributed Gateway turn. It records exact Source/model attempts from the effective plan in attempted order and one terminal outcome. Historical records remain readable without a route_origin or manual_override field; ambiguous attempts produce no record.",
"type": "object",
"definitions": {
"strippedReasoningEfforts": {
@@ -36,9 +36,9 @@
"additionalProperties": false,
"properties": {
"contract_version": {
- "enum": [5, 6, 7, 8],
- "$comment": "The only versioned object that is written to disk instead of exchanged inside one request, so its released values are a set rather than a constant. A record a v5 build persisted keeps validating -- tests/fixtures/model_hub/released_v5_permission_denied.json is the evidence -- while new records carry the terminal value, which is the last member. Every other versioned object is an in-process envelope and stays pinned to that value alone.",
- "description": "Generation that wrote this record. Nothing branches on it: readers accept every released value and the shape is identical across them."
+ "enum": [5, 6, 7, 8, 9],
+ "$comment": "The only versioned object written to disk, so released versions form a set rather than a constant. Historical records validate after the existing persistence-read normalization of retired reasons; tests/fixtures/model_hub/released_v5_permission_denied.json exercises that boundary, not raw-file validation. Reading preserves the writer generation and requires no new route fields. New records carry the terminal member. Other versioned objects are ephemeral envelopes pinned to that value alone.",
+ "description": "Generation that wrote this record. Readers retain every supported released value, apply existing retired-reason normalization independently of version, and do not require route_origin or manual_override."
},
"turn_id": {
"type": "string",
@@ -160,7 +160,42 @@
"engine_down"
]
},
- "stream_started": { "type": "boolean" }
+ "stream_started": { "type": "boolean" },
+ "http_status": {
+ "type": ["integer", "null"],
+ "minimum": 100,
+ "maximum": 599,
+ "description": "Optional observed upstream HTTP status for this exact terminal attempt. Null means no valid HTTP status was observed. Historical records may omit it; no value is reconstructed from the classification."
+ },
+ "upstream_error_code": {
+ "enum": [
+ "permission_error",
+ "authentication_error",
+ "invalid_api_key",
+ "account_banned",
+ "account_disabled",
+ "account_suspended",
+ "request_too_large",
+ "invalid_parameter",
+ "invalid_request_error",
+ "validation_error",
+ "context_length_exceeded",
+ "model_not_found",
+ "not_found_error",
+ "rate_limit_error",
+ "rate_limit_exceeded",
+ "quota_exceeded",
+ "insufficient_quota",
+ "billing_error",
+ "overloaded",
+ "overloaded_error",
+ "server_error",
+ "internal_error",
+ "api_error",
+ null
+ ],
+ "description": "Optional observed machine code from classification.UPSTREAM_MACHINE_ERROR_CODES. If model_not_found was observed and classification returned upstream_request_invalid, retain that specific code over a co-occurring generic invalid_request_error type; otherwise use existing specificity order. This diagnostic selection never reranks or changes classification. Never derive a code from invalid_parameter; unknown codes, raw messages, bodies, headers and credentials are not retained. Absent evidence is null; historical records may omit the field."
+ }
},
"dependencies": {
"stripped_reasoning_efforts": ["declared_reasoning_efforts"],
@@ -359,7 +394,7 @@
],
"examples": [
{
- "contract_version": 8,
+ "contract_version": 9,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -384,7 +419,7 @@
"blockers": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -405,7 +440,7 @@
"blockers": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -425,7 +460,7 @@
]
},
{
- "contract_version": 8,
+ "contract_version": 9,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
@@ -445,7 +480,29 @@
"blockers": []
},
{
- "contract_version": 8,
+ "contract_version": 9,
+ "turn_id": "turn_modelmissing01",
+ "ts": "2026-09-05T17:31:10Z",
+ "agent": "claude",
+ "requested_model_id": "claude-opus-4-6",
+ "outcome": "failed_terminal",
+ "failed_attempts": [],
+ "served": null,
+ "terminal_error": {
+ "source_id": "src_anthkey01",
+ "configured_model_id": "unlisted-upstream-model",
+ "channel": "hub",
+ "reason": "invalid_parameter",
+ "stream_started": false,
+ "http_status": 404,
+ "upstream_error_code": "model_not_found"
+ },
+ "canceled_attempt": null,
+ "model_supply_state": null,
+ "blockers": []
+ },
+ {
+ "contract_version": 9,
"turn_id": "turn_01k9x5ca",
"ts": "2026-07-29T07:08:00Z",
"agent": "codex",
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index 4ab0a9f56..9c3d3dcf4 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -1,6 +1,8 @@
# Model Hub E2E Test Plan
-Status: draft, 2026-09-01. Baseline code: `master @ fbb4c532`.
+Status: routing-mode acceptance revision, 2026-09-06. Contract: `model-hub-routing-modes.md`
+(original `2db273891`, owner scope/synchronization decision `c1d398d5f`). The older survey
+below remains background for unrelated capabilities; routing expectations follow this revision.
Companion inventories (kept in session, summarized here): capability list C1–C81 and issue list B1–B17 produced during the 2026-09-01 survey.
## 1. Goals and ground rules
@@ -40,7 +42,7 @@ Out of scope (documented, not dropped silently):
### B. API-key sources (C16–C29)
| ID | Steps | Expect | Status |
|---|---|---|---|
-| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract v7 | assert |
+| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract_version 9 | assert |
| B2 | manual protocol ≠ actual | create refused with matching proof error | assert |
| B3 | pull models (mock returns `display_name`, `context_length`, `pricing`, `supported_parameters`) | unrelated metadata is dropped; `supported_parameters` is retained in observation and the provenance ladder applies protocol-default tiers | assert |
| B4 | discovery fails | 422 `inventory_unavailable` unless `accept_unavailable_inventory:true`; then source commits with `state.status=error` | assert |
@@ -95,7 +97,7 @@ Out of scope (documented, not dropped silently):
| ID | Steps | Expect | Status |
|---|---|---|---|
| G1 | guard echo with a gap missing `agents` | no confirm-loop (B7) — fix-first; baseline documents | fix-first |
-| G2 | `PUT /agents/{backend}/sources` vs `POST .../chains/reorder` divergence | decide: delete orphan endpoint or unify (B3) | baseline |
+| G2 | Sources PUT and compatibility chains/reorder change defaults | same effective guard plan and canonical projection; manual arrays unchanged; omitted reorder order is read-only | assert |
| G3 | malformed JSON on mode/chain routes | error code distinguishable from business refusals (B13) | fix-first |
### H. Cross-protocol functional floor (owner ruling baseline)
@@ -105,6 +107,37 @@ Out of scope (documented, not dropped silently):
| H2 | same with parallel tools | passes (M0 matrix failed 5/8 — if still failing, recorded as known relay behavior per ruling, surfaced in release notes, not a gate) | baseline |
| H3 | image block passthrough | behavior documented (currently untested anywhere); at minimum: no crash, terminal frame well-formed | probe |
+### I. Routing modes and compatibility
+
+| ID | Property | Evidence |
+| --- | --- | --- |
+| RM-1 | Manual intent survives every unrelated config/catalog/health/process transition; equal-to-automatic saves remain manual and explicit empty overrides remain empty | Seed every supported saved shape, mutate defaults/inventory/catalog, reload and compare exact arrays and unrelated config |
+| RM-2 | Automatic matching precedes passthrough, and live health/transport restrictions never choose another tier | All backends with API-key unknown passthrough only, unmatched subscription-only defaults Unconfigured, known-model subscription admission and stale-hop retention, native Claude aliases/date/version rules, complete non-retired evidence, literal API matching, native-only matching with Hub-only invocation, tombstones and empty inventories |
+| RM-3 | One planning input produces identical effective hops/origin in preview, read/list, summaries, adoption, guards, probe, launch and execution | Real API/controller boundaries, assert canonical model ids and Source ids; unknown inventory carries no invented reasoning tiers |
+| RM-4 | Restore/Undo/Cancel/Save preserve draft and persistence truth | Browser GET -> edit -> preview null -> Undo or Cancel -> reload; Save DELETE vs manual PUT; equal arrays, explicit empty, failed saves, stale preview and duplicate submission |
+| RM-5 | Effective removal confirmation is exact and atomic for defaults/Restore/inventory/catalog/Source writes | Refuse, alter state, retry stale plan, confirm current plan; no partial writes; pure reorders preserve manual arrays and need no confirmation |
+| RM-6 | Pinned CPA reaches the selected upstream with the exact canonical unknown model, without fake inventory or cross-Source fallback | Real backend launch -> correlation/gateway -> adapter -> pinned CPA -> local upstream; Hub API-key credentials on all API protocols and admitted non-ASCII ids/payloads; no subscription expansion |
+| RM-7 | Transport registration remains separate from inventory and capabilities | Compare truthful SourceBinding.model_ids/Source.models with deterministic route_model_ids and compiler union; load absent field as empty; unchanged target sets do not restart; registration changes drain active transport leases before supervised restart, block new invocations behind the barrier and release leases on completion/close/cancellation independently of service settlement; prove sync cancellation/rollback and concurrent Save without deadlock; Hub OAuth registration remains unchanged |
+| RM-8 | Request-only unknown-model errors preserve Source health and existing failure/stream boundaries | Typed upstream model_not_found, exact Source/model attribution, no fallback or global health transition |
+| RM-9 | Released config and turn records remain readable | Seed every supported historical shape, empty/populated/stale/dormant OpenCode arrays and unrelated sections; read TurnProvenance versions 5 through 9 without required route-origin fields |
+| RM-10 | Approved help, labels and layout work on desktop/mobile in both themes | Screenshots against approved routing frames; hover/focus/touch help, Escape/outside dismissal, no row-open from badge, no overlapping labels/buttons |
+| RM-11 | Preview is an operationally read-only request | With runtime stopped assert unchanged config/events/engine lifecycle, no credential access or upstream egress, for manual, empty and restored drafts |
+| RM-12 | Recorded error detail uses the latest retained exactly attributed turn, never a synthetic last-request history | Exercise backend/model provenance GET against the existing bounded store: exact backend/model isolation, latest persisted ordering independent of outcome, later success/cancel clearing, empty/evicted/ambiguous history, old records without optional metadata and deleted historical Sources. Capture real model_not_found with observed HTTP status; reject unsafe upstream text and invented codes. Prove retrieval never starts/syncs the engine or writes config/history/events. Browser evidence covers the Latest recorded turn label, same-record structured details, generic old-record copy, retry, pending-read invalidation on close/model change, unchanged route origin and no history writes from Cancel/Restore/Save |
+| RM-13 | Every actual invocation atomically admits a current effective candidate before transport, without holding the global mutation lock during network | Deterministically pause resolution across target removal/change and Source configuration changes; exercise ordinary/fallback, bounded credential-refresh retry and probe through the same admission path. Preserve failed-Source exclusions, reject stale exact refresh pairs without fabricated attempts or synthetic upstream errors, and verify service-mutation then adapter-routing lock order. Pre-admission failure/cancellation releases exclusion; callback failure releases the lease before network; post-admission completion/cancel releases it. Concurrent independent HTTP requests progress during buffered/first-token/stream waits, with no per-request registration or persistent generation store |
+
+All fixtures use test-owned HOME/XDG/config/credentials and local upstreams. Never use
+personal state. Development acceptance uses coordinated local Incus only, preserving
+master state. Mocked peer suites do not replace the pinned-engine boundary proof.
+
+The Python `MH-ROUTING` scenarios in
+`tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py` remain
+canonical catalog evidence. `ui/e2e/model-routing-origin.spec.ts` adds Playwright
+evidence for RM-4: Restore, Undo and Cancel send no mutation; Save uses DELETE,
+handles confirmation and retains automatic intent after reload. Its test label
+does not create a catalog citation: the current browser citation resolver is
+Vitest-only. No new catalog engine or browser INDEX row is required. Run this
+supplement separately against the coordinated hermetic gateway fixture.
+
## 4. Mapping to existing coverage
Unit/contract suites already cover: config validation, guard structure, classification tables, oauth registry, usage ledger, runtime injection. E2E must **not** duplicate them; it owns the seams those can't see: double-observe cost, cooldown-vs-next-turn timing, UI copy on live errors, guard echo round-trip, engine config conservation, member-role dead-ends.
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index 4d88c9b1e..7e5563547 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -1,5 +1,73 @@
# Model Hub — Implementation Plan
+## Routing modes delivery - contract_version 9
+
+The current implementation contract is `model-hub-routing-modes.md`: original freeze
+`2db273891`, owner scope/synchronization decision `c1d398d5f`, recorded-error closure
+`0de3d2f47`/`9cb9ebb53`, and atomic-admission amendment `c50bc43a5`. Its delivery ownership replaces
+the historical independent-lane workflow below for this feature: one assigned shared
+worktree, disjoint file ownership, one atomic feature PR, and orchestrator-only
+commit/push/review integration. Historical lane tables remain importer ownership indexes;
+they do not authorize another write lane or override this contract.
+
+Persist `routes` as sparse manual overrides: absent means automatic, present means exact
+manual intent, including empty/stale/dormant arrays. Source creation and catalog reconcile
+never seed or append manual routes. Sources PUT edits backend default membership/order;
+manual PUT creates intent even when equal to automatic, DELETE restores by removing the
+key, and preview evaluates an isolated draft without side effects. One pure resolver owner
+returns manual_override, route_origin and hops for every read, summary, guard, adoption,
+probe, launch and execution consumer. Match eligible defaults first, then unchanged-id
+passthrough only when no match exists; health and process availability never choose a tier.
+
+Schema/API/type/mirror closure is contract_version 9 on the complete tested head.
+D26 binds the RouteOrigin schema to actual Python/TypeScript consumers and AgentSupply;
+D27 binds the effective-route decision table to API markers. Existing registry absence,
+credential/channel, guard, outcome and ownership checks remain enforced.
+TurnProvenance accepts released versions 5 through 9 with its historical required fields;
+no route-origin requirement is retrofitted onto persisted records. Compatibility fixtures
+preserve every supported config shape and unrelated sections.
+
+Recorded error detail reads the existing bounded provenance store on demand through
+the backend/model GET and the ordinary v9 envelope, never through AgentChain. Optional
+terminal HTTP status and recognized upstream machine code preserve old records;
+diagnostic code selection follows `9cb9ebb53` without changing classification. D28
+mirrors that decision table; the direct backend test
+`tests/test_model_hub_provenance.py::test_terminal_diagnostic_schema_uses_the_production_machine_code_authority`
+compares schema enum minus null with production `UPSTREAM_MACHINE_ERROR_CODES`.
+
+Transport registration is separate from inventory: SourceBinding.route_model_ids is a
+default-empty tuple, mirrored in the internal SourceRecord with absent-as-empty loading.
+The deterministic sorted/deduplicated set comes from effective Hub-channel targets across
+backend catalog models and retained resolver-selectable route keys, including dormant
+OpenCode overrides, independent of health and backend mode. The compiler registers
+inventory plus targets for transport only; Source.models, discovery, candidate evidence
+and capabilities remain truthful inventory. All configuration/load synchronization uses
+the existing owner, leaves unchanged target sets running, and preserves in-flight work.
+Persisted normalized catalog/target identities remain usable when longer than a later
+new-identifier admission bound; route edits, preview, restore and history reads must not
+re-admit existing identities as though they were new. New identifiers remain bounded.
+Only Hub API-key Sources receive unknown-model transport targets. Subscriptions retain
+known-model admission and existing registration. No underlying engine expansion, OAuth
+alias substitution or alternate subscription transport belongs to this delivery.
+The adapter drains active transport leases before the existing supervised restart and
+holds new invocations behind the same barrier. Lease release follows completion, early
+close or cancellation independently of service settlement/mutation locks. Sync cancellation,
+failure/rollback and concurrent Save must release barriers without deadlock or interrupting
+active output. Unchanged target sets remain restart-free; invocations never register.
+
+Atomic admission follows `model-hub.md` Transport registration and the `c50bc43a5`
+amendment: one shared resolve/fallback/refresh/probe path revalidates current config
+under service mutation exclusion, then the adapter routing lock/lease handoff calls
+optional `on_admitted` before network. The handoff records only admitted attempts and
+releases service exclusion; every failure/cancellation releases its owned lock/lease.
+No network-duration global lock or per-request registration is allowed.
+
+Acceptance is the RM-1 through RM-13 property set in `model-hub-e2e-test-plan.md`, together
+with existing failure/credential/streaming invariants. Backend owns consuming runtime/tests,
+frontend owns UI types and behavior, and the spec lane owns these documents and contract
+mirrors. Every new cross-layer conflict returns to the orchestrator with full consumers.
+
+
> **2026-09-04 override — OpenCode v4 (`model-hub.md` §4.8 v4, `opencode-overlay.md` v4,
> `backend-model-catalogs.md` v3).** This document is a historical lane plan. Wherever a row,
> acceptance criterion, fixture, or handoff below says that an OpenCode menu id is
@@ -137,7 +205,7 @@ that reconciliation may change content but is not expected to change file owners
| **K2 conversion fidelity** | codex | Preserve the recorded M0 measurements and go/no-go rows; record the 2026-08-08 owner waiver of an official-API attribution re-test and the accepted relay-attributed reasoning degradation without rewriting the evidence or adding product/UI scope | — |
| **K5 UI specification closure** | codex | Sole ownership of `docs/plans/model-hub-ui-spec.md` across three serialized rounds: (1) the frame registry in in-flight PR #1336; (2) K4 gap-reference upgrades plus the AC-49 withdrawn-evidence cleanup and AC-50 live-backoff presentation registration; (3) the G-32 interaction specification. K5 edits no contract, implementation, locale, or UI file. **K3 residual-queue transfer recorded by PM ruling 2026-08-11 23:09.** | round 1 is independently in flight; round 2 waits for K4 merged; round 3 waits for rounds 1 and 2 merged and must merge before I4's second increment |
| **K6 post-#1312 Turn-outcome contract closure** | codex; dispatch at activation | One bounded contract round, dispatched by the orchestrator only after K4 and #1312 merge. Exclusive scope is `docs/plans/model-hub.md` §4.5's Turn-outcome matrix/consumer segment; `docs/plans/model-hub-contracts/{api.md,turn-provenance.schema.json,resolution-event.schema.json,mirror-registry.json}`; and the corresponding binding/ledger rows in this document. It closes only registered G-34 plus any §4.5 gap row left by the merged #1312 head, changes either schema only when the selected outcome/copy/payload requires it, and owns no implementation, test, UI, or locale file. **Single-round scope and dispatch edge fixed by PM ruling 2026-08-12 02:00.** | K4 + #1312 merged; must merge before I7 starts |
-| **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; resolver unit coverage through #1312; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through #1312's same-tested-head transition. I1 also finishes #1312's already-open shared native-launch-module edits before the transfer recorded solely in I7's row. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks during I1: I1 repairs breakage caused by removed resolver symbols but does not refactor them. I1 owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while #1312 is active. After #1312 merges, only K6's bounded contract scope transfers immediately; the implementation/test files explicitly named by I7 remain unavailable to I7 until K6 merges, and the other I1 files retain their stated owner. **Turn-outcome transfer revised 2026-08-12 02:00.** | K1. **Merges first** |
+| **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_routing_modes.py`; `tests/test_model_hub_api.py`; resolver unit coverage through #1312; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through #1312's same-tested-head transition. I1 also finishes #1312's already-open shared native-launch-module edits before the transfer recorded solely in I7's row. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks during I1: I1 repairs breakage caused by removed resolver symbols but does not refactor them. I1 owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while #1312 is active. After #1312 merges, only K6's bounded contract scope transfers immediately; the implementation/test files explicitly named by I7 remain unavailable to I7 until K6 merges, and the other I1 files retain their stated owner. **Turn-outcome transfer revised 2026-08-12 02:00.** | K1. **Merges first** |
| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/**`; `tests/test_model_hub_runtime.py`; after #1312 merges, `tests/test_model_hub_l3.py` transfers to I2 for managed-Gateway runtime behavior, except for I7's one authorized AC-50 strict-xfail marker deletion. I2 owns authoritative raw shaped-error and `stream_started` facts produced by the managed Gateway only; this boundary flips at the first user-visible model-output byte, never at HTTP status, headers, or another response byte. Native backend callback facts and every classification/state decision belong to I7. The K4 increment additionally owns AC-38's install worker, persisted status/lease, orphan reconciliation, and runtime-level no-op assertions without moving the HTTP/API boundary out of I7. **Native failure ownership revised 2026-08-11 22:37.** | I1 + K4 merged; `test_model_hub_l3.py` transfer waits for #1312 merged |
| **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree. The K4 increment owns AC-48's OAuth registry: it atomically claims the exact nonce/vendor/channel tuple before provider work, coalesces concurrent retries to one pending terminal result, releases failure/task cancellation only before a flow exists, atomically converts success to one echoed-nonce flow, retains an explicitly canceled nonce-bearing flow as the same terminal `cancelled` flow until its existing expiry, and releases the tuple at expiry. AUTH-SETUP-210 blocks the first provider call, overlaps the same-nonce retry, and proves provider invocation exactly once. For AC-52, AUTH-SETUP-109 is the Hub-held re-auth closed loop: missing/false acknowledgement rejects before any adapter/provider call, true acknowledgement starts exactly one Hub flow, and terminal status/repair projection agrees; I7 owns the API/service gate and I5 only consumes the completed scenario. **Explicit-cancel totality revised 2026-08-12 00:37; Hub re-auth scenario binding revised 2026-08-12 01:30.** | K4 merged + #1312 merged |
| **I4 Sources / Gateway UI** *(tentative; one lane, two increments)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive. The current increment consumes the already-specified install/unsupported-host surfaces for AC-38/AC-43; each model row may open frame 02, render the drawing, and consume the chain read projection, but no chain-write caller is wired and Save remains disabled. Exact-chain editing and its UI tests belong to the second increment only after K5's third-round G-32 specification merges. That second increment sends visible noninterrupting hop removal as one ordinary PUT and echoes both refusal-plan arrays unchanged only when protected supply would be interrupted, after I7 freezes both fixtures; the current increment continues to consume master's pre-I7 refusal shape and must not add inactive confirmation fields. It consumes AC-36/37/39–42/44–50 only after K5 round 2 changes their G rows from gaps to contract references and registers the live-backoff presentation; AC-51's read-before-retry client rule activates in the second increment after I7 freezes the deletion/recreate fixture. AC-53's materialization-error `interrupted_pairs` consumer activates only in that second increment after K5 round 2 registers E6 and I7 freezes positive/negative API payload fixtures. AC-54's `accept_unavailable_inventory` producer also belongs to the second increment after K5 round 2 names state ⑤ and I7 freezes both server-result cells; clean creation and pull-origin state ⑤′ never emit it. This is an ordering split inside I4, not a new lane identity. **Revised through the 2026-08-12 04:40 PM ruling.** | current increment: I1 envelopes + K4 contracts; second increment: K5 rounds 1–3 merged + frozen I7/I2/I3 fixtures |
@@ -544,7 +612,7 @@ The contracts README's wording stays as written: it is still true, and still GA-
- **Unit**: configured-chain execution, serializer completeness, overlay generation
(identifier stability invariant), and native-config import parsers. Add/import tests
- prove that every one-time match is written at the deterministic position chosen by
+ prove that every effective match is written at the deterministic position chosen by
§4.2's sole placement policy, remains visible and adjustable, and never creates a
persisted policy discriminator or “not enabled” state.
- **Contract**: REST API against `model-hub-contracts` schemas (both
@@ -748,7 +816,7 @@ text and AC-8's contract text as one criterion even though only one of them is f
| **AC-19** | P2 | Close the final eligibility reason-key vocabulary | `agent-supply.schema.json` | **I1** (final contract) + **I4** (`ui/src/i18n/{en,zh}.json` mirrors) | **settled 08-09 — retired consent/OpenCode reasons removed; closed-vocabulary invariant retained** |
| **AC-20** | P2 | Enforce the hub-mode half of the mode invariant | `agent-supply.schema.json` | **L1 v3** (contract) | no |
| **AC-21** | P2 | Make the mirror registry encode its promised checks | `model-hub-contracts/README.md` | **L1 v3** (registry + checker) | no |
-| **AC-22** | P1 | Make one persisted ordered per-model chain the only Gateway routing configuration and execute it verbatim | `model-hub.md` + final `agent-supply.schema.json`, `agent-chain.schema.json`, `api.md`, and provenance/event mirrors | **I1** (final contracts, add-time match, §4.3 executor, shared tests) + I2 (runtime consumer) + I4 (Gateway UI) + I5 (scenario) | **amended 08-09 S-1 — configuration chooses; runtime only walks and classifies** |
+| **AC-22** | P1 | Sparse manual intent and one effective planner govern every consumer; inherited plans match eligible defaults before unchanged-id Hub API-key passthrough | `model-hub.md` §4.2/§4.3, routing contract and RM acceptance properties | Backend + frontend + spec lanes under orchestrator | amended 2026-09-06 routing modes |
| **AC-23** | P1 | Make subscription custody vendor-specific, enforce one native Source per backend, and distinguish a Native Gateway hop from Direct mode | `model-hub.md` + final source/OAuth/supply/API/adapter contracts | **I1** (contracts/defaults/shared guard) + I2 (dispatch) + I3 (OAuth/native import) + I4 (product states) + I5 (scenario) | **amended 08-09 — Claude native, ChatGPT Hub; Direct and Native are distinct product terms** |
| **AC-24** | P1 | Show the sole subscription-routing warning when, and only when, Claude is added as a Hub-held Source | `model-hub.md` + Models UI/i18n + scenario evidence | I4 (flow and copy) + I5 (scenario); I1 owns any contract term if implementation proves one necessary | **settled 08-07 — informational warning, not consent** |
| **AC-25** | P1 | Split subscription recommendations by vendor and disable duplicate native creation | `model-hub.md` + final source/OAuth/API contracts + add-flow UI evidence | **I1** (defaults + shared singleton guard) + I3 (OAuth) + I4 (guidance) + I5 (scenario) | **amended 08-08 — vendor defaults retained; 08-07 takeover notice withdrawn** |
@@ -828,7 +896,7 @@ I1 owns the remaining implementation closure and any contract field not changed
freeze. The mechanical gate is a **same tested PR head**, not a commit boundary: the
registered version and protocol consumers must coexist on that head before I1 merges.
-- The terminal `contract_version` is owner-fixed at **5** in every registered version consumer:
+- The terminal `contract_version` is owner-fixed at **9** in every registered version consumer:
`docs/plans/model-hub-contracts/mirror-registry.json`,
`docs/plans/model-hub-contracts/agent-chain.schema.json`,
`docs/plans/model-hub-contracts/probe-result.schema.json`,
@@ -886,19 +954,19 @@ external resolver importers.
| ID | Contract file | Final required shape |
| --- | --- | --- |
-| **FC-01** | `README.md` | Names §4.3 as the sole configured-chain execution authority and §4.2 as the sole Add-time Source placement authority; documents the same-tested-head terminal closure, the prelaunch full-handoff gate, and downstream read-only ownership; indexes the contract files and terminal `contract_version: 5`; describes Sources, exact configured routes, add-time matching, channel custody, configuration eligibility, inventory, adoption, and pull-only supply visibility without reproducing either authority. |
-| **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable` and live connection backoff in AgentChain, ProbeResult, the API marker, and both frontend locale objects), credential refresh-capability branches, guard/OAuth/Source-create state machines, the guard-error-to-required-plan-array relation, network phase totality, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. The D21 fixture compares every consumer individually to the reason authority and mutation-tests ProbeResult drift; a surviving consumer cannot mask a missing peer. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **5**. **D21 consumer-completeness revision: 2026-08-11 23:49 K4.** |
+| **FC-01** | `README.md` | Names §4.2 as the sole effective planner and §4.3 as its executor, indexes every contract file, and requires contract_version 9 closure on one tested head. Documents sparse manual overrides, default membership/order, automatic matching and API-key passthrough, historical config/turn readability, custody and pull-only supply visibility. |
+| **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable` and live connection backoff in AgentChain, ProbeResult, the API marker, and both frontend locale objects), credential refresh-capability branches, guard/OAuth/Source-create state machines, the guard-error-to-required-plan-array relation, network phase totality, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. The D21 fixture compares every consumer individually to the reason authority and mutation-tests ProbeResult drift; a surviving consumer cannot mask a missing peer. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **9**. **D21 consumer-completeness revision: 2026-08-11 23:49 K4.** |
| **FC-03** | `source.schema.json` | **Revised 2026-08-11 by the owner-authorized K4 completion and 19:56 network ruling.** `Source` requires canonical id, kind, vendor, `protocol: anthropic | openai_responses | openai_chat`, credential reference/custody, channel, ordinary `created_at` audit metadata, state/usage, and an unordered model inventory whose ids are unique within that Source. Every model is `{id, origin: "discovered" | "manual", reasoning_efforts: string[], retired?: boolean, display_name?, discovered_at?}`; omission means `retired: false`, only a discovered row may be true, and true is a persistent tombstone excluded from supply. The list is required, may be empty, and its reasoning list is editable for either origin. Only shaped explicit upstream errors enter existing non-permanent Source classifications; unclassified transport failures never write persistent health. Hub-held subscriptions require no flag, consent field, or acknowledgement record. |
| **FC-04** | `oauth-flow.schema.json` | Subscription flows carry explicit vendor and `supply_channel`; an omitted channel resolves Claude to `native_cli` and ChatGPT to `hub`, while both opposite explicit choices remain legal. The native option exposes `native_source_already_exists` plus `existing_source_id` before login when the backend singleton is occupied. Claude Hub carries one informational risk-copy key; no other path carries warning or consent state. |
-| **FC-05** | `agent-supply.schema.json` | Each backend stores `mode: hub | direct`, one explicit `sources.order`, and exactly one `{hops: [{source_id, model_id}, ...]}` row per menu model. `hops` is always present and may be empty; neither order has a policy discriminator. It enforces at most one native Source per backend and exposes `adopted_by: [{backend, menu_model}]` from persisted references; Source-card attribution reuses that projection. `supply_status` is the sole backend-health projection, and every `model_supply` row with `chain_length: 0` must carry `has_runnable_hop: false`. Fresh-install construction uses Gateway; the onboarding service supplies Direct for an existing installation with no Model Hub state. No separate mapping, matching, enrollment, or takeover field exists. **Empty-chain correlation revision: 2026-08-11 22:37 K4.** |
-| **FC-06** | `agent-chain.schema.json` | Returns the stored exact Source/model hops in the same order with only `current`, `runnable`, closed blocker reasons (`source_missing`, `model_unsupported`, `native_cli_unavailable`, Source-state reasons, and live `models.source.backoff.connection_failed`), and retry metadata added. `health: backoff` is a Source-scoped in-memory connection throttle before the first user-visible model-output byte with a `retry_at` strictly later than the read assembler's captured time; an expired overlay is normalized to underlying non-backoff health before serialization and never persists in Source/config state. Only output from that affected Source clears its streak; another Source's fallback output does not. The live overlay applies only over an otherwise healthy, exact-capability-present hop. Cooldown, needs-action, error, missing-Source, and unsupported-model facts suppress it and retain their established projection, so durable blockers roll up `interrupted`; only the native-process exception preserves backoff health/deadline while `native_cli_unavailable` takes the reason slot. A nonempty process-available chain blocked only by cooldown/ordinary backoff validates as `waiting` and cannot validate as `interrupted`. The shape has no route-policy or capability-matching discriminator. Takeover derives from stored first hop plus live current position and adds no field. **Blocker-precedence revision: 2026-08-11 23:49 K4.** |
+| **FC-05** | `agent-supply.schema.json` | Each backend stores mode, default sources.order and a sparse map of manual {hops} overrides. Key absence inherits; key presence is exact intent, including empty. Actual effective routes own adoption and summaries; every model_supply row requires route_origin and effective chain_length, with null origin and false has_runnable_hop exactly for zero-length plans. Health remains a separate projection. New menu rows receive no key. |
+| **FC-06** | `agent-chain.schema.json` | AgentChain requires manual_override and route_origin and returns effective Source/model hops in planner order. Manual arrays remain exact; empty plans have null origin. Live current/runnable/blocker/retry annotations preserve the tier and membership. API-key inventory absence alone is not model_unsupported; subscriptions retain known-model admission; explicit retirement remains a blocker. Existing healthy/cooldown/backoff/action/process precedence remains unchanged, including native_cli_unavailable and waiting/interrupted relations. |
| **FC-07** | `observation-result.schema.json` + `probe-result.schema.json` | Keeps unsaved Add Source connectivity/protocol/inventory observation separate from saved-Route runtime probes. Add-flow results report classified reachability/authentication plus an observed protocol only after a real upstream response, never a credential ref or request/status evidence detail. A failed observation may request a manual three-value probe-order hint but cannot save a protocol without response proof. `ProbeResult` remains the configured-Route runtime domain; its distinct live backoff key for unclassified pre-output connection failure implies exactly `channel: hub`, `reachable: false`, and `latency_ms: null`, rejecting native probes and measured-latency results. **Probe relation revision: 2026-08-11 23:49; observation evidence expansion remains withdrawn by the 20:35 owner ruling.** |
-| **FC-08** | `turn-provenance.schema.json` | Gateway turn records contain no route-policy discriminator; they record exact requested/configured model ids, exact Source attribution, ordered attempts, and the closed outcome set owned by §4.5's authoritative Turn-outcome copy matrix. `requested_model_changed` is derived from those exact ids and is never persisted. The schema mirrors the outcome set without reproducing its branches. A canceled in-flight attempt carries no fabricated Source failure. No separate mapping field, compatibility discriminator, or internal-version conversion state exists. |
+| **FC-08** | `turn-provenance.schema.json` | Gateway turn records preserve exact requested/attempted model ids, Source attribution, order and closed outcomes from §4.5. `requested_model_changed` is derived from those exact ids and is never persisted. Historical versions 5 through 9 remain readable without requiring manual_override or route_origin. Canceled attempts fabricate no Source failure; no separate mapping or compatibility discriminator is persisted. |
| **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. |
| **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. |
-| **FC-11** | `opencode-overlay.md` | **Superseded 2026-09-04 by `model-hub.md` §4.8 v4 and `opencode-overlay.md` v4: OpenCode menu identity is the bare canonical model id, add-time matching is literal equality, and the overlay generates one provider per downstream protocol — no normalized provider ids anywhere.** Former shape: keeps stable normalized provider ids for menu identity and add-time match suggestions, supports the three protocols, and pins the exact configured Source/model hop per invocation. Runtime performs no provider matching, and no vendor metadata chooses a saved protocol. |
-| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, exact route GET/PUT, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting `route_replace` removal is ordinary success; only protected-supply interruption enters that guard. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |
-| **FC-13** | `migration-scan.schema.json` | Describes only the user-facing copy-only import of existing Claude, Codex, and OpenCode local configuration. Its action enum and one contract example/fixture per value mirror §6's authoritative Native-config import action matrix, including the `keep_native` default and the rejected/deferred `reauth` and `controlled_import` cases. Successful `keep_native` and `import` items run Add Source's one-time match and sole §4.2 placement policy, then report the same visible `added_to` positions. Originals are never modified or deleted, duplicate native selection fails before OAuth or partial commit, and it contains no Model Hub internal contract/data conversion. |
+| **FC-11** | `opencode-overlay.md` | OpenCode menu identity is bare canonical model id with server-owned native_protocol. The overlay generates one provider per downstream protocol. The shared planner uses literal inventory matching or unchanged-id Hub API-key passthrough, and invocation pins the selected effective Source/model pair; manual mappings remain exact. Overlay identity does not encode current Source, route origin, health or credentials. |
+| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, effective route GET/list, manual PUT, DELETE Restore and POST preview, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting `route_replace` removal is ordinary success; only protected-supply interruption enters that guard. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, second persisted route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |
+| **FC-13** | `migration-scan.schema.json` | Copy-only native config import uses the §6 action matrix. keep_native/import place Sources into backend defaults and report effective added_to positions without writing manual route keys. Original files remain byte-identical, duplicate native selection fails before OAuth/partial commit. Supported internal persisted shapes still use compatibility loading; import is a separate user workflow. |
| **FC-14** | `runtime-dependency.schema.json` | Defines the single local engine asset, immutable version/SHA, loopback binding, lifecycle/health, management and Gateway tokens, and fail-closed behavior. `installing` is exactly the unverified non-listening shape with null installed version; any verified/listening runtime settles outside that transition. Engine availability is local Gateway health and never mutates an upstream Source cooldown. This entry does not widen the GA asset-mirror or platform-matrix research scope. **Installing-shape revision: 2026-08-11 23:09 K4.** |
The final set contains no `subscription_hub_experimental`, `experimental_consent_at`,
@@ -915,19 +983,19 @@ collectively touch every applicable row and leave no downstream compatibility ta
| Landing point | Required result |
| --- | --- |
-| `config/v2_config.py` | Final Source/model/protocol/configured-route types, one canonical validation boundary shared by every persisted-Source writer and subsequent load, singleton and exact-pair uniqueness validation, one explicit Source order per backend and one explicit hops array per menu model, persisted discovered-model retirement plus the committed Source-create `client_nonce` column, serializer completeness, fresh-install Gateway construction, and existing-install-with-no-Hub-state Direct onboarding. No durable pre-create claim, receipt, digest, tombstone, terminal-envelope snapshot, plaintext key, or policy state exists. A committed nonce survives with its Source, Source deletion releases it, and the post-read same-nonce request creates a new id. Unclassified transport failure and live connection backoff never serialize into Source/config state. **Retirement/nonce/network revision: 2026-08-11 21:14 K4.** |
-| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 stored-chain executor and one Add Source implementation of §4.2's placement policy; the latter chooses and persists each matched hop position before returning `added_to`. Also owns the complete credential-failure matrix keyed by refresh capability, closed error classes, `adopted_by`, Source-global health, local-engine distinction, and all route/inventory guards. After K4, #1312, and K6 merge, I7 owns `resolver.py`, `classification.py`, and `tests/test_model_hub_resolution.py`: Add-time matching, inventory membership, new-Route validation, runnability, and invocation admit only `retired: false` rows; the network classifier executes every shaped/unclassified × `stream_started: false/true` cell at the first user-visible model-output boundary and alone owns live connection-backoff state. Only later output from the affected Source resets its streak; another Source's successful fallback does not. Before serialization, the read assembler normalizes an expired overlay to underlying non-backoff health. Concurrent cooldown, needs-action, error, missing-Source, or unsupported-model facts suppress a live overlay and keep the stronger projection; none may roll up as waiting. Simultaneous native-process unavailability is the sole exception and takes reason precedence while backoff health/deadline remains. `service.py` is the single shared guard planner for every matrix row; it recomputes and compares duplicate-free refusal arrays, emits SupplyGap rows in canonical `(backend, model_id)` order with stable-id-sorted `agents`, enforces each lead error's corresponding nonempty plan array, commits noninterrupting `route_replace` normally, and uses `source_last_supplier` only for interruption. It is also the sole AC-53 materialization decision owner: a failed terminal settlement attaches the exact nonempty acquisition-stage `interrupted_pairs` report only after persisted route impact, otherwise omitting the field. Discovered-model DELETE persists the retirement tombstone and refresh never revives it. Source-create reserves its nonce only in process before work, releases it only after retained-material reconciliation, atomically reclaims it after release, persists it only on success, and returns committed conflict for list-based reconciliation; process restart or deletion releases the live-only nonce and the post-read same-nonce request is a fresh create. Runtime never matches, places, substitutes, or writes a network health verdict. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
+| `config/v2_config.py` | Final Source/model/protocol/configured-route types, one canonical validation boundary shared by every persisted-Source writer and subsequent load, singleton and exact-pair uniqueness validation, one default Source order per backend and sparse manual hops overrides, persisted discovered-model retirement plus the committed Source-create `client_nonce` column, serializer completeness, fresh-install Gateway construction, and existing-install-with-no-Hub-state Direct onboarding. No durable pre-create claim, receipt, digest, tombstone, terminal-envelope snapshot, plaintext key, or policy state exists. A committed nonce survives with its Source, Source deletion releases it, and the post-read same-nonce request creates a new id. Unclassified transport failure and live connection backoff never serialize into Source/config state. **Retirement/nonce/network revision: 2026-08-11 21:14 K4.** |
+| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 effective-chain executor and one Add Source implementation of §4.2's placement policy; the latter persists default Source placement, then projects effective `added_to` without writing manual arrays. Also owns the complete credential-failure matrix keyed by refresh capability, closed error classes, `adopted_by`, Source-global health, local-engine distinction, and all route/inventory guards. After K4, #1312, and K6 merge, I7 owns `resolver.py`, `classification.py`, and `tests/test_model_hub_resolution.py`: Effective matching, new-Route validation, runnability, and invocation exclude explicit retired pairs; missing API-key inventory alone remains callable; subscription membership remains required; the network classifier executes every shaped/unclassified × `stream_started: false/true` cell at the first user-visible model-output boundary and alone owns live connection-backoff state. Only later output from the affected Source resets its streak; another Source's successful fallback does not. Before serialization, the read assembler normalizes an expired overlay to underlying non-backoff health. Concurrent cooldown, needs-action, error, missing-Source, or unsupported-model facts suppress a live overlay and keep the stronger projection; none may roll up as waiting. Simultaneous native-process unavailability is the sole exception and takes reason precedence while backoff health/deadline remains. `service.py` is the single shared guard planner for every matrix row; it recomputes and compares duplicate-free refusal arrays, emits SupplyGap rows in canonical `(backend, model_id)` order with stable-id-sorted `agents`, enforces each lead error's corresponding nonempty plan array, commits noninterrupting `route_replace` normally, and uses `source_last_supplier` only for interruption. It is also the sole AC-53 materialization decision owner: a failed terminal settlement attaches the exact nonempty acquisition-stage `interrupted_pairs` report only after persisted route impact, otherwise omitting the field. Discovered-model DELETE persists the retirement tombstone and refresh never revives it. Source-create reserves its nonce only in process before work, releases it only after retained-material reconciliation, atomically reclaims it after release, persists it only on success, and returns committed conflict for list-based reconciliation; process restart or deletion releases the live-only nonce and the post-read same-nonce request is a fresh create. Execution consumes the shared effective plan; it never reselects a tier or writes a network health verdict. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
| `modules/agents/model_hub.py`; Model Hub failure callbacks in `modules/agents/{base,claude_agent}.py`, `modules/agents/codex/{agent,event_handler}.py`, and `modules/agents/opencode/{agent,poll_loop}.py` | After K4, #1312, and K6 merge, I7 moves the native launch seam from persistent 30-second network cooldowns to AC-50's phase-aware decision. Each backend callback supplies exact failure shape and `stream_started`, which flips only at the first user-visible model-output byte; `modules/agents/model_hub.py` alone classifies and chooses persistent Source state, live connection backoff, or event-only handling. Exact cross-backend fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py` cover both phases and prove zero persistent write for unclassified transport failures; the post-output same-current-hop fixture consumes K6's G-34 outcome/copy/payload row exactly. `tests/{test_claude_cli_path,test_multi_platform_runtime}.py` receive only required signature adaptations. I2 owns the equivalent raw phase facts only for the managed Gateway. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
| `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py` | Vendor-specific OAuth defaults, duplicate-native rejection before adapter work, all-exit transient credential cleanup, durable revoke reconciliation, and pre-provider exact-tuple OAuth-start claim/coalescing/release/flow conversion and nonce echo. The registry releases only a failed/task-canceled start before a flow exists; it retains an explicitly canceled nonce-bearing committed flow as the same terminal `cancelled` flow until existing expiry, then releases the tuple. The row also owns the complete four-row native-config action matrix with original files untouched. Every imported Source passes the canonical final-shape validator before commit; no import writer bypasses it with direct dataclass construction. **OAuth explicit-cancel revision: 2026-08-12 00:37 K4.** |
-| `core/handlers/model_hub/{rpc,request,provenance,events}.py`, `vibe/ui_server.py`, `vibe/model_hub_client.py`, `core/controller.py` | Final API envelopes/routes mirror the guarded-mutation and guard-totality matrices, including current-plan refusal, exact plan-echo confirmation, empty-plan ordinary success, Source-delete, discovered-model retirement, ordinary noninterrupting Route replacement versus interrupted refusal, existing-chain reorder, runtime install/no-op, all three nonce-retry states, read-before-retry plus restart/deletion fresh-create behavior, nonce-bearing canceled-flow replay/expiry versus no-nonce forget, terminal materialization error/report totality, and live connection-backoff reads. `rpc.py`, `request.py`, `ui_server.py`, and `model_hub_client.py` only carry refusal plans when a refusal exists; they do not mint or persist confirmation state. For AC-53, `ui_server.py` and `model_hub_client.py` preserve an exact nonempty `interrupted_pairs` error member and omit it otherwise; they never synthesize `[]`, `flow`, or future-tense `would_interrupt` on an error. After K6, `events.py` transfers from I1 to I7 and records each network-totality cell without turning an unclassified failure into persistent state; unclassified interruption after user-visible model output is event-only. Provenance mirrors the complete K6-frozen turn-outcome matrix, including `canceled` and G-34's selected row, and never invents an outcome id, copy key, or payload shape. Direct-mode responses remain explicit. During implementation, absence of `VIBE_MODEL_HUB_ENABLED` keeps the controller/routes/UI disabled; explicit enablement must construct the v3 aggregate. This is a release-control gate, not a compatibility layer. I6 removes it only after I5 evidence is green. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
+| `core/handlers/model_hub/{rpc,request,provenance,events}.py`, `vibe/ui_server.py`, `vibe/model_hub_client.py`, `core/controller.py` | Final API envelopes/routes mirror the guarded-mutation and guard-totality matrices, including current-plan refusal, exact plan-echo confirmation, empty-plan ordinary success, Source-delete, discovered-model retirement, ordinary noninterrupting Route replacement versus interrupted refusal, guarded default-order update, runtime install/no-op, all three nonce-retry states, read-before-retry plus restart/deletion fresh-create behavior, nonce-bearing canceled-flow replay/expiry versus no-nonce forget, terminal materialization error/report totality, and live connection-backoff reads. `rpc.py`, `request.py`, `ui_server.py`, and `model_hub_client.py` only carry refusal plans when a refusal exists; they do not mint or persist confirmation state. For AC-53, `ui_server.py` and `model_hub_client.py` preserve an exact nonempty `interrupted_pairs` error member and omit it otherwise; they never synthesize `[]`, `flow`, or future-tense `would_interrupt` on an error. After K6, `events.py` transfers from I1 to I7 and records each network-totality cell without turning an unclassified failure into persistent state; unclassified interruption after user-visible model output is event-only. Provenance mirrors the complete K6-frozen turn-outcome matrix, including `canceled` and G-34's selected row, and never invents an outcome id, copy key, or payload shape. Direct-mode responses remain explicit. During implementation, absence of `VIBE_MODEL_HUB_ENABLED` keeps the controller/routes/UI disabled; explicit enablement must construct the v3 aggregate. This is a release-control gate, not a compatibility layer. I6 removes it only after I5 evidence is green. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
| `core/handlers/model_hub/adapter.py` | Exact byte mirror of `model-hub-contracts/adapter-interface.py`, including three protocols and observation/cleanup signatures. |
-| `core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**` | Exact stored-hop execution, three-protocol transport, credential refresh capability, authoritative `stream_started` facts at the first user-visible model-output byte, pre-output fallthrough, post-output no replay, and local Gateway failures at any request phase excluded from Source state and fallback. I2 transports raw phase/shaped-error evidence but does not own the network taxonomy, Source decision, or live-backoff executor transferred to I7. The runtime owns the persisted install worker/lease, orphan reconciliation, host detection, installed-state no-op, and the exact installing shape `{installed_version: null, verified: false, listening: null}` without owning HTTP routes. Turn copy is selected only from the K6-frozen authoritative outcome matrix after I7's state decision and live annotation of the same stored chain. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
-| `ui/src/components/settings/models/**` | Final Source/Gateway types and calls; protocol selector only after failed observation as a probe-order hint; Source cards reuse `adopted_by`; Add Source renders the stored backend Source order plus returned `added_to` positions without inferring newness from order; state ⑤ alone emits `accept_unavailable_inventory: true`, while clean creation and pull-origin state ⑤′ omit it; backend groups consume `supply_status`; takeover derives from the chain; saved Source details exposes only guarded Refresh models; Direct groups expose reversible mode actions. For frame 02, I4's current increment opens the editor from each model row, renders the drawing, and consumes the chain read projection only: it wires no chain-write caller and keeps Save disabled. Exact stored-hop/mapping editing and exact two-array plan echo belong to I4's second increment after K5 round 3 and I7 refusal fixtures merge. Live connection-backoff presentation also belongs to the second increment after K5 round 2 corrects its UI-spec copy and I7 freezes producer fixtures. AC-53 error-gap rendering likewise belongs to the second increment after K5 round 2 registers E6 and I7 freezes positive/negative payloads; `modelsApi.ts` carries only an actually present nonempty `interrupted_pairs`, and `OAuthConnectDialog.tsx` refetches Source state after the materialization error. The current increment consumes master's pre-I7 refusal shape and must not add inactive confirmation fields. K5 round 2 separately removes the withdrawn observation request/status detail slots. The current increment also consumes the already-specified install/unsupported-host states; the second consumes the remaining K4 projections/actions only after their named K5 round-2 upgrades. **Materialization-response revision: 2026-08-12 01:28 by PM ruling.** No bottom-only “new” section, policy control, “not enabled” hint, latency/last-check copy, separate experimental-consent surface, separate mapping object, takeover field, supplying-backends field, or vendor default protocol exists. Any new-item marker is transient presentation state, not a route field. `vendorMeta.ts` may order probes but cannot choose a saved protocol. Narrowing `SourceProtocol` must be checked against production and test files, not only the production-only `tsconfig.app.json` program. |
+| `core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**` | Exact effective-hop execution, three-protocol transport, credential refresh capability, authoritative `stream_started` facts at the first user-visible model-output byte, pre-output fallthrough, post-output no replay, and local Gateway failures at any request phase excluded from Source state and fallback. I2 transports raw phase/shaped-error evidence but does not own the network taxonomy, Source decision, or live-backoff executor transferred to I7. The runtime owns the persisted install worker/lease, orphan reconciliation, host detection, installed-state no-op, and the exact installing shape `{installed_version: null, verified: false, listening: null}` without owning HTTP routes. Turn copy is selected only from the K6-frozen authoritative outcome matrix after I7's state decision and live annotation of the same effective chain. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
+| `ui/src/components/settings/models/**` | Final Source/Gateway types and calls; protocol selector only after failed observation as a probe-order hint; Source cards reuse `adopted_by`; Add Source renders the stored backend Source order plus returned `added_to` positions without inferring newness from order; state ⑤ alone emits `accept_unavailable_inventory: true`, while clean creation and pull-origin state ⑤′ omit it; backend groups consume `supply_status`; takeover derives from the chain; saved Source details exposes only guarded Refresh models; Direct groups expose reversible mode actions. For frame 02, I4's current increment opens the editor from each model row, renders the drawing, and consumes the chain read projection only: it wires no chain-write caller and keeps Save disabled. Exact stored-hop/mapping editing and exact two-array plan echo belong to I4's second increment after K5 round 3 and I7 refusal fixtures merge. Live connection-backoff presentation also belongs to the second increment after K5 round 2 corrects its UI-spec copy and I7 freezes producer fixtures. AC-53 error-gap rendering likewise belongs to the second increment after K5 round 2 registers E6 and I7 freezes positive/negative payloads; `modelsApi.ts` carries only an actually present nonempty `interrupted_pairs`, and `OAuthConnectDialog.tsx` refetches Source state after the materialization error. The current increment consumes master's pre-I7 refusal shape and must not add inactive confirmation fields. K5 round 2 separately removes the withdrawn observation request/status detail slots. The current increment also consumes the already-specified install/unsupported-host states; the second consumes the remaining K4 projections/actions only after their named K5 round-2 upgrades. **Materialization-response revision: 2026-08-12 01:28 by PM ruling.** No bottom-only “new” section, redundant policy control, “not enabled” hint, latency/last-check copy, separate experimental-consent surface, separate mapping object, takeover field, supplying-backends field, or vendor default protocol exists. Any new-item marker is transient presentation state, not a route field. `vendorMeta.ts` may order probes but cannot choose a saved protocol. Narrowing `SourceProtocol` must be checked against production and test files, not only the production-only `tsconfig.app.json` program. |
| `ui/src/i18n/{en,zh}.json`, `vibe/i18n/{en,zh}.json` | Exact mirrored final reason/detail and `supply_status` keys, including `native_cli_unavailable` and `route_unconfigured`; every Turn-outcome copy-matrix key; the derived takeover label; distinct Direct/Native terms; the sole Claude Hub warning; compact protocol-observation failure copy; and no retired policy, separate experimental-consent, or mechanism-copy keys. After K5 round 2's UI-spec sync, I4's second increment adds the distinct short connection-backoff copy for `models.source.backoff.connection_failed`; it never reuses quota-cooldown wording. A registry-generated guard compares closed outcome/discriminator, blocker/remedy, and credential-remedy relations with both locale sets. |
| `tests/test_model_hub_config.py` | The adapter parity and terminal-version gates remain exact; round-trip/completeness fixtures use only final Source and route shapes. It validates committed Source `client_nonce` persistence and live-only uniqueness, deletion release, rejects durable claim/receipt/digest/tombstone fields and unregistered observation evidence, and mechanically closes OAuth cancel totality: pending-start cancellation releases, explicit nonce-bearing cancellation retains the same terminal flow until expiry, no-nonce cancellation forgets, and the old blanket-forget promise is absent. It proves live backoff cannot serialize as Source state, rejects pure cooldown/backoff chains mislabeled `interrupted`, and keeps durable/capability blockers interrupted under a concurrent deadline. D21 compares AgentChain, ProbeResult, the API marker, and both UI locales individually, with a ProbeResult mutation that must break equality. D22 proves the same five OAuth terminal decision ids exist exactly once in authority and API, success re-auth may carry an empty complete report, materialization errors carry an exact nonempty report if and only if persisted acquisition impact exists, and every other error omits the member. The narrow K4 ledger assertion binds AC-52 and the I3/auth-setup landing row to AUTH-SETUP-109, its two exact scenario files, the pre-adapter negative cells, the provider-once positive cell, the terminal repair projection, and the K4+#1312 activation edge. The same fixture rejects zero-length model supply marked runnable, each installing-shape contradiction, every guard error paired with an empty required plan array, duplicate hop/gap plan entries, and any credential response that revives the OAuth-only repair tail. The K4 AC-54 fixture validates the optional boolean, rejects non-booleans, and freezes every repeat-observation × consent row plus its owner/files/activation handoff. K6 never owns this file; after K6 freezes G-34, I7 adds the mechanical matrix/schema consumer fixture under the three-way activation edge. **Turn-outcome handoff revision: 2026-08-12 02:00 K4.** |
-| `tests/test_model_hub_api.py` | The current line-1204 `experimental_consent_at` assertion becomes an absence assertion; API fixtures cover unique final model entries, edited-effort and retirement preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, all three pre-observation nonce retry states, deterministic policy-chosen Add Source placement with the returned persisted position, and every guarded-mutation row. OAuth API fixtures prove nonce-bearing explicit cancel retains the same `cancelled` flow and exact-tuple retry performs zero provider starts, existing expiry releases it for one fresh start, and no-nonce cancel forgets. Terminal materialization fixtures prove a native re-auth failure after acquisition has stranded at least one sibling emits that exact nonempty `interrupted_pairs` in the standard error envelope with no `flow`; the same materialization error with no gap and every non-materialization error omit the member rather than sending `[]`. Successful terminal re-auth keeps the complete array and may send `[]`. Guard fixtures cover every totality cell: unforced empty/nonempty plans, forced nonempty exact/missing/different plan echoes, and a forced request whose old nonempty echo recomputes to an empty plan. They prove every exactly confirmed nonempty plan commits once, every other nonempty forced plan returns the current refusal without removing a hop, every empty plan follows ordinary success, a noninterrupting `route_replace` removal succeeds once without 409, an interrupting replacement refuses with `source_last_supplier`, every produced guard code has its schema-required nonempty evidence array, every produced plan array is duplicate-free, and permuted guard inputs emit canonically ordered SupplyGap rows and agent ids. Source-create fixtures prove process-local pre-work reservation, read-before-retry, in-progress conflict/no work, released atomic reserve/exactly one fresh attempt including after restart, committed conflict plus list lookup of exactly one nonce-bearing Source, AC-26 pending-revocation settlement, and Source-delete release followed by same-nonce fresh creation with a new id and one upstream attempt. AC-54 adds repeated-observation fixtures for failed inventory with omitted/false rejection, true empty-inventory commit, successful rediscovery with stale true, and protocol-unproved rejection regardless of the flag. Observation fixtures reject request/status evidence not present in the six-field contract. Network fixtures cover all four shaped/transport × `stream_started: false/true` cells at the first user-visible model-output boundary, same-Source output reset, other-Source fallback non-reset, clocked future/expired read assembly, bounded auto-clearing live backoff, and zero config writes for unclassified failures. Concurrent-transition fixtures overlay an active deadline with healthy, cooldown, needs-action, error, missing-Source, unsupported-model, and unavailable-native facts: only healthy/capability-present hops project ordinary backoff; durable/capability blockers keep their established projection and `interrupted`; the native exception preserves deadline with reason priority. Probe payload fixtures cover the exact Hub/unreachable/null-latency relation. Credential PUT payloads use only the standard guarded Source envelope; the OAuth repair tail remains flow-only. AgentSupply fixtures prove the valid `{chain_length: 0, has_runnable_hop: false}` pair, reject the corresponding true pair, and prove pure process-available cooldown/backoff chains are waiting rather than interrupted. The same file covers Source deletion from all backend Source orders and routes with survivor order preserved, discovered retirement, existing-chain reorder, exact installing shape plus runtime install/no-op, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. **OAuth terminal fixture revision: 2026-08-12 01:28.** |
-| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | After K6 merges, `tests/test_model_hub_resolution.py` transfers to I7 and proves `retired: false` filtering in Add-time matching, inventory membership, new-Route validation, runnability, and invocation plus the complete network-classification/live-backoff table; I2 retains runtime/l3 files and supplies exact managed-Gateway raw shaped/transport facts and `stream_started` phase at the first user-visible model-output byte without owning state decisions, while I3 retains OAuth. Together they cover sole §4.3 stored-chain consumption, no runtime matching or substitution branch, exact effort membership, every K6-frozen turn-outcome/copy row including G-34, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, persisted install/restart/no-op behavior, canceled provenance, vendor OAuth defaults, and OAuth nonce released/in-flight/committed totality with pre-provider claim, concurrent coalescing, cleanup release, atomic flow conversion, echo, explicit canceled-flow replay with provider-zero, and expiry-triggered fresh start. Until I7 lands AC-50, only `test_probe_transport_failures_await_ac50_backoff_contract` carries the corrected narrow authorization: it already asserts the future `connection_failed` live-backoff projection and zero Source/config writes under strict xfail, while `test_chain_projection_and_probe_latency_partition` and all unrelated assertions remain active. I7's first mechanical action deletes only that marker in the same commit that makes these forward assertions XPASS; an accidental early implementation is therefore a failing XPASS. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **5** through #1312; afterward I2 owns that file's runtime updates except for the one deletion. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
-| `ui/src/components/settings/models/**/*.test.*` | No protocol control on the normal add flow, honest manual probe-order fallback, final inventory editing, visible and adjustable backend Source order plus policy-chosen Add Source placement, no position-based newness or bottom-only new section, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no policy/not-enabled/latency or separate experimental-consent surface. Under the 2026-08-11 18:10 PM ruling, the current-increment frame-02 fixture proves that a model row opens the drawn editor, renders the chain read projection, keeps Save disabled, and emits no chain mutation. Exact configured-chain editing and its save/refusal/reconciliation tests are second-increment obligations after K5 round 3 and I7 fixtures merge; a visible noninterrupting hop removal sends one ordinary PUT with no wire confirmation, while a protected-supply interruption echoes both returned refusal arrays, replaces the displayed plan when either differs after recomputation, and never forces a nonempty plan without an exact echo. The Add Source client reads Sources before a lost-response retry and treats a released nonce as fresh. Only state ⑤ sends `accept_unavailable_inventory: true`; clean creation, every retry that has not received that consent, and pull-origin state ⑤′ omit it. After K5 round 2 and I7 fixtures, the same second increment proves live connection backoff uses its distinct short-delay copy rather than quota cooldown copy; K5 round 2 removes the withdrawn observation request/status slots. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |
+| `tests/test_model_hub_api.py` | The current line-1204 `experimental_consent_at` assertion becomes an absence assertion; API fixtures cover unique final model entries, edited-effort and retirement preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, all three pre-observation nonce retry states, deterministic policy-chosen Add Source placement with the returned persisted position, and every guarded-mutation row. OAuth API fixtures prove nonce-bearing explicit cancel retains the same `cancelled` flow and exact-tuple retry performs zero provider starts, existing expiry releases it for one fresh start, and no-nonce cancel forgets. Terminal materialization fixtures prove a native re-auth failure after acquisition has stranded at least one sibling emits that exact nonempty `interrupted_pairs` in the standard error envelope with no `flow`; the same materialization error with no gap and every non-materialization error omit the member rather than sending `[]`. Successful terminal re-auth keeps the complete array and may send `[]`. Guard fixtures cover every totality cell: unforced empty/nonempty plans, forced nonempty exact/missing/different plan echoes, and a forced request whose old nonempty echo recomputes to an empty plan. They prove every exactly confirmed nonempty plan commits once, every other nonempty forced plan returns the current refusal without removing a hop, every empty plan follows ordinary success, a noninterrupting `route_replace` removal succeeds once without 409, an interrupting replacement refuses with `source_last_supplier`, every produced guard code has its schema-required nonempty evidence array, every produced plan array is duplicate-free, and permuted guard inputs emit canonically ordered SupplyGap rows and agent ids. Source-create fixtures prove process-local pre-work reservation, read-before-retry, in-progress conflict/no work, released atomic reserve/exactly one fresh attempt including after restart, committed conflict plus list lookup of exactly one nonce-bearing Source, AC-26 pending-revocation settlement, and Source-delete release followed by same-nonce fresh creation with a new id and one upstream attempt. AC-54 adds repeated-observation fixtures for failed inventory with omitted/false rejection, true empty-inventory commit, successful rediscovery with stale true, and protocol-unproved rejection regardless of the flag. Observation fixtures reject request/status evidence not present in the six-field contract. Network fixtures cover all four shaped/transport × `stream_started: false/true` cells at the first user-visible model-output boundary, same-Source output reset, other-Source fallback non-reset, clocked future/expired read assembly, bounded auto-clearing live backoff, and zero config writes for unclassified failures. Concurrent-transition fixtures overlay an active deadline with healthy, cooldown, needs-action, error, missing-Source, unsupported-model, and unavailable-native facts: only healthy/capability-present hops project ordinary backoff; durable/capability blockers keep their established projection and `interrupted`; the native exception preserves deadline with reason priority. Probe payload fixtures cover the exact Hub/unreachable/null-latency relation. Credential PUT payloads use only the standard guarded Source envelope; the OAuth repair tail remains flow-only. AgentSupply fixtures prove the valid `{chain_length: 0, has_runnable_hop: false}` pair, reject the corresponding true pair, and prove pure process-available cooldown/backoff chains are waiting rather than interrupted. The same file covers Source deletion from all backend Source orders and routes with survivor order preserved, discovered retirement, guarded default-order update, exact installing shape plus runtime install/no-op, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. **OAuth terminal fixture revision: 2026-08-12 01:28.** |
+| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | After K6 merges, `tests/test_model_hub_resolution.py` transfers to I7 and proves `retired: false` filtering in Effective planning, manual validation, runnability, and invocation plus the complete network-classification/live-backoff table; I2 retains runtime/l3 files and supplies exact managed-Gateway raw shaped/transport facts and `stream_started` phase at the first user-visible model-output byte without owning state decisions, while I3 retains OAuth. Together they cover sole §4.3 effective-chain consumption, one shared effective planner, with no duplicate matching or substitution branch, exact effort membership, every K6-frozen turn-outcome/copy row including G-34, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, persisted install/restart/no-op behavior, canceled provenance, vendor OAuth defaults, and OAuth nonce released/in-flight/committed totality with pre-provider claim, concurrent coalescing, cleanup release, atomic flow conversion, echo, explicit canceled-flow replay with provider-zero, and expiry-triggered fresh start. Until I7 lands AC-50, only `test_probe_transport_failures_await_ac50_backoff_contract` carries the corrected narrow authorization: it already asserts the future `connection_failed` live-backoff projection and zero Source/config writes under strict xfail, while `test_chain_projection_and_probe_latency_partition` and all unrelated assertions remain active. I7's first mechanical action deletes only that marker in the same commit that makes these forward assertions XPASS; an accidental early implementation is therefore a failing XPASS. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **9** through #1312; afterward I2 owns that file's runtime updates except for the one deletion. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
+| `ui/src/components/settings/models/**/*.test.*` | No protocol control on the normal add flow, honest manual probe-order fallback, final inventory editing, visible and adjustable backend Source order plus policy-chosen Add Source placement, no position-based newness or bottom-only new section, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no redundant policy/not-enabled/latency or separate experimental-consent surface. Under the 2026-08-11 18:10 PM ruling, the current-increment frame-02 fixture proves that a model row opens the drawn editor, renders the chain read projection, keeps Save disabled, and emits no chain mutation. Exact configured-chain editing and its save/refusal/reconciliation tests are second-increment obligations after K5 round 3 and I7 fixtures merge; a visible noninterrupting hop removal sends one ordinary PUT with no wire confirmation, while a protected-supply interruption echoes both returned refusal arrays, replaces the displayed plan when either differs after recomputation, and never forces a nonempty plan without an exact echo. The Add Source client reads Sources before a lost-response retry and treats a released nonce as fresh. Only state ⑤ sends `accept_unavailable_inventory: true`; clean creation, every retry that has not received that consent, and pull-origin state ⑤′ omit it. After K5 round 2 and I7 fixtures, the same second increment proves live connection backoff uses its distinct short-delay copy rather than quota cooldown copy; K5 round 2 removes the withdrawn observation request/status slots. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |
| `tests/scenarios/auth_setup/{catalog.yaml,test_auth_setup_scenarios.py}` | After K4 and #1312 merge, I3 owns AUTH-SETUP-210 and AUTH-SETUP-109. AUTH-SETUP-210 blocks the first OAuth-start provider call, loses that caller's response, overlaps a same-nonce retry that coalesces to the same terminal flow/provider, then asserts provider start exactly once. AUTH-SETUP-109 selects a Hub-held Source and proves missing and false re-auth acknowledgement return `reauth_confirmation_required` before any adapter/provider call, true acknowledgement starts exactly one Hub flow, and terminal status plus repair projection agree. Pending-start failure/task-cancellation release and committed-flow replay cover the other nonce rows; I3 unit/API fixtures separately prove explicit canceled-flow replay starts no provider and expiry permits exactly one fresh start. I5 consumes both completed scenarios but does not edit either file. **Hub re-auth scenario binding revised 2026-08-12 01:30 by PM ruling.** |
| `tests/scenarios/model_hub/**`, `tests/scenario_harness/model_hub_native_oauth.py` | End-to-end final-shape setup, all four native-import action rows, reversible Direct/Gateway onboarding, subscription custody, protocol observation, one-time add matching plus deterministic persisted placement, exact configured route execution and mapping, guarded saved refresh and Source-delete envelopes, silent successful takeover, truthful blocked/native/engine terminal copy, and exhaustion failure without takeover semantics. The I3-owned migration scenario validates each imported Source, serializes the full result, and reloads it through the same canonical validator. |
@@ -1655,59 +1723,40 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/README.md`, [thread](htt
**Acceptance.** Contract layer, owed by **L1**. A harness generated purely from the registry rows — with no hand-written supplements — runs both relations: the reason ↔ `detail_key` bijection in both directions, and `resolution-event.agent` ⊆ home set ∪ `{system}`. Three mutations are caught by that generated harness: deleting one `detail_key` from either side; **swapping two `detail_key`s between reasons in one file while leaving M4's `pairs` list alone** (07-29, review round 3 — the case a set-only bijection cannot see, and the one that ships wrong copy to a real user); and adding an undeclared value to `resolution-event.agent`, whose enum already holds four, `claude`/`codex`/`opencode`/`system`, so the test adds a fifth. Fails today: M4 reads `none` and M6 omits the field, so a faithful generator emits neither check and still reports the registry fully covered.
-### AC-22 — Make one ordered per-model route chain the only Gateway routing model
-
-**Owner rulings 2026-08-07 and 2026-08-09 S-1.** Per-model ordering remains in scope,
-but `follow | custom` does not. Every `(backend, menu model)` stores one ordered `hops`
-array of exact `(source_id, model_id)` pairs. Add Source matches once and writes those
-pairs; the Gateway UI edits the same configuration; runtime walks it verbatim.
-
-**Acceptance.** Config, schema, API, and UI contain one persisted backend Source order
-and no placement-policy or route-policy discriminator, missing-row default, separate
-mapping object, or runtime Source/model matching branch. Every menu model owns an explicit
-`hops` array, including an empty array for an unconfigured route. For every accepted
-Add/import match, fixtures assert that §4.2's sole placement policy chooses one
-deterministic position, the transaction persists and returns that position, the Gateway
-shows it, and the user can adjust it.
-They do not assert the current policy's concrete position. Existing Source-order entries
-and hops preserve their relative order, no “not enabled” state is emitted, and
-refresh/catalog/runtime paths never rerun placement. Explicit edits preserve submitted
-order and model ids and cannot change another menu model.
-
-A table-driven runtime suite executes the normative §4.3 pseudocode against the stored
-array. It fails any implementation that normalizes a provider, walks inventory to pick a
-model, prepends Native, or otherwise constructs a second chain. Every hop is rechecked
-only for live runnability immediately before its turn. Exact configured reasoning-effort
-membership is honored. Credential fixtures execute every authoritative matrix row;
-fallthrough follows stored order, and a static-key `401` makes no duplicate request.
-
-Turn fixtures execute every §4.5 outcome row: a nonempty all-blocked chain produces
-`no_candidate` with its actual blockers; an empty chain produces `route_unconfigured`;
-`native_cli_unavailable` is `interrupted`; local engine loss before the request,
-mid-request, and after streamed output is terminal `engine_down` with no Source mutation,
-replay, or next-hop walk; streamed Source failures persist attributable state without
-replay; retry copy appears only when the next turn's same stored chain has a different
-current hop.
-
-Source-card attribution consumes `adopted_by: [{backend, menu_model}]`. The backend
-subtitle and Usage page consume the exact four-value `supply_status`; no independent
-walk or parallel prose status exists. Takeover derives from the stored first hop and
-live current position without a field.
-
-Mutation fixtures cover non-forced exact-hop refusal, confirmed cascade with survivor
-order intact, background stale-hop retention, and the forced Source-delete success
-envelope. Deletion removes the Source id from every backend Source order and Route chain
-in the same transaction and the result passes canonical serialization/reload validation. No path
-substitutes another model or claims invalidated supply survived.
-
-Fresh installs write `mode: "hub"`; existing installations with no Model Hub state
-start in `direct`. Until I5's evidence is merged, absence of `VIBE_MODEL_HUB_ENABLED`
-keeps the controller, API, and Models UI disabled; I1 proves the v3 aggregate only under
-explicit enablement, and I6 later deletes the gate in one ownership transfer. A newly introduced menu model gets an explicit empty route and is
-not retroactively matched. Historical AC-5/AC-8 mapping fixtures are non-executable;
-I1 replaces their guard intent with configured-route fixtures. The final no-parallel-
-mapping shape remains owner-vetoable; a veto blocks I1 rather than reviving two route
-authorities.
+### AC-22 — Preserve sparse intent through one effective route planner
+
+**Current authority: routing modes, 2026-09-06.** A backend owns default membership/order
+and sparse manual overrides. Key absence inherits; key presence preserves exact submitted
+hops, including empty and equal-to-automatic arrays. No second persisted policy flag or
+separate mapping object exists. Existing supported persisted arrays, including stale and
+dormant records, load without historical-authorship inference; new catalog rows have no key.
+
+**Acceptance.** One pure planner selects manual, matching defaults, or unchanged-id
+passthrough. Every read/preview/summary/guard/adoption/probe/launch/execution consumer agrees
+on exact pairs and origin. A matched tier never gains speculative passthrough, and
+invocation-channel/health restrictions never create a different tier. The native Claude
+parser is reused; other backends and API Sources use literal ids. Explicit retirement is
+an exclusion; API-key inventory is not an invocation whitelist. Subscriptions retain
+known-model admission, stale-hop retention and existing errors. Unmatched subscription-only
+defaults remain Unconfigured.
+
+Runtime executes planned hops in order and retains every credential/failure/streaming
+matrix property. Source health remains global; unknown-model request errors are nonfallback
+and do not mutate it. Exact inventory reasoning declarations alone allow forwarding effort.
+Takeover/current/supply are live projections separate from route origin. No second matching
+algorithm exists in frontend, guards, probes or runtime adapters.
+
+Preview has no persistence, event, credential, engine or egress effect. Save PUT persists
+manual intent; Restore DELETE removes it; both use canonical mutation results and existing
+guard protocols. Default Sources PUT and compatibility reorder preserve manual arrays and
+guard effective removals/supply loss. Source deletion atomically removes references while
+preserving survivors. Manual inventory deletion removes evidence without deleting explicit
+routes. Fixtures preserve unrelated config and historical TurnProvenance across reload.
+
+Fresh installations retain Hub defaults; existing installations without Hub state retain
+Direct onboarding. Native binding/custody, backend catalog admission, OpenCode native
+protocol declarations and source isolation remain enforced. RM-1 through RM-11 supply the
+cross-layer evidence, including pinned CPA and actual upstream model/source capture.
### AC-23 — Make subscription custody vendor-specific with a native singleton
@@ -1849,9 +1898,9 @@ user-authored model deletion stage inventory and run AC-22's exact-hop **and** p
guards before committing. Their JSON bodies and canonical guarded/success responses
mirror their rows in FC-12; force-cascade fixtures cover each mutation. Native CLI
and Hub OAuth re-auth instead
-use AC-2's pre-login acknowledgement and retain newly invalid hops as visible,
-non-runnable entries with exactly `reason: "model_unsupported"` and `retry_at: null`
-after the irreversible exchange.
+use AC-2's pre-login acknowledgement and report actual effective supply changes after
+the irreversible exchange. Missing API-key inventory alone does not invalidate a manual target;
+explicit retirement and credential/channel blockers retain their existing reasons.
UI evidence covers loading, reachable, authentication failure, discovery failure,
empty result, merge result, manual add, all-inventory reasoning-efforts list editing
with an empty/no-default state, guarded removal, and mobile treatment. The control form
@@ -1946,20 +1995,13 @@ configuration, and leaves native config byte-identical. UI and locale guards res
Direct for `mode: direct`, reserve Native for `native_cli` hops, and reject “not through
Gateway” mechanism copy.
-### AC-32 — Keep route selection stable while live runnability changes
+### AC-32 — Separate effective planning from live runnability
-**Owner S-1 transfer, 2026-08-09.** Add-time matching and placement write visible
-configuration. Runtime may inspect whether an exact stored hop can execute now, but it
-may not choose different route membership or order from hidden live inputs.
-
-**Acceptance.** Given byte-identical persisted Model Hub configuration and an identical
-turn request, the ordered `(source_id, model_id)` Route selected for execution is
-byte-identical even when wall-clock time, Source quota, Source health, or native-process
-availability differs. Those live inputs may change only each stored hop's
-`runnable/reason/retry_at` annotation and the current execution position; they may
-neither add, remove, reorder, remap, nor substitute a hop. A behavior-level test runs
-the same configuration/request against changed live inputs and compares membership and
-order before inspecting the permitted annotations.
+**Acceptance.** Identical planning inputs yield identical ordered pairs and origin across
+time, quota, health, native readiness and request transport restrictions. These live facts
+only annotate runnability, current position, reasons and retry time. Manual intent survives
+unrelated configuration/catalog changes; automatic routes follow changed defaults/evidence.
+A behavior fixture compares the plan first, then the permitted live annotations.
### AC-33 — Generate the authority closure from live inputs
@@ -2017,20 +2059,14 @@ confirmed success retains the row and excludes it from supply. The generated sam
closure also proves that no Source-model request body repeats `source_id`; this is a
derived check, not a copied occurrence count.
-### AC-35 — Preserve the G-9 Source-order tombstone
-
-**Acceptance.** For a fixture with at least two nonempty stored Routes, every successful
-`PUT /api/models/agents/<backend>/sources` changes and re-echoes only
-`sources.order`. Before/after Route documents are byte-identical, and the route exposes
-no `force`, guarded `409`, `would_remove_hops`, or `would_interrupt` branch. The API
-route table and §4.5 explicitly keep this write outside the exhaustive Source-mutation
-matrix.
+### AC-35 — Guard default routing without rewriting manual intent
-**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns
-`core/handlers/model_hub/{service,rpc,request}.py`, `vibe/{ui_server,model_hub_client}.py`,
-and `tests/test_model_hub_api.py` for the byte-before/after Route fixture. There is no
-I4 write consumer. After that fixture freezes, I5 consumes it in
-`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.
+**Acceptance.** Sources PUT and compatibility chains/reorder update only backend default
+membership/order. Every manual array remains byte-identical. Before/after effective plans
+drive the exact existing removal/supply guard; confirmed writes require both echoed arrays.
+Pure reorder without removal needs no confirmation. Omitted reorder order is read-only.
+Success returns canonical AgentSupply, and the frontend consumes it before refreshing chains.
+RM-5 covers refusal, stale confirmation, fresh confirmation and atomic persistence.
### AC-36 — Expose G-11 CLI installation presence per backend
@@ -2331,7 +2367,7 @@ canceled flow with zero provider starts. Clocked expiry releases the tuple, and
same-tuple retry afterward starts exactly one fresh flow. Explicit cancellation without
a nonce forgets the flow. A different tuple cannot resolve to the retained flow, and a
new user action always generates a new nonce. This zero-new-concept closure keeps
-`contract_version: 5` under the PM ruling of 2026-08-12 00:37.
+`contract_version: 9` under the PM ruling of 2026-08-12 00:37.
The contract fixture accepts a nonce-bearing flow with a date-time expiry, rejects that
same flow with `expires_at: null`, and accepts the null expiry after `client_nonce` is
@@ -2497,7 +2533,7 @@ acknowledgement permits exactly one ordinary re-auth start. The rule does not ex
transactional API-key replacement through `PUT /credential`. A negative Hub fixture and
the corresponding native fixture prove zero adapter calls; positive fixtures prove both
channels cross the same server boundary. This additive pre-release correction keeps
-`contract_version: 5` under the PM ruling of 2026-08-12 00:15.
+`contract_version: 9` under the PM ruling of 2026-08-12 00:15.
**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns
`core/handlers/model_hub/{service,rpc,request,errors}.py`,
@@ -2594,7 +2630,7 @@ producer.
### Post-consolidation review ledger — sealed 2026-08-08
The orchestrator-authorized consolidation commit closes the constructive prose loop.
-The 2026-08-09 owner rulings explicitly reopen the no-migration final shape,
+The 2026-09-06 routing contract supersedes the former no-migration premise,
response-observed protocol, enumerated 18-thread closeout, and the two narrowed UI-lane
AC handoffs routed by the owner; they do not repeal the seal for review-generated scope.
After that head, a review finding permits a normative-text edit only when it identifies
@@ -2628,7 +2664,7 @@ architecture inputs to S-1, not sealed-ledger deferrals.
| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. I1 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) |
| **Assign the actual auth-setup scenario file**<br><br>Fresh evidence after the recorded auth-scenario thread is the repository layout: repo-wide search finds the harness at `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`, while this lane assigns the nonexistent `tests/test_auth_setup_scenarios.py`. Because I5 owns only the Model Hub scenario tree, the real closed-loop OAuth/setup test remains outside every active lane and can stay stale while the listed work completes; correct the path and ownership here and in the landing ledger.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I3 |
| **Assign the shared backend launch seam to an active lane**<br><br>**Closed by PM rulings 2026-08-11 22:37 and 2026-08-12 02:00.** Through #1312, I1 owns `modules/agents/model_hub.py`. After K4, #1312, and K6 merge, I7 exclusively owns that shared classification/state seam plus the narrow Model Hub failure callbacks in Claude, Codex, and OpenCode. Backend callbacks supply raw failure shape and exact `stream_started` phase, whose boundary is the first user-visible model-output byte; I7 removes the native 30-second persistent network cooldown and implements AC-50's live-backoff/event-only totality, consuming K6's G-34 Turn-outcome row for the post-output same-current-hop case. I2 retains only managed-Gateway raw phase facts. Exact cross-backend phase fixtures and mechanical signature consumers are named in the binding table and landing checklist, leaving one active owner and one three-way activation edge.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 + AC-50 | `modules/agents/model_hub.py`; Model Hub callbacks in `modules/agents/{base,claude_agent}.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`; `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server,test_claude_cli_path,test_multi_platform_runtime}.py` | I7 after K4 + #1312 + K6 merge |
-| **Specify the add-time model matching algorithm**<br><br>**Closed by owner ruling 2026-08-09: `matching-v1`. Amended 2026-09-04 (§4.2, §4.8 v4): the OpenCode branch — exact checked identifier or unique bare-suffix match — is retired; OpenCode menu ids match by literal model-id equality exactly like Codex.** The Add Source path transcribes the former resolver semantics: Claude native aliases use discovered-only inventory and the deterministic `(version_tuple, date_or_zero, model_id)` maximum; OpenCode (v4), Codex, and non-native sources use literal equality. The stored hop is the concrete upstream id and runtime never repeats matching. | AC-22 | `model-hub.md` §4.2 `matching-v1`, `opencode-overlay.md`, `api.md`, `core/handlers/model_hub/{service,resolver}.py`, and backend fixtures in `tests/test_model_hub_{api,resolution}.py` | I1 |
+| **Specify one effective model planner.** Manual overrides win; otherwise eligible defaults provide complete non-retired matching evidence before unchanged-id Hub API-key passthrough. Reuse native Claude alias/version/date parsing; every other backend/API Source matches literal ids. | AC-22 + AC-32 | `model-hub.md` §4.2, D26/D27, API/adapter/schema and backend consumer fixtures | Backend + spec lanes |
| **Assign the controller gate removal to I1**<br><br>Fresh evidence beyond the resolved default-off thread is that this landing row promises an available Models controller but assigns only handler files and `vibe/ui_server.py`; neither the active lane scopes nor the complete checklist includes `core/controller.py` or `tests/test_controller_model_hub_gate.py`. The current controller returns early when `VIBE_MODEL_HUB_ENABLED` is absent, and that test explicitly expects `model_hub_runtime is None`, so I1 can satisfy every named file/test while fresh installations still have no runtime. Add the controller and its gate test to I1's owned transition.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L145-L147) | AC-22 + AC-31 | `core/controller.py`; `tests/test_controller_model_hub_gate.py` | I1 |
**Forward stop.** After the S-1 head, if a review reports at least three findings in the same
diff --git a/docs/plans/model-hub-routing-modes.md b/docs/plans/model-hub-routing-modes.md
new file mode 100644
index 000000000..6691b348c
--- /dev/null
+++ b/docs/plans/model-hub-routing-modes.md
@@ -0,0 +1,371 @@
+# Model Hub Routing Modes: Implementation Contract
+
+Status: owner-approved design, orchestrator-frozen implementation contract, 2026-09-06.
+Implementation base: `1e21561fa374a95005aa9d2776719bb9fc5ac8a0`.
+
+This contract replaces the former one-time matching and stored-route-only policy.
+The feature PR must update the existing behavior specification, schemas, mirror
+registry, API, UI, and consuming tests together. Those existing documents must not
+retain contradictory current-policy claims when this implementation ships.
+
+## Example and Intent
+
+For backend defaults `[A, B]`, model M automatically uses B if B lists M and A does
+not. A is not prepended as a speculative candidate. If neither lists M, the chain
+is `[A/M, B/M]`, with M forwarded unchanged. A saved manual chain replaces this
+generated chain completely, including an explicitly empty manual chain.
+
+The upstream inventory is evidence for matching, not an invocation whitelist.
+Credentials, protocol and channel compatibility, backend model admission, source
+membership, explicit retirement, and live health remain separate boundaries.
+
+### Owner Scope Decision
+
+The owner selected API-key passthrough for this delivery on 2026-09-06.
+Unknown-model passthrough is available only to eligible Hub sources whose
+`kind` is `api_key`. Subscription sources, including Hub-held OAuth and native
+CLI subscriptions, retain their existing model admission and exact invocation
+capabilities. They still participate in automatic matching and manual routes;
+they are not speculative unknown-model candidates. An empty subscription-only
+default set for an unmatched model is Unconfigured, never falsely Passthrough.
+
+For manual writes, API-key targets may be absent from inventory; subscription
+targets keep the existing membership/retirement admission and stale-hop retention
+rules. Preserve subscription compatibility and normal errors, and do not imply
+that changing route labels upgrades the underlying engine's model support.
+Source inventory and reasoning metadata stay truthful for both kinds. All broad
+inventory-independence and unknown-target statements below apply to API-key
+sources under this explicit scope; the same shared route owner handles both.
+No underlying CPA extension, engine upgrade, OAuth alias substitution, or
+alternate subscription transport is part of this delivery.
+
+## Persistent Intent and Compatibility
+
+Existing `model_hub.agents[backend].sources.order` is the sole backend-default
+membership and priority owner. Existing `routes` becomes a sparse map of manual
+overrides, with unchanged value shape:
+
+```ts
+type RouteHop = { source_id: string; model_id: string };
+type ManualRouteOverride = { hops: RouteHop[] };
+type RouteOrigin = "automatic" | "manual" | "passthrough" | null;
+type ManualRouteOverrides = Record<string, ManualRouteOverride>;
+```
+
+Key absence means automatic. Key presence means explicit override, including an
+empty array. Saving a model route always creates an override even when identical
+to the generated result. Restoring automatic deletes the key. There is no second
+persisted policy flag and no inference from array equality.
+
+Preserve existing override entries and exact arrays losslessly, including empty,
+stale, and dormant OpenCode entries. Historical discriminator-free records cannot
+reveal whether an old empty array was generated or deliberately cleared. Retained
+entries are frozen routes, not a claim of known historical human authorship. The
+UI can restore them explicitly. Do not globally reinterpret old empty arrays as
+automatic or clear existing config during regression deployment.
+
+New catalog rows and missing fixed-menu rows receive no route key. Stop default
+seeding and source-add appends to persisted routes. Older supported config shapes
+continue through the existing safe loader; use explicit historical intent when
+available, never infer it from a backend source order. The blanket pre-release
+no-migration prose must not override the persisted-shape compatibility rule.
+
+## One Route Owner
+
+Extend `core/handlers/model_hub/resolver.py` with one pure effective-route owner.
+It produces `{manual_override, route_origin, hops}` from current configuration,
+backend, and canonical requested model. Preview may call it with an isolated
+draft configuration; no public sentinel or duplicate matching algorithm is needed.
+
+1. A manual key returns the exact saved hops and order.
+2. Otherwise scan configuration-eligible sources in backend default order for
+ matching evidence. Include all accepted matching pairs in that order.
+3. If there are no matching pairs, use each eligible API-key default source with
+ the exact requested id. Do not append speculative candidates to a matched tier
+ or include subscription sources as unknown-model passthrough candidates.
+4. An empty resulting chain has null origin. A nonempty chain has its chosen
+ origin regardless of current health or native process readiness.
+
+Reuse native Claude alias/version/date matching, including its existing parser.
+Other backends and API sources match literal canonical ids; do not add vendor or
+general fuzzy matching. Use complete non-retired inventory consistently. A
+`retired:true` source/model tombstone excludes that exact pair from matching,
+passthrough, and invocation. Missing inventory alone does not. Removing a manual
+inventory row removes matching evidence, not an upstream capability; it must not
+silently delete an explicit route. Source deletion still removes references
+atomically with existing guarded integrity rules.
+
+Choose the matching tier before applying an invocation transport restriction.
+A Hub-only HTTP request must not invent a different passthrough tier because the
+selected matching tier contains a native hop. Native singleton/backend binding,
+CLI readiness, direct-mode bypass, credential custody and origin restrictions
+remain in force. Do not broaden backend catalog admission or OpenCode native
+protocol declaration as a side effect of relaxing source inventory checks.
+
+All reads, previews, summaries, probes, launches, request execution, adoption
+reports, and mutation guards consume this same effective plan. Live inspection
+annotates runnability/current/health; it never changes tier or membership. The
+existing executor owns failover, credential recovery, and streaming cutoffs.
+Unknown model errors remain request-nonfallback and do not change source health.
+Exact reasoning effort is forwarded only if declared by the exact source model;
+unknown passthrough models do not acquire invented capabilities or reasoning tiers.
+
+## API Shapes and Responsibilities
+
+Advance the terminal in-request contract to `contract_version` 9 on the complete
+feature head. Retain readable historical TurnProvenance versions through 9.
+
+The server adds the following required fields to `AgentChain`:
+
+```ts
+manual_override: ManualRouteOverride | null;
+route_origin: RouteOrigin;
+```
+
+`manual_override` reports actual persisted key presence. `chain` is the effective
+ordered plan with existing live annotations, not the persisted map. Existing
+`current`, `supply_state`, health, reason, and retry fields retain their meaning.
+For a saved empty override, `manual_override` is `{hops:[]}`, `chain` is empty and
+`route_origin` is null. Preview reports the draft override rather than saved intent.
+
+`AgentSupply.routes` contains only manual overrides. Add required `route_origin`
+to each `model_supply` summary and derive `chain_length` from the effective plan.
+Frontend labels consume these explicit fields. No UI inventory matching or
+array-equality heuristic is permitted. `added_to`, `adopted_by`,
+`in_current_model_chain`, and supply guards use effective routes. Inventory
+candidate metadata remains inventory evidence and must not be fabricated for a
+passthrough target.
+
+| Endpoint | Exact request and responsibility |
+| --- | --- |
+| GET `.../agents/<backend>/sources` | Existing AgentSupply success envelope; server projects backend defaults. |
+| PUT `.../agents/<backend>/sources` | `{order, force?, would_remove_hops?, would_interrupt?}`; atomically replace default membership/order and preserve all manual overrides. Guard effective supply/hop removal using the existing exact-plan confirmation protocol. Pure reordering without removal needs no guard. |
+| GET `.../agents/<backend>/chain?model=<id>` | Existing chain success envelope, extended AgentChain. |
+| GET `.../agents/<backend>/chains` | Existing chain-list success envelope, same owner and fields for every routeable model. |
+| PUT `.../agents/<backend>/chain?model=<id>` | `{hops, force?, would_remove_hops?, would_interrupt?}`; persist explicit override, including equal and empty arrays. Return existing chain-mutation success envelope. |
+| DELETE `.../agents/<backend>/chain?model=<id>` | Optional `{force?, would_remove_hops?, would_interrupt?}`; remove override, recompute defaults, return the same mutation envelope. Idempotent if absent. Guard actual effective removal/supply loss. |
+| POST `.../agents/<backend>/chain/preview?model=<id>` | `{manual_override:null \| {hops:RouteHop[]}}`; return chain success envelope for draft replacement/removal. No persistence, events, engine startup/sync, credentials, or upstream egress. |
+| POST `.../agents/<backend>/chains/reorder` | Existing optional order plus optional guard fields; default-order compatibility entry point with the same effective guards. Never reorder manual arrays. With no order, return the current projection. New UI uses Sources PUT. |
+| PUT `.../agents/<backend>/models` | Preserve existing baseline/concurrency/expected-suppliers/guard contract. New rows automatic, retained rows preserve intent, removal cleans intent through existing guarded mutation. |
+
+All paths above use `/api/models` as their prefix. Existing success/error envelope
+field names and exact guard plan structures are reused, not renamed. Chain writes
+validate canonical nonempty identifiers, source existence/eligibility, and explicit
+retirement, but do not require source inventory membership. Manual override hops
+may use an eligible source outside the backend default subset.
+
+Identity normalization and new-identifier admission are distinct. An existing
+catalog identifier or retained exact target may exceed a later admission length
+bound without losing edit, preview, restore, or provenance-read capability. Use
+the persisted normalized identity and existing catalog/target evidence for those
+operations; apply admission bounds to newly introduced identifiers. This does not
+admit new padded aliases or bypass source, channel, or retirement validation.
+
+Server handlers, RPC, UI server, CLI/client wrappers, endpoint tables, response
+schemas and UI client must expose the same operations. Preview is read-only even
+when runtime is stopped. Mutation responses are authoritative after Save; failed
+or ambiguous writes follow the existing reconciliation and guard mechanisms.
+
+## Interface and Interaction
+
+Approved design: `avibe-docs/design.pen`, frames `bmi25` (dark), `ziils` (light),
+`NuxyR` (help/touch), `jCs2A` (manual/restore), `ztAos` (defaults), `P6Zi8k`
+(automatic/error/empty), reusable row `tFl3R`. Exact pixels remain owned there.
+
+- Show Automatic, Manual, Passthrough with distinct existing mint, new manual blue,
+ and amber tokens. Null origin shows Unconfigured, not a success label.
+- Hover/focus explains each origin; touch tap opens the same help without opening
+ the row dialog. Escape and outside interaction dismiss help. Avoid nested buttons.
+- Rename Adjust priority to Default routing. It edits one backend's default
+ membership/order; manual routes are independent. Show affected inherited/manual
+ counts without implying historical authorship or runtime health.
+- Route dialog opens inherited state with Edit route. Manual editing preserves
+ add/edit/remove/reorder and allows exact model ids missing from the source list.
+- Restore automatic lives in the dialog footer and changes draft only. Call preview
+ with null override, show its actual target and origin, which may be Passthrough.
+ Undo restore reinstates the prior manual draft. Cancel/close never writes.
+ Save uses DELETE for restored automatic, PUT for manual draft, consumes the full
+ canonical mutation result, and preserves existing guarded confirmation handling.
+- Preserve the draft on failed Save, avoid stale preview overwriting newer edits,
+ and disable duplicate submissions. Default configuration changes must not leak
+ between backend groups.
+- No eligible defaults show Unconfigured and a Configure default routing action.
+ An explicit empty override stays empty and offers Restore automatic in the dialog.
+- Request errors are separate from route origin. Model-not-found keeps Passthrough
+ and shows the recorded-turn detail surface below; do not mark the whole source failed.
+- Apply complete EN/ZH localization and keyboard/touch behavior. Documentation
+ remains English; public user documentation has matching English/Chinese pages.
+
+### Recorded Error Detail Closure
+
+The approved error panel must use real history. The existing bounded
+`BoundedProvenanceStore` is the sole retained outcome owner; its records describe
+exactly attributed, settled turns, not every upstream request. Keep its existing
+500-entry retention, atomic writes, and exclusion of ambiguous attribution. Do not
+introduce a second history store or turn request failures into Source health events.
+
+Add GET `/api/models/agents/<backend>/provenance?model=<id>` through the existing
+service, RPC, client, and UI-server path. Validate the backend and its canonical
+catalog model identifier. Reuse the existing envelope:
+`{ok:true,contract_version:9,provenance:TurnProvenance|null}`
+for the most recently persisted retained record matching both backend and requested
+model, regardless of outcome; no record means null, not a fabricated success.
+This is a read-only, on-demand dialog read and never starts or syncs the engine.
+The existing GET `/api/models/turns/<turn_id>/provenance` remains unchanged.
+Do not add history to the pure effective-route owner or every chain-list response.
+
+For newly observed terminal errors, retain optional `http_status` (valid HTTP
+status integer or null) and `upstream_error_code` (known machine code or null)
+inside the existing `terminal_error` object. Derive the latter only from observed
+codes recognized by the existing `UPSTREAM_MACHINE_ERROR_CODES` authority. For an
+observed `model_not_found` whose classified result is `upstream_request_invalid`,
+retain that specific code instead of a co-occurring generic `invalid_request_error`
+type. Otherwise use the existing machine-code specificity order. This is diagnostic
+selection only and must not rerank or change the classifier's decisions;
+never persist arbitrary upstream strings, raw bodies, messages, headers, or
+credentials for this panel. Preserve exact observed `model_not_found` when present,
+without reconstructing it from the broader `invalid_parameter` classification.
+Historical records may omit both fields and must remain readable unchanged.
+These observations do not alter classification, fallback, or source health.
+
+The route dialog loads this projection independently of its route draft. Show an
+error panel only if the latest retained turn has a terminal error; a later served,
+canceled, or other non-terminal-error record must not leave an older error looking
+current. Label it "Latest recorded turn" / "最近已记录回合", with the recorded
+timestamp and exact historical source/model. The details action opens that same
+record's structured fields; do not infer a source from today's route. Missing
+machine codes get generic reason-based copy, never invented model-not-found copy.
+Keep route origin unchanged. Read failures retain an explicit retry state; changing
+models or closing the dialog invalidates pending reads. Cancel/Restore/Save never
+write or rewrite history. Deleted sources remain historical identifiers.
+
+Contract and consuming tests must cover old records without optional metadata,
+model/backend isolation, latest-success clearing, bounded/absent history, unsafe
+upstream text exclusion, read-only retrieval, and real model-not-found display.
+
+### Atomic Invocation Admission
+
+Transport draining alone does not protect a request that resolved an old target
+but has not entered the adapter when a configuration Save removes that target.
+Close this boundary for ordinary resolution, fallback, the bounded credential
+refresh retry, and selected-model probing through the same service admission path.
+
+Extend the internal `EngineAdapter.invoke` contract with optional keyword
+`on_admitted: Callable[[], None] | None = None`. The service revalidates the current
+effective candidate, exact source configuration, and synchronized engine projection
+under its existing mutation lock. The adapter takes its existing routing lock,
+validates source/origin, acquires the active transport lease, then calls
+`on_admitted` exactly once before any network wait. This handoff releases service
+mutation exclusion and records the actual attempt. Network, buffered response,
+first-token wait, and stream consumption remain outside the service mutation lock.
+
+Lock order is always service mutation then adapter routing, matching source sync.
+Every pre-admission failure or cancellation releases service exclusion; every
+post-admission completion or cancellation releases the transport lease. A callback
+failure before network must release the lease too. Do not manufacture an attempt
+for a stale plan that never entered transport. Recompute unattempted candidates
+from current config while preserving already failed-source exclusions; a credential
+refresh may retry only its still-valid exact source/model. Probe uses the same
+admission primitive instead of a second direct adapter path.
+
+No per-request engine registration, retained invented model inventory, synthetic
+upstream model-not-found, persistent generation store, or network-duration global
+lock is allowed. Deterministic tests must cross a concurrent target removal/change,
+source change, refresh retry, probing, pre-admission cancellation and callback
+failure; concurrent independent HTTP requests must still make progress.
+
+## Engine Proof and Acceptance
+
+Remove inventory cardinality/membership admission gates from the service engine
+bindings and runtime registry without changing credential or source isolation.
+Keep SourceBinding model ids truthful. The pinned CPA executable must be proven
+to invoke the chosen source with an unknown canonical model; changing Python
+checks alone is insufficient. Do not fabricate source inventory, silently upgrade
+CPA, restart it per request, or let CPA select another source. An engine capability
+gap is escalated to the orchestrator before a substitute transport is implemented.
+
+### Engine Registration Amendment
+
+The pinned CPA proof at source `2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`
+confirmed that unregistered source-prefixed targets are rejected before upstream
+egress for all three API protocols. Explicitly registered positive controls
+preserved the exact upstream id and selected source. This is a transport registry
+constraint, not evidence about upstream model availability.
+
+Add `SourceBinding.route_model_ids: tuple[str, ...] = ()` and the corresponding
+internal SourceRecord field, loading its absence as empty. The service produces
+this deterministic, deduplicated, sorted set from effective Hub-channel route
+targets across all backend catalog models and retained route keys, including
+dormant OpenCode overrides that the resolver can still select. It is independent
+of health and of backend direct/hub mode, and never changes per request. Every
+actual mapped target, including a manual target missing from inventory, must be
+represented before use.
+Retaining transport coverage does not add a catalog row or expand model admission.
+
+`model_ids` continues to carry truthful non-retired source inventory. The engine
+config compiler may register the stable union of inventory ids and route target
+ids for transport. The latter never enter Source.models, discovery results,
+capability metadata, candidate matching evidence, or user inventory. Only actual
+inventory declarations supply reasoning capability information. This is an
+engine transport projection of configured route intent, not model discovery.
+
+All relevant config commits/reconciliation and load-time synchronization must
+refresh this projection through the existing source-sync owner. Preview remains
+side-effect-free, and order-only changes with an unchanged target set do not
+restart the engine. Registration updates must preserve in-flight invocations.
+Hub OAuth registration is not expanded by this field. Only API-key sources need
+unknown route targets; subscriptions keep their existing registration behavior.
+No per-request restart, invented inventory, silent engine upgrade, or alternate
+transport is authorized by this amendment.
+
+### Registration Synchronization Decision
+
+Pinned-engine experiments proved file/atomic/management configuration hot reload
+with unchanged PID and uninterrupted existing streams for all three protocols.
+However, neither the management acknowledgment nor `/v1/models` provides an
+atomic scheduler/config-generation completion barrier. The feature therefore
+retains the existing supervised restart transaction with explicit in-flight
+protection instead of introducing an unproven readiness heuristic.
+
+The adapter owns invocation leases and drains existing transport operations
+before a configuration-triggered engine restart. New invocations wait behind the
+same configuration barrier. Lease release belongs to transport completion,
+close, or cancellation, independently of service settlement and its mutation
+lock. A synchronization cancellation or exception cannot leak a barrier or
+lease. Do not cancel unrelated active requests just to save configuration.
+Pure reordering with unchanged registration remains restart-free, and ordinary
+invocations never trigger registration changes. Exercise buffered and streaming
+completion, early close, cancellation, sync failure/rollback, and concurrent Save
+to prove there is no deadlock or partial-output interruption.
+
+Acceptance states properties, with fixtures covering the supported shapes:
+
+1. Persisted manual intent survives every unrelated configuration, catalog, health
+ and process transition; automatic routes follow defaults and matching evidence.
+2. Preview, reads, summaries, guards, probes and runtime agree on one effective plan;
+ provenance is independent of transient health and transport readiness.
+3. Save/Restore/Undo/Cancel remain transactionally honest across UI, API and reload.
+4. Real backend launch, correlation/gateway, adapter, pinned CPA and local upstream
+ agree on exact model and source, including unknown models and non-ASCII data,
+ without fake inventory, private-prefix leakage or engine cross-source fallback.
+5. Request-only errors preserve source health and existing failure/streaming policy.
+6. Existing persisted shapes, historical turn records and unrelated configuration
+ survive compatibility loading; no real user's config is a test fixture.
+7. Desktop/light/dark/mobile screenshots match approved frames, labels and controls
+ do not overlap, and hover/focus/touch actions have their intended targets.
+
+Run focused unit/contract/scenario and browser evidence on the integrated head,
+then exact-head bot review and all required CI gates. Merge only after the entire
+PR has zero unresolved threads and is CLEAN. Fast-forward the control checkout
+without reverting unrelated edits. Deploy through the LOCAL Incus runner without
+resetting master state; coordinate the shared regression instance before update.
+Final success requires merged-head end-to-end acceptance, not mocked peer suites.
+
+## Delivery Ownership
+
+One feature PR is intentional: executable schema/type/mirror closure needs all
+consumers on one head. The orchestrator commits this contract before workers edit,
+allocates disjoint file scopes in one task worktree, and alone stages/commits/pushes,
+owns review-loop diagnosis, merges, and gates final regression acceptance. Workers
+report interface gaps instead of changing other lanes' files. No stacked PRs and
+no delegated merge approver are introduced.
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 351915e46..2fa93e513 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -10,6 +10,77 @@ at 40 sources instead of 4* — so every implementation lane invents its own ans
and the answers disagree. Everything below was decided while the frames were being
drawn; this file is where those decisions land instead of evaporating.
+## Routing modes revision - 2026-09-06
+
+Owner scope decision `c1d398d5f` restricts unknown-model passthrough and inventory-
+independent manual invocation to Hub API-key Sources. Subscriptions keep existing
+known-model matching/admission and stale-hop retention. Unmatched subscription-only
+defaults render Unconfigured. The route wire fields and approved helper interactions
+remain unchanged; copy must not imply expanded subscription support.
+
+The approved `model-hub-routing-modes.md` contract (`2db273891`) and frames `bmi25`
+(dark), `ziils` (light), `NuxyR` (hover/focus/touch help), `jCs2A` (manual/restore),
+`ztAos` (defaults), `P6Zi8k` (automatic/error/empty), and reusable row `tFl3R` govern
+routing surfaces. Existing Source, OAuth, credentials and reconciliation workflows below
+remain applicable. This revision replaces all-chain priority with backend defaults.
+
+The UI consumes `AgentChain.manual_override`, `AgentChain.route_origin` and effective
+`chain`, plus `AgentSupply.model_supply[].route_origin`. It never matches inventories,
+derives origin from array equality, or treats historical manual arrays as known human
+authorship. Nonempty plans display Automatic (mint), Manual (manual blue) or
+Passthrough (amber); null origin displays Unconfigured (neutral), independently of health.
+Use `--route-manual` and matching soft tokens: dark `#8BB4FF`, light `#245BCD`.
+Approved route rows are 36px, chips 23px and radius 8px; exact pixels remain in Pencil.
+
+Origin help works on hover and keyboard focus; touch tap opens the same help without
+opening the row editor. Escape/outside dismiss it; avoid nested buttons. Retain approved
+helper text and complete EN/ZH pairs in design/locales. Recorded model-not-found keeps
+Passthrough and uses the retained-turn detail surface below without marking the Source failed.
+
+Inherited dialogs open with Edit route. Manual editing retains add/edit/remove/reorder
+and accepts exact API-key upstream ids absent from inventory; subscription targets retain
+known-model admission. Restore automatic in the footer
+changes the draft to null and calls preview; its result may be Passthrough or Unconfigured.
+Undo restore reinstates the prior manual draft. Cancel/close never writes. Save sends
+DELETE for restored automatic or PUT for manual hops, consuming the complete canonical
+mutation result and exact-plan guards. Failed saves retain draft intent; stale preview
+responses cannot replace newer edits; duplicate submissions are disabled.
+
+Lost-response reconciliation compares actual `manual_override` as well as effective
+pairs: equal arrays can represent different saved intent. Preview is read-only with runtime
+stopped and never starts the engine. An explicit empty override stays empty and offers
+Restore automatic; inherited emptiness offers Configure default routing. Backend changes
+cannot leak drafts. Origin, runtime health, request errors and draft state remain separate.
+
+### Latest recorded turn detail
+
+The Recorded Error Detail Closure (`0de3d2f47`, corrected by `9cb9ebb53`) supplies the approved error panel's
+data through on-demand GET `/api/models/agents/<backend>/provenance?model=<id>`.
+This read is independent of route draft/preview and returns the latest retained exactly
+attributed settled turn for both identifiers, regardless of outcome, or null in the
+existing `{ok: true, contract_version: 9, provenance}` envelope. It reads
+the existing 500-record store only; neither AgentChain nor the pure planner owns history.
+
+Show an error panel only when that latest record has `terminal_error`. A newer served,
+canceled or other non-terminal-error result clears the old error; null is absent retained
+history, not a fabricated successful request. Use the exact label "Latest recorded turn"
+/ "最近已记录回合", the record's timestamp, and historical `source_id` and
+`configured_model_id`. Never infer a Source from today's chain; a deleted Source remains
+identifiable by its recorded id. The details action opens the same structured record,
+not a synthesized string or an independent request history.
+
+Display optional observed `http_status` and `upstream_error_code` only as recorded.
+Missing metadata in old records uses generic reason-based copy. Show model-not-found
+copy only for observed `upstream_error_code: model_not_found`, not for the broader
+`invalid_parameter` reason. Never display or persist arbitrary upstream text through
+this panel. Route origin, Source health and fallback semantics remain unchanged.
+
+The read has explicit loading, absent, terminal-error, non-error and retry states.
+Closing the dialog or changing backend/model invalidates in-flight responses; failure
+keeps a retry affordance without claiming no history. Cancel/Restore/Undo/Save neither
+write nor rewrite the retained record. No polling or every-request completeness claim
+is introduced.
+
## 0. Scope, authority, provenance
### 0.1 Frames covered
@@ -90,50 +161,13 @@ that a page with this title and these two tabs exists at this address.
This file **references anchors and never restates spec content**. If you want to
know what a chain is, read §4.3 there; this file only says where it is drawn.
-**Verification basis.** Every anchor and every `[spec]` / `[contract]` claim below
-was checked against **`ceace07f`** — the squash of the spec lane's PR #1215, and an
-ancestor of `master` — **not** against the pre-#1215 `master` whose §3, §4.1, §4.2,
-§4.6 and §5 it supersedes. Every anchor this file cites is reachable from `master`
-today, and the standing caveat that this file must not merge before #1215 lands is
-retired by #1215 having landed.
-
-The basis moved three times while this file was being written: `7984aabf` → `176b41b7`
-→ `ca45aeb6` → `ceace07f`. The first move added AC-29/30/31, and **AC-30** (takeover is
-derived, and a chain with no runnable hop renders none of takeover's visual semantics)
-and **AC-31** (Direct is a mode and the first state of an existing install; Native names
-a hop and never a mode) land directly on frames 08, 09 and 10. The second move is
-**S-1**, and it is larger: a configured chain is now stored configuration executed as
-written, with no runtime Source/model matching and no `follow | custom` state. The
-backend order remains a separate projection; the explicit `chains/reorder` operation
-may apply its stable ordering to existing hops without matching, adding, removing or
-remapping them. The third is the remainder of #1215's
-own review — five commits between `ca45aeb6` and the squash, sixteen contract files,
-1245 insertions against 1000 deletions — and it is the one move this document did not
-re-read commit by commit. It did not have to: the contract artefacts in this worktree
-are `ceace07f`'s byte-for-byte, so §0.10's class E re-derives every `[contract]` claim
-here from the landed text on every run, and drift against the basis is a red gate
-rather than a reading.
-
-Re-reading on each move is not bookkeeping, and this round proves it twice over. Two of
-the three frame-versus-contract conflicts in §0.6 existed only at `176b41b7`. And at
-`ca45aeb6`, **D-28 turned out to be ruling on `order_enrolled_by`, a field S-1 deletes**
-— a decision that still read as a live citation because a citation to a removed name
-looks exactly like a citation to a present one. Nothing flags it; only re-reading the
-basis does. It is re-derived in §2 with that history attached rather than quietly
-repointed.
-
-**What S-1 deleted, and what this file does about it.** §1.1's legend note,
-`gateway.row.followsOrder` / `gateway.row.custom`, and the whole of §1.2's follow/custom
-machinery specified a derivation S-1 abolishes. They were `[frame]` strings measured from
-frames 01 and 02 as they were drawn before the rebuild. **Frame 02 has since been redrawn
-under S-1 and merged**, so the resolution is no longer a scheduled rewrite: the stale
-specification is deleted, and the current export remains the visual authority. §1.2
-registers only its controls' semantics and the interaction states that cannot live in a
-drawing; §1.1 keeps the same boundary for its legend note and the two model-row keys. The
-rule this follows is the one this file uses everywhere: **a decision may be written down;
-a fact about a drawing may not be written down twice.** Prose that reproduces a frame is
-a second copy of the frame, and second copies go stale silently — which is exactly how
-these three passages survived S-1 in the first place.
+**Verification basis.** The routing behavior and wire contract were frozen at
+`2db273891`, its Engine Registration Amendment at `f8d14358a`, and the API-key scope
+and registration-synchronization decision at `c1d398d5f`. Approved routing
+frames are published by AVIBE Docs design commit `f846e515`; their ids remain those
+listed in the routing revision. The retained legacy frame catalog describes unrelated
+Source/OAuth/repair surfaces. It cannot restore the retired stored-chain-only policy.
+D26/D27 and API/schema parity validate current producer/consumer contracts on one head.
### 0.3 Provenance markers
@@ -260,11 +294,11 @@ half named in its Missing cell has an owner.
| # | Surface | Missing | Evidence / disposition (contract baseline `1993f4fd0`) |
| --- | --- | --- | --- |
| G-3 | 06 model inventory — **retirement is contracted; its discovered-row affordance remains open** | a way to retire a *discovered* model from the drawn inventory; ~~a place to remember that it was retired~~ | `DELETE /api/models/sources/<source_id>/models/<model_id>` now persists `models[].retired: true` for a discovered row instead of deleting it. `source.schema.json` keeps that row readable, never supplying, and refresh never revives it; §4.5 applies the same exact-hop and last-supplier guards. §1.6 registers that representation as the ordinary row chrome with muted ink and the existing tag component. Frame 06 still draws removal only for manual entries, so no registered control invokes the discovered-row route; only that producer half remains live instead of treating wire reachability as a UI consumer. |
-| G-9 | ~~03 order save that drops sources~~ **withdrawn — this was never a gap** | ~~the guarded-change response for the whole-order `PUT`~~ nothing | The row read the absence of a `409` branch on the whole-order `PUT` (§1.3 Saving names the route; a withdrawn row deliberately does not, so it can excuse nothing) as something `api.md` still owed, on the strength of FC-12's 「row-for-row」 clause. It owed nothing. `model-hub.md` §4.5's Source-mutation envelope matrix is declared **authoritative and exhaustive** over 「all Source/inventory mutations, including writes that cannot remove supply」, and its eight rows do not include this route; FC-12 names 「the explicit backend Source-order PUT」 as a separate item from the mirroring clause. The PUT still has no guard and only stores the order; the separate `chains/reorder` operation now applies that order to existing Routes. Kept as a withdrawn row rather than deleted, because the number is cited in this file's own history and because a gap register that silently loses entries cannot be audited. The row names no route and quotes no body, so there is nothing left in it for a checker to excuse — but a withdrawn row is still a *number* the register defines, and a citation resolves against numbers, not against verdicts. So the rule that keeps it inert is written here rather than enforced: **no surface may carry `[contract-gap]` G-9**, and the number is not reused |
+| G-9 | Default membership guard, revised 2026-09-06 | Existing exact-plan fields | Sources PUT and compatibility reorder compare effective plans. Pure reorder needs no guard; removal may require confirmation. Closed by the routing contract. |
| G-10 | 01 shell pill, install in flight — **and 08's 安装并切换**, the other press that promises one — **registered against the runtime install contract** | ~~a server-side install state, and the route that enters it~~ nothing | `POST /api/models/runtime/install` is the idempotent producer. `RuntimeDependency.status.health: installing` survives reload, successful verification settles at `not_started`, and failure settles at `not_installed` with the closed `status.error_key`. §1.0 and §1.9 consume that one machine; any mounted surface observing durable `installing` owns the derived 2s status loop, while a held initiating sequence only decides whether settlement lands at Not started or continues through Starting. Unmount stops the loop; reload owns G-10's first read and restores no intent. |
| G-11 | 09 direct-only home, zero backends — **registered against AgentSupply** | ~~an installation flag per agent backend, and the payload that carries it~~ nothing | Every `GET /api/models/agents` row now carries server-authoritative `cli_present`; the zero-installed state is exactly all rows false. §1.8 derives `installedAgents` once from that field and uses the same set for mode dispatch, rows and the count pill. Source presence is evaluated first so an empty installed set cannot hide retained Sources; only `sources == []` + the empty set enters No backend found. |
| G-12 | 01 upstream card and 06 header, `needs_action` — **registered by frame 12** | ~~the control that replaces a dead credential~~ nothing | §1.11 registers the two repair producers drawn on the source cards: 更换 Key sends the credential-replacement flow to `PUT /api/models/sources/<id>/credential`, and 重新授权 starts `POST /api/models/sources/<id>/reauth`. §1.1 and §1.6 cite that owner instead of pointing at each other. Kept as a registered row so the former absence and its closing frame remain auditable |
-| G-13 | 03 order drawer, chains that already exist — **registered by the global priority save** | ~~an action that re-applies the current order to chains built before it~~ ~~the route behind it~~ | `POST /api/models/agents/<backend>/chains/reorder` is the sole explicit operation that stores a supplied Source order and reorders every stored Route by it. The combined mutation is idempotent, adds/removes/remaps nothing and has no guard; a failure leaves the drawer draft untouched for retry. |
+| G-13 | Default routing save | Complete default order and guard plan | Sources PUT preserves manual arrays and returns authoritative AgentSupply. Failed saves retain the draft. |
| G-14 | 08 adopt-gateway confirm, `effects.1` — **registered against the mode transaction** | ~~the adoption itself: turning the backend's existing CLI login into that backend's first `native_cli` Source~~ nothing | A qualifying `direct` → `hub` mode `PATCH` now atomically adopts the recognized CLI login as the first singleton `native_cli` Source and returns the updated `AgentSupply`; an absent or unrecognized login or an existing native Source creates and reorders nothing, and repeats create no duplicate. §1.9's consequence pair states both branches and never treats `cli_present` as recognition evidence; its M5 handoff rereads Sources before the committed result lands because the response cannot carry the possibly created Source. |
| G-15 | 06 source detail, a source's own name and Base URL — **registered by frame 11** | ~~any affordance that edits them~~ nothing | §1.10 registers the overflow action, edit dialog and guarded `PATCH /api/models/sources/<id>` producer drawn in frame 11. Kept as a registered row so the former absence and its closing frame remain auditable |
| G-16 | 01 upstream card and 06 source detail — **registered by frame 11** | ~~any affordance that removes a source~~ nothing | §1.10 registers the overflow action and the source-removal guard dialog drawn in frame 11 for `DELETE /api/models/sources/<id>`. The existing 06 model-row 移除 remains a different operation. Kept as a registered row so the former ambiguity and its closing frame remain auditable |
@@ -277,7 +311,7 @@ half named in its Missing cell has an owner.
| G-23 | `Qp6FI`, the shared guarded-change confirm — both callers, §1.6's *Refetch refused* and *Guard refused* | a body block that lists `would_interrupt` | **The refusal carries a list and the dialog draws a sentence.** `would_interrupt` is `SupplyGap[]`, each entry `{backend, model_id, agents}` with `model_id` the protected **menu** model and `agents` the enabled named Vibe Agents that pinned it `[contract]`, and `model-hub.md` requires that 「the confirm copy names affected Agents when any exist」. `Qp6FI` as measured has exactly one label, one count pill, one row list and one hint line, and all four are the `would_remove_hops` side; the only rendering of the gap array is `guard.hint.interrupt`, one sentence that reports the array is non-empty. The strings are specified — `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, with `gateway.modelCount` as the pill — because copy is this document's register and an authority requires these; the block that holds them is drawing, so it is a gap rather than an invention. The same absence makes `source_last_supplier` unrenderable: its `api.md` example carries `would_remove_hops: []` beside a populated `would_interrupt`, which this dialog would draw as an empty list under a bare sentence |
| G-24 | 01 run pill, *Unsupported host* — **registered against RuntimeDependency** | ~~a host-platform or installability discriminator in the runtime payload~~ nothing | Every runtime response now carries server-authoritative `host_platform`; an exact match in `manifest.assets[].platform` is the support predicate. §1.0 never substitutes the browser platform. |
| G-25 | 01 gateway group, the unavailable marker — **registered against AgentSupply model supply; collapse ownership retired 2026-08-23** | ~~a per-model fact that separates a chain with a live hop from one whose hops are all stale~~ nothing | `model_supply[].has_runnable_hop` now carries that server-derived fact under the same runnability axiom as AgentChain. §1.1 uses it only to choose the row marker: a nonempty chain with no runnable hop renders `legend.unavailable`; the forced-false `chain_length: 0` subset branches first to the existing `models.launch.route_unconfigured` treatment instead of borrowing paused-supply copy. The six-row prefix owns collapse independently of this field. |
-| G-26 | 03 order drawer, a reorder — **registered against the same explicit reorder contract as G-13** | ~~a policy value that reads the stored Source order~~ nothing | `POST /api/models/agents/<backend>/chains/reorder` stores the supplied Source-order sequence and applies a stable total sort over every stored Route in the same mutation. A source outside the order remains a later Route hop when it is already configured there. |
+| G-26 | Default membership/manual independence | Shared effective planner | Sources outside defaults may remain in manual routes. Defaults update inherited routes under effective guards. |
| G-27 | 05 add-by-key, the persisting `POST /api/models/sources` — **registered against `source-create.schema.json`** | ~~the request shape that route accepts~~ nothing | The schema is the complete request: required `vendor` and write-only `key`; optional `display_name`, `base_url`, `protocol`, `client_nonce` and `accept_unavailable_inventory` `[contract]`. On `custom` with Auto, `protocol` is omitted and the server still requires matching response proof. A supplied protocol is persisted when observation is authenticated and either the vendor catalog pins it, the client declared it on `custom`, or a matching response proves it. §1.5 sends the consent boolean true only from ⑤, where a repeated observation still has to establish the protocol before a failed inventory may commit. |
| G-28 | `Qp6FI` guarded-change hop rows — **registered against `RouteHopRef.position`** | ~~the hop's position, on the reference the refusal returns~~ nothing | `guard-refusal.schema.json` carries one-based pre-mutation `position` on every `RouteHopRef`. §1.6 and §1.10 render it directly and issue no per-chain lookup. |
| G-29 | 05 add-by-key, ⑦'s lost-response reconciliation — **registered against Source-create nonce totality** | ~~anything the client holds *before* the send that the committed Source can afterwards be recognized by~~ nothing | The client generates `SourceCreate.client_nonce` before send. A list read finds exact `Source.client_nonce` after commit; in-flight and committed retries return distinct `409` conflicts, released/list-miss retries are fresh. A committed retry never replays an old response; it returns `source_nonce_conflict` and the client rereads the list to claim the Source. |
@@ -558,7 +592,7 @@ list is supposed to empty — by being decided elsewhere:
rather than as a property of how the frame happens to be drawn.
- **Which projection a backend-order surface consumes** — ruled. Order surfaces read
`AgentSupply.sources`, the backend's stored Source order; source cards read
- `adopted_by`; the stored chain is a third projection owned by §1.2; **none may stand in
+ `adopted_by`; the effective chain is a third projection owned by §1.2; **none may stand in
for another**. D-28 carries the rule, the reason, the restatement that the Source order
is a backend priority and never a runtime capability filter, and the note that S-1
deleted the field the ruling originally named.
@@ -613,7 +647,7 @@ registration, not something a reviewer is expected to infer from prose.
| C4 — in-flight response owner | A busy state with no cancellation route cannot be dismissed; if cancellation is contracted, name the state that owns its late response | [x] Saving owns the route `PUT`; Cancel, close, Escape and outside dismissal stay disabled until its response is classified | [x] Saving source and Removing source disable Cancel, close, Escape and outside dismissal until the request settles | [x] Pre-flow reauth and credential replacement are locked while busy; after a flow is acquired §1.4 Dismissing owns cancellation and any late answer | [x] N/A — the menu sends no request; selection transfers ownership synchronously to §1.4 |
| C5 — existing visual state | Hold the exact rendered origin; a no-op exit must not manufacture another state | [x] The exact opening AgentChain and invoking row are held; abandoning a reversible draft restores that origin | [x] Edit/remove dialogs hold the exact §1.6 origin | [x] Blocked-card, vendor-observation, source-detail and key-entry origins are held exactly | [x] Closed is the same footer/trigger state that existed before Open |
| C6 — committed-report exit | Once a mutation has committed, every dismissal path is the report's Done-equivalent exit and may neither restore a pre-write origin nor discard held response or D-36 commit evidence. A failed projection member adds read-only Retry for only that subset and MUST NOT remove Done or any equivalent dismissal | [x] Route impact reported retains R6 through AR-M3; successful members remain installed while failed members become stale. Empty-tail and matching-readback commits enter Route committed, reconciling, whose DP-4 exits retain evidence and transfer the active generation | [x] Save/remove impact reports retain their envelopes and every Done exit through M1/M2 read failure; inferred commits retain their exact Source/absence evidence through the same reads | [x] Repair impact retains R3/R4's distinct envelopes through M3/M4 read failure, and Repair unresolved retains R3 through M3; Retry is additive and no path restores the invoking origin | [x] N/A — the menu commits nothing and owns no response report |
-| C7 — authoritative field validation | Register every editable field against the authority that normalizes or rejects it; no field may rely on a generic request failure as its validator | [x] V5 consumes exact-pair uniqueness, server eligibility and callable-inventory authority while permitting unchanged stale pairs | [x] V1/V2 register every frame-11 field, including the complete Base URL normalizer | [x] V3/V4 register the replacement key and paste-back value; the shared reauth acknowledgement is the contracted literal `true`, not a free-form draft | [x] N/A — vendor rows emit closed enum values and expose no editable field |
+| C7 — authoritative field validation | Register every editable field against the authority that normalizes or rejects it; no field may rely on a generic request failure as its validator | [x] V5 consumes exact-pair uniqueness, server eligibility and retirement; API-key targets may be absent from inventory, while subscriptions retain known-model admission and unchanged stale pairs | [x] V1/V2 register every frame-11 field, including the complete Base URL normalizer | [x] V3/V4 register the replacement key and paste-back value; the shared reauth acknowledgement is the contracted literal `true`, not a free-form draft | [x] N/A — vendor rows emit closed enum values and expose no editable field |
| C8 — acknowledgement consequence coverage | For every capability that requires acknowledgement, register every applicable channel, the exact confirmed request value and one complete consequence sentence that is true for that channel before the irreversible boundary | [x] N/A — route replacement has no capability acknowledgement; F3 confirms an exact current server impact plan under the guard-totality table | [x] The existing overflow reauth action transfers its exact Source/channel to §1.11's shared confirmation phase; frame 11 adds no alternate shortcut | [x] Hub and `native_cli` both confirm and send literal `true`, but select separate complete bodies: Hub names only the failure-time cost and safe cancellation; native names the immediate shared-login outage and selected-Source-only recovery | [x] N/A — vendor selection starts create intent and crosses no existing-credential boundary |
| C9 — report-free reconciliation failure | For every committed mutation that skips its report because impact arrays are empty or unavailable after D-36 inference, register the pending/failure states, held write evidence and read-only Retry | [x] Route committed, reconciling holds the returned chain plus empty tails, or the exact matching AgentChain GET readback plus unavailable response tails, while AR-M is pending. An Agents-first failure settles as the exact failed Retry subset while mode-dependent companions remain deferred and non-stale; every other AR-M3 result likewise retains every success and retries only its exact acquired failed subset | [x] M1, or M2 through M0, enters Committed projection stale with the updated Source or committed absence plus exact empty/unavailable disposition held; Retry repeats only its complete-surface read | [x] A non-blocked M3/M4 empty envelope or RR-7 inferred commit with an unavailable response tail enters the same state; a blocked R3 result stays in Repair unresolved instead | [x] N/A — the menu commits nothing and invalidates no projection |
| C10 — mutation attempt scope and commit evidence | For every mutation covered by this frame group, name every projection its attempt may invalidate before the response is observed; both a received success envelope and authoritative D-36 commit evidence MUST pass through the owning M row before visible exit, with response-only members marked unavailable rather than invented | [x] R6 owns every received member; exact ordered D-36 readback enters Route committed, reconciling / M6 with `removed_hops` / `interrupted` unavailable | [x] R1/R2 own received save/delete envelopes; D-36 inferred save/delete commits enter the same M1/M2 reads with response-only impact arrays unavailable | [x] RR-1–RR-10 name repair attempt scope; R3/R4 classify received Source outcome, while RR-7 inferred repair commit enters M3/M4 with its absent response tail explicitly unavailable | [x] N/A — vendor selection commits nothing; create's later mutation remains owned by §1.4/RR-3 rather than the menu |
@@ -721,7 +755,7 @@ consumed by frame 02, frames 11/12 and their shared OAuth form.
| V2 | frame 11 `base_url` | `normalize_model_hub_base_url`, used by the source metadata handler | Empty draft → `null`. Otherwise trim, require a parseable HTTP(S) URL with a hostname, no username/password or fragment, no credential-bearing query key and no credential-shaped material; compare/send the normalizer output, including its lowercase scheme and trailing-path-slash removal | Disable Save; keep the draft local. The field is editable only for an `api_key` / Hub Source with a stored credential |
| V3 | frame 12 replacement `key` | credential-replacement handler: required non-empty string; `force` remains a separate boolean | Trim; a non-empty result enables submit and is held through F1/F3 | Disable submit; never send an empty key |
| V4 | §1.4 paste-back `value` consumed by frame 12 reauth | OAuth submit shape plus the selected `presentation.expects` | Trim; a non-empty code or callback URL enables submit, and the same normalized value is retained through reconciliation | Disable submit; never infer a second format beyond the server-declared enum |
-| V5 | frame 02 ordered `hops` draft | `model-hub.md` §4.4/§4.6 server-validated Route invariants plus AgentSupply eligibility and Source inventory | Project every row to the exact `{source_id, model_id}` pair sent on the wire. Pairs are unique. A newly added or changed pair must name an existing server-eligible Source and one exact callable, non-retired inventory model; identity and explicit cross-model mappings are both legal. An unchanged persisted pair may be retained or reordered even while its live annotation is stale/non-runnable | Exclude invalid pairs from the Add-hop chooser and disable Save while any new/changed draft row is invalid or duplicated. Never delete or rewrite an unchanged stale pair merely because it cannot be offered as a new choice. When a reconciliation refresh invalidates a new/changed row, ET-17e alone enters Invalid after refresh, renders `route.invalidAfterRefresh` on every offending row, keeps Remove enabled and gives Save that visible line as its disabled description |
+| V5 | frame 02 ordered `hops` draft | `model-hub.md` §4.4/§4.6 server-validated Route invariants plus AgentSupply eligibility and Source inventory evidence | Project every row to the exact `{source_id, model_id}` pair sent on the wire. Pairs are unique. A newly added or changed pair must name an existing server-eligible Source and a canonical nonempty, non-retired model id. API-key targets need not be in inventory; subscriptions retain known-model admission. Identity and explicit cross-model mappings are both legal. An unchanged persisted pair may be retained or reordered even while its live annotation is stale/non-runnable | Exclude invalid pairs from the Add-hop chooser and disable Save while any new/changed draft row is invalid or duplicated. Inventory absence alone cannot invalidate an API-key target. Never delete or rewrite an unchanged stale pair merely because it cannot be offered as a new choice. When a reconciliation refresh invalidates a new/changed row, ET-17e alone enters Invalid after refresh, renders `route.invalidAfterRefresh` on every offending row, keeps Remove enabled and gives Save that visible line as its disabled description |
**F1's last clause used to read 「nothing is persisted」, and a lost answer is not a
refusal** `[derived]`. Several states this treatment lands on are creates that are not
@@ -734,8 +768,9 @@ promise is how a user ends up with the same source listed twice. So the promise
what the evidence covers, and 重试 out of a no-answer failure re-reads the collection it
was writing into before it re-sends — a row already sitting there closes as the success it
is, rather than colliding with itself. An unguarded idempotent replacement may owe nothing
-extra: §1.3's 保存顺序 sends the same complete order to the atomic chains/reorder
-operation, so retrying the save lands the same result without a persisted half-state.
+extra only when its computed guard plan is empty. §1.3 default membership saves may
+have effective impact: retain the draft, read canonical defaults after ambiguous results,
+and apply the existing exact-plan confirmation before another write.
§1.2 is deliberately different even though it also replaces an array: the write
has a guarded plan and response-only impact evidence, so D-36 reads the exact Route before
any resend and an inferred commit marks that evidence unavailable. Which side a state
@@ -820,7 +855,7 @@ state exit; held intent never bypasses the evidence column.
| §1.1 | Group interrupted — a source needs action | The enabled-Agent aggregate reads `interrupted`, no Agent is usable or waiting, and at least one member is blocked by a source in `needs_action` or `error` `[derived]` | F2 — the group keeps its last rendering | `gateway.group.status.interrupted` | The source leaves `needs_action` / `error` → whichever aggregate the named Agents then produce. Frame 12 owns the credential repair controls; 06 keeps 重新拉取 for a source whose stored credential still works `[contract]` |
| §1.1 | Group unconfigured | `named_agents` is nonempty and every member either has no `effective_model_id` or reads `route_reason: route_unconfigured` `[derived from contract]` | F5 — a rendered configuration statement, not a request or a Source-health failure | `gateway.group.status.unconfigured` — 未配置型号路由 / No model route configured | Any member gains both an effective model and a configured Route → whichever aggregate the named Agents then produce. Distinct from *No enabled Agent uses this backend*, where there is no Agent member, and from *Group interrupted*, where at least one configured Route exists but cannot currently supply |
| §1.1 | Group interrupted — a hop's source is gone | The enabled-Agent aggregate reads `interrupted`, no Agent is usable or waiting, and at least one member's chain names a source that no longer exists `[derived]` | F2 — the group keeps its last rendering | `gateway.group.status.interrupted` | The payload stops reporting the blocker → whichever aggregate the named Agents then produce. Adding the source again produces a different source and does not re-satisfy the stored hop, so the exit is §1.2's explicit remove/change of that exact stale pair |
-| §1.1 | Group interrupted — a hop's model is no longer callable | The enabled-Agent aggregate reads `interrupted`, no Agent is usable or waiting, and at least one member's chain pins a model its source no longer advertises `[derived]` | F2 — the group keeps its last rendering | `gateway.group.status.interrupted` | 重新拉取 on 06 puts the model back into that source's inventory → whichever aggregate the named Agents then produce. The contract keeps the hop visible and non-runnable until an explicit refresh or edit and never re-points it `[contract]`; §1.2 owns the explicit remove/change while allowing the unchanged stale pair to remain |
+| §1.1 | Group interrupted — a hop's model is no longer callable | The enabled-Agent aggregate reads `interrupted`, no Agent is usable or waiting, and the chain reports a model-admission blocker. Missing subscription inventory or explicit retirement may explain that blocker; missing API-key inventory alone cannot `[contract]` | F2 — the group keeps its last rendering | `gateway.group.status.interrupted` | Render only the server's current projection. Subscription refresh may restore known-model admission; refresh never un-retires a row. Retained manual hops remain visible and never silently re-point; §1.2 owns explicit remove/change |
| §1.1 | Backend has no usable source | Every candidate filtered out | F5 | `gateway.supply.none` | Any source becomes eligible; 来源顺序 → 03 |
| §1.1 | Fixed backend has no models | A fixed-menu backend resolves to zero model rows `[derived]` | F5 | `gateway.group.emptyModels` | A model becomes available to that backend |
| §1.1 | OpenCode menu has no selection | OpenCode is in Hub mode and `menu.checked` is empty `[contract]` | F5 | `gateway.group.emptySelection`, `gateway.selectedModelCount_*`, `gateway.manageModels` | **Manage models** opens the OpenCode model-menu dialog; saving at least one eligible identifier returns to Ready with one route row per saved model |
@@ -849,7 +884,7 @@ state exit; held intent never bypasses the evidence column.
| §1.3 | Zero eligible sources | No source is eligible for this backend | F5 | `order.empty.noEligible` | 关闭. A source becomes eligible → Ready. 保存顺序 is disabled |
| §1.3 | Empty order, held-out sources remaining | The ordered section is empty and the held-out section is not | F5 | `order.empty.ordered` | 排进来 → Dirty. 保存顺序 stays enabled — an empty order is a real configuration |
| §1.3 | Dirty (uncommitted moves) | 排进来, 移出, a drag, or a keyboard move | F5 — nothing has been sent, so nothing can fail | `order.action.include`, `order.action.exclude` | 保存顺序 → Saving; 取消 → discard, close |
-| §1.3 | Saving | 保存顺序 pressed — send `{order: string[]}` to `POST /api/models/agents/<backend>/chains/reorder`, which stores the order and applies it to existing Routes in one mutation `[contract]` | F1 | `order.save`, `order.fail.save`, `order.retry` | Success → close; failure → keep every move held and 重试 the same save |
+| §1.3 | Saving | 保存顺序 pressed — send `{order: string[]}` to `PUT /api/models/agents/<backend>/sources`, which stores defaults and preserves manual overrides under effective guards `[contract]` | F1 | `order.save`, `order.fail.save`, `order.retry` | Success → close; failure → keep every move held and 重试 the same save |
| §1.4 | Default | A frame 13 vendor row has supplied the vendor | F5 | `addSub.title` … `addSub.hint.chatgpt` | The recommended option is pre-selected; selecting the other replaces it. 去登录 synchronously preallocates PD-1's blank browser context, then sends `POST /api/models/oauth/start`; RR-1/RR-2 classify any accepted flow **before** presentation: non-terminal transfers the context to PD-2, then `presentation.expects: none` → Awaiting sign-in, a paste presentation in E3a `starting` / `awaiting_action` → Awaiting paste-back, and a paste presentation already in E3b `verifying` → Awaiting paste-back completion; each navigates when `presentation.auth_url` is non-null now or on a later flow read. Terminal → immediate status read with no form reopened. Refused because that backend already holds its one `native_cli` Source `[contract]` → Already bound, and any other answer that is not a flow → Start failed; either path closes an unused blank context. Polling, re-render and reconciliation never auto-open a second context `[derived]` |
| §1.4 | Second pass `[derived]` | Re-opened while this backend already holds its one `native_cli` source `[contract]` | F5 | `addSub.opt.added` | The native row is inert whichever account that source holds; the hub row stays choosable and is selected on open, whatever the recommendation says |
| §1.4 | Awaiting sign-in | An acquired flow carries `presentation.expects: none` and no `device_code`; Form B remains G-33. `GET /api/models/oauth/status/<flow_id>` is polled every 2s until the §1.4 evidence-class matrix selects an exit `[contract]` | → OAuth failed / OAuth materialization failed. E2 transport/outage evidence, including `engine_down`, is inconclusive and the next 2s tick retries under the same bound (D-16); E4 or E8/E9 with the held Source present/unread stops at OAuth failed; only E6's two materialization codes stop at OAuth materialization failed | `addSub.signIn`; PD-4 resolves `presentation.instructions_key` and uses the device-code helper on null or lookup failure | PD-2 keeps the authorization link actionable. E5 `success` → `intent: create` closes **into 06 for the source that terminal names** with `added_to` and `adopted_by` in hand; `intent: reauth` → §1.11's R3 repair terminal `[contract]`; E4 → OAuth failed; E8/E9 first run RR-5's registered read, then absent → M0 / Source gone, present or unread → OAuth failed (the unread branch retains read-only Retry); E7 → M0 / Source gone; the polling bound passes with no terminal reading → OAuth failed — the bound is `OAuthFlow.expires_at` when the flow carries one `[contract]` and 15 minutes from acquisition when it does not `[derived]`; dismissed any of the three ways → Dismissing |
@@ -1071,7 +1106,7 @@ sections. §1.8 states the direct-only body condition.
| Tabs ×3 | Section switch | — | yes | 来源与网关 / 用量 / 日志; the active one gets the mint underline |
| Upstream module | Source inventory + info icon | `GET /api/models/sources` `[spec]` | info icon and rows: yes | Tooltip: `upstream.info`; open 06 for that source |
| Wire corridor | Routing space between Sources and Agents; it draws no independent axis | derived, decorative | no | — |
-| Gateway module | One group per backend, each with model rows + info icon | per-backend supply + chains `[spec]` | info icon, rows, collapse, 「调整优先级」, mode switch | Tooltip: `gateway.info`; open 02 / expand / open 03 for **that backend** / open 10's confirm |
+| Gateway module | One group per backend, each with model rows + info icon | per-backend supply + chains `[spec]` | info icon, rows, collapse, 「默认路由」, mode switch | Tooltip: `gateway.info`; open 02 / expand / open 03 for **that backend** / open 10's confirm |
| Legend | Colour → meaning | static; kept in bijection with the inks the page draws | no | — |
**The Logs tab owns the switch-history feed** `[derived]`. It is absent from the
@@ -1456,7 +1491,7 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `gateway.heading` | 网关路由 | Gateway routes |
| `gateway.infoLabel` `[derived]` | 什么是网关路由 | What gateway routes are |
| `gateway.info` `[derived]` | 网关路由决定每个 Agent 的型号在已有路由中的来源里先使用哪个上游来源;当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。 | Gateway routes decide which upstream source each Agent's model uses first among the sources already configured in its route. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically. |
-| `gateway.sourceOrder` | 调整优先级 | Adjust priority |
+| `gateway.sourceOrder` | 默认路由 | Default routing |
| `gateway.manageModels` `[derived]` | 管理模型 | Manage models |
| `gateway.switchToGateway` | 切换到网关 | Switch to gateway |
| `gateway.switchToDirect` | 切到直连 | Switch to direct |
@@ -1745,7 +1780,7 @@ dispatch arbitrates → each backend's models resolve to these sources today.
| `wmROQ` / `Xitl7` footer buttons | Add subscription / Add API key | — | yes | 添加订阅 opens frame 13; its selected vendor opens 04. 添加 API Key opens 05 |
| `f8w6Xp` + `pnYa0` wire corridor | the relations cross between the columns without an independent axis | decorative | no | — |
| `GLylJ` backend group | backend tile, name, model count, head buttons, and one `{{mode}} · {{health}}` line. For an open menu the count is the explicit selected count, never the number of models available from Sources | per-backend mode + supply health | head: buttons only | OpenCode's **Manage models** opens its model-menu dialog; other actions are registered below |
-| `ehGRK` / `bGsC7` 「调整优先级」 | — | — | yes | Open 03 **for that backend** |
+| `ehGRK` / `bGsC7` 「默认路由」 | — | — | yes | Open 03 **for that backend** |
| OpenCode 「管理模型」 `[derived]` | — | `menu.checked` plus the server-owned eligible Source inventory | yes | Open the OpenCode model-menu dialog; the same action remains available in the empty row area |
| `IyKyp` 「切换到网关」 | — | backend in 直连 | yes | Open the 10 confirm for that backend |
| `z02Ep` / `gbrq2` 「切到直连」 | — | backend on the gateway | yes | That backend leaves the gateway immediately — **no confirm** (D-30) |
@@ -1810,7 +1845,7 @@ exit keys on elapsed time」 is the rule the two source rows above are written t
**The three head buttons are mutually constrained** `[frame]`, and the constraint is
the whole model in one line: a backend is either on the gateway or not. On the gateway
-it carries 调整优先级 + 切到直连; in 直连 it carries 切换到网关 and **nothing else** —
+it carries 默认路由 + 切到直连; in 直连 it carries 切换到网关 and **nothing else** —
Claude Code's head has no order button, because a direct backend consults no source
order and an editor there would edit a list nothing reads. D-9a states the rule, and it
is a set equality over the three groups.
@@ -1951,15 +1986,15 @@ Other limits `[derived]`:
**The question it answers:** *for this one model, which sources will be tried, and in
what order?*
-**S-1 removed the mode choice this section used to specify.** A configured chain is
-stored configuration executed as written; there is no `follow` / `custom` pair, no
-segmented control to switch between them, and no second projection derived from a
-recommendation. Everything this section previously said about those two modes — the
-element inventory, the foot semantics, the metrics, the three inks, the mode copy —
-described a frame that no longer exists, and is deleted rather than rewritten.
+**Sparse manual intent replaces the historical stored-chain-only model.** The
+server's effective projection owns Automatic, Manual, Passthrough or Unconfigured;
+there is no `follow` / `custom` discriminator or client-side recommendation engine.
+Inherited routes enter editing through Edit route. Manual arrays execute as saved;
+Restore automatic stages null, previews the effective plan, and removes the saved
+override only on Save. The routing revision above owns the approved current frames.
**The current export remains the visual authority; this section registers its behaviour.**
-The normal dialog contains one ordered list of exact hops, a grip and ordinal on each row,
+The manual-edit branch contains one ordered list of exact hops, a grip and ordinal on each row,
the Source display name and exact upstream model id, a per-row remove action, 添加一跳,
按来源顺序重排, the persisted-configuration hint, 取消 and 保存 `[frame]`. The title holds
the menu model, the subtitle holds the backend product name, and the opening model row is
@@ -1982,17 +2017,22 @@ while `route.sourceMissing` means the chain annotation and never the local join
**One held identity, one origin and one wire projection** `[contract]` `[derived]`.
Opening 02 holds `(backend, menu_model)` and reads
-`GET /api/models/agents/<backend>/chain?model=<id>`. The draft is only the ordered
-projection of `AgentChain.chain` to `{source_id, model_id}`; live `channel`, `health`,
-`runnable`, `reason`, `retry_at`, `current` and `supply_state` remain read annotations and
-are never echoed into the write. The returned projection becomes the exact reversible
-origin. All local edits operate on a copy, so 取消 can restore that value without another
-authority. Empty `hops` is a valid explicit unconfigured Route, not absence of a Route.
+`GET /api/models/agents/<backend>/chain?model=<id>`. Hold `manual_override` separately
+from the effective `chain`. Edit route initializes a manual draft from effective exact
+pairs; Restore automatic stages null. Live `channel`, `health`, `runnable`, `reason`,
+`retry_at`, `current` and `supply_state` remain read annotations and are never echoed
+into a write. The reversible origin includes saved intent as well as pairs, so equal
+arrays cannot settle a lost response with different manual intent. Local edits operate
+on a copy; Cancel never writes. Empty `hops` is an explicit empty manual override,
+not absence of a Route. Preview reports the draft and cannot replace saved authority.
V5 is the sole Add-hop and draft validator. 添加一跳 opens the product's standard anchored
selection surface without assigning new frame geometry: candidates come from the current
-AgentSupply eligibility plus Source inventory, are grouped by Source, name the exact
-upstream model id, and exclude duplicate pairs. The selector owns exactly one active
+AgentSupply eligibility plus Source inventory evidence, are grouped by Source, name the exact
+upstream model id, and exclude duplicate pairs. Eligible API-key Sources additionally
+accept a canonical typed upstream id absent from inventory; subscription candidates
+retain known-model admission. Typed ids never create inventory or capability metadata.
+The selector owns exactly one active
candidate, which is also its selected pair: ET-5a selects the first listed candidate as the
surface opens, and every ET-5d move atomically replaces both values. Which element holds DOM
focus is the standard surface's business — the filter field owns the caret and carries the
@@ -2013,13 +2053,12 @@ the list and may be reordered or removed, because the contract validates only ne
changed pairs. ET-17e alone owns the state edge when refreshed Hub authority invalidates a
new or changed row; this paragraph supplies the predicate, not a parallel destination.
-**按来源顺序重排 is a local sort of this draft, not the all-chain mutation** `[spec]`
+**按来源顺序重排 is a local sort of this manual draft** `[spec]`
`[derived]` `[contract]`. `model-hub.md` §4.2/§4.6 and `api.md` Per-backend source order
-make the sole-consumer rule govern server-side implicit application of stored Source order:
-the all-chain route is the only such post-creation operation. The per-model PUT accepts only
-explicit `hops`, its handler never reads `sources.order`, and the contract explicitly permits
-an editor to use its page-held Source-order projection as a local draft-sorting aid. The
-control applies §4.6's stable total key to the current draft only: a hop whose
+make `sources.order` the shared automatic planner's default membership/order. The
+per-model PUT persists the explicit `hops` without sorting them; an editor may use
+its page-held default-order projection as an explicit local draft-sorting aid. The
+control applies a stable total key to the current draft only: a hop whose
Source is in the backend's page-held current Source order sorts by `(0, source_order_index,
original_index)`; an unlisted Source sorts by `(1, original_index, original_index)`.
Membership, exact model mappings and within-Source relative order are preserved. The
@@ -2027,22 +2066,22 @@ result remains local until 保存. This editor reads an already page-held displa
under an explicit user gesture and produces only that one local draft: it never reruns
placement or matching. The per-model write body remains only explicit `hops`; Source order
is neither sent nor interpreted by that route. This control never calls
-`POST /api/models/agents/<backend>/chains/reorder`, because that route changes every
-stored Route. Frame 03's global-priority save owns that broader action (G-13); this
+`PUT /api/models/agents/<backend>/sources`, because that route changes backend
+defaults. Frame 03 owns that backend-scoped action (G-13); this
control only sorts the one route draft held by frame 02.
**Save sequencing is total** `[contract]` `[derived]`:
| Step | Evidence held | Request / disposition |
| --- | --- | --- |
-| RS-1 — local edit | opening AgentChain + V5-valid ordered draft | Send nothing. ET-5a–ET-7f own the atomic selector/draft/focus transitions; Save is enabled only when the ordered pair array differs from the opening origin; empty is allowed |
-| RS-2 — first save | one immutable submitted `hops` array | ET-9a sends the complete array without `force` or plan echoes and transfers focus/ownership to Saving |
+| RS-1 — local edit | opening AgentChain intent + V5-valid ordered draft or restored null | No mutation. Preview may project the draft read-only. Save compares intent as well as pairs: equal-to-automatic manual saves and explicit empty overrides are valid changes. Undo restore reinstates the previous draft; Cancel never writes |
+| RS-2 — first save | one immutable submitted manual override or restored null | Send the complete manual array with PUT, or DELETE for restored null, without `force` or plan echoes; transfer focus/ownership to Saving |
| RS-3 — ordinary success | R6 `{chain, removed_hops, interrupted}` | Hold all three members; cardinality is evidence consumed by ET-10/ET-11, which alone select the report or report-free M6 edge |
-| RS-4 — guarded refusal | HTTP 409 `source_last_supplier` + complete `would_remove_hops` and nonempty `would_interrupt` | ET-12 renders shared `Qp6FI`. The refusal persisted nothing and the draft remains unchanged. G-23 still records the missing drawn SupplyGap block; this section registers the data/copy consumer but invents no block geometry |
-| RS-5 — confirm | the immutable submitted `hops` + both exact arrays from the currently displayed refusal | ET-13b verifies the exact held plan and re-sends it with `force: true`, `would_remove_hops` and `would_interrupt`; confirmation never creates a new mutation body |
+| RS-4 — guarded refusal | Existing HTTP 409 guard envelope and both complete refusal arrays | PUT guards protected-supply interruption; DELETE Restore guards actual effective removal or supply loss. Render the applicable existing guard and evidence blocks. The refusal persists nothing and retains draft intent |
+| RS-5 — confirm | immutable submitted intent + both exact arrays from the currently displayed refusal | Re-send the same PUT or DELETE with `force: true`, `would_remove_hops` and `would_interrupt`; confirmation never changes the submitted intent |
| RS-6 — plan changed | a forced request returns another guarded 409 | ET-12 replaces both displayed arrays with the recomputed plan and requires another explicit confirmation; the old preview is discarded |
| RS-7 — impact disappeared | the forced request recomputes an empty guarded plan | The server returns ordinary R6 success; ET-10/ET-11 consume the actual envelope and the UI fabricates no refusal |
-| RS-8 — shaped rejection | a non-guard, non-`direct_mode` error response | ET-14 settles that attempt terminal-rejected. Retry is a new explicit workflow: revalidate the retained draft, freeze a new submitted generation and send one ordinary **non-forced** PUT; any new guard starts its own Qp6FI phase. It never runs D-36 or reuses prior force/plan evidence |
+| RS-8 — shaped rejection | a non-guard, non-`direct_mode` error response | Settle that attempt terminal-rejected. Retry revalidates retained intent, freezes a new generation and sends one ordinary non-forced PUT or DELETE as appropriate. It never runs D-36 or reuses prior force/plan evidence |
| RS-9 — no response / no Route authority | transport no-answer or `direct_mode` without an exact Route result | ET-15/ET-18a set attempt settlement `unknown`. D-36 may read only: matching proves commit; nonmatching or failed observation never proves the old PUT terminal and never emits a recovery PUT. The user may abandon; any later edit begins a distinct workflow from newly read authority |
**Direct-mode evidence retires the editor; only `AgentSupply` projects the destination
@@ -2074,8 +2113,9 @@ receipt or server-held confirmation state** `[contract]`. Only an exact unchange
both refusal arrays confirms a nonempty recomputed plan. For `mutation.route_replace`,
submitted removals by themselves do not activate the guard: a visible noninterrupting
removal succeeds ordinarily and appears in `removed_hops`; only nonempty
-`would_interrupt` refuses. Every 409 therefore names a current nonempty interruption plan
-and mutates nothing. ET-13a and ET-13b separately own abandoning and confirming that refusal.
+`would_interrupt` refuses. For `mutation.route_restore`, actual effective removals also
+activate the existing guard even without interruption. Every refusal carries its exact
+current plan and mutates nothing. ET-13a and ET-13b own abandoning and confirming it.
**R6 and M6 own the success before the dialog may disappear** `[contract]` `[derived]`.
The returned `chain` is the post-write projection and commit evidence. Later reads may
@@ -2278,7 +2318,7 @@ cannot name the reducer/CA result for one row is incomplete.
| RT-2 — M6 chain becomes Direct | AR-M has installed Hub Agents; its chain member returns `direct_mode` | AR-MD provisionally removes prior Route work, preserves independent successes and uses ET-18aM/ET-18aP to acquire landing Agents authority. Direct keeps Route not applicable; Hub acquires a new post-landing chain epoch |
| RT-3 — Direct after Source success | Source settles successfully before either AR-D5 or AR-MD | Keep that Source installed/carried; disown only pending siblings. The landing Agents result, not the Direct error, selects the page form |
| RT-4 — active Retry loses admission | Activate Retry in save reconciliation, mounted M6, transferred M6 or error-handoff page phases | CA synchronously moves focus to the destination phase's first FF-1-valid owner before disabling/inerting Retry; ET supplies no competing focus patch |
-| RT-5 — local Source-order draft sort | Activate frame-02 sort, then save its explicit pairs | Follow `model-hub.md` §4.2/§4.6 and `api.md`'s negative fixture: the local gesture may reorder the draft; the per-model PUT transmits only explicit `hops`, its server path never reads `sources.order`; frame 03 separately applies the global priority through the all-chain reorder operation |
+| RT-5 — local Source-order draft sort | Activate frame-02 sort, then save its explicit pairs | Follow `model-hub.md` §4.2/§4.6 and `api.md`'s negative fixture: the local gesture may reorder the draft; the per-model PUT transmits only explicit `hops`, its server path never reads `sources.order`; frame 03 separately saves default membership/order while preserving manual routes |
| RT-6 — Hub landing closes Sources | DM-1–DM-3 owns the landing Agents read; before it settles another client completes Direct → Hub and atomically creates a native Source | LF-H installs exact Hub AgentSupply, invokes M5's Source read outside M6 and calls the landing current only after that read. Failure keeps AgentSupply, marks only Sources stale and retries only Sources |
| RT-7 — CA activation modality | For every enabled CA row, activate its control once by pointer, Enter and Space; repeat for disabled/inert rows | All three enabled gestures emit that row's one `Activation`, including CA-P1 → ET-18c. Every disabled/inert gesture emits nothing; no keyboard enumeration may restate CA IDs |
| RT-8 — DM-2 unknown crosses ordinary M5 | Route PUT returns shaped `direct_mode`; LF-D installs Direct; the ordinary §1.9 mode PATCH later returns exact Hub | DM-2 creates `(unknown, page session, Direct-suspended)` before modal handoff. M5/LF-H closes Source, the common hook changes legality and RO-O sends exactly one chain GET: match enters M6; nonmatch installs current Route and remains page-owned unknown; neither branch sends PUT |
@@ -2598,276 +2638,49 @@ shared `models.hub.guard.*` owner.
---
-### 1.3 Frame 03 `qZhJ3` — Source-order drawer (per backend)
-
-**The question it answers:** *for one backend, which upstream sources should the gateway
-try first, and what should it try next when the first one cannot serve the request?* One
-ordered list, scoped to one backend, controls both the persisted priority and the order
-of that backend's existing Route hops.
-
-**It governs global route priority** `[spec]`. `POST /api/models/agents/<backend>/chains/reorder`
-stores the supplied complete order and applies the current Source-order sequence to every
-stored Route with a stable total sort, without adding, removing or remapping a hop
-`[contract]`. The combined mutation is atomic; if it fails, the drawer keeps the draft and
-retries the same save, so no partial success is presented as complete.
-
-The scope in that sentence is the whole point of the frame, and it is what the frame
-used to get wrong. An earlier version drew one product-global order with native
-sources held out of it; `model-hub.md` §3 defines 来源顺序 as an ordered subset
-eligible for **one backend** and never product-global. The owner ruled for the
-behaviour spec and the frame was rebuilt. See §0.6 E-1 — kept as a closed conflict
-rather than deleted, because the resolution went against the drawing.
-
-**Entry point.** The 调整优先级 button on a backend's group head in the gateway module
-— `ehGRK` on Codex, `bGsC7` on OpenCode in frame 01, redrawn as `N50iJ7` / `nzwR3` in
-03's own dimmed background `[frame]`. **A backend in 直连 mode has no
-such button** — Claude Code's head carries only 切换到网关 `[frame]`. This is not an
-omission to be tidied up: a direct backend uses its own login and consults no source
-order, so an order editor there would edit a list nothing reads. §2 D-9a states the
-rule, and it is a set equality.
-
-**Geometry** `[frame]`
-
-| Element | Metric |
-| --- | --- |
-| Scrim `UA2Q1` | 1440×1100, `#05050BE0` |
-| Drawer `hnsO5` | 460 wide, **full 1100 height**, right-anchored, `$--surface`, left border only |
-| `head` `qNs0K` | `padding [18,20]`, vertical, `gap 6`, 82 tall `[frame]` — the only overlay head in the product that is not `[16,20]` / `gap 4`, because it stacks a title over a subtitle |
-| Title | 15 / 700, `$--foreground`, + 13px info icon `#FFFFFF59` |
-| Close `fUvS9` | 15px, `#FFFFFF59`; `order.cancel` is its accessible name in both locales (§1.0) `[derived]` |
-| Subtitle | 11.5 / normal, `#FFFFFF73` |
-| `dbody` `Gd4Bl` | `fill_container` height, `padding 20`, `gap 18` `[frame]`, **the sole scroll owner** `[derived]` |
-| Section label | 10.5 / 700, `#FFFFFF73` |
-| Ordered row | 58 tall, radius 9, `#FFFFFF08`, `gap 12` |
-| Held-out row | 58 tall, radius 9, `#FFFFFF05` |
-| Grip icon | 14px — `#FFFFFF4D` on ordered rows, `#FFFFFF33` on held-out rows |
-| Ordinal badge | 22×22, radius 6; **#1** `#5BFFA01A` / `$--mint`; **#2+** `#FFFFFF0A` / `$--muted` |
-| Source name / meta | 12.5 / 600 `$--foreground` over 10.5 / normal `#9BA3B8B3` |
-| Type tag | radius 999, 10 / 600 — the provenance palette in §2 D-19 |
-| `foot` | `#FFFFFF05`, 1px top border, buttons radius 7, 12 / 600 |
-
-**The ordinal badge inks the first position, and only the first** `[frame]`. Rank 1 is
-mint; every later rank is the muted neutral. Mint here is **control ink, not relation
-ink** (§1.0): it means *first in this stored order*. On save, the explicit
-`chains/reorder` operation uses that order to sort each existing Route's hops; the badge
-still does not claim that this source is healthy or carrying the current request. The
-badge moves only when the order is edited `[derived]`.
-
-**This drawer must not claim live supply, and the reason is the contract, not caution**
-`[contract]`. The per-backend order is a persisted priority and an explicit input to
-`chains/reorder`, while execution still reads each model's exact stored chain and takes
-the first runnable hop. A source can therefore be first in the priority list while its
-hop is cooling, out of quota or process-unavailable. The list controls ordering; the
-chain's live annotations decide which hop answers. A backend-level surface that inked
-rank 1 as the live answer would still be wrong when another hop is runnable.
-
-The rule generalises past this drawer: **a surface may only assert a fact whose inputs
-it displays.** The per-model current source is owned by the frame that shows models —
-01 and 08's 当前 … rows, at per-model grain, including 当前 aihub(接管). This drawer
-owns the order and asserts the order. Two surfaces, two claims, one owner each; where
-they overlap they would have had to agree, and the way to guarantee agreement is to
-stop one of them from making the claim at all.
-
-**Element inventory**
-
-| Element | Displays | Interactive | On activate |
-| --- | --- | --- | --- |
-| Ordered rows | The order, ranked from 1 | drag, and fully by keyboard | Reorder |
-| Grip | Drag affordance | drag / Space | Grab and drop |
-| 排进来 `MJZ2I` | Add a held-out source to the order | yes | Append at the end, then focus the moved row `[derived]` |
-| 移出 `A2Hz9O` / `FjqVJ` | Take an ordered source out of the order | yes | Move the row to the held-out section, then focus the moved row `[derived]` |
-| 取消 / 关闭 `fUvS9` | Leave without saving; the icon is the button's second press and carries `order.cancel` as its name (§1.0) | yes | Close, discarding uncommitted moves |
-| 保存顺序 | Commit | yes | Persist the order, apply it to existing Routes, close |
-
-**排进来 and 移出 are one control in two directions, and both are drawn** `[frame]`. The
-held-out row carries `MJZ2I`; each ordered row carries the same button reversed —
-`A2Hz9O` on `YXG4r`, `FjqVJ` on `m18t4` — in an identical treatment (`#FFFFFF0A`,
-`radius 8`, `$--border-strong`, `padding [9,12]`, `gap 6`, label Inter 11.5 / 700).
-Membership in this order is a two-way relation, so it gets one affordance with two
-labels rather than one affordance and one omission. A drawer whose only way *out* of the
-order was drag-and-drop would make the two directions unequal for no reason: one a
-button, the other a gesture — and the gesture is the direction with no keyboard
-equivalent that produces the same result.
-
-**Changing the order is not a guarded change, and this drawer starts no confirmation
-at all** `[contract]`. The drawer sends the complete order to the explicit
-`POST /api/models/agents/<backend>/chains/reorder` route. That response is the
-authoritative `AgentSupply` echo after the order has been stored and existing Routes
-have been stably reordered in one mutation. A source removed from the priority list
-remains a valid Route hop when it is still present in a chain; the reorder operation only
-places listed Sources first and preserves every hop pair. There is nothing for a guard to
-refuse, and a failed request leaves the draft available for retry.
-
-*An earlier version of this section had it removing hops.* It read the order save as
-「a save that drops sources is not a different kind of change from any other that would
-remove hops」, gave §1.3 a Guard-refused state, and promised in the confirm copy that
-移出的来源会从这个后端的所有路由链里消失 — while four paragraphs above, this same section
-said reordering leaves every existing chain untouched *and called that the property which
-makes the list safe to edit*. Both could not be true, and the one that had authority is
-the one this file was not free to choose: `model-hub.md` §4.5's Source-mutation envelope
-matrix is declared **authoritative and exhaustive** over 「all Source/inventory
-mutations, including writes that cannot remove supply」, its eight rows do not include
-this route, and FC-12 lists 「the explicit backend Source-order PUT」 as its own item
-beside 「every Source/inventory mutation mirrors §4.5's total matrix row-for-row」. An
-exhaustive table that omits a route is not a table with a hole in it. So the success echo
-`api.md` gives this route, and its 「no policy state exists」, are the matrix being
-mirrored correctly rather than a mirror left half-finished, and what G-9 recorded as owed
-was never owed — which is why it is now recorded as withdrawn rather than left standing.
-The cost of leaving it standing was not a documentation defect: a registered gap reads as
-*not built yet*, so the next reader to close it would have taught the server to delete
-configured routes on a reorder, and the copy above would have been the warning that made
-it look intended.
-
-**There is no mode, and the drawer has no ownership state** `[frame]` `[spec]`. Every
-element on this surface is either part of one stored order or an action that edits it:
-two sections, the rows in them, and a foot that commits or discards. The order the user
-sees is the backend's global priority and the order applied to existing Routes on save;
-the only way it changes is that somebody changes it here or a new source is placed by the
-add transaction.
-*This section used to specify the opposite, and what it lost is worth naming.* An earlier
-version drew a 跟随推荐 / 自定义 segmented control, a three-state ownership machine, a
-hint row reading 「顺序已改成「自定义」:新来源不会自动排进来。」 and a 恢复推荐顺序 escape.
-All four are deleted. Under the configured-chain ruling (`model-hub.md`, owner 2026-08-09)
-there is **no `follow | custom` state and no second projection from a recommendation**, so
-a mode switch would have been a pointer standing where a result belongs — the drawer would
-have shown the *name of a policy* rather than the order that executes. The escape hatch
-went with it, and that is a real loss: 恢复推荐顺序 was a one-press way back from a
-reorder the user regretted. What replaced it is not a smaller version of the same thing —
-it is nothing, because the honest replacement is *undo the last change*, which this
-version does not build. D-10a's one-way-door concern is therefore **not** answered by this
-frame; it is answered by the order still being fully editable by hand, which is weaker and
-is recorded as such.
-*The hint row's job disappeared rather than moving.* It existed because 自定义 froze the
-order, so a newly added source could be silently held out and the user had to be told.
-Under the add-time placement policy (`model-hub.md` §4.2) every accepted match is written
-at a determinate position by the same transaction that adds the source, and the
-transaction returns it: `POST /api/models/sources` answers with `added_to`, whose entries
-carry `backend`, `menu_model`, `source_id`, `model_id` and `position`, the last one-based
-in the persisted Route chain after commit `[contract]`. So 「新来源不会自动排进来」 is no
-longer true and the state it warned about no longer exists — the warning was retired
-because the condition was, not because the surface moved.
-
-*Nothing renders where it landed, and that is a gap rather than a decision.* A user who
-has just added a source needs to know where it went, and the one moment the answer is in
-hand is the add transaction's own response — a drawer opened later cannot read it back,
-unlike persisted `Source.adopted_by`. **No frame in this document
-draws `added_to`** `[contract-gap]` **G-22**. The surface that would own it is the add
-flow's terminal, 06 for the source just created — §1.4's *Awaiting sign-in* and §1.5's ②
-both land there, and both land holding the array. This file states the landing and not the
-rendering, because specifying an element no frame draws would be this document inventing
-design (§0.2).
-
-**The held-out section is not an exclusion list.** Its label reads 「未排入这条顺序」
-`[frame]`. A source outside this backend's order is still a source: it may sit in another
-backend's order, and a chain elsewhere can name it. The earlier design read this section
-as 「不参与排序」, which said something much stronger and false. The two sections
-partition the eligible sources exactly: no source is in both, and none is in neither.
-
-**Keyboard operation** `[derived]`. Drag-and-drop is the drawn affordance; it is not the
-specified one, because a reorder surface that only accepts a pointer is unusable by
-keyboard and by assistive tech, and this drawer is the only way to express a preference
-the resolver reads. Required bindings, on a focused row:
-
-| Key | Effect |
-| --- | --- |
-| `Space` | Grab the row, or drop a grabbed row at its current position |
-| `↑` / `↓` | Grabbed: move the row one position. Not grabbed: move focus between rows |
-| `Escape` | Grabbed: cancel the grab and restore the pre-grab order. Not grabbed: close the drawer |
-| `Enter` | On 排进来 / 移出: move that source between the two sections and put focus on the moved row |
-
-Ordinals renumber contiguously from 1 after every move, grabbed state is announced
-(`aria-grabbed` plus a live-region message naming the new position), and the order a
-keyboard produces is byte-identical to the one a drag produces — they must write the
-same value through the same commit path, not two paths that agree today. Every binding in
-the table above commits through that one path, and so does every button on a row.
-
-**The subtitle says what this drawer stores and what its Save applies** `[contract]`.
-The `chains/reorder` request persists the complete Source order and applies it to every
-existing Route using the stable sort defined in `model-hub.md` §4.6. Therefore the first
-source is tried first and the next priority is used automatically for fallback-eligible
-quota, rate-limit, server, authentication, and network failures. If the request fails,
-the drawer keeps the same draft and retries it; no partial priority state is visible.
-
-**Copy** — namespace `models.hub.order.*`
-
-| Key | 中文 | English |
+### 1.3 Default routing - per backend (approved frame `ztAos`)
+
+The backend action is Default routing / 默认路由. It edits that backend's default Source
+membership and priority. Inherited Automatic and Passthrough routes follow it; Manual
+overrides retain their exact arrays. Show affected inherited/manual model counts from
+server projections without claiming historical human authorship or current health.
+
+Read `AgentSupply.sources.order` and eligibility; save the complete subset with
+`PUT /api/models/agents/<backend>/sources`. Optional `force`, `would_remove_hops`
+and `would_interrupt` follow the existing exact-plan guard. Pure reordering needs no
+guard; membership removal can remove effective hops or supply and must display the
+actual refusal, echoing both arrays unchanged on confirmation. Success returns the
+authoritative `{agent: AgentSupply}`; reconcile chains and adoption through existing
+reads. A failed or ambiguous save keeps the draft and reads canonical defaults before
+another write. Switching backends cannot reuse another backend's draft.
+
+Both include and exclude actions exist. Sources outside defaults remain available for
+manual routes. Empty defaults are valid and leave inherited routes Unconfigured; existing
+manual arrays survive. Zero eligible Sources shows the empty state. Blocked Sources keep
+their rank. Rank is configured priority only, never the currently serving Source.
+
+Keyboard/touch operate the same list: include/exclude buttons are focusable; Space
+grabs/drops; arrows move a grabbed row or focus; Escape cancels the grab before closing.
+Announce new positions and retain moved-row focus. Long lists scroll with header/footer
+visible; labels and controls fit desktop/mobile and both color schemes.
+
+Retain the approved helper text: inherited routes first use matching Sources in default
+order; without a match eligible Hub API-key Sources forward the original id in that order.
+Subscriptions are not speculative candidates. Manual routes remain
+independent. Helpers must respect existing fallback and streaming boundaries.
+
+| UI label | English | Chinese |
| --- | --- | --- |
-| `title` | {{backend}} · 全局路由优先级 | {{backend}} · Global route priority |
-| `subtitle` | 在每个型号已有路由中的来源里,排在前面的上游将优先被使用。当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。 | Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically. |
-| `infoLabel` `[derived]` | 什么是全局路由优先级 | What global route priority is |
-| `section.ordered` | 排在这条顺序里 | In this order |
-| `section.ordered.note` | 拖动排序 | Drag to reorder |
-| `section.heldOut` | 未排入这条顺序 | Not in this order |
-| `section.heldOut.note` | 这些来源仍保留在已有路由里,排在这条顺序之后。要从路由中移除,请编辑对应型号的网关路由。 | These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route. |
-| `action.include` | 排进来 | Add to order |
-| `action.exclude` | 移出 | Remove from order |
-| `empty.noEligible` `[derived]` | 这个后端还没有可用来源。 | No source is available to this backend yet. |
-| `empty.ordered` `[derived]` | 这条顺序现在是空的。把下面的来源排进来。 | This order is empty. Add a source from below. |
-| `cancel` | 取消 | Cancel |
-| `save` | 保存顺序 | Save order |
-| `fail.read` `[derived]` | 来源列表没读到 | The source list could not be read |
-| `fail.save` `[derived]` | 顺序没保存上 | The order was not saved |
-| `retry` `[derived]` | 重试 | Retry |
+| Group action/title | Default routing | 默认路由 |
+| Route origin | Automatic / Manual / Passthrough | 自动 / 手动 / 透传 |
+| Empty plan | Unconfigured | 未配置 |
+| Empty inherited action | Configure default routing | 配置默认路由 |
+| Dialog footer action | Restore automatic | 恢复自动 |
+| Draft recovery | Undo restore | 撤销恢复 |
-**One failed read is not an engine verdict** `[derived]`. This drawer's list came from
-one request, and that request failing says the request failed. Sending the drawer to §1.0
-Unreachable — as this section read until this round — makes the page behind it declare the
-runtime down on that single piece of evidence, and it does so while the page's own runtime
-read may be sitting right there saying `ok`. The two readings then disagree on screen, and
-the one with less evidence wins. So the failure stays where the evidence is: the drawer
-keeps its own row, says what it could not read, and offers the read again. A runtime that
-really is down is reported by the read that actually watches it, and 重试 from here will
-find that out honestly rather than announce it.
-
-**These three keys are what F1 costs, and 重试 is bought once** `[derived]`. Saving and
-Sources unread are both F1 states, and F1 is 「the message is replaced in the slot the
-result would have used, the primary becomes 重试」 (§0.8) — so each owes one line, and a
-drawer that carried neither would be specifying a treatment it cannot render. The label is
-shared because it is the same word in the same place on a surface that never shows both
-lines at once: a drawer with no list to reorder has nothing to save. Both lines say what
-did not happen and nothing about why. The save sends the complete order to the atomic
-reorder operation, while the drawer keeps every move the user made, and the frozen rule against enumerating request-level failure
-kinds means a 401, a 409 and a timeout are the same sentence here — the same shape
-§1.6 gives `fail.tier`.
-
-**The copy says priority and fallback** `[derived]`. 保存顺序 stores the source order and
-applies it to existing Route hops (§4.6), so the first listed upstream is tried first and
-the next priority is used automatically for fallback-eligible quota, rate-limit, server,
-authentication, and network failures.
-The two section labels remain about membership in the priority list: 排在这条顺序里 and
-未排入这条顺序.
-
-**Extreme data** `[derived]`
-
-- **13 rows**: `dbody` scrolls; the head and the foot with its two buttons stay pinned.
- The page behind the scrim does not scroll.
-- **Zero eligible sources**: both sections are empty; the drawer shows one line —
- 「这个后端还没有可用来源。」 — and 保存顺序 is disabled. The drawer still opens; a
- surface that refuses to open cannot explain why it is empty.
-- **Empty order, held-out sources remaining** `[derived]`: the *ordered* section renders
- 「这条顺序现在是空的。把下面的来源排进来。」 and the held-out rows stay listed with their
- 排进来 buttons; 保存顺序 stays enabled. This is a different emptiness from the one above
- and needs saying, because it is reachable by two routes and the repair is already on
- screen: a user can empty the order by hand with 移出, and a source that stops being
- eligible for this backend leaves both sections, so an order can also empty itself while
- a usable source sits one press away. 保存顺序 is deliberately **not** disabled here: an empty order is a real
- configuration — it means *place no source automatically when a new route is built* —
- and refusing to save it would trap a user who genuinely wants that in a drawer they
- cannot leave without undoing their work. What it does **not** mean is that the backend
- stops being supplied. This save stores the order and stably reorders existing
- Route hops without changing their membership or mappings; frame 01 goes on rendering
- whichever hop is runnable first. 没有可用来源 appears when a backend has no runnable
- hop, which an empty priority order neither causes nor prevents — it decides only what
- the next 加入 finds waiting for it.
-- **Exactly one source**: it renders at rank 1 with the mint badge, the grip is present
- but inert, and the drawer is still reachable — the order is trivially satisfied, not
- meaningless.
-- **A `needs_action` source already in the order** keeps its rank and shows its cause;
- it is not silently dropped.
-- **Long names**: source name truncates at the row width with the full value in
- `title`; the meta line truncates from the middle, keeping both ends.
-
----
+Reuse existing localized Save/Cancel/Retry and guard-impact copy. Origin-help behavior
+follows the routing revision above. Compatibility chains/reorder is not the new UI save
+path; when called it uses the same default guards and preserves manual arrays.
### 1.4 Frame 04 `XvCC4` — Add subscription
@@ -5461,19 +5274,12 @@ instead (§1.6, E-2), and the reasoning it replaced that with is better: the hin
never a decision the user can revisit, so making it findable buys nothing and teaches
everyone else that protocols are their problem.
-**D-9 — The source order is a backend-scoped priority, persisted separately and applied
-explicitly to existing Routes.** One order per gateway-mode backend. The atomic
-`chains/reorder` operation stores the complete order and stably places listed Sources
-first in every existing Route while preserving each exact hop pair. Runtime then reads
-the stored chain and chooses its first runnable hop among the sources already configured
-there. No later state of the list changes a chain until the user saves the drawer again.
-*Why:* N sources × M models of hand-wiring is a configuration surface nobody can hold in
-their head, so a backend-level priority gives one clear way to update all existing
-chains without inventing a second per-model policy. The operation changes order only,
-never membership or mappings. Per-backend rather than global because eligibility already
-differs per backend: a global list would have to render entries that cannot apply.
-
-**D-9a — A backend in 直连 mode exposes no order surface at all.** No 调整优先级 button
+**D-9 — Default routing belongs to one backend.** Its ordered subset supplies the
+effective planner for inherited models. Sources PUT changes this subset under exact-plan
+guards and leaves manual arrays unchanged. Inventory chooses the matching tier before
+passthrough; health determines which planned hop is runnable.
+
+**D-9a — A backend in 直连 mode exposes no order surface at all.** No 默认路由 button
on its group head, and the drawer is unreachable for it.
*Why:* a direct backend consults no source order, so the editor would edit a list
nothing reads — the most expensive kind of dead control, because it looks like it
@@ -5548,7 +5354,7 @@ is caught by users.
**D-18 — Placement is the mode surface; there is no mode switch widget.** A backend's
mode is expressed by *where its configuration lives* — a 直连 backend has a
-切换到网关 action and nothing else, a 网关 backend has 调整优先级, model rows and
+切换到网关 action and nothing else, a 网关 backend has 默认路由, model rows and
切到直连.
*Why:* a mode toggle would make the two modes look like two settings of one thing,
inviting the user to flip it and see. They are two different configuration models with
@@ -5671,62 +5477,12 @@ fact a source can carry, while an unknown protocol is a value every later reques
have to guess. Stated as a property rather than as a permission, it also decides cases
nobody has drawn yet: any future add path inherits the same test.
-**D-28 — A backend-order surface reads `AgentSupply.sources`, that backend's stored Source
-order; a source card reads `adopted_by`. Neither substitutes for the other.** §1.3 owns
-the first reading — it is the list the atomic `POST /api/models/agents/<backend>/chains/reorder`
-stores and re-echoes in `{agent: AgentSupply}` —
-and §1.0 owns the second; this decision is only about the prohibition on deriving either
-from the other.
-*Why:* the two diverge on an ordinary page, not only in edge cases, and they diverge in
-**both** directions. `adopted_by` names Hub-mode backends whose persisted Route chains
-reference the source, de-duplicated by backend and carrying no position. The Source order
-names the sources a user placed under a backend, in a sequence, and `agent-supply.schema.json`
-calls it 「stored configuration and an Add-time placement input」. Those are different sets
-in each direction: a source can sit in a backend's order while no chain on that backend
-names it, and a source can be adopted by a backend whose order does not contain it,
-because a chain may name any source and 移出 does not remove the hop. Read the order into
-the card and it reports a priority rather than adoption; read `adopted_by` into the drawer
-and every held-out source and every ordered-but-unreferenced source vanishes from the list
-the drawer exists to edit, while the field's missing position makes an order impossible to
-reconstruct at all.
-
-*And neither is the stored chain, which is a third projection with its own owner.* §1.2's
-route-chain editor is where hop order lives, at per-model grain. The prohibition covers
-that pair too: a card that read a chain would have to pick one hop — first, serving, any —
-and each answer is a different sentence that changes under the user with no edit and no
-notification. **Naming the Source order here does not make it live supply state.**
-`model-hub.md` §4.2 is explicit that it is a visible Gateway priority and that runtime
-executes the exact hop order stored for each model. The drawer's atomic chains/reorder
-save is the explicit bridge: it stores the priority and applies it to existing Routes
-without changing hop membership or mappings. This decision assigns each surface
-the projection it displays; it does not promote any of the three into an input for another.
-
-Neither projection reports live supply, and the card must not be written as though one
-did. `api.md` calls `adopted_by` 「the stable Source-card projection of persisted
-references」, and *stable* is the whole property: the array is unchanged by a cooldown, a
-revoked credential, or a takeover routing past this hop. So the card's question is 「who
-has this configured」, the drawer's is 「in what order」, and 「who is drawing from it right
-now」 is a third question **neither field answers** — it needs the per-chain runnability
-read, at row grain, on a payload this page does not fetch. Naming it as a third question
-rather than assigning it to `adopted_by` is the point of this decision: the earlier
-wording claimed the field 「combines runnability」, which the contract does not say and the
-word *stable* rules out, and a card built on that reads 使用中 beside a source whose
-credential died an hour ago.
-
-*This decision was re-derived at `ca45aeb6`, and the field it originally named is gone.*
-It used to read 「a backend-order surface reads `order_enrolled_by`」, with a divergence
-argued from enrolment-without-adoption. S-1 deletes enrolment, and `order_enrolled_by`
-goes with it, so the old sentence named a field no implementation can read. The decision
-survives because what it actually governs is *which projection answers which question*,
-and the projections that answer them still exist — `AgentSupply.sources` and `adopted_by`
-— but it survives as a re-derivation, not as a citation that quietly kept pointing at a
-deleted field. The first re-derivation replaced the deleted field with 「the stored
-chain」, which was the wrong substitute for a second time: §1.3 saves and reads back
-`AgentSupply`, never a chain, so the rule named a projection its own owning section does
-not fetch. The correction is recorded here rather than applied silently, because the
-failure mode is the interesting part — a re-derivation done in one pass over the decision
-and not over the section it governs. Worth recording, because nothing in the review
-flagged it: a citation to a deleted name reads exactly like a citation to a live one.
+**D-28 — Each surface consumes its server-owned projection.** Default routing reads
+`AgentSupply.sources`; Source cards read effective `adopted_by`; model rows/editors
+read effective AgentChain with actual `manual_override` and `route_origin`.
+Default Sources may be absent from matching tiers; manual routes may name other eligible
+Sources. Neither membership nor adoption is live health. No frontend inventory matching
+or array-equality heuristic derives route intent.
**D-29 — The page is 「模型」, the module is 「来源与网关」, and 「模型网关」 is never
rendered.** The project's name for this work is not a string in the product.
@@ -5893,10 +5649,10 @@ rather than spot-corrected.
| Which nouns UI copy may use, and which are required | `model-hub.md` §3 — *Vocabulary (v3 recut; UI copy uses only these nouns)* |
| What a source is and what it carries | `model-hub.md` §4.1 — *Supply — Sources (global assets, no ordering)* |
| How a chain is populated when a Source is added | `model-hub.md` §4.2 — *Gateway strategy — add-time defaults, then explicit configuration* |
-| **How a request executes a stored chain — the sole authority** | `model-hub.md` §4.3 — *The only normative configured-chain execution algorithm* |
+| **How a request executes an effective chain — the sole authority** | `model-hub.md` §4.3 — *The only normative effective-chain execution algorithm* |
| Whether eligibility is client- or server-decided | `model-hub.md` §4.4 — *Configuration eligibility is server-authoritative (v3)* |
| Source states, self-healing classes, `detail_key` vocabulary | `model-hub.md` §4.5 — *State taxonomy — classified by "does it heal itself"* |
-| How a configured chain is stored and mutated | `model-hub.md` §4.6 — *Configured-chain storage and mutation* |
+| How a configured chain is stored and mutated | `model-hub.md` §4.6 — *Route intent storage and mutation* |
| Downstream Agents | `model-hub.md` §4.7 |
| OpenCode identifier scheme | `model-hub.md` §4.8 — *locked 07-23, retained in v3* |
| Which module owns which class of configuration | `model-hub.md` §5 — *Surfaces — two modules, one understandable handoff* |
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 111f3bd7c..8f83e6e77 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1,19 +1,13 @@
# Model Hub — Product Spec
-Status: **v3.1** (2026-09-05): §4.8 replaced by the OpenCode v4 identifier scheme and §4.2's
-OpenCode branch retired · v3.0 (2026-08-09) supersedes v2.0 (2026-07-29) outright
-Owner decisions incorporated through: 2026-09-05 (+08:00)
-Design source: `../avibe-docs/design.pen`. The V6 frames remain the visual baseline;
-the v3 interaction draft for the two-module information architecture is owner-approved
-as the implementation baseline (2026-08-07 afternoon). The design lane still owes
-production-complete desktop/mobile states.
-Pre-release (owner, 2026-09-05): Model Hub has not shipped; no revision of its persisted
-state or contracts carries migration or compatibility handling (see `model-hub-contracts/README.md`).
-Contracts: v3.1 changes `model-hub-contracts/api.md` (OpenCode identifier rule) and rewrites
-`model-hub-contracts/opencode-overlay.md` (v4); every other contract file is unchanged.
-`model-hub-implementation.md` records the exhaustive final-shape handoff. Its mechanical
-closure must coexist on one tested PR head; all remaining consumers and evidence must
-land before release.
+Status: **Routing modes, contract_version 9** (2026-09-06).
+Owner-approved implementation contract: `model-hub-routing-modes.md`, frozen before
+implementation at `2db273891`, amended by owner scope/synchronization decision `c1d398d5f`. It replaces one-time matching with sparse manual
+intent and a shared effective planner. The complete schema, runtime, UI and consumer
+closure lands on one tested feature head. Supported persisted shapes and historical
+TurnProvenance remain readable under the repository persisted-shape rule.
+Design source: `../avibe-docs/design.pen`; approved routing frames `bmi25`, `ziils`,
+`NuxyR`, `jCs2A`, `ztAos`, `P6Zi8k`, and reusable row `tFl3R`.
## 0. Revision note — why v3 replaces v2
@@ -26,25 +20,22 @@ Its end-to-end product model is:
retry, and recovery;
3. downstream Agents — consumers of the Gateway, not owners of upstream credentials.
-Every `(backend, menu model)` owns one persisted ordered route chain, and every hop
-names the exact `(source_id, model_id)` to call. This formally supersedes v2 §9's “No
-per-model ordering” non-goal on 2026-08-07.
-
-**Configured-chain ruling (owner 2026-08-09, S-1).** Matching happens when a Source is
-added and writes the resulting exact hops. From then on the Gateway screen is the
-configuration and the configuration is what executes: users add, remove, reorder, or
-edit a hop's explicit model mapping, while runtime only walks those hops and classifies
-live availability and fallthrough. There is no `follow | custom` state, no runtime
-Source/model matching, and no second projection from a backend order. §4.3 is the only
-normative execution algorithm for this stored chain.
-
-The final product has no separate fixed-menu `mappings` structure beside route chains.
-A same-model choice is simply a hop whose `model_id` equals the menu model; a mapped
-choice is a hop whose explicit `model_id` differs. Both are ordinary configured hops.
-The final shape and its rationale are in §4.6 and are **owner-vetoable (2026-08-07,
-amended by S-1 on 2026-08-09)**. Model Hub has not shipped, so no compatibility layer,
-data conversion, policy transition, or second routing authority is part of the
-implementation.
+Every `(backend, menu model)` has one effective ordered route. A sparse persisted
+`routes` map stores only manual overrides; every hop names the exact
+`(source_id, model_id)` to call. Absence inherits automatic defaults, while a present
+empty override intentionally supplies nothing. Saving a route establishes manual
+intent even when its array equals the generated result; restoring automatic deletes
+the key.
+
+For API-key defaults [A, B], model M uses B alone when only B lists M. When neither lists M,
+the route is [A/M, B/M], forwarding M unchanged. A saved manual route replaces the
+whole generated chain. API-key inventory is matching evidence, not an invocation whitelist. Subscriptions keep
+their existing known-model admission, matching and stale-hop retention rules. Unknown
+passthrough is restricted to eligible Hub API-key Sources; unmatched subscription-only
+defaults are Unconfigured.
+§4.2 owns effective planning and §4.3 owns execution of that plan. There is no separate
+mapping structure or second persisted policy flag. Existing populated, empty, stale
+and dormant overrides remain exact; historical arrays do not prove human authorship.
**Subscription ruling (owner 2026-08-07, amended later the same day).** Recommended
custody is vendor-specific. Claude subscriptions stay in Claude Code's local login by
@@ -105,13 +96,12 @@ base URLs, protocol conversion, account pools or routers.
Source. Each backend has at most one native Source. §4.3 defines the complete
native-to-Gateway handoff, recovery, and no-replay behavior without placing a hidden
native attempt ahead of a user-owned configured chain.
-3. **Every route is visible configuration.** Each `(backend, menu model)` stores one
- exact ordered chain of `(source_id, model_id)` hops. Adding a Source proposes and
- persists its matches once; afterward the user edits that same chain directly.
+3. **Every route exposes its intent and effective result.** Backend defaults generate
+ automatic matches or unchanged-id API-key passthrough. A manual override replaces that result
+ exactly, including an empty array; Restore automatic removes the override.
4. **The user owns every configured order and mapping.** No health score, learned
- ranking, vendor label, or runtime inventory walk silently rewrites the chain. Avibe
- may skip an unrunnable hop for the current turn; it never mutates configured order
- or model ids as a side effect.
+ ranking or vendor label rewrites manual intent. Automatic routes follow current
+ defaults and evidence; live availability only annotates the chosen plan.
5. **Adaptation stays local and invisible.** The Gateway performs protocol
conversion, retry, failover, and recovery. Agents consume a stable model menu;
users never configure an engine plugin or account pool.
@@ -384,7 +374,7 @@ third-party and open-source upstreams expose it as their only compatible surface
A source carries **no position, rank, or priority field of its own**. The Sources
module is an asset inventory sorted for reading convenience. Gateway configuration
-owns one explicit Source order per backend and one exact Route chain per menu model;
+owns backend default Source orders and sparse manual per-model overrides;
neither order is stored on a Source.
**Supply channel.** Each source has a `supply_channel`:
@@ -423,134 +413,74 @@ That sentence does not appear for native Claude, ChatGPT in either channel, or w
the user later places an already-added Source in a cross-vendor chain.
The same model may be supplied by multiple Sources; §4.3 alone executes the exact
-stored route for that model.
-
-### 4.2 Gateway strategy — add-time defaults, global priority, then explicit configuration
-
-One record per Agent backend owns `mode`, its menu, one stored Source order, and one
-stored Route chain for each menu model. The Source order is the visible Gateway priority
-and the Add-time placement input. Saving that priority atomically stores the complete
-order and applies it to existing Routes without changing their hop membership or
-mappings. There is no backend Source-order policy discriminator
-and no per-model route policy. Runtime executes the exact hop order stored for each model.
-
-Matching has exactly three one-time write points. Add Source matches the discovered
-inventory observed by that transaction and appends accepted hops. A backend menu-model
-add matches that one new row against the complete non-retired inventory (discovered and
-manual) of configuration-eligible Sources in the backend's stored Source order, then
-writes accepted hops in that order. A built-in reconcile add uses that same menu-model
-match and seeds the built-in snapshot's label and reasoning efforts. A later refresh,
-restart, health change, or turn never repeats any match for an existing row. Users maintain persisted chains directly after creation:
-add or remove a hop, move it, or edit its explicit upstream `model_id` mapping.
-
-Cancellation of Source creation has one commit boundary. Before the durable Source
-commit, AC-26's transient-reference cleanup and pending-revocation accounting complete
-before cancellation settles. After the commit, cancellation only ends the caller's
-wait: Source creation and accepted placement finish atomically, remain readable after
-reload, and have no server-side abort or rollback branch.
-
-**Add-time Source placement policy (sole authority; owner 2026-08-09 S-1).** The Add
-Source service owns one write-time rule that chooses deterministic positions for the
-new Source and every accepted exact match. The same transaction writes those positions,
-returns each hop through `added_to.position`, and exposes the canonical backend Source
-order; the Gateway renders the stored results and the user may adjust them immediately.
-No adapter, UI consumer, refresh path, or runtime resolver may implement or rerun
-placement. This named policy is one implementation rule, not a plugin point, registry,
-user setting, or persisted policy discriminator.
-
-**Current policy value (`placement-v1`).** Append a newly added Source to each
-configuration-eligible backend Source order, and append every accepted exact match to
-that menu model's current Route-chain tail. For a newly added menu model, write one
-accepted hop per supplier in the already stored Source order. This is only the current policy value, not
-an API, UI, or acceptance invariant. A later version may choose a better visible
-position from model fit or a fixed Source-reliability priority, but it must still run
-only at one of the three one-time write points, persist the chosen position, and leave runtime to execute that
-configuration verbatim. There is no “new Source not enabled” state or prompt, and the
-UI never uses position to distinguish new from old.
-
-No health score, latency, cost, usage, vendor label, creation timestamp, or later
-inventory result reorders existing configuration. `created_at` remains ordinary Source
-metadata for audit/display; routing and placement never read or mutate it.
-
-The explicit `POST /api/models/agents/<backend>/chains/reorder` operation is the sole
-server-side post-creation operation that implicitly applies the stored Source-order
-sequence to existing Routes. When the UI supplies an `order` body, persisting that
-order and applying it to existing Routes are one mutation; an omitted body applies the
-already stored order. It reorders existing hops only, preserves every exact
-`(source_id, model_id)` member and mapping, and never reruns matching. Its complete stable
-order is defined in §4.6. A user-authored per-model `hops` PUT carries only the submitted
-explicit hop order, and its server handler never reads `sources.order`; an editor may use
-its page-held Source-order projection to help sort a local draft, but that draft becomes
-explicit `hops` with no Source-order semantics on the wire. Because the all-chain operation
-cannot remove supply, it has no guarded `409`, `force`, or interruption branch even when
-the first hop changes.
-
-On `PATCH /api/models/agents/<backend>/mode`, a `direct` → `hub` transition also owns
-one bounded adoption transaction. If the backend has a sanctioned, recognized CLI
-login and no `native_cli` Source, that transaction creates the singleton native Source,
-applies `placement-v1`, commits every accepted exact match, changes mode, and only then
-assembles the returned AgentSupply. An existing native Source, an absent or
-unrecognized login, or another mode transition creates nothing. Repetition cannot
-create a second native Source.
-
-**Current matching value (`matching-v1`).** Add Source uses the discovered inventory
-observed by that transaction. A menu-model add uses the same matcher, including the
-Claude alias rule, over each ordered eligible Source's complete non-retired inventory.
-All three persist the concrete upstream id in the Route hop. Matching runs once for each add
-and is never re-run by refresh, restart, health changes, or turn execution.
-
-| Backend/source case | Candidate set | Accepted match and tie-break |
-| --- | --- | --- |
-| Claude fixed-menu id on a native `anthropic` Source | The Source's `discovered` models observed by this add transaction | A dated request is literal only. An undated version request matches the same family and exact version tuple; a bare `opus`, `sonnet`, or `haiku` alias matches that family at any version. Select `max(version_tuple, date_or_zero, model_id)`. `fable` has no bare alias. |
-| OpenCode menu id (v4, 2026-09-04) | The Source's observed models | Literal model-id equality only, exactly as Codex. The retired `provider/model` projection has no matching branch. |
-| Codex fixed-menu id, or any non-native Source | The Source's observed models | Literal model-id equality only. Explicit user route edits may name an exact model, but runtime never infers or substitutes one. |
+effective route for that model.
-The resulting hop always contains the selected concrete upstream model id, never the menu
-alias. A missing or ambiguous match leaves that menu model's Route empty; it does not
-create a runtime matching branch.
+### 4.2 Gateway strategy - backend defaults and sparse manual overrides
-The `matching-v1` decision is normative and exhaustive:
+Each backend owns `sources.order`, the sole default membership and priority, and a
+sparse `routes` map. Source assets own no ordering. Source creation and native import
+append a new eligible Source to defaults in the existing deterministic placement
+transaction. They never append hops to manual arrays or seed route keys. Catalog
+creation and built-in reconciliation add model metadata without a route key.
-```text
-for each configuration-eligible Source added in this transaction:
- candidates = [request.protocol] if selected else SOURCE_PROTOCOLS
- observed = response_backed_observation(Source, candidates)
- if observed.protocol is null:
- persist no Source and no Route hop
- return the classified observation failure
-
- for each backend menu model M:
- candidates = observed.discovered_models
- if backend == claude and Source is native anthropic:
- match = native_claude_alias(M, candidates)
- else:
- match = literal_model_id(M, candidates)
-
- if match is not null:
- append {source_id: Source.id, model_id: match} to the stored Route tail
-
- persist the Source and all accepted concrete hops once
-```
+Cancellation retains one durable Source commit boundary: before commit, transient
+cleanup and pending-revocation accounting finish; after commit, cancellation ends the
+caller wait but does not roll back committed Source/default placement.
-`native_claude_alias` is the literal former resolver rule: dated requests are literal;
-undated version requests require an equal version tuple; bare aliases match a family;
-the total order is `(version_tuple, date_or_zero, model_id)`. No other backend gets an
-alias family — OpenCode menu ids match literally (v4, 2026-09-04) — and explicit
-user-authored Route edits remain literal configuration.
+The pure planner in `core/handlers/model_hub/resolver.py` produces
+`{manual_override, route_origin, hops}` from the current configuration, backend and
+canonical requested model. Preview invokes that owner with an isolated draft config.
+Reads, summaries, guards, adoption, probes, launches and execution consume this result.
-**Routing configuration is per backend and per model; health is Source-global.** Quota
-and reachability belong to the Source, not the Agent that touched it. §4.3 reads the
-stored chain and annotates its live execution state; it does not construct another
-chain.
+**Effective-route decision matrix (authoritative and exhaustive).** Conditions are
+evaluated in this order, before transient health or invocation-channel filtering.
-### 4.3 The only normative configured-chain execution algorithm
+| Decision | Condition | Effective hops | Origin |
+| --- | --- | --- | --- |
+| `route_plan.manual` | a manual key exists | exact saved array and order, including empty | manual when nonempty, otherwise null |
+| `route_plan.automatic` | no manual key; eligible defaults provide matching evidence | all accepted matching pairs in default order | automatic |
+| `route_plan.passthrough` | no manual key and no matching pairs; eligible non-retired Hub API-key defaults remain | exact requested id on each such API-key Source; no subscription speculation | passthrough |
+| `route_plan.empty` | no manual key and neither tier has any eligible pair | empty | null |
+
+Matching uses complete non-retired inventory, independent of health and CLI readiness:
-For backend `B` and menu model `M`, let `C` be the exact persisted hop array at
-`B.routes[M].hops`. Every hop is `{source_id, model_id}` and its `model_id` is the exact
-upstream value to invoke. Configuration writes validate Source existence, channel
-binding, and that the Source can call the submitted model; any alias resolution or
-suggested mapping is completed before the hop is stored. Runtime never matches by
-vendor or inventory, inserts a Source, substitutes a model, or reorders `C`.
+| Backend/source case | Accepted match and tie-break |
+| --- | --- |
+| Claude on native anthropic Source | Reuse the existing alias parser: dated request is literal; undated version requires exact family/version tuple; bare opus, sonnet or haiku matches the family. Select max(version tuple, date or zero, model id). Fable has no bare alias. |
+| Other backend or API Source | Literal canonical model-id equality only. No vendor or fuzzy inference. |
+
+A matching tier never gains speculative passthrough hops. A Hub-only HTTP request
+filters transport availability after planning; a native matching tier cannot cause a
+second passthrough tier to be invented. Explicit `retired: true` excludes that exact
+Source/model pair from matching, passthrough and invocation. An absent API-key inventory row
+alone excludes nothing from invocation. Subscription membership and retirement admission
+remain unchanged, including stale-hop retention. Deleting an API-key manual inventory row
+removes matching evidence and preserves explicit routes; subscription deletion retains
+its existing admission and guard semantics. Source deletion still atomically
+removes its references under §4.5 guards.
+
+The planner never writes configuration. Manual intent survives Source additions,
+default edits, discovery, catalog changes, health changes and reload. Automatic routes
+follow current defaults and evidence. Equal-to-automatic manual saves remain manual;
+there is no historical-authorship inference or global reinterpretation of empty arrays.
+Source health, quota, latency, cost, usage and timestamps never choose a tier or reorder
+it. Live inspection only annotates runnability, current position and recovery state.
+
+Sources PUT replaces defaults atomically and guards actual effective hop/supply removal.
+The compatibility chains/reorder POST has identical semantics when order is supplied;
+without order it returns the current projection. Neither operation changes manual
+arrays. Pure reordering without removal needs no guard. Direct-to-Hub adoption still
+recognizes and creates at most one sanctioned native Source in the mode transaction,
+appends default membership, and then projects the effective routes.
+
+### 4.3 The only normative effective-chain execution algorithm
+
+For backend `B` and menu model `M`, let `C` be §4.2's effective hop array.
+Each hop's model id is the exact upstream value to invoke. New or changed manual pairs
+validate canonical nonempty identifiers, Source existence/eligibility and explicit
+retirement; API-key inventory membership is not required. Subscription targets retain
+existing model-membership admission and stale-hop retention. Existing stale manual arrays remain
+readable. The executor preserves the chosen tier, membership and order.
The following pseudocode is normative and exhaustive:
@@ -559,7 +489,7 @@ if B.mode == "direct":
return DIRECT
attempted = false
-for hop in C, in stored order:
+for hop in C, in effective-plan order:
live = inspect_exact_hop(hop)
annotate hop with live.runnable, live.reason, and live.retry_at
if not live.runnable:
@@ -765,7 +695,7 @@ Source this runtime has not attempted again. Refusing a health write is never pu
history, the terminal outcome, and the projection are unaffected.
**Takeover projection.** A configured route is in **takeover** exactly when its current
-hop is not the first stored hop and that first hop is unavailable for a
+hop is not the first effective hop and that first hop is unavailable for a
self-healing quota/cooldown or live connection-backoff reason. This is computed from the resolved chain's current
hop and live runnability; it is never a stored boolean or a second routing field. A
chain with no runnable hop is not takeover: it reaches §4.5's truthful `exhausted`
@@ -800,7 +730,7 @@ channel-aware matrix:
inside that CLI. For `hub`, it may contain any supported backend selected by Gateway
configuration, including a cross-vendor consumer. No flag or consent record changes
either result. Runtime does not re-run this matrix to choose or reject a provider; a
-validated stored hop is its authority.
+validated effective hop is its authority.
The agents payload
now carries a per-source eligibility signal (`eligible` + `reason_key`) computed
@@ -835,7 +765,7 @@ configuration:
drawer unable to say anything about a model the menu offers. Neither half is
expressible — `uniqueItems` compares whole items, so rows differing only in
`chain_length` pass, and coverage is a relation to a different document.
-- **`AgentChain.chain`** — preserves the exact stored hop order and model ids. Its only
+- **`AgentChain.chain`** — preserves the exact effective-plan hop order and model ids. Its only
additional fields are live annotations and current execution position; no consumer
performs another Source/model walk.
@@ -950,7 +880,7 @@ splits — on whether the user owes an action:
| `ok` | 正常 | — | serving from the intended head of the chain |
| `degraded` | 降级 | — | serving via a fallback, and/or some sources in the chain are down |
| `waiting` | 暂时全部在冷却 | **yes** | nothing runnable right now, but every blocker is a persisted cooldown or live connection backoff — recovers unattended at the earliest `retry_at` |
-| `interrupted` | 无可用来源 | **no** | nothing runnable and the stored chain is empty or at least one hop has a non-self-healing blocker: `needs_action`, `error`, `source_missing`, `model_unsupported`, or `native_cli_unavailable` |
+| `interrupted` | 无可用来源 | **no** | nothing runnable and the effective chain is empty or at least one hop has a non-self-healing blocker: `needs_action`, `error`, `source_missing`, `model_unsupported`, or `native_cli_unavailable` |
These four values are the **only backend-level supply-health wording**. The Gateway
backend-group subtitle and the Usage page render this projection directly; neither
@@ -1101,7 +1031,7 @@ What survives the cut, so the removed text is not read back in:
pill to 「affected」 for as long as the event is retained — a recovery could never
clear it. The event is what the **feed** renders; it is not what the **pill** reads.
The pill reads the source's live blocking state — the same **contracted** facts the
- configured-chain executor checks before invoking each stored hop: `state.status` and,
+ configured-chain executor checks before invoking each effective hop: `state.status` and,
for a cooling-down source, `state.retry_at` (`source.schema.json`), surfaced per chain entry as
`runnable` (`agent-chain.schema.json`). **No `blocked_until` field exists anywhere in
the contracts** (corrected 07-29, review round 9: the earlier
@@ -1116,7 +1046,7 @@ What survives the cut, so the removed text is not read back in:
none needed. That test is the
consumer's, evaluated at render time; it is not a field.
Note that the configured-chain grain is what makes it right: Source inventory alone
- does not mean a backend uses that Source. Only an exact stored hop creates impact, so
+ does not mean a backend uses that Source. Only an exact effective hop creates impact, so
an unrelated Source failure cannot mark a backend degraded. A **backend-scoped** kind
(`supply_interrupted`, whose cause is that backend's configured route) still names
exactly the one backend it is about, because
@@ -1148,7 +1078,7 @@ switch, remedy, or message branch absent from it.
| `turn.exhausted` | `exhausted` | final model `supply_state` from the §4.5 taxonomy | fallback walked to the end; no attempt completed | `waiting` renders `models.launch.waiting`; `interrupted` renders `models.launch.interrupted` with the classified blockers |
| `turn.request_nonfallback` | `failed_terminal` | any non-fallback request-level failure | the attempted Source remains runnable and no switch occurred | `models.launch.request_incompatible`: this request is incompatible; switching Sources will not help |
| `turn.engine_down` | `failed_terminal` | local `engine_down` at any request phase, including after an upstream attempt or streamed output | no Source is blamed or mutated; no replay or next-hop walk occurs | `models.errors.engine_down`; after output began it also states that this turn's output may be incomplete |
-| `turn.streamed_fallback` | `failed_terminal` | streamed fallback-class Source failure, plus `source_transition_persisted: boolean` recording whether its cooldown or `needs_action` transition was committed | replay is forbidden. When `source_transition_persisted=true`, render `models.launch.retry` only when live inspection of the same stored chain makes a different hop current for the next turn; otherwise no switch exists. When `false`, attempt history remains committed, no switch/current change is claimed, and the existing config-recovery warning owns remediation | persisted with a different current hop: “The next turn has switched Sources; retry.” Persisted with no runnable hop: use the same `waiting`/`interrupted` rendering selected for `exhausted`. Not persisted: `modelHub.errors.stream_interrupted`, with no route-change or new-remedy claim |
+| `turn.streamed_fallback` | `failed_terminal` | streamed fallback-class Source failure, plus `source_transition_persisted: boolean` recording whether its cooldown or `needs_action` transition was committed | replay is forbidden. When `source_transition_persisted=true`, render `models.launch.retry` only when live inspection of the same effective chain makes a different hop current for the next turn; otherwise no switch exists. When `false`, attempt history remains committed, no switch/current change is claimed, and the existing config-recovery warning owns remediation | persisted with a different current hop: “The next turn has switched Sources; retry.” Persisted with no runnable hop: use the same `waiting`/`interrupted` rendering selected for `exhausted`. Not persisted: `modelHub.errors.stream_interrupted`, with no route-change or new-remedy claim |
| `turn.no_candidate.unconfigured` | `no_candidate` | configured chain is empty | no Source was attempted because no hop is configured | `models.launch.route_unconfigured`, naming the requested model and pointing to Models |
| `turn.no_candidate.blocked` | `no_candidate` | configured chain is nonempty and model `supply_state` is `waiting` or `interrupted` | no Source was attempted because every exact hop is currently blocked | derive copy from the exact blocker set and reuse `_launch_failure` remedies: reauthorize, replace the key, or top up; `waiting` uses `models.launch.waiting`, while `interrupted` uses `models.launch.interrupted` |
| `turn.canceled` | `canceled` | the turn FSM, never a transport inference, settled Stop/cancel | no Source failure or route switch is fabricated | no Model Hub supply copy; the existing turn-canceled surface owns the message |
@@ -1163,7 +1093,7 @@ land as standalone prose.
required only for `turn.streamed_fallback`. UI consumers deliberately do not consume it:
the selected copy key already carries the complete user-visible truth, following the
same optional-consumer discipline as `AgentSupply.routes`. It does not change
-`contract_version`, which remains `5`.
+`contract_version`, which is `9`.
One asymmetry has to be named, because it is easy to implement wrong: an Agent can enter
`interrupted` with **no Source changing state at all** — its route is unconfigured, a
@@ -1202,26 +1132,19 @@ the same references and positions as its refusal. This explicit cascade is
not the silent side effect prohibited by §2; without the confirmation, neither the
Source nor any chain changes.
-The same invariant applies to **every Source-inventory mutation**, not only Source
-deletion. Reversible or transactional changes — API-key Base URL replacement, API-key
-credential replacement, explicit refresh/recovery, discovered-model retirement, and
-manual-model deletion — first
-stage the resulting inventory and run **both** guards: compare it with every exact
-configured hop and recompute `would_interrupt` for every protected menu model. If an
-exact configured model would cease to be callable, the non-forced mutation is refused
-with `source_model_in_route_chain` and ordered `would_remove_hops`; another Source
-supplying the same menu model does not make that exact reference disposable. If no
-exact hop is lost but a protected route loses its last supplier, it is refused with
-`source_last_supplier`. When both apply, the exact-hop error leads and the response
-still carries both complete arrays. A confirmed `force=true` with an exact echo of both arrays applies the inventory
-change and removes only those invalidated hops in one transaction, preserving the
-identity and relative order of all survivors and keeping an empty route configured.
-It also reports every resulting supply gap; force is confirmation, not a claim that
-the mutation is interruption-free.
+Every Source/inventory mutation compares the before and staged-after effective plans
+under one commit lock. Inventory disappearance can change an automatic matching tier;
+it never invalidates an explicit API-key manual invocation by itself. Subscription
+model-membership admission remains unchanged. Explicit retirement
+excludes the exact pair, while manual inventory deletion removes matching evidence
+without deleting explicit API-key hops; subscription admission remains unchanged. Refusals report complete effective removals and protected
+supply loss in the existing arrays. Forced success must match both echoed arrays and
+preserves surviving manual intent; Source deletion removes its actual references.
+Automatic recomputation never persists a generated route or rewrites manual intent.
**Guard confirmation totality matrix (authoritative and exhaustive; owner subtraction
ruling 2026-08-11 20:35, with direct-Route scope corrected at 21:14).** The shared layer
-recomputes under the atomic commit boundary. For Source and inventory mutations, a
+recomputes under the atomic commit boundary. For Source, inventory, default-membership and Restore mutations, a
guarded-impact plan is nonempty when the staged mutation has at least one
`would_remove_hops` or `would_interrupt` item. For `mutation.route_replace`, only a
nonempty `would_interrupt` activates the plan: the refusal also reports its submitted
@@ -1267,34 +1190,24 @@ present even when empty.
| `mutation.source_refresh` | refresh/recover saved Source | `POST /api/models/sources/<id>/refresh` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409` | same Source success envelope |
| `mutation.model_create` | create a user-authored model entry | `POST /api/models/sources/<source_id>/models` with `{model_id, display_name?, reasoning_efforts}` | not guarded: it creates one new exact `id` with `origin: "manual"` and changes no existing `id`, `origin`, or Route | `{source: Source}` |
| `mutation.model_efforts` | replace one model entry's capability list | `PATCH /api/models/sources/<source_id>/models/<model_id>` with `{reasoning_efforts}` | not guarded: it changes no `id`, `origin`, or Route | `{source: Source}` |
-| `mutation.model_delete` | retire a discovered model or delete a manual model | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; discovered retirement is staged before evaluating exact-hop and protected-supply loss | same Source success envelope; discovered success preserves the row with `retired: true`, manual success removes it |
+| `mutation.model_delete` | retire a discovered pair or remove manual matching evidence | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; recompute effective impact after retirement or evidence removal; manual deletion preserves explicit hops | same Source success envelope; discovered success preserves the row with `retired: true`, manual success removes it |
| `mutation.source_delete` | delete Source | `DELETE /api/models/sources/<id>?force=<bool>` with body `{would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; a nonempty recomputed plan commits only when both arrays exactly match | `{removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` after atomically pruning the Source from every backend Source order and every Route chain while preserving each survivor order; the deleted Source is not returned and legacy `{ok}` is invalid |
| `mutation.route_replace` | replace one model's complete Route chain | `PUT /api/models/agents/<backend>/chain?model=<id>` with `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | only when `would_interrupt` is nonempty: `source_last_supplier` in the same guarded `409`, including all submitted removals; noninterrupting removal is ordinary success because it is the user's visible direct edit | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; noninterrupting removal needs no wire confirmation, and survivor order is the submitted order |
+| `mutation.route_restore` | restore automatic for one model | `DELETE /api/models/agents/<backend>/chain?model=<id>` with optional `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409` for actual effective removal or protected-supply loss | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; absent key is idempotent |
+| `mutation.default_sources` | replace backend default membership/order | `PUT /api/models/agents/<backend>/sources` with `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}`; compatibility `POST .../chains/reorder` accepts optional order and the same guards | same guarded `409` for effective removal or protected-supply loss; pure reorder needs none | `{agent: AgentSupply}`; preserve manual arrays; omitted reorder order returns current projection |
The request carrier shown in each row is the only one. The final `api.md`, server/client
envelopes, confirmation UI, and route tests mirror this matrix row-for-row.
-`PUT /api/models/agents/<backend>/sources` is intentionally outside the matrix: it
-changes only the persisted Source-order sequence, never a Route chain or its members, and
-must not gain a guarded `409` branch. The UI uses the explicit
-`POST /api/models/agents/<backend>/chains/reorder` operation with the complete order;
-that operation stores the order and applies it to existing Routes in one mutation while
-preserving the PUT's storage-only contract.
-Automatic background discovery never performs this cascade: when neither literal
-inventory nor sanctioned-alias evidence remains, it records the model as
-`model_unsupported`, keeps the configured hop visible and non-runnable, and waits for
-an explicit user refresh/edit to repair or confirm removal.
-
-Native CLI re-authentication and Hub OAuth re-authentication are the irreversible
-exception. Each presents AC-2's server-enforced acknowledgement **before** login starts;
-the user can abort there, but the product promises no rollback or post-login refusal
-once the OAuth exchange has begun. After authentication, the engine commits the
-resulting credential and any inventory it can establish. Exact hops whose source/model
-pair is no longer present remain visible but non-runnable with exactly
-`reason: "model_unsupported"` and `retry_at: null`, and the response reports the
-resulting gaps and `needs_action` work for a later explicit edit or force cascade. It never silently
-replaces the configured model or claims that the old supply is intact. Thus no
-credential lifecycle event or inventory drift silently calls a model the Source no
-longer advertises or rewrites the user's chain.
+The default-sources and restore rows use the same exact-plan confirmation protocol.
+Generated before/after hops determine reported positions and losses; `AgentSupply.routes`
+continues to carry only manual intent. Background inventory changes recompute automatic
+routes and keep explicit pairs callable unless explicitly retired or otherwise blocked.
+
+Native and Hub OAuth re-authentication retain acknowledgement before irreversible login.
+After authentication, credential and available inventory commit without rollback.
+Report resulting effective supply gaps. Missing API-key inventory does not itself make an
+explicit model unsupported; subscription targets retain existing membership checks; credential, Source, retirement and channel blockers retain
+their existing reasons and health taxonomy.
**Turn provenance.** Each turn whose attribution is **exact** records the model@source
that served it — the write rule below is what 「exact」 means, and it is the promise's
@@ -1302,22 +1215,51 @@ scope, not a caveat on it — and that record is readable through a contracted r
**It has no chat surface** (owner
ruling 2026-07-29 14:03, superseding the earlier 「per-turn detail in the conversation
surface」 phrasing): users should be unaware of supply machinery, so provenance
-inspection is a **debug affordance, not a user feature**, and it appears neither in
-the Web transcript nor on any IM platform. If it is ever surfaced, the place is the
-请求日志 / 诊断 entry in the 「模型」 page's 高级 area — a post-v3 candidate, not v3.
+inspection remains a **debug affordance** and appears neither in the Web transcript
+nor on any IM platform. The Recorded Error Detail Closure (`0de3d2f47`/`9cb9ebb53`)
+authorizes the route dialog's Latest recorded turn panel, superseding the earlier
+post-v3-only placement. It shows the latest retained exact turn's terminal error,
+not every request and not an error inferred from today's chain.
Mid-stream failure rendering comes only from §4.5's Turn-outcome copy matrix; this
provenance section does not infer or announce a switch. A Source left needing repair
still surfaces as 需处理 on the Models page, not as an appended turn message.
This promise needs an interface, not just a paragraph, so the frozen contract carries one:
-`turn-provenance.schema.json` + `GET /api/models/turns/<turn_id>/provenance`.
-It defines *what* is recorded and *how it is read*; where it is stored is the
-implementing lane's call, with one constraint — provenance is written when the turn
-resolves and stays readable after the process exits, because "which source paid for
+`turn-provenance.schema.json`, existing GET `/api/models/turns/<turn_id>/provenance`,
+and on-demand GET `/api/models/agents/<backend>/provenance?model=<id>`.
+The latter uses the standard v9 envelope and returns the latest persisted retained
+record matching backend/requested model, regardless of outcome, or null. It never
+starts/syncs the engine or adds history to AgentChain. The existing
+`BoundedProvenanceStore` remains the sole owner, with atomic writes and 500-record
+retention. Provenance is written when the turn resolves and stays readable after the
+process exits while retained, because "which source paid for
this turn" is a billing question the user asks days later, not just live. A turn
that switched sources mid-flight lists every attempt in order, so the record
explains the switch rather than merely naming the winner.
+**Recorded-error diagnostic selection (authoritative and exhaustive).**
+New terminal-error records may retain observed `http_status` (100-599 or null) and
+`upstream_error_code` (recognized upstream code or null). Historical records may omit
+both without rewriting. The diagnostic selection below does not change classification,
+fallback, specificity ranks or Source health. Arbitrary upstream strings, messages,
+bodies, headers and credentials are never persisted for the panel.
+
+| Decision | Condition | Recorded upstream_error_code |
+| --- | --- | --- |
+| `recorded_error.specific_model_not_found` | model_not_found was observed and the classified result is upstream_request_invalid | model_not_found, including when a generic invalid_request_error type was also observed |
+| `recorded_error.known_code` | the preceding row does not apply and at least one observed code belongs to UPSTREAM_MACHINE_ERROR_CODES | first recognized observed code in the existing machine-code specificity order |
+| `recorded_error.no_safe_code` | neither preceding row applies | null; never reconstruct a code from a reason or the current route |
+
+D28 mirrors this decision table. Enum membership is separately enforced by the backend
+consuming test `tests/test_model_hub_provenance.py::test_terminal_diagnostic_schema_uses_the_production_machine_code_authority`,
+which compares the schema code enum minus null with production
+`classification.UPSTREAM_MACHINE_ERROR_CODES`. Null is allowed separately, not added
+to the production vocabulary. A later retained turn without terminal_error clears the
+panel's older error. The panel and its details use the same record's timestamp and exact
+historical Source/model, including deleted Source ids; missing codes use generic reason
+copy. The dialog invalidates pending reads on close or model change and exposes retry
+after read failure. Cancel/Restore/Save never rewrite history.
+
**The write rule is: record only when the attribution is exact** (07-29 15:07 ruling,
guarded 16:35). The gateway credential is minted per **process scope**, and the turn is
resolved from that scope through the turn FSM. When the scope holds exactly one active
@@ -1374,44 +1316,44 @@ reconstructible by appending. That is a shape decision rather than a validation
it makes 「两个成功者」, 「成功者不在最后」 and 「摘要指向列表里没有的来源」 impossible to
write down, instead of invariants prose asks every implementer to respect.
-### 4.6 Configured-chain storage and mutation
+### 4.6 Route intent storage and mutation
-This section defines §4.3's persisted input and mutation boundary. Every known
-`(backend, menu model)` has one row:
+The sparse `routes` map stores only manual overrides:
```json
-{"hops": [{"source_id": "src_...", "model_id": "upstream-model-id"}]}
+{
+ "sources": {"order": ["src_default01", "src_default02"]},
+ "routes": {
+ "explicit-model": {"hops": [{"source_id": "src_default02", "model_id": "upstream-id"}]},
+ "deliberately-empty": {"hops": []}
+ }
+}
```
-Each backend also persists one `sources.order: string[]`. It is a visible Gateway
-configuration and Add-time placement input, contains only existing configuration-
-eligible Source ids, and has no `follow | custom` or other policy discriminator. A
-Source deletion removes its id from every backend order in the same transaction and
-preserves the relative order of survivors. Serialization/reload rejects a dangling id.
-
-`POST /api/models/agents/<backend>/chains/reorder` applies that sequence to every
-existing Route without changing Route membership or mappings. When its optional `order`
-body is present, it stores that sequence in the same mutation. For an original hop at
-index `i`, use stable key `(0, source_order_index, i)` when its Source appears in the
-current order and `(1, i, i)` otherwise, then sort lexicographically. Thus all listed
-Sources come first in configured order, hops sharing a listed Source retain their
-relative order, and all unlisted-Source hops follow while retaining their mutual
-relative order. The operation is idempotent, never runs matching, and never adds,
-removes, remaps, guards, or reports interruption. It is the only server-side existing-
-chain operation that implicitly reads and applies `sources.order`; storing a new Source
-order alone leaves every Route byte-identical. A per-model Route PUT is instead an explicit
-user-authored `hops` replacement: its handler does not read `sources.order`, even when the
-client used its already-held Source-order projection as a local draft-sorting aid.
-
-`hops` may be empty and is always present. A newly introduced menu model runs
-`matching-v1` once at that write and starts empty only when no ordered Source supplies it.
-Refresh, restart, health changes, and turns do not retroactively match it. Only either
-add-time match, an explicit user edit, or a confirmed guarded cascade changes the array.
-Hop order, Source identity, and model mapping are user-visible configuration.
+Other model ids have no key and follow §4.2. Manual sources may be eligible Sources
+outside the default subset. Preserve every existing override and exact array, including
+empty, stale and dormant OpenCode entries; older supported config shapes use the safe
+loader and explicit historical intent where available, never inference from Source
+order. Unrelated config remains unchanged across compatibility loading and reload.
+
+GET chain and chains return effective hops with `manual_override` and `route_origin`.
+PUT chain always persists the submitted override. DELETE chain removes the key,
+recomputes defaults and is idempotent when absent. POST chain/preview requires
+`{manual_override: null | {hops: RouteHop[]}}` and returns the same AgentChain read
+envelope without persistence, events, engine startup/sync, credentials or upstream
+egress, even with runtime stopped. Empty effective chains have null origin; a present
+empty override is distinguished by `manual_override: {hops: []}`.
+
+Restore automatic changes the editor draft only. Undo restores the manual draft;
+Cancel writes nothing. Save sends DELETE for restored automatic or PUT for manual,
+consumes the authoritative mutation envelope, retains failed drafts and follows the
+existing exact-plan guard/reconciliation protocol. Sources PUT and compatibility
+chains/reorder update defaults only, preserving manual arrays and using effective
+removal/supply guards. §4.5 fixes the exact request and response fields.
The full-list model PUT keeps its three-way merge. Caller additions are the ids in the
desired list but not its baseline; only one still absent from the latest stored list is
-seeded, so a concurrently added row and its Route survive untouched. For caller additions,
+added without a route key, so a concurrently added row and its manual intent survive untouched. For caller additions,
the optional `expected_suppliers` map echoes the picker's ordered `(source_id, model_id)`
projection. The server recomputes every listed projection before staging the mutation. Any
difference refuses the whole write with `candidate_suppliers_changed` and a `changed` map
@@ -1428,7 +1370,7 @@ notification from the UI process. A partial snapshot only exposes fewer built-in
moment; it never infers a removal or tombstone. Each snapshot change adds, but never
removes, missing built-ins not in the set, in snapshot order among built-ins already present
(or at the menu tail when none remain), seeds snapshot label and reasoning efforts, and
-runs the same one-time menu-add match. Remote-catalog payload, validators, success, failure,
+leaves each new row automatic without seeding route keys. Remote-catalog payload, validators, success, failure,
and backoff state are keyed by the configured catalog source. Claude's locked `default` row
is excluded.
@@ -1441,17 +1383,12 @@ guarded cascade removes it. Source deletion follows §4.5's transaction: a non-f
delete refuses while any route names the Source; a confirmed delete removes all such
hops across all backends and preserves survivor order.
-There is no separate `mappings` field, policy discriminator, matching resolver, or
-mapping diagnostic. `model_id == menu_model` is an identity mapping;
-another explicit `model_id` is a user-configured substitution and must be invoked as
-written. **The system never invents a substitution; user-configured mappings are legal
-and authoritative.** This final-shape decision is **owner-vetoable (2026-08-07,
-amended by S-1 on 2026-08-09)**.
-
-The chain resource is `GET /api/models/agents/<backend>/chain?model=<id>`, with a
-matching `PUT` carrying `{hops: [{source_id, model_id}, ...]}`. The read projection
-returns the same stored array, in the same order, with only §4.3 live annotations and
-current execution position added.
+There is no separate `mappings` field or second persisted policy discriminator.
+A manual hop's differing model id is the mapping itself. Automatic native alias
+matching is confined to §4.2's existing parser; API-key passthrough preserves the requested id.
+All read and write wrappers expose the same GET/PUT/DELETE/preview operations and
+server-authored fields. Historical TurnProvenance keeps its exact attempts and remains
+readable for released versions through 9 without requiring new route fields.
### 4.7 Downstream — Agents
@@ -1538,10 +1475,10 @@ Required interaction rules:
- Sources remains an unordered asset inventory; there is no reorder affordance in that
module.
-- Gateway is the primary editing surface. Each model row shows the exact stored order
+- Gateway is the primary editing surface. Each model row shows the exact effective order
and mapping that runtime will execute; blocked hops remain in place and dim.
-- Add Source writes each one-time match at the deterministic position chosen by §4.2's
- placement policy. That position is visible immediately and remains user-editable.
+- Add Source commits §4.2 default placement and reports effective adoption positions
+ immediately. Manual overrides remain unchanged; defaults remain user-editable.
The UI never uses position to mean “new”: it has no bottom-only new section or other
ordering-dependent newness. If temporary differentiation is needed, it uses a
dismissible/transient marker derived from the add result, not a route field.
@@ -1623,8 +1560,8 @@ delivery lane. It must not appear as a placeholder third module in the v3 UI.
| Decision | Action | Eligible detected item | Default / apply behavior |
| --- | --- | --- | --- |
-| `import.keep_native` | `keep_native` | Claude or Codex subscription OAuth held by the sanctioned local CLI | selected by default; retain the credential in the CLI store, create the backend's singleton `native_cli` Source, and run the same one-time route match plus §4.2 placement as Add Source; reject a duplicate native Source before OAuth or partial commit |
-| `import.copy_key` | `import` | API key plus optional Base URL, including an OpenCode provider key | selected by default; copy into a validated Hub Source, run the same one-time route match plus §4.2 placement as Add Source, and leave the original file byte-identical |
+| `import.keep_native` | `keep_native` | Claude or Codex subscription OAuth held by the sanctioned local CLI | selected by default; retain the credential in the CLI store, create the backend's singleton `native_cli` Source, and run the same §4.2 default placement and effective adoption as Add Source; reject a duplicate native Source before OAuth or partial commit |
+| `import.copy_key` | `import` | API key plus optional Base URL, including an OpenCode provider key | selected by default; copy into a validated Hub Source, run the same §4.2 default placement and effective adoption as Add Source, and leave the original file byte-identical |
| `import.reauth` | `reauth` | detected material that cannot be safely copied or retained as a usable native login | not auto-applied as import; direct the user into the explicit authentication flow |
| `import.controlled` | `controlled_import` | future engine-owned OAuth-import capability that can preserve refresh semantics | reserved and not selectable/applicable in v3; explicit OAuth add is the only hub-held subscription path |
@@ -1638,12 +1575,50 @@ through explicit OAuth add, not native-file import. The import entry points are
open after upgrade, the setup wizard, and the backend-page banner.
- **Add-source closing loop (v3).** Creating a Source returns
`added_to: [{backend, menu_model, source_id, model_id, position}]` for every exact hop
-written by the one-time match. `adopted_by: [{backend, menu_model}]` is the stable
-Source-card projection of those persisted Hub-mode references; transient health and process
- availability do not change it. A Source with no automatic match reports an empty
+selected by the effective planner after commit. `adopted_by: [{backend, menu_model}]` is the stable
+Source-card projection of those effective Hub-mode references; transient health and process
+ availability do not change it. A Source with no effective adoption reports an empty
`added_to` and remains available for an explicit route edit, without a separate “not
enabled” state.
+## Transport registration and delivery evidence
+
+The committed Engine Registration Amendment (`f8d14358a`) separates truthful
+`SourceBinding.model_ids` inventory from default-empty `route_model_ids` transport
+targets. The service derives sorted unique effective Hub targets across backend catalogs
+and retained resolver-selectable route keys, including dormant OpenCode overrides,
+independent of health and backend mode; the compiler registers their union for transport.
+Targets never enter Source.models, discovery, matching evidence or reasoning capabilities.
+Load and config synchronization use the existing owner and preserve active requests.
+
+The owner scope decision `c1d398d5f` limits unknown-target transport registration to
+Hub API-key Sources. Subscription OAuth/native admission and registration remain unchanged;
+no engine expansion, OAuth alias substitution or alternate transport ships in this feature.
+
+Registration retains the existing supervised restart transaction. Adapter invocation
+leases drain active buffered/streaming operations before configuration restart; new
+invocations wait behind the same barrier. Release follows transport completion, early
+close or cancellation independently of service settlement and its mutation lock.
+Sync cancellation/failure must release barriers and leases. Pure reorders with unchanged
+registration never restart, ordinary requests never register targets, and no unrelated
+active request is canceled to save configuration. Tests cover completion, early close,
+cancellation, rollback and concurrent Save without deadlock or partial-output loss.
+
+The Atomic Invocation Admission amendment (`c50bc43a5`) closes the gap between
+resolving a candidate and acquiring its transport lease. Ordinary resolution/fallback,
+bounded credential-refresh retry and selected-model probing share service admission.
+Under the existing mutation lock, revalidate the current effective candidate, exact
+Source configuration and synchronized engine projection. The adapter then acquires its
+routing lock and transport lease and calls optional `on_admitted` exactly once before
+any network wait; that handoff releases mutation exclusion and records the real attempt.
+Lock order remains service mutation then adapter routing. Network, first-token waits
+and stream consumption never hold the service mutation lock. Failure/cancellation before
+admission releases exclusion without a fabricated attempt; callback failure and every
+post-admission terminal path release the lease. Recompute unattempted candidates while
+preserving failed-Source exclusions; refresh retries only the still-valid exact pair.
+No per-request registration, synthetic model-not-found or persistent generation store
+is introduced. The internal callback adds no UI wire field.
+
## 7. Security boundaries
- Three credential rings, never mixed: management key (Avibe→engine admin
@@ -1700,7 +1675,7 @@ one pinned hop it receives.
Route chain.
- **Per-model ordering is explicitly in scope.** Owner ruling 2026-08-07
supersedes v2's “No per-model ordering” non-goal. The scope is exactly §4.3 and
- §4.6's stored configured-chain input;
+ §4.6's sparse manual intent and §4.2's effective plan;
there is no session-level or request-level editor.
- **No native CLI account selector or multiple native slots.** A backend has one
`native_cli` Source because its official CLI has one current local login. Additional
@@ -1780,17 +1755,16 @@ directions into questions that later lanes must answer before writing mechanical
- [ ] §4.1 exposes exactly `anthropic | openai_responses | openai_chat`, retains Chat
Completions, and shows Auto detect plus those three protocol choices before
observation; an ambiguous Auto result requires one concrete choice to retry.
-- [ ] §4.2 alone owns one-time placement: Add Source, menu-model add, and built-in
- reconcile persist every accepted match at one deterministic policy-chosen position;
- no runtime path reruns placement, and no UI test infers newness from position.
+- [ ] §4.2 alone owns effective planning. Manual arrays survive unrelated changes;
+ automatic routes follow current default membership/order and matching evidence,
+ with unchanged-id Hub API-key passthrough only when the matching tier is empty;
+ unmatched subscription-only defaults remain Unconfigured.
- [ ] §4.4 allows every hub-held subscription to serve every backend while retaining
native CLI's sanctioned-backend binding.
-- [ ] §4.3 is the document's only configured-chain execution algorithm: it reads stored
- hops verbatim, checks only live runnability and error fallthrough, and derives the
- non-persisted takeover projection; §4.6 stores the same exact pairs the UI shows.
-- [ ] The owner-vetoable final route shape is acceptable: every backend has one explicit
- Source order, every menu model has one explicit `hops` array, and no
- `follow | custom`, separate mapping, or runtime matching authority exists.
+- [ ] §4.3 executes the shared effective plan without changing its tier or membership;
+ live annotations and the non-persisted takeover view remain independent of origin.
+- [ ] Sparse manual intent distinguishes key absence, equal-to-automatic explicit saves,
+ and explicit empty overrides. Restore/Preview/Undo/Cancel/Save follow the frozen API.
- [ ] §4.5 keeps state source-global, status live-derived, and every successful
takeover silent; `supply_status` is the sole backend-health line, and a no-runnable-
hop exhaustion never borrows takeover semantics; terminal in-turn errors plus
@@ -1799,8 +1773,8 @@ directions into questions that later lanes must answer before writing mechanical
Configure Agents is deferred without a placeholder design. Source-card supply
attribution reuses `adopted_by`, and saved Source details has only guarded
「重新拉取」 with no latency or “last checked” copy.
-- [ ] §6 reports the exact hops Add Source wrote through `added_to`, and Source-card
- `adopted_by` reflects only persisted Hub-mode route references.
+- [ ] §6 reports the exact effective hops after Source creation through `added_to`, and Source-card
+ `adopted_by` reflects effective Hub-mode route references.
- [ ] §6 reserves Direct for `mode: direct`, labels a `native_cli` Gateway hop Native,
and defines a visible, reversible Direct ↔ Gateway action for every backend.
- [ ] §9 explicitly supersedes the old no-per-model-ordering non-goal and states that
diff --git a/scripts/check_model_hub_authorities.py b/scripts/check_model_hub_authorities.py
index 6e7a0542b..ce667b576 100644
--- a/scripts/check_model_hub_authorities.py
+++ b/scripts/check_model_hub_authorities.py
@@ -270,6 +270,32 @@ def _python_string_assignment(source: AuthorityInput, spec: dict[str, Any]) -> s
raise ValueError(f"assignment not found: {spec['name']}")
+def _typescript_string_union(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:
+ declaration = re.search(
+ rf"^export\s+type\s+{re.escape(spec['name'])}\s*=\s*([^;]+);",
+ source.text(spec["file"]),
+ flags=re.MULTILINE,
+ )
+ if declaration is None:
+ raise ValueError(f"exported type not found: {spec['name']}")
+ body = declaration.group(1).strip()
+ literal = re.compile(r'''\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|null)\s*(\||$)''')
+ values: set[str] = set()
+ offset = 1 if body.startswith("|") else 0
+ while offset < len(body):
+ token = literal.match(body, offset)
+ if token is None:
+ raise ValueError(f"not a string/null union: {spec['name']}")
+ if token.group(1) != "null":
+ values.add(ast.literal_eval(token.group(1)))
+ offset = token.end()
+ if token.group(2) and offset == len(body):
+ raise ValueError(f"incomplete union: {spec['name']}")
+ if not values:
+ raise ValueError(f"empty string union: {spec['name']}")
+ return values
+
+
def _versioned_schema_nodes(node: Any):
"""Yield every contract_version subschema from an arbitrary schema tree."""
@@ -325,6 +351,8 @@ def _extract(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:
return _python_literal_annotation(source, spec)
if kind == "python_string_assignment":
return _python_string_assignment(source, spec)
+ if kind == "typescript_string_union":
+ return _typescript_string_union(source, spec)
if kind == "json_object_keys":
return _json_object_keys(source, spec)
raise ValueError(f"unknown extractor: {kind}")
diff --git a/tests/e2e/drivers/mock_llm_upstream.py b/tests/e2e/drivers/mock_llm_upstream.py
index 4fec75afb..16e6a720c 100644
--- a/tests/e2e/drivers/mock_llm_upstream.py
+++ b/tests/e2e/drivers/mock_llm_upstream.py
@@ -22,7 +22,7 @@ from urllib.parse import urlsplit
AUTH_BEHAVIORS = frozenset(
{"ok", "401", "403_banned", "402", "429", "quota_message", "5xx"}
)
-STREAM_BEHAVIORS = frozenset({"healthy", "interrupt_after_first_output"})
+STREAM_BEHAVIORS = frozenset({"healthy", "interrupt_after_first_output", "pause_after_first_output"})
PROTOCOLS = frozenset({"anthropic", "openai_responses", "openai_chat"})
MODELS_ENDPOINT_BEHAVIORS = frozenset(
{"ok", "http_404", "http_500", "timeout", "malformed_json"}
@@ -200,6 +200,7 @@ class MockUpstreamState:
"models": [copy.deepcopy(model) for model in DEFAULT_MODELS],
"protocol": "openai_chat",
"models_endpoint": "ok",
+ "model_errors": {},
}
self._requests: deque[dict[str, Any]] = deque(
maxlen=MAX_CAPTURED_REQUESTS
@@ -216,6 +217,7 @@ class MockUpstreamState:
"models",
"protocol",
"models_endpoint",
+ "model_errors",
}
if unknown:
raise ConfigurationError(
@@ -232,6 +234,12 @@ class MockUpstreamState:
if candidate["models_endpoint"] not in MODELS_ENDPOINT_BEHAVIORS:
raise ConfigurationError("unsupported models endpoint behavior")
candidate["models"] = _validated_models(candidate["models"])
+ model_errors = candidate["model_errors"]
+ if not isinstance(model_errors, dict) or any(
+ not isinstance(model, str) or not model.strip() or error != "model_not_found"
+ for model, error in model_errors.items()
+ ):
+ raise ConfigurationError("model_errors must map non-empty model ids to model_not_found")
with self._lock:
self._config = candidate
return copy.deepcopy(self._config)
@@ -354,6 +362,13 @@ class MockLLMUpstreamHandler(BaseHTTPRequestHandler):
_invalid_probe_payload(protocol),
)
return
+ model = _requested_model(body)
+ if model in config["model_errors"]:
+ error = {"type": "not_found_error", "code": "model_not_found", "message": f"model {model} not found"}
+ if protocol != "anthropic":
+ error.update(type="invalid_request_error", code="model_not_found", param="model")
+ self._write_json(HTTPStatus.NOT_FOUND, {"error": error})
+ return
if isinstance(body, dict) and body.get("stream") is True:
self._write_stream(protocol, body, config["stream"])
return
@@ -475,12 +490,18 @@ class MockLLMUpstreamHandler(BaseHTTPRequestHandler):
self.close_connection = True
frames = _stream_frames(protocol, body)
limit = len(frames)
+ first_output = {"anthropic": 3, "openai_responses": 4, "openai_chat": 2}[protocol]
if stream_behavior == "interrupt_after_first_output":
- limit = 3 if protocol == "anthropic" else 2
+ limit = first_output
try:
- for frame in frames[:limit]:
+ for index, frame in enumerate(frames[:limit], start=1):
self.wfile.write(frame)
self.wfile.flush()
+ if stream_behavior == "pause_after_first_output" and index == first_output:
+ deadline = time.monotonic() + 30
+ while self.state.config()["stream"] == "pause_after_first_output":
+ if time.monotonic() >= deadline or self.server.shutdown_event.wait(0.01):
+ return
except (BrokenPipeError, ConnectionResetError):
return
@@ -914,6 +935,11 @@ def _anthropic_stream_frames(model: str) -> list[bytes]:
def _responses_stream_frames(model: str) -> list[bytes]:
+ text = {"type": "output_text", "text": "mock response", "annotations": []}
+ message = {
+ "id": "msg_mock_001", "type": "message", "role": "assistant",
+ "status": "completed", "content": [text],
+ }
return [
_sse(
"response.created",
@@ -928,27 +954,62 @@ def _responses_stream_frames(model: str) -> list[bytes]:
},
},
),
+ _sse(
+ "response.output_item.added",
+ {
+ "type": "response.output_item.added", "sequence_number": 1, "output_index": 0,
+ "item": {**message, "status": "in_progress", "content": []},
+ },
+ ),
+ _sse(
+ "response.content_part.added",
+ {
+ "type": "response.content_part.added", "sequence_number": 2,
+ "item_id": "msg_mock_001", "output_index": 0, "content_index": 0,
+ "part": {**text, "text": ""},
+ },
+ ),
_sse(
"response.output_text.delta",
{
"type": "response.output_text.delta",
- "sequence_number": 1,
+ "sequence_number": 3,
"item_id": "msg_mock_001",
"output_index": 0,
"content_index": 0,
"delta": "mock response",
},
),
+ _sse(
+ "response.output_text.done",
+ {
+ "type": "response.output_text.done", "sequence_number": 4,
+ "item_id": "msg_mock_001", "output_index": 0, "content_index": 0,
+ "text": "mock response",
+ },
+ ),
+ _sse(
+ "response.content_part.done",
+ {
+ "type": "response.content_part.done", "sequence_number": 5,
+ "item_id": "msg_mock_001", "output_index": 0, "content_index": 0, "part": text,
+ },
+ ),
+ _sse(
+ "response.output_item.done",
+ {"type": "response.output_item.done", "sequence_number": 6, "output_index": 0, "item": message},
+ ),
_sse(
"response.completed",
{
"type": "response.completed",
- "sequence_number": 2,
+ "sequence_number": 7,
"response": {
"id": "resp_mock_001",
"object": "response",
"status": "completed",
"model": model,
+ "output": [message],
"usage": {
"input_tokens": 12,
"input_tokens_details": {
diff --git a/tests/e2e/test_model_hub_mock_upstream.py b/tests/e2e/test_model_hub_mock_upstream.py
index 2172b91c7..91c106b8c 100644
--- a/tests/e2e/test_model_hub_mock_upstream.py
+++ b/tests/e2e/test_model_hub_mock_upstream.py
@@ -252,6 +252,9 @@ def _send_through_opencode_gateway_engine(
variant: dict[str, Any],
prompt_start_delay_seconds: float = 0,
require_terminal_result: bool = False,
+ inventory_models: list[dict[str, Any]] | None = None,
+ automatic_route: bool = False,
+ isolated_upstream: MockLLMUpstream | None = None,
) -> tuple[dict[str, Any], dict[str, Any] | None]:
binary = shutil.which("opencode")
if binary is None:
@@ -266,6 +269,9 @@ def _send_through_opencode_gateway_engine(
"openai_responses": "/v1/responses",
"openai_chat": "/v1/chat/completions",
}[upstream_protocol]
+ inventory = inventory_models if inventory_models is not None else [
+ {"id": stored_model, "supported_parameters": ["reasoning"]},
+ ]
with _engine_app(model_hub_app_factory) as app:
configured = app.client.post(
"/api/config",
@@ -276,12 +282,7 @@ def _send_through_opencode_gateway_engine(
_configure_protocol(
mock_llm_upstream,
upstream_protocol,
- models=[
- {
- "id": stored_model,
- "supported_parameters": ["reasoning"],
- }
- ],
+ models=inventory,
)
source, _ = _create_source(
app,
@@ -294,10 +295,17 @@ def _send_through_opencode_gateway_engine(
else None
),
)
- source_model = next(
- model for model in source["models"] if model["id"] == stored_model
- )
- assert "high" in source_model["reasoning_efforts"], source_model
+ if inventory_models is None:
+ source_model = next(model for model in source["models"] if model["id"] == stored_model)
+ assert "high" in source_model["reasoning_efforts"], source_model
+ else:
+ assert {model["id"] for model in source["models"]} == {model["id"] for model in inventory}
+ if isolated_upstream is not None:
+ _configure_protocol(isolated_upstream, upstream_protocol, models=[{"id": stored_model}])
+ _create_source(
+ app, isolated_upstream, protocol=upstream_protocol, nonce="scn_routingoutside001",
+ extra=({"base_url": f"{isolated_upstream.url}/v1"} if upstream_protocol == "openai_responses" else None),
+ )
sources = app.client.put(
"/api/models/agents/opencode/sources",
{"order": [source["id"]]},
@@ -333,15 +341,16 @@ def _send_through_opencode_gateway_engine(
{"mode": "hub"},
)
assert mode.status == 200, mode.json()
- chain = app.client.put(
- f"/api/models/agents/opencode/chain?model={menu_model}",
- {
- "hops": [
- {"source_id": source["id"], "model_id": stored_model}
- ]
- },
+ route_path = f"/api/models/agents/opencode/chain?model={menu_model}"
+ chain = app.client.get(route_path) if automatic_route else app.client.put(
+ route_path, {"hops": [{"source_id": source["id"], "model_id": stored_model}]},
)
assert chain.status == 200, chain.json()
+ if inventory_models is not None:
+ assert chain.json()["chain"]["route_origin"] == ("passthrough" if automatic_route else "manual")
+ assert chain.json()["chain"]["manual_override"] == (
+ None if automatic_route else {"hops": [{"source_id": source["id"], "model_id": stored_model}]}
+ )
options = app.client.post(
"/api/opencode/options",
@@ -368,6 +377,8 @@ def _send_through_opencode_gateway_engine(
started = app.client.post("/api/models/runtime/start", {})
assert started.status == 200, started.json()
+ engine_state = app.avibe_home / "runtime" / "model-hub" / "state"
+ engine_configs = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in engine_state.glob("instances/*/config.yaml")}
agent = app.client.post(
"/api/agents",
@@ -413,13 +424,10 @@ def _send_through_opencode_gateway_engine(
_configure_protocol(
mock_llm_upstream,
upstream_protocol,
- models=[
- {
- "id": stored_model,
- "supported_parameters": ["reasoning"],
- }
- ],
+ models=inventory,
)
+ if isolated_upstream is not None:
+ isolated_upstream.reset_requests()
sent = app.client.post(
f"/api/sessions/{session.json()['id']}/messages",
{"text": "hello"},
@@ -453,6 +461,17 @@ def _send_through_opencode_gateway_engine(
break
time.sleep(0.1)
assert len(captured) == 1, app.diagnostics()
+ if inventory_models is not None:
+ assert captured[0]["body"]["model"] == stored_model
+ current = app.client.get("/api/models/sources")
+ assert current.status == 200, current.json()
+ current_source = next(row for row in current.json()["sources"] if row["id"] == source["id"])
+ assert {row["id"] for row in current_source["models"]} == {row["id"] for row in inventory}
+ assert app.client.get(route_path).json()["chain"]["manual_override"] == chain.json()["chain"]["manual_override"]
+ assert engine_configs
+ assert {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in engine_state.glob("instances/*/config.yaml")} == engine_configs
+ if isolated_upstream is not None:
+ assert not [row for row in isolated_upstream.requests() if row["path"] == upstream_path]
if require_terminal_result:
assert result is not None, app.diagnostics()
assert result["text"] == "mock response", {
@@ -520,6 +539,27 @@ def _send_through_opencode_gateway_engine(
return captured[0]["body"], result
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
[email protected]("inventory", [[], [{"id": "unrelated-listed-model"}]], ids=["empty", "incomplete"])
[email protected]("automatic", [True, False], ids=["passthrough", "manual"])
+def test_mh_routing_005_real_opencode_gateway_cpa_preserves_unknown_model_and_source_isolation(
+ model_hub_app_factory, mock_llm_upstream, protocol, inventory, automatic,
+):
+ """MH-ROUTING-005: real backend -> gateway -> pinned CPA forwards an unlisted exact model only to its source."""
+ native = "anthropic" if protocol == "anthropic" else "openai_responses"
+ menu = "claude-opus-5" if native == "anthropic" else "deepseek-v3.2"
+ target = menu if automatic else "vendor/unlisted-route-target"
+ variant = {"effort": "high"} if native == "anthropic" else {"reasoningEffort": "high"}
+ with MockLLMUpstream() as other:
+ captured, result = _send_through_opencode_gateway_engine(
+ model_hub_app_factory, mock_llm_upstream, upstream_protocol=protocol, native_protocol=native,
+ stored_model=target, variant=variant, inventory_models=inventory, automatic_route=automatic,
+ isolated_upstream=other, require_terminal_result=True,
+ )
+ assert captured["model"] == target
+ assert result is not None
+
+
@pytest.mark.parametrize(
"fixture",
OPENCODE_V4_S3_PASSTHROUGH_FIXTURES.values(),
@@ -894,6 +934,9 @@ def test_mock_upstream_control_validation_capture_envelope_and_reset(
{"protocol": "invalid"},
{"models_endpoint": "invalid"},
{"models": [""]},
+ {"model_errors": []},
+ {"model_errors": {"": "model_not_found"}},
+ {"model_errors": {"unknown-model": "server_error"}},
):
status, _, payload = _json_request(
mock_llm_upstream.url,
@@ -948,6 +991,49 @@ def test_mock_upstream_control_validation_capture_envelope_and_reset(
assert captured == {"requests": []}
[email protected]("protocol", PROTOCOL_CASES)
[email protected]("inventory", [[], [{"id": "catalog-only-model"}]])
+def test_mh_routing_001_mock_model_errors_are_request_scoped_and_inventory_independent(
+ mock_llm_upstream, protocol, inventory,
+) -> None:
+ """MH-ROUTING-001: truthful inventory never gates capture or request-only errors."""
+
+ missing = "vendor/unknown-model-20260906"
+ healthy = "vendor/other-unlisted-model"
+ case = PROTOCOL_CASES[protocol]
+ original = _configure(
+ mock_llm_upstream.url,
+ protocol=protocol,
+ models=inventory,
+ model_errors={missing: "model_not_found"},
+ )
+ for model, expected_status in [(missing, 404), (healthy, 200)]:
+ body = {**case["body"], "model": model}
+ if protocol == "openai_responses":
+ body["input"] = "Original identifier and request: 中文"
+ else:
+ body["messages"] = [{"role": "user", "content": "Original identifier and request: 中文"}]
+ status, _, payload = _json_request(
+ mock_llm_upstream.url, case["path"], method="POST", body=body,
+ )
+ assert status == expected_status, payload
+ if model == missing:
+ assert model in payload["error"]["message"]
+ if protocol != "anthropic":
+ assert payload["error"]["code"] == "model_not_found"
+ assert mock_llm_upstream.requests()[-1]["body"] == body
+
+ assert mock_llm_upstream.state.config() == original
+ assert _configure(mock_llm_upstream.url, model_errors={})["models"] == inventory
+ status, _, _ = _json_request(
+ mock_llm_upstream.url,
+ case["path"],
+ method="POST",
+ body={**case["body"], "model": missing},
+ )
+ assert status == 200
+
+
def test_mock_upstream_contract_client_ignores_inherited_proxy(
monkeypatch,
mock_llm_upstream,
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index 7f172842f..0c1308ebd 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -19,7 +19,9 @@ from tests.e2e.test_model_hub_migration import _write
from tests.e2e.test_model_hub_runtime import (
_engine_app,
_install_engine,
+ _isolated_engine_adapter,
)
+from config.v2_config import ModelHubBackendModelConfig, ModelHubConfig, ModelHubRouteConfig, ModelHubRouteHopConfig
from tests.e2e.test_model_hub_sources import (
MENU_MODEL,
SYNTHETIC_API_KEY,
@@ -41,6 +43,312 @@ from tests.scenario_harness.model_hub import (
pytestmark = pytest.mark.e2e_model_hub
+def _real_route_service(tmp_path, adapter, mocks, protocol, inventory, *, manual=False, backend="opencode"):
+ target = "vendor/unlisted-route-target" if backend == "opencode" else fixed_model(backend)
+ menu = "vendor/menu-route-model" if manual else target
+ sources = []
+ for index, mock in enumerate(mocks):
+ models = [target] if index else inventory
+ mock.configure(protocol=protocol, models=[{"id": model} for model in models])
+ item = source(f"src_gateway{index:03d}", models, vendor="custom", protocol=protocol)
+ item.base_url = mock.url + ("/v1" if protocol == "openai_responses" else "")
+ item.credential_ref = adapter.state_store.store_api_key(
+ f"sk-synthetic-gateway-{index}", vendor="custom", protocol=protocol, base_url=item.base_url,
+ )
+ sources.append(item)
+ config = config_with_sources(sources, backend=backend, menu_model=menu)
+ agent = config.agents[backend]
+ if backend == "opencode":
+ agent.menu.checked = [menu]
+ agent.models = [ModelHubBackendModelConfig(
+ id=menu, origin="manual", native_protocol="anthropic" if protocol == "anthropic" else "openai_responses",
+ )]
+ agent.sources.order = [sources[0].id]
+ if manual:
+ agent.routes[menu] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(sources[0].id, target),))
+ else:
+ agent.routes.pop(menu)
+ service = service_for(tmp_path, MemoryModelHubStore(config), adapter)
+ return service, menu, target, sources
+
+
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
[email protected]("inventory", [[], ["unrelated-listed-model"]], ids=["empty", "incomplete"])
[email protected]("manual", [False, True], ids=["passthrough", "manual"])
[email protected]("stream", [False, True], ids=["buffered", "streaming"])
+def test_mh_routing_008_real_gateway_cpa_exact_model_and_source(tmp_path, monkeypatch, protocol, inventory, manual, stream):
+ """MH-ROUTING-008: real gateway/adapter/pinned CPA forwards exact unlisted API-key targets without source fallback."""
+ async def exercise(adapter, first, second):
+ service, menu, target, sources = _real_route_service(tmp_path, adapter, [first, second], protocol, inventory, manual=manual)
+ await service.runtime_start()
+ connection = adapter.supervisor.client_if_running().connection
+ config_path = next(adapter.state_store.root.glob("instances/*/config.yaml"))
+ before = (config_path.read_bytes(), config_path.stat().st_mtime_ns)
+ gateway = ModelHubTurnGateway(service)
+ base_url, token = await gateway.endpoint(
+ "opencode", process_scope=str(tmp_path), turn_id="turn_routing_exact", requested_model_id=menu,
+ resolved_model_id=target, source_id=sources[0].id,
+ )
+ paths = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}
+ prompt = "Original request: \u4e2d\u6587"
+ payload = {"model": menu, "stream": stream}
+ if protocol == "openai_responses":
+ payload["input"] = prompt
+ else:
+ payload.update(max_tokens=32, messages=[{"role": "user", "content": prompt}])
+ first.reset_requests()
+ second.reset_requests()
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(f"{base_url}/v1/{paths[protocol]}", json=payload,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=15)
+ assert response.status == 200, raw
+ assert b"mock response" in raw
+ finally:
+ await gateway.close()
+ captured = [row for row in first.requests() if row["path"] == f"/v1/{paths[protocol]}"]
+ assert len(captured) == 1, first.requests()
+ assert captured[0]["body"]["model"] == target
+ assert prompt in json.dumps(captured[0]["body"], ensure_ascii=False)
+ assert not [row for row in second.requests() if row["path"] == f"/v1/{paths[protocol]}"]
+ assert [row.id for row in service.store.load().sources[0].models] == inventory
+ assert adapter.state_store.get_source(sources[0].id).model_ids == tuple(inventory)
+ assert (config_path.read_bytes(), config_path.stat().st_mtime_ns) == before
+ assert adapter.supervisor.client_if_running().connection == connection
+ assert service.agent_chain("opencode", menu)["route_origin"] == ("manual" if manual else "passthrough")
+
+ with MockLLMUpstream() as first, MockLLMUpstream() as second, _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:
+ asyncio.run(exercise(adapter, first, second))
+
+
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
[email protected]("inventory", [[], ["unrelated-listed-model"]], ids=["empty", "incomplete"])
+def test_mh_routing_012_persisted_dormant_opencode_override_reaches_exact_source_and_target(
+ tmp_path, monkeypatch, protocol, inventory,
+):
+ """MH-ROUTING-012: resolver-selectable dormant routes are registered without expanding the menu or inventory."""
+ async def exercise(adapter, first, second):
+ arranged, dormant, target, sources = _real_route_service(
+ tmp_path, adapter, [first, second], protocol, inventory, manual=True,
+ )
+ config = arranged.store.load()
+ catalog = "vendor/independent-catalog-model"
+ agent = config.agents["opencode"]
+ agent.menu.checked = [catalog]
+ agent.models = [ModelHubBackendModelConfig(
+ id=catalog, origin="manual",
+ native_protocol="anthropic" if protocol == "anthropic" else "openai_responses",
+ )]
+ persisted = tmp_path / "persisted-dormant-route.json"
+ persisted.write_text(json.dumps(config.to_payload()), encoding="utf-8")
+ loaded = ModelHubConfig.from_payload(json.loads(persisted.read_text(encoding="utf-8")))
+ assert dormant in loaded.agents["opencode"].routes
+ assert dormant not in {model.id for model in loaded.agents["opencode"].models}
+ assert loaded.agents["opencode"].menu.checked == [catalog]
+ agent_before = loaded.agents["opencode"].to_payload()
+ inventory_before = [item.to_payload()["models"] for item in loaded.sources]
+ persisted_before = persisted.read_bytes()
+ service = service_for(tmp_path, MemoryModelHubStore(loaded), adapter)
+ await service.runtime_start()
+ connection = adapter.supervisor.client_if_running().connection
+ config_path = next(adapter.state_store.root.glob("instances/*/config.yaml"))
+ engine_before = (config_path.read_bytes(), config_path.stat().st_mtime_ns)
+ gateway = ModelHubTurnGateway(service)
+ base_url, token = await gateway.endpoint(
+ "opencode", process_scope=str(tmp_path), turn_id="turn_dormant_route",
+ requested_model_id=dormant, resolved_model_id=target, source_id=sources[0].id,
+ )
+ paths = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}
+ payload = {"model": dormant, "stream": False}
+ prompt = "Persisted route request: \u4e2d\u6587"
+ if protocol == "openai_responses":
+ payload["input"] = prompt
+ else:
+ payload.update(max_tokens=32, messages=[{"role": "user", "content": prompt}])
+ first.reset_requests()
+ second.reset_requests()
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(f"{base_url}/v1/{paths[protocol]}", json=payload,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=15)
+ assert response.status == 200, raw
+ assert b"mock response" in raw
+ finally:
+ await gateway.close()
+ captured = [row for row in first.requests() if row["path"] == f"/v1/{paths[protocol]}"]
+ assert len(captured) == 1, first.requests()
+ assert captured[0]["body"]["model"] == target
+ assert _request_credential(captured[0]) == "sk-synthetic-gateway-0"
+ assert prompt in json.dumps(captured[0]["body"], ensure_ascii=False)
+ assert not [row for row in second.requests() if row["method"] == "POST"]
+ assert service.store.load().agents["opencode"].to_payload() == agent_before
+ assert [item.to_payload()["models"] for item in service.store.load().sources] == inventory_before
+ assert adapter.state_store.get_source(sources[0].id).model_ids == tuple(inventory)
+ assert (config_path.read_bytes(), config_path.stat().st_mtime_ns) == engine_before
+ assert adapter.supervisor.client_if_running().connection == connection
+ assert persisted.read_bytes() == persisted_before
+ assert service.agent_chain("opencode", dormant)["route_origin"] == "manual"
+ (tmp_path / "received-dormant-route.json").write_text(json.dumps({
+ "dormant_model": dormant, "source_id": sources[0].id, "target": target,
+ "inventory": inventory, "menu": agent_before, "received": captured,
+ }, indent=2), encoding="utf-8")
+
+ with MockLLMUpstream() as first, MockLLMUpstream() as second, _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:
+ asyncio.run(exercise(adapter, first, second))
+
+
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
[email protected]("disconnect", [False, True], ids=["complete", "client-close"])
+def test_mh_routing_009_save_drains_active_stream_without_truncation_or_deadlock(tmp_path, monkeypatch, protocol, disconnect):
+ """MH-ROUTING-009: Save waits for real stream completion or client close, then serves the new target without deadlock."""
+ async def exercise(adapter, mock):
+ service, menu, target, sources = _real_route_service(tmp_path, adapter, [mock], protocol, [])
+ await service.runtime_start()
+ old_connection = adapter.supervisor.client_if_running().connection
+ gateway = ModelHubTurnGateway(service)
+ base_url, token = await gateway.endpoint(
+ "opencode", process_scope=str(tmp_path), turn_id="turn_active_save", requested_model_id=menu,
+ resolved_model_id=target, source_id=sources[0].id,
+ )
+ path = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}[protocol]
+ terminal = {"anthropic": b"message_stop", "openai_responses": b"response.completed", "openai_chat": b"[DONE]"}[protocol]
+ payload = {"model": menu, "stream": True}
+ if protocol == "openai_responses":
+ payload["input"] = "save during output"
+ else:
+ payload.update(max_tokens=32, messages=[{"role": "user", "content": "save during output"}])
+ mock.configure(stream="pause_after_first_output")
+ mock.reset_requests()
+ save = None
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(f"{base_url}/v1/{path}", json=payload,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ assert response.status == 200
+ prefix = b""
+ while b"mock response" not in prefix:
+ prefix += await asyncio.wait_for(response.content.readuntil(b"\n\n"), timeout=10)
+ next_target = "vendor/next-unlisted-target"
+ save = asyncio.create_task(service.set_agent_chain("opencode", menu, {
+ "hops": [{"source_id": sources[0].id, "model_id": next_target}],
+ }))
+ await asyncio.sleep(0.05)
+ assert not save.done(), "Save must wait for the active transport to finish"
+ assert adapter.supervisor.client_if_running().connection == old_connection
+ if disconnect:
+ response.close()
+ saved = await asyncio.wait_for(save, timeout=15)
+ mock.configure(stream="healthy")
+ else:
+ mock.configure(stream="healthy")
+ saved, tail = await asyncio.wait_for(asyncio.gather(save, response.read()), timeout=15)
+ assert terminal in prefix + tail
+ assert saved["chain"]["manual_override"] == {"hops": [{"source_id": sources[0].id, "model_id": next_target}]}
+ async with client.post(f"{base_url}/v1/{path}", json={**payload, "stream": False},
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=10)
+ assert response.status == 200, raw
+ captured = [row["body"]["model"] for row in mock.requests() if row["path"] == f"/v1/{path}"]
+ assert captured == [target, next_target]
+ assert service.store.load().sources[0].models == []
+ finally:
+ mock.configure(stream="healthy")
+ if save is not None and not save.done():
+ save.cancel()
+ await asyncio.gather(save, return_exceptions=True)
+ await gateway.close()
+
+ with MockLLMUpstream() as mock, _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:
+ asyncio.run(exercise(adapter, mock))
+
+
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
+def test_mh_routing_010_model_not_found_stays_request_scoped_through_real_gateway_cpa(tmp_path, monkeypatch, protocol):
+ """MH-ROUTING-010: an unlisted-model error does not poison source health or retry another source."""
+ async def exercise(adapter, first, second):
+ backend = {"openai_responses": "codex", "openai_chat": "opencode", "anthropic": "claude"}[protocol]
+ service, menu, target, sources = _real_route_service(tmp_path, adapter, [first, second], protocol, [], backend=backend)
+ sources[1].models = []
+ second.configure(models=[])
+ service.store.load().agents[backend].sources.order = [item.id for item in sources]
+ await service.runtime_start()
+ before = [item.state.to_payload() for item in service.store.load().sources]
+ gateway = ModelHubTurnGateway(service)
+ base_url, token = await gateway.endpoint(
+ backend, process_scope=str(tmp_path), turn_id="turn_model_error", requested_model_id=menu,
+ resolved_model_id=target, source_id=sources[0].id,
+ )
+ path = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}[protocol]
+ payload = {"model": menu, "stream": False}
+ if protocol == "openai_responses":
+ payload["input"] = "missing model"
+ else:
+ payload.update(max_tokens=32, messages=[{"role": "user", "content": "missing model"}])
+ first.configure(model_errors={target: "model_not_found"})
+ first.reset_requests()
+ second.reset_requests()
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ async with client.post(f"{base_url}/v1/{path}", json=payload,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=10)
+ assert response.status == 400, raw
+ assert json.loads(raw)["error"]["code"] == "upstream_request_invalid"
+ assert [item.state.to_payload() for item in service.store.load().sources] == before
+ assert service.agent_chain(backend, menu)["route_origin"] == "passthrough"
+ gateway.correlation.settle(
+ "turn_model_error", settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts="2026-09-05T18:00:00+00:00",
+ )
+ failed = service.get_model_provenance(backend, menu)
+ if backend == "opencode":
+ # The shared OpenCode process intentionally has no exact turn discriminator.
+ assert failed is None
+ else:
+ assert failed is not None
+ assert failed["turn_id"] == "turn_model_error"
+ assert failed["terminal_error"] == {
+ "source_id": sources[0].id,
+ "configured_model_id": target,
+ "channel": "hub",
+ "reason": "invalid_parameter",
+ "stream_started": False,
+ "http_status": 404,
+ "upstream_error_code": "not_found_error" if protocol == "anthropic" else "model_not_found",
+ }
+ first.configure(model_errors={})
+ base_url, token = await gateway.endpoint(
+ backend, process_scope=str(tmp_path), turn_id="turn_model_success",
+ requested_model_id=menu, resolved_model_id=target, source_id=sources[0].id,
+ )
+ async with client.post(f"{base_url}/v1/{path}", json=payload,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=10)
+ assert response.status == 200, raw
+ gateway.correlation.settle(
+ "turn_model_success", settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts="2026-09-05T18:00:01+00:00",
+ )
+ latest = service.get_model_provenance(backend, menu)
+ if backend == "opencode":
+ assert latest is None
+ else:
+ assert latest is not None
+ assert latest["turn_id"] == "turn_model_success"
+ assert latest["terminal_error"] is None
+ assert latest["served"]["source_id"] == sources[0].id
+ assert service.provenance.get("turn_model_error") == failed
+ assert [row["body"]["model"] for row in first.requests() if row["path"] == f"/v1/{path}"] == [target, target]
+ assert not [row for row in second.requests() if row["path"] == f"/v1/{path}"]
+ finally:
+ await gateway.close()
+
+ with MockLLMUpstream() as first, MockLLMUpstream() as second, _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:
+ asyncio.run(exercise(adapter, first, second))
+
+
@pytest.mark.parametrize("settings_scope", ["home", "project", "local"])
def test_mh_claude_launch_001_settings_cannot_bypass_the_configured_route(
model_hub_app_factory, mock_llm_upstream, settings_scope,
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index 723543886..8c1404ca7 100644
--- a/tests/e2e/test_model_hub_runtime.py
+++ b/tests/e2e/test_model_hub_runtime.py
@@ -11,6 +11,7 @@ import subprocess
import sys
import tempfile
import time
+from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
@@ -49,6 +50,49 @@ def _engine_app(model_hub_app_factory):
)
+@contextmanager
+def _isolated_engine_adapter(tmp_path, monkeypatch):
+ """Use the existing verified offline archive seeder without starting a backend CLI."""
+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+ from vibe.model_hub_runtime.state import EngineStateStore
+ from vibe.model_hub_runtime.supervisor import EngineSupervisor
+
+ manifest = _local_engine_manifest()
+ fixture = ModelHubTestApp(
+ Path(__file__).resolve().parents[2], tmp_path,
+ extra_env={"VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": manifest},
+ )
+ with monkeypatch.context() as isolated:
+ for key, value in fixture.env.items():
+ isolated.setenv(key, value)
+ fixture.home.mkdir(parents=True)
+ (tmp_path / "tmp").mkdir()
+ fixture._seed_local_engine_archive()
+ root = fixture.avibe_home / "runtime" / "model-hub"
+ installer = EngineRuntimeManager(runtime_dir=root / "engine", manifest_path=manifest, offline=True)
+ installed = installer.ensure()
+ assert installed["installed"], installed
+
+ def spawn(args, **kwargs):
+ if sys.platform == "darwin":
+ args = [
+ "/usr/bin/sandbox-exec", "-p",
+ '(version 1)(allow default)(deny network-outbound (remote ip "*:*"))'
+ '(allow network-outbound (remote ip "localhost:*"))',
+ *args,
+ ]
+ return subprocess.Popen(args, **kwargs)
+
+ state = EngineStateStore(root / "state")
+ supervisor = EngineSupervisor(installer=installer, state_store=state, process_factory=spawn)
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=state)
+ try:
+ yield adapter
+ finally:
+ supervisor.stop()
+
+
def _install_engine(app) -> list[str]:
observed: list[str] = []
response = app.client.post("/api/models/runtime/install", {})
@@ -599,7 +643,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(
assert response.status == 404, (method, path, body)
assert body == {
"ok": False,
- "contract_version": 8,
+ "contract_version": 9,
"error": "feature_disabled",
}
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index 22fc394dd..f565d4d97 100644
--- a/tests/e2e/test_model_hub_sources.py
+++ b/tests/e2e/test_model_hub_sources.py
@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
pytestmark = pytest.mark.e2e_model_hub
-CONTRACT_VERSION = 8
+CONTRACT_VERSION = 9
MENU_MODEL = "claude-sonnet-4-6"
SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"
@@ -29,6 +29,7 @@ def _configure_protocol(
stream="healthy",
protocol=protocol,
models_endpoint="ok",
+ model_errors={},
models=models
if models is not None
else [{"id": "mock-model"}],
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index da0de2bf0..4e9da5c0f 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -209,7 +209,11 @@ class ModelHubScenarioAdapter:
request,
stream: bool,
origin: str,
+ *,
+ on_admitted=None,
) -> ScenarioInvokeHandle:
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id, origin))
self.requests.append(request)
result = self.invoke_results.popleft()
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 13a4fce1d..db81f56ca 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -140,8 +140,12 @@ capabilities:
- tests/scenario_harness/model_hub.py
unit_or_contract_tests:
- tests/test_model_hub_api.py
+ - tests/test_model_hub_admission.py
- tests/test_model_hub_config.py
+ - tests/test_model_hub_provenance.py
- tests/test_model_hub_resolution.py
+ - tests/test_model_hub_routing_modes.py
+ - tests/test_model_hub_transport_leases.py
- tests/test_model_hub_injection.py
- tests/test_model_hub_runtime.py
- tests/test_model_hub_l3.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 198dee075..2d7a20d9d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -104,11 +104,11 @@ scenarios:
layer: unit
test: ui/src/components/settings/models/RouteChainDialog.test.tsx::MH-ROUTE-EDIT-001
- id: MH-MATCH-001
- name: Add-time matching persists each exact hop and returns its visible position
+ name: Source addition projects automatic positions without writing manual overrides
status: covered
kind: selection
layer: scenario
- test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_001_add_source_persists_and_reports_each_exact_position
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_001_add_source_projects_automatic_positions_without_persisting_hops
- id: MH-MATCH-002
name: Matching tie-break is deterministic across inventory processing order
status: covered
@@ -116,12 +116,12 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_002_matching_tie_break_is_independent_of_inventory_order
- id: MH-MENU-ADD-001
- name: Adding a provider menu model seeds every overlapping supplier in Source order
+ name: Adding a provider menu model projects overlapping suppliers in default order without persisting automatic hops
status: covered
kind: mutation
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order
- # The client half of MH-MENU-ADD-001: the server seeds a route from whatever
+ # The client half of MH-MENU-ADD-001: the server projects a route from whatever
# supply exists at commit time, and this is what makes that supply the one the
# user was shown. The picker's other two doors — an id the list already holds,
# and one no provider offers, reached through the models.dev lookup — are each
@@ -144,11 +144,71 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order
- id: MH-SUPPLY-GAP-001
- name: Inventory loss leaves the affected menu model visibly unconfigured
+ name: Inventory loss preserves an explicit API-key route target
status: covered
kind: recovery
layer: scenario
- test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_supply_gap_001_manual_target_survives_inventory_loss
+ - id: MH-ROUTING-001
+ name: Model-specific mock errors preserve truthful inventory and unrelated model requests
+ status: covered
+ kind: contract
+ layer: e2e
+ test: tests/e2e/test_model_hub_mock_upstream.py::test_mh_routing_001_mock_model_errors_are_request_scoped_and_inventory_independent
+ - id: MH-ROUTING-002
+ name: Matching precedes API-key passthrough and health cannot change route membership
+ status: covered
+ kind: determinism
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_routing_002_match_tier_precedes_passthrough_and_health_never_changes_membership
+ - id: MH-ROUTING-003
+ name: Manual unknown and empty targets survive refresh, default reorder, and reload
+ status: covered
+ kind: persistence
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_routing_003_manual_intent_survives_refresh_default_reorder_and_reload
+ - id: MH-ROUTING-004
+ name: Restore and undo previews are inert and committed restore deletes the override idempotently
+ status: covered
+ kind: mutation
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_override
+ - id: MH-ROUTING-005
+ name: Real OpenCode launch, gateway, and pinned CPA preserve unlisted API-key targets and source isolation
+ status: assert
+ kind: transport
+ layer: e2e
+ test: tests/e2e/test_model_hub_mock_upstream.py::test_mh_routing_005_real_opencode_gateway_cpa_preserves_unknown_model_and_source_isolation
+ - id: MH-ROUTING-006
+ name: Subscription sources retain inventory admission and never advertise unknown-model passthrough
+ status: covered
+ kind: compatibility
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_routing_006_subscription_inventory_admission_is_not_expanded
+ - id: MH-ROUTING-008
+ name: Buffered and streaming real gateway calls preserve exact unlisted model, source, inventory, and engine configuration
+ status: assert
+ kind: transport
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_routing_008_real_gateway_cpa_exact_model_and_source
+ - id: MH-ROUTING-009
+ name: Registration-changing Save waits for active output completion or client close without deadlock or truncation
+ status: assert
+ kind: concurrency
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_routing_009_save_drains_active_stream_without_truncation_or_deadlock
+ - id: MH-ROUTING-010
+ name: Real gateway model-not-found preserves source health and records exact attributed errors superseded by success
+ status: assert
+ kind: recovery
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_routing_010_model_not_found_stays_request_scoped_through_real_gateway_cpa
+ - id: MH-ROUTING-012
+ name: Persisted dormant OpenCode overrides reach the exact API-key source and unlisted target without menu or inventory mutation
+ status: assert
+ kind: compatibility
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_routing_012_persisted_dormant_opencode_override_reaches_exact_source_and_target
- id: MH-PROTOCOL-001
name: Source protocol is response-observed before persistence with no transient residue
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 4f9abc0e5..ed2b45f78 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -1,4 +1,4 @@
-"""First-wave Model Hub scenarios for the v3 configured-chain contract."""
+"""Model Hub routing intent, effective projection, and persistence scenarios."""
from __future__ import annotations
@@ -52,6 +52,141 @@ def _route_pairs(
return tuple((hop.source_id, hop.model_id) for hop in config.agents[backend].routes[menu_model].hops)
+def _routing_config(backend, sources, *, manual=None):
+ model = "vendor/unlisted-routing-model" if backend == "opencode" else fixed_model(backend)
+ config = config_with_sources(sources, backend=backend, menu_model=model)
+ agent = config.agents[backend]
+ if backend == "opencode":
+ agent.menu.checked = [model]
+ agent.models = [ModelHubBackendModelConfig(id=model, origin="manual", native_protocol="openai_responses")]
+ if manual is None:
+ agent.routes.pop(model)
+ else:
+ agent.routes[model] = ModelHubRouteConfig(
+ hops=tuple(ModelHubRouteHopConfig(source_id, target) for source_id, target in manual)
+ )
+ return config, model
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("inventory", [[], ["unrelated-inventory-model"]], ids=["empty", "incomplete"])
+def test_mh_routing_002_match_tier_precedes_passthrough_and_health_never_changes_membership(
+ tmp_path, backend, inventory,
+):
+ """MH-ROUTING-002: inventory evidence selects the tier; health only annotates its ordered members."""
+ first = source("src_routefirst", inventory)
+ second = source("src_routesecond", inventory)
+ outside = source("src_routeoutside", [])
+ config, model = _routing_config(backend, [first, second, outside])
+ outside.models = [source_model(model)]
+ config.agents[backend].sources.order = [second.id, first.id]
+ store = MemoryModelHubStore(config)
+ service = service_for(tmp_path, store, ModelHubScenarioAdapter())
+ before = config.to_payload()
+ chain = service.agent_chain(backend, model)
+ assert chain["manual_override"] is None
+ assert chain["route_origin"] == "passthrough"
+ assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == [
+ (second.id, model), (first.id, model),
+ ]
+ assert store.load().to_payload() == before
+ first.models.append(source_model(model))
+ first.state.status = "needs_action"
+ first.state.detail_key = "models.source.needs_action.credential_revoked"
+ chain = service.agent_chain(backend, model)
+ assert chain["route_origin"] == "automatic"
+ assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == [(first.id, model)]
+ assert chain["manual_override"] is None
+ first.models.clear()
+ assert service.agent_chain(backend, model)["route_origin"] == "passthrough"
+ assert model not in round_trip(store.load()).agents[backend].routes
+ assert store.saved_payloads == []
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("empty", [False, True], ids=["unknown-target", "explicit-empty"])
+def test_mh_routing_003_manual_intent_survives_refresh_default_reorder_and_reload(tmp_path, backend, empty):
+ """MH-ROUTING-003: manual targets, including empty overrides, survive unrelated configuration changes."""
+ first = source("src_manualfirst", ["listed-only"])
+ second = source("src_manualsecond", ["listed-only"])
+ manual = [] if empty else [(first.id, "vendor/unlisted-original")]
+ config, model = _routing_config(backend, [first, second], manual=manual)
+ store = MemoryModelHubStore(config)
+ adapter = ModelHubScenarioAdapter(refresh_models=("new-discovered-model",))
+ service = service_for(tmp_path, store, adapter)
+ original = config.agents[backend].routes[model].to_payload()
+ asyncio.run(service.refresh_source(first.id))
+ asyncio.run(service.set_agent_sources(backend, {"order": [second.id, first.id]}))
+ asyncio.run(service.reorder_agent_chains(backend, [first.id, second.id]))
+ reloaded = service_for(tmp_path / "reload", MemoryModelHubStore(round_trip(store.load())), adapter)
+ chain = reloaded.agent_chain(backend, model)
+ assert chain["manual_override"] == original
+ assert chain["route_origin"] == (None if empty else "manual")
+ assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == manual
+ assert [item.id for item in store.load().sources[0].models] == ["new-discovered-model"]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_override(tmp_path, backend, monkeypatch):
+ """MH-ROUTING-004: draft restore is read-only; committed restore removes the override idempotently."""
+ first = source("src_restorefirst", [])
+ config, model = _routing_config(backend, [first], manual=[(first.id, "vendor/manual-target")])
+ store = MemoryModelHubStore(config)
+ adapter = ModelHubScenarioAdapter()
+ service = service_for(tmp_path, store, adapter)
+ original = config.to_payload()
+
+ async def forbidden_start():
+ pytest.fail("A route preview must never start the engine")
+
+ monkeypatch.setattr(adapter, "start", forbidden_start)
+ before_events = service.events.list()
+ preview = service.preview_agent_chain(backend, model, {"manual_override": None})
+ assert preview["manual_override"] is None
+ assert preview["route_origin"] == "passthrough"
+ assert [(hop["source_id"], hop["model_id"]) for hop in preview["chain"]] == [(first.id, model)]
+ undone = service.preview_agent_chain(
+ backend, model, {"manual_override": config.agents[backend].routes[model].to_payload()},
+ )
+ assert undone["route_origin"] == "manual"
+ assert store.load().to_payload() == original
+ assert store.saved_payloads == adapter.synced == adapter.invocations == []
+ assert service.events.list() == before_events
+
+ with pytest.raises(ModelHubError) as refused:
+ asyncio.run(service.delete_agent_chain(backend, model))
+ assert store.load().to_payload() == original
+ restored = asyncio.run(service.delete_agent_chain(backend, model, {"force": True, **refused.value.data}))
+ assert restored["chain"]["manual_override"] is None
+ assert restored["chain"]["route_origin"] == "passthrough"
+ assert model not in round_trip(store.load()).agents[backend].routes
+ repeated = asyncio.run(service.delete_agent_chain(backend, model))
+ assert repeated["chain"]["manual_override"] is None
+ assert repeated["removed_hops"] == repeated["interrupted"] == []
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_mh_routing_006_subscription_inventory_admission_is_not_expanded(tmp_path, backend):
+ """MH-ROUTING-006: subscription-only defaults do not advertise unknown-model passthrough."""
+ subscription = source("src_subscription", [], kind="subscription")
+ config, model = _routing_config(backend, [subscription])
+ service = service_for(tmp_path, MemoryModelHubStore(config), ModelHubScenarioAdapter())
+ chain = service.agent_chain(backend, model)
+ assert chain["manual_override"] is None
+ assert chain["route_origin"] is None
+ assert chain["chain"] == []
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_chain(backend, model, {
+ "hops": [{"source_id": subscription.id, "model_id": model}],
+ }))
+ subscription.models = [source_model(model)]
+ assert service.agent_chain(backend, model)["route_origin"] == "automatic"
+ saved = asyncio.run(service.set_agent_chain(backend, model, {
+ "hops": [{"source_id": subscription.id, "model_id": model}],
+ }))
+ assert saved["chain"]["route_origin"] == "manual"
+
+
def test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity() -> None:
"""MH-S1-001: live health changes annotate exact hops but never choose new ones."""
@@ -138,10 +273,10 @@ def test_mh_config_001_chain_is_the_persisted_artifact_until_explicit_edit(
assert adapter.discovery_calls == [(first.vendor, first.protocol, first.base_url, first.credential_ref)]
-def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
+def test_mh_match_001_add_source_projects_automatic_positions_without_persisting_hops(
tmp_path: Path,
) -> None:
- """MH-MATCH-001: add-time matching writes exact hops and returns their persisted positions."""
+ """MH-MATCH-001: source placement projects automatic hops without creating a manual override."""
menu_model = fixed_model("claude")
existing = source("src_existing01", [menu_model])
@@ -151,6 +286,7 @@ def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
menu_model=menu_model,
hops=[(existing.id, menu_model)],
)
+ config.agents["claude"].routes.pop(menu_model)
store = MemoryModelHubStore(config)
adapter = ModelHubScenarioAdapter(
observation=SourceObservation(
@@ -177,22 +313,24 @@ def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
)
)
added_id = result["source"]["id"]
- route = store.load().agents["claude"].routes[menu_model]
- positions = {(hop.source_id, hop.model_id): index for index, hop in enumerate(route.hops, start=1)}
- returned = {(item["source_id"], item["model_id"]): item["position"] for item in result["added_to"]}
-
- assert returned
+ route = service.agent_chain("claude", menu_model)
+ assert route["manual_override"] is None
+ assert route["route_origin"] == "automatic"
+ assert result["added_to"]
assert all(item["source_id"] == added_id for item in result["added_to"])
- assert returned == {pair: positions[pair] for pair in returned}
- assert result["adopted_by"] == [{"backend": "claude", "menu_model": menu_model}]
+ for item in result["added_to"]:
+ projected = service.agent_chain(item["backend"], item["menu_model"])["chain"]
+ hop = projected[item["position"] - 1]
+ assert (hop["source_id"], hop["model_id"]) == (item["source_id"], item["model_id"])
+ assert {"backend": "claude", "menu_model": menu_model} in result["adopted_by"]
assert store.load().agents["claude"].sources.order[-1] == added_id
assert adapter.revoked == adapter.provisioned_transient
- persisted_after_add = _route_pairs(store.load(), "claude", menu_model)
+ assert menu_model not in store.load().agents["claude"].routes
asyncio.run(service.refresh_source(added_id))
restarted = service_for(tmp_path / "restart", store, adapter)
- assert _route_pairs(store.load(), "claude", menu_model) == persisted_after_add
- assert _route_pairs(round_trip(restarted.store.load()), "claude", menu_model) == persisted_after_add
+ assert menu_model not in round_trip(restarted.store.load()).agents["claude"].routes
+ assert restarted.agent_chain("claude", menu_model)["manual_override"] is None
assert len(adapter.observation_calls) == 1
@@ -241,7 +379,7 @@ def test_mh_match_002_matching_tie_break_is_independent_of_inventory_order() ->
def test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order(
tmp_path: Path,
) -> None:
- """MH-MENU-ADD-001: one menu add persists the complete ordered supplier projection."""
+ """MH-MENU-ADD-001: menu addition projects all suppliers without persisting automatic hops."""
model_id = "overlapping-provider-model"
first = source(
@@ -293,15 +431,14 @@ def test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order(
)
after = store.load().to_payload()
- assert _route_pairs(store.load(), "codex", model_id) == (
+ assert resolve_model_hub_turn(store.load(), "codex", model_id).source_model_ids == (
(second.id, model_id),
(first.id, model_id),
)
assert after["sources"] == before["sources"]
assert after["agents"]["codex"]["sources"] == before["agents"]["codex"]["sources"]
- assert {key: value for key, value in after["agents"]["codex"]["routes"].items() if key != model_id} == before[
- "agents"
- ]["codex"]["routes"]
+ assert after["agents"]["codex"]["routes"] == before["agents"]["codex"]["routes"]
+ assert model_id not in after["agents"]["codex"]["routes"]
assert after["agents"]["claude"] == before["agents"]["claude"]
assert after["agents"]["opencode"] == before["agents"]["opencode"]
@@ -373,10 +510,10 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
assert adapter.revoked == [doomed.credential_ref]
-def test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss(
+def test_mh_supply_gap_001_manual_target_survives_inventory_loss(
tmp_path: Path,
) -> None:
- """MH-SUPPLY-GAP-001: a now-unsupplied menu model stays visible with a zero-length Route."""
+ """MH-SUPPLY-GAP-001: missing inventory evidence never deletes an explicit manual target."""
menu_model = fixed_model("claude")
supplied = source("src_supply01", [menu_model])
@@ -394,28 +531,13 @@ def test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss(
)
service = service_for(tmp_path, store, adapter)
- with pytest.raises(ModelHubError) as refusal:
- asyncio.run(service.refresh_source(supplied.id))
- result = asyncio.run(
- service.refresh_source(
- supplied.id,
- force=True,
- confirmed_remove_hops=refusal.value.data["would_remove_hops"],
- confirmed_interruptions=refusal.value.data["would_interrupt"],
- )
- )
- assert result["removed_hops"] == [
- {
- "backend": "claude",
- "menu_model": menu_model,
- "source_id": supplied.id,
- "model_id": menu_model,
- "position": 1,
- }
- ]
+ result = asyncio.run(service.refresh_source(supplied.id))
+ assert result["removed_hops"] == []
model_supply = next(row for row in service.list_agents()[0]["model_supply"] if row["model_id"] == menu_model)
- assert model_supply["chain_length"] == 0
- assert service.agent_chain("claude", menu_model)["chain"] == []
+ assert model_supply["chain_length"] == 1
+ chain = service.agent_chain("claude", menu_model)
+ assert chain["route_origin"] == "manual"
+ assert chain["manual_override"] == {"hops": [{"source_id": supplied.id, "model_id": menu_model}]}
def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state_is_cleaned(
diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
index 8794d750d..6aa5f8a9e 100644
--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
@@ -146,7 +146,9 @@ class AdapterBoundaryFake:
async def credential_supports_refresh(self, credential_ref: str) -> bool:
return credential_ref in self.refreshable_credential_refs
- async def invoke(self, source_id, model_id, request, stream, origin) -> InvokeHandle:
+ async def invoke(self, source_id, model_id, request, stream, origin, *, on_admitted=None) -> InvokeHandle:
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id, origin))
self.requests.append(request)
result = self.results.popleft()
diff --git a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
index 13ffb7612..1f8a55bfc 100644
--- a/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
@@ -49,7 +49,9 @@ def _enable_model_hub(monkeypatch: pytest.MonkeyPatch) -> None:
class EngineLossAdapter(ModelHubScenarioAdapter):
- async def invoke(self, source_id, model_id, request, stream, origin):
+ async def invoke(self, source_id, model_id, request, stream, origin, *, on_admitted=None):
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id, origin))
self.requests.append(request)
raise RuntimeError("scenario engine unavailable")
@@ -93,7 +95,9 @@ class MidTurnEngineLossHandle:
class MidTurnEngineLossAdapter(ModelHubScenarioAdapter):
- async def invoke(self, source_id, model_id, request, stream, origin):
+ async def invoke(self, source_id, model_id, request, stream, origin, *, on_admitted=None):
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id, origin))
self.requests.append(request)
return MidTurnEngineLossHandle(source_id, model_id)
diff --git a/tests/test_model_hub_admission.py b/tests/test_model_hub_admission.py
new file mode 100644
index 000000000..2b2a92278
--- /dev/null
+++ b/tests/test_model_hub_admission.py
@@ -0,0 +1,306 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from config.v2_config import ModelHubBackendModelConfig, ModelHubModelConfig, ModelHubSourceStateConfig
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+from core.handlers.model_hub.service import ModelHubError
+from tests.test_model_hub_resolution import _service, _source
+from tests.test_model_hub_routing_modes import MODEL, _sparse_config
+from tests.test_model_hub_transport_leases import _transport
+
+
+def _outcome(source, target=MODEL, *, status=200):
+ return RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS if status == 200 else RawOutcomeKind.HTTP_ERROR,
+ http_status=status,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ source_id=source.id,
+ model_id=target,
+ )
+
+
+async def _save_route(service, hops):
+ try:
+ return await service.set_agent_chain("claude", MODEL, {"hops": hops})
+ except ModelHubError as refusal:
+ assert "would_interrupt" in refusal.data
+ return await service.set_agent_chain("claude", MODEL, {"hops": hops, "force": True, **refusal.data})
+
+
+def _gate_method(owner, name, *, call_number=1):
+ entered, release = asyncio.Event(), asyncio.Event()
+ original = getattr(owner, name)
+ calls = 0
+
+ async def gated(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == call_number:
+ entered.set()
+ await release.wait()
+ return await original(*args, **kwargs)
+
+ setattr(owner, name, gated)
+ return entered, release
+
+
[email protected]("probe", [False, True])
[email protected]("change", ["target", "source", "empty"])
+def test_demand_snapshot_is_revalidated_before_transport_and_observer(tmp_path, probe, change):
+ async def run():
+ source = _source("src_race0001", ())
+ service, store, adapter = _service(tmp_path, _sparse_config(source))
+ entered, release = _gate_method(service, "_prepare_engine_for_demand")
+ observations = []
+ task = asyncio.create_task(
+ service.probe_agent("claude", MODEL)
+ if probe
+ else service.resolve(
+ backend="claude", model_id=MODEL, request={}, attempt_observer=lambda *args: observations.append(args)
+ )
+ )
+ await asyncio.wait_for(entered.wait(), 2)
+ if change == "target":
+ await _save_route(service, [{"source_id": source.id, "model_id": "new-target"}])
+ expected = "new-target"
+ elif change == "source":
+ await service.patch_source(source.id, {"display_name": "Changed source"})
+ expected = MODEL
+ else:
+ await _save_route(service, [])
+ expected = None
+ adapter.outcomes.append(_outcome(source, expected or MODEL))
+ release.set()
+ if expected is None:
+ with pytest.raises(ModelHubError):
+ await asyncio.wait_for(task, 2)
+ assert adapter.invocations == []
+ assert observations == []
+ else:
+ result = await asyncio.wait_for(task, 2)
+ assert adapter.invocations == [(source.id, expected)]
+ if not probe:
+ assert result.model_id == expected
+ assert result.source_label == store.config.sources[0].display_name
+ assert [(row[0], row[1]) for row in observations] == [(source.id, expected)] * 2
+ assert adapter.synced[-1][0].route_model_ids == (expected,)
+ assert not service._mutation_lock.locked()
+
+ asyncio.run(run())
+
+
[email protected]("probe", [False, True])
+def test_refresh_retry_never_uses_a_removed_exact_target(tmp_path, probe):
+ async def run():
+ source = _source("src_refresh01", ())
+ service, _, adapter = _service(tmp_path, _sparse_config(source))
+ adapter.refreshable_credential_refs.add(source.credential_ref)
+ adapter.outcomes.extend([_outcome(source, status=401), _outcome(source, "new-target")])
+ entered, release = _gate_method(service, "_invoke_admitted", call_number=2)
+ observations = []
+ task = asyncio.create_task(
+ service.probe_agent("claude", MODEL)
+ if probe
+ else service.resolve(
+ backend="claude", model_id=MODEL, request={}, attempt_observer=lambda *args: observations.append(args)
+ )
+ )
+ await asyncio.wait_for(entered.wait(), 2)
+ await _save_route(service, [{"source_id": source.id, "model_id": "new-target"}])
+ release.set()
+ result = await asyncio.wait_for(task, 2)
+ assert adapter.invocations == [(source.id, MODEL), (source.id, "new-target")]
+ assert (result["model_id"] if probe else result.model_id) == "new-target"
+ if not probe:
+ begun = [row for row in observations if row[4] is None]
+ assert [(row[0], row[1]) for row in begun] == adapter.invocations
+
+ asyncio.run(run())
+
+
+def test_fallback_replans_unattempted_hops_but_keeps_failed_source_excluded(tmp_path):
+ async def run():
+ first, second = _source("src_failed001", ()), _source("src_second001", ())
+ service, store, adapter = _service(tmp_path, _sparse_config(first, second))
+ adapter.outcomes.extend([_outcome(first, status=503), _outcome(second, "new-target")])
+ entered, release = _gate_method(service, "_invoke_admitted", call_number=2)
+ task = asyncio.create_task(service.resolve(backend="claude", model_id=MODEL, request={}))
+ await asyncio.wait_for(entered.wait(), 2)
+ # A recovered first Source must still not be retried in this turn.
+ async with service._mutation_lock:
+ previous = store.load()
+ updated = service._clone_config(previous)
+ updated.sources[0].state = ModelHubSourceStateConfig(status="standby")
+ await service._commit_synced(previous, updated)
+ await _save_route(
+ service,
+ [
+ {"source_id": first.id, "model_id": "retry-first"},
+ {"source_id": second.id, "model_id": "new-target"},
+ ],
+ )
+ release.set()
+ result = await asyncio.wait_for(task, 2)
+ assert result.source_id == second.id
+ assert adapter.invocations == [(first.id, MODEL), (second.id, "new-target")]
+
+ asyncio.run(run())
+
+
+def test_same_target_source_configuration_change_rebuilds_exact_request(tmp_path):
+ async def run():
+ source = _source("src_capability", ())
+ service, store, adapter = _service(tmp_path, _sparse_config(source))
+ entered, release = _gate_method(service, "_prepare_engine_for_demand")
+ adapter.outcomes.append(_outcome(source))
+ observations = []
+ task = asyncio.create_task(
+ service.resolve(
+ backend="claude",
+ model_id=MODEL,
+ request={"reasoning_effort": "high"},
+ attempt_observer=lambda *args: observations.append(args),
+ )
+ )
+ await asyncio.wait_for(entered.wait(), 2)
+ async with service._mutation_lock:
+ previous = store.load()
+ updated = service._clone_config(previous)
+ updated.sources[0].credential_ref = "cred_replacement"
+ updated.sources[0].models = [
+ ModelHubModelConfig(
+ id=MODEL,
+ provenance="discovered",
+ reasoning_efforts=["high"],
+ )
+ ]
+ await service._commit_synced(previous, updated)
+ release.set()
+ await asyncio.wait_for(task, 2)
+ assert adapter.invocations == [(source.id, MODEL)]
+ assert adapter.invocation_requests == [{"reasoning_effort": "high"}]
+ assert adapter.synced[-1][0].credential_ref == "cred_replacement"
+ assert observations[0][6] == ()
+
+ asyncio.run(run())
+
+
+async def _transport_service(tmp_path, adapter, binding):
+ source = _source(binding.source_id, (), vendor="custom", credential_ref=binding.credential_ref)
+ source.protocol, source.base_url = binding.protocol, binding.base_url
+ config = _sparse_config(source)
+ config.agents["claude"].mode = "direct"
+ agent = config.agents["opencode"]
+ agent.mode = "hub"
+ agent.models = [ModelHubBackendModelConfig(id="unknown", native_protocol="openai_chat")]
+ agent.sources.order = [source.id]
+ service, _, _ = _service(tmp_path / "service", config, adapter)
+ adapter.state_store.sync_sources(service._bindings(config))
+ service._engine_synced = True
+
+ async def prepare(**_kwargs):
+ await service._ensure_engine_synced()
+
+ service._prepare_engine_for_demand = prepare
+ return service
+
+
[email protected]("stream", [False, True])
+def test_independent_http_progress_after_admission_releases_mutation_lock(tmp_path, stream):
+ async def run():
+ async with _transport(tmp_path) as (adapter, _supervisor, binding, received, finish, requests):
+ service = await _transport_service(tmp_path, adapter, binding)
+ first = asyncio.create_task(
+ service.resolve(backend="opencode", model_id="unknown", request={}, stream=stream)
+ )
+ await asyncio.wait_for(received.wait(), 2)
+ assert not service._mutation_lock.locked()
+ second = asyncio.create_task(service.resolve(backend="opencode", model_id="unknown", request={}))
+ async with asyncio.timeout(2):
+ while len(requests) < 2:
+ await asyncio.sleep(0)
+ assert adapter._active_transports == 2
+ assert not service._mutation_lock.locked()
+ finish.set()
+ results = await asyncio.wait_for(asyncio.gather(first, second), 2)
+ for result in results:
+ if result.handle.stream is not None:
+ async for _part in result.handle.stream:
+ pass
+ await result.handle.close_stream()
+ assert adapter._active_transports == 0
+
+ asyncio.run(run())
+
+
[email protected]("probe", [False, True])
+def test_cancel_before_adapter_admission_releases_service_exclusion_without_attempt(tmp_path, probe):
+ async def run():
+ async with _transport(tmp_path) as (adapter, _supervisor, binding, _received, _finish, requests):
+ service = await _transport_service(tmp_path, adapter, binding)
+ observations = []
+ entered = asyncio.Event()
+ invoke = adapter.invoke
+
+ async def entering(*args, **kwargs):
+ entered.set()
+ return await invoke(*args, **kwargs)
+
+ adapter.invoke = entering
+ await adapter._routing_lock.acquire()
+ task = asyncio.create_task(
+ service.probe_agent("opencode", "unknown")
+ if probe
+ else service.resolve(
+ backend="opencode",
+ model_id="unknown",
+ request={},
+ attempt_observer=lambda *args: observations.append(args),
+ )
+ )
+ await asyncio.wait_for(entered.wait(), 2)
+ assert service._mutation_lock.locked()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, 2)
+ assert not service._mutation_lock.locked()
+ adapter._routing_lock.release()
+ assert requests == observations == []
+ assert adapter._active_transports == 0
+
+ asyncio.run(run())
+
+
[email protected]("failure", ["callback", "origin", "missing_source"])
+def test_adapter_pre_network_failures_do_not_leak_leases_or_service_exclusion(tmp_path, failure):
+ async def run():
+ async with _transport(tmp_path) as (adapter, _supervisor, binding, _received, _finish, requests):
+ service = await _transport_service(tmp_path, adapter, binding)
+ if failure != "callback":
+ from dataclasses import replace
+
+ adapter.state_store.sync_sources(
+ [] if failure == "missing_source" else [replace(binding, allowed_origins=("claude",))]
+ )
+
+ def observer(*_args):
+ raise ValueError("fixture callback failure")
+
+ with pytest.raises(ModelHubError):
+ await service.resolve(
+ backend="opencode",
+ model_id="unknown",
+ request={},
+ attempt_observer=observer,
+ )
+ assert not service._mutation_lock.locked()
+ assert not adapter._routing_lock.locked()
+ assert adapter._active_transports == 0
+ assert requests == []
+
+ asyncio.run(run())
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index ef8328240..edd4de741 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -280,7 +280,9 @@ class FakeAdapter:
models=tuple(models),
)
- async def invoke(self, source_id, model_id, request, stream, origin):
+ async def invoke(self, source_id, model_id, request, stream, origin, *, on_admitted=None):
+ if on_admitted is not None:
+ on_admitted()
return FakeInvokeHandle(
RawCallOutcome(
kind=RawOutcomeKind.SUCCESS,
@@ -387,7 +389,7 @@ def _refresh_fixture_routes(config: ModelHubConfig) -> None:
by_id = {source.id: source for source in config.sources}
for backend, agent in config.agents.items():
agent.sources.order = config.recommended_source_order(backend)
- agent.routes = {model_id: ModelHubRouteConfig() for model_id in agent.routes}
+ agent.routes = {model.id: ModelHubRouteConfig() for model in agent.models}
for source_id in agent.sources.order:
source = by_id[source_id]
for model in source.models:
@@ -915,7 +917,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):
assert adapter.start_calls == 1
assert store.config.enabled is True
assert runtime["enabled"] is True
- assert runtime["contract_version"] == 8
+ assert runtime["contract_version"] == 9
assert runtime["status"]["health"] == "ok"
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -1135,7 +1137,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 8, "status": {"health": "ok"}}
+ return {"contract_version": 9, "status": {"health": "ok"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1152,7 +1154,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 8, "status": {"health": "not_started"}}
+ return {"contract_version": 9, "status": {"health": "not_started"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1169,7 +1171,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 8, "status": {"health": "installing"}}
+ return {"contract_version": 9, "status": {"health": "installing"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1187,7 +1189,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypat
def rpc(operation, payload=None):
calls.append((operation, payload))
return {
- "contract_version": 8,
+ "contract_version": 9,
"changed": True,
"status": {"health": "not_started", "verified": True},
}
@@ -1221,6 +1223,84 @@ def test_reorder_client_preserves_explicit_null_order(monkeypatch):
assert calls == [("reorder_agent_chains", {"backend": "claude", "order": None})]
+def test_preview_and_restore_cross_client_and_controller_without_preview_sync(monkeypatch, tmp_path):
+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+ from vibe import model_hub_client
+
+ service, store, adapter = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(store, ("src_rpc00001",), model_id)
+ store.config.agents["claude"].routes[model_id] = ModelHubRouteConfig()
+ before = store.config.to_payload()
+ calls = []
+
+ async def rpc(operation, payload=None):
+ calls.append((operation, payload))
+ return await dispatch_model_hub_rpc(service, operation, payload or {})
+
+ monkeypatch.setattr(model_hub_client, "_rpc", rpc)
+ monkeypatch.setattr(model_hub_client, "_rpc_sync", lambda operation, payload=None: asyncio.run(rpc(operation, payload)))
+ remote = ModelHubRemoteService()
+ draft = remote.preview_agent_chain("claude", model_id, {"manual_override": None})
+ assert draft["route_origin"] == "automatic"
+ assert draft["manual_override"] is None
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+ restored = asyncio.run(remote.delete_agent_chain("claude", model_id))
+ assert restored["chain"] == draft
+ assert model_id not in store.config.agents["claude"].routes
+ assert calls == [
+ ("preview_agent_chain", {"backend": "claude", "model_id": model_id, "chain": {"manual_override": None}}),
+ ("delete_agent_chain", {"backend": "claude", "model_id": model_id, "chain": None}),
+ ]
+
+
+def test_chain_preview_is_read_only_and_restore_accepts_no_http_body(monkeypatch, tmp_path):
+ service, store, adapter = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(store, ("src_http0001",), model_id)
+ store.config.agents["claude"].routes[model_id] = ModelHubRouteConfig()
+ before = store.config.to_payload()
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ origin = "http://127.0.0.1:15131"
+ headers = csrf_headers(client, origin)
+ response = client.post(
+ f"/api/models/agents/claude/chain/preview?model={model_id}",
+ json={"manual_override": None}, headers=headers, base_url=origin,
+ )
+ assert response.status_code == 200
+ draft = response.get_json()["chain"]
+ assert draft["manual_override"] is None
+ assert draft["route_origin"] == "automatic"
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+ restored = client.delete(
+ f"/api/models/agents/claude/chain?model={model_id}", headers=headers, base_url=origin,
+ )
+ assert restored.status_code == 200
+ assert restored.get_json()["chain"] == draft
+ assert model_id not in store.config.agents["claude"].routes
+
+
[email protected]("body", [[], {}, {"manual_override": []}, {"manual_override": {"hops": [], "mode": "manual"}}])
+def test_preview_rejects_invalid_shape_without_state_change(monkeypatch, tmp_path, body):
+ service, store, adapter = _service(tmp_path)
+ before = store.config.to_payload()
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ origin = "http://127.0.0.1:15131"
+ response = client.post(
+ "/api/models/agents/claude/chain/preview?model=claude-opus-4-6",
+ json=body, headers=csrf_headers(client, origin), base_url=origin,
+ )
+ assert response.status_code in (400, 409)
+ assert response.get_json()["ok"] is False
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
@@ -2138,7 +2218,7 @@ def test_backend_catalog_add_edit_and_runtime_refresh(
response = asyncio.run(service.set_agent_models(backend, baseline, [*baseline, added]))
assert response["agent"]["catalog_models"][-1] == added
- assert store.config.agents[backend].routes[model_id].hops == ()
+ assert model_id not in store.config.agents[backend].routes
assert refreshed == [backend]
if backend == "opencode":
assert store.config.agents[backend].menu.checked == [model_id]
@@ -2520,7 +2600,8 @@ def test_backend_catalog_add_validates_supplier_echo_and_stores_draft_literally(
)
assert result["agent"]["catalog_models"][-1] == added
- assert [(hop.source_id, hop.model_id) for hop in store.config.agents["codex"].routes[model_id].hops] == [
+ assert model_id not in store.config.agents["codex"].routes
+ assert [(hop["source_id"], hop["model_id"]) for hop in service.agent_chain("codex", model_id)["chain"]] == [
(source.id, model_id) for source in reversed(sources)
]
after = store.config.to_payload()
@@ -2681,7 +2762,8 @@ def test_builtin_reconcile_inserts_in_snapshot_order_and_preserves_every_other_r
created = next(model for model in agent.models if model.id == "gpt-new")
assert created.display_name == "GPT New"
assert created.reasoning_efforts == ["low", "high"]
- assert [(hop.source_id, hop.model_id) for hop in agent.routes["gpt-new"].hops] == [(source.id, "gpt-new")]
+ assert "gpt-new" not in agent.routes
+ assert service.agent_chain("codex", "gpt-new")["current"] == {"source_id": source.id, "model_id": "gpt-new"}
assert "gpt-hidden" not in {model.id for model in agent.models}
assert "x" * (MODEL_ID_MAX_LENGTH + 1) not in {model.id for model in agent.models}
assert {model.id: model.to_payload() for model in agent.models if model.id in unchanged} == unchanged
@@ -3625,6 +3707,7 @@ def test_agents_endpoint_projects_exact_chain_runnability(tmp_path):
"model_id": model_id,
"chain_length": 1,
"has_runnable_hop": True,
+ "route_origin": "manual",
}
empty_model = next(model for model, row in supplied.items() if row["chain_length"] == 0)
assert supplied[empty_model]["has_runnable_hop"] is False
@@ -3899,7 +3982,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):
assert response.status_code == 200
assert response.get_json() == {
"ok": True,
- "contract_version": 8,
+ "contract_version": 9,
"agent": {
"backend": "codex",
"mode": "hub",
@@ -4009,9 +4092,8 @@ def test_direct_to_hub_atomically_adopts_recognized_native_login(tmp_path):
assert native.supply_channel == "native_cli"
assert native.vendor == "anthropic"
assert store.config.agents["claude"].sources.order[0] == native.id
- assert any(
- hop.source_id == native.id for route in store.config.agents["claude"].routes.values() for hop in route.hops
- )
+ assert store.config.agents["claude"].routes == {}
+ assert service.agent_chain("claude", "claude-opus-4-6")["chain"][0]["source_id"] == native.id
repeated = asyncio.run(service.set_agent_mode("claude", "hub"))
@@ -4220,7 +4302,7 @@ def test_direct_to_hub_adoption_does_not_leak_partial_state_on_save_failure(tmp_
assert store.config.sources == []
-def test_reorder_agent_chains_applies_source_order_without_changing_pairs(tmp_path):
+def test_reorder_agent_chains_without_order_is_read_only(tmp_path):
service, store, adapter = _service(tmp_path)
model_id = "claude-opus-4-6"
original = _set_claude_route_fixture(
@@ -4238,8 +4320,8 @@ def test_reorder_agent_chains_applies_source_order_without_changing_pairs(tmp_pa
reordered = store.config.agents["claude"].routes[model_id].hops
assert [(hop.source_id, hop.model_id) for hop in reordered] == [
- ("src_second001", model_id),
("src_first0001", model_id),
+ ("src_second001", model_id),
]
assert sorted((hop.source_id, hop.model_id) for hop in reordered) == sorted(
(hop.source_id, hop.model_id) for hop in original
@@ -4247,12 +4329,12 @@ def test_reorder_agent_chains_applies_source_order_without_changing_pairs(tmp_pa
assert adapter.synced == []
assert service._engine_synced is True
assert agent["routes"][model_id]["hops"] == [
- {"source_id": "src_second001", "model_id": model_id},
{"source_id": "src_first0001", "model_id": model_id},
+ {"source_id": "src_second001", "model_id": model_id},
]
-def test_reorder_agent_chains_commits_source_order_with_route_reorder(tmp_path):
+def test_reorder_agent_chains_commits_defaults_without_reordering_manual_route(tmp_path):
service, store, _ = _service(tmp_path)
model_id = "claude-opus-4-6"
_set_claude_route_fixture(
@@ -4274,12 +4356,12 @@ def test_reorder_agent_chains_commits_source_order_with_route_reorder(tmp_path):
]
assert agent["sources"]["order"] == ["src_second001", "src_first0001"]
assert [hop["source_id"] for hop in agent["routes"][model_id]["hops"]] == [
- "src_second001",
"src_first0001",
+ "src_second001",
]
-def test_new_source_is_appended_to_route_hops(tmp_path):
+def test_new_source_is_appended_to_defaults_only(tmp_path):
service, store, _ = _service(tmp_path)
model_id = "claude-opus-4-6"
_set_claude_route_fixture(store, ("src_listed01", "src_heldout1"), model_id)
@@ -4305,7 +4387,6 @@ def test_new_source_is_appended_to_route_hops(tmp_path):
assert [hop.source_id for hop in agent.routes[model_id].hops] == [
"src_listed01",
"src_heldout1",
- "src_new0001",
]
@@ -4341,7 +4422,6 @@ def test_new_source_preserves_explicit_route_order(tmp_path):
assert [hop.source_id for hop in agent.routes[model_id].hops] == [
"src_explicit01",
"src_listed01",
- "src_new0001",
]
@@ -4372,8 +4452,8 @@ def test_reorder_route_accepts_source_order_atomically(monkeypatch, tmp_path):
"src_first0001",
]
assert [hop["source_id"] for hop in payload["agent"]["routes"][model_id]["hops"]] == [
- "src_second001",
"src_first0001",
+ "src_second001",
]
@@ -5453,7 +5533,7 @@ def test_delete_guard_reports_only_routes_emptied_by_this_mutation(tmp_path):
claude = store.config.agents["claude"]
claude.sources.order = [source.id]
claude.routes = {
- **{model_id: ModelHubRouteConfig() for model_id in claude.routes},
+ **{model.id: ModelHubRouteConfig() for model in claude.models},
"claude-opus-4-6": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)),
"claude-sonnet-4-6": ModelHubRouteConfig(),
}
@@ -7075,7 +7155,7 @@ def test_failed_same_handle_hub_reauth_requires_user_action(
assert service.oauth_flows.binding(flow["flow_id"]) is None
-def test_failed_zero_model_hub_source_is_omitted_from_restart_sync(tmp_path):
+def test_failed_zero_model_subscription_retains_omission_from_restart_projection(tmp_path):
class StrictProjectionAdapter(FakeAdapter):
async def sync_sources(self, bindings):
assert all(binding.model_ids for binding in bindings)
@@ -7340,7 +7420,7 @@ def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(tmp_path):
assert service.oauth_flows.binding(flow["flow_id"]) is None
-def test_credential_route_carries_body_force_override_and_structured_guard(
+def test_credential_inventory_narrowing_preserves_exact_routes(
monkeypatch,
tmp_path,
):
@@ -7377,90 +7457,24 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
headers = csrf_headers(client, base_url)
request_body = {"key": "sk-narrower-route-key"}
- refused = client.put(
+ before_routes = store.config.agents["claude"].to_payload()["routes"]
+ response = client.put(
f"/api/models/sources/{created['id']}/credential",
json=request_body,
headers=headers,
base_url=base_url,
)
- assert refused.status_code == 409
- refusal = refused.get_json()
- route_hop_schema = _schema("guard-refusal.schema.json")["definitions"]["RouteHopRef"]
- for hop in refusal["would_remove_hops"]:
- Draft7Validator(route_hop_schema).validate(hop)
- assert refusal["error"] == "source_model_in_route_chain"
- assert refusal["would_remove_hops"]
- assert all(hop["source_id"] == created["id"] for hop in refusal["would_remove_hops"])
- assert refusal["would_interrupt"] == [
- {
- "backend": "claude",
- "model_id": "claude-opus-4-6",
- "agents": ["claude"],
- },
- {
- "backend": "claude",
- "model_id": "claude-sonnet-4-6",
- "agents": [],
- },
- ]
- unconfirmed = client.put(
- f"/api/models/sources/{created['id']}/credential",
- json={**request_body, "force": True},
- headers=headers,
- base_url=base_url,
- )
- assert unconfirmed.status_code == 409
- assert unconfirmed.get_json()["would_remove_hops"] == refusal["would_remove_hops"]
- assert unconfirmed.get_json()["would_interrupt"] == refusal["would_interrupt"]
-
- stale_confirmation = client.put(
- f"/api/models/sources/{created['id']}/credential",
- json={
- **request_body,
- "force": True,
- "would_remove_hops": refusal["would_remove_hops"],
- "would_interrupt": refusal["would_interrupt"][:-1],
- },
- headers=headers,
- base_url=base_url,
- )
- assert stale_confirmation.status_code == 409
- assert stale_confirmation.get_json()["error"] == refusal["error"]
- assert stale_confirmation.get_json()["would_remove_hops"] == refusal["would_remove_hops"]
- assert stale_confirmation.get_json()["would_interrupt"] == refusal["would_interrupt"]
-
- committed = client.put(
- f"/api/models/sources/{created['id']}/credential",
- json={
- **request_body,
- "force": True,
- "would_remove_hops": refusal["would_remove_hops"],
- "would_interrupt": refusal["would_interrupt"],
- },
- headers=headers,
- base_url=base_url,
- ).get_json()
-
- assert committed["removed_hops"] == refusal["would_remove_hops"]
- assert committed["interrupted"] == refusal["would_interrupt"]
- assert committed["source"]["credential_ref"] == "cred_route_5"
- removed_identities = {
- (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"]) for hop in committed["removed_hops"]
- }
- assert all(
- (backend, menu_model, hop.source_id, hop.model_id) not in removed_identities
- for backend, agent in store.config.agents.items()
- for menu_model, route in agent.routes.items()
- for hop in route.hops
- )
- assert adapter.revoked == [
- "cred_test001",
- "cred_route_2",
- "cred_route_3",
- "cred_route_4",
- "cred_route_1",
- ]
+ assert response.status_code == 200
+ committed = response.get_json()
+ assert committed["removed_hops"] == []
+ assert committed["interrupted"] == []
+ assert committed["source"]["credential_ref"] == "cred_route_2"
+ assert store.config.agents["claude"].to_payload()["routes"] == before_routes
+ chain = service.agent_chain("claude", "claude-opus-4-6")
+ assert chain["current"] == {"source_id": created["id"], "model_id": "claude-opus-4-6"}
+ assert chain["route_origin"] == "passthrough"
+ assert adapter.revoked == ["cred_test001", "cred_route_1"]
def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
@@ -8141,7 +8155,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t
assert accepted.status_code == 200
runtime = accepted.get_json()["runtime"]
assert adapter.start_calls == 1
- assert runtime["contract_version"] == 8
+ assert runtime["contract_version"] == 9
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -8777,7 +8791,7 @@ def test_source_patch_rejects_one_discovered_model_under_two_spellings(tmp_path)
assert store.config.sources[0].base_url == "https://relay.example/v1"
-def test_base_url_change_guards_and_prunes_invalid_exact_hops(
+def test_base_url_change_preserves_missing_inventory_exact_hops(
monkeypatch,
tmp_path,
):
@@ -8807,58 +8821,35 @@ def test_base_url_change_guards_and_prunes_invalid_exact_hops(
headers = csrf_headers(client, origin)
replacement_url = "https://other-relay.example/v1"
- refused = client.patch(
+ before_routes = store.config.agents["claude"].to_payload()["routes"]
+ response = client.patch(
f"/api/models/sources/{source['id']}",
json={"base_url": replacement_url},
headers=headers,
base_url=origin,
)
- assert refused.status_code == 409
- refusal = refused.get_json()
- assert refusal["error"] == "source_model_in_route_chain"
- assert refusal["would_remove_hops"]
- assert store.config.sources[0].base_url is None
- refused_retarget = adapter.retargeted_credentials[0]
- assert refused_retarget[:4] == (
+ assert response.status_code == 200
+ committed = response.get_json()
+ committed_retarget = adapter.retargeted_credentials[0]
+ assert committed_retarget[:4] == (
old_credential_ref,
"anthropic",
"anthropic",
replacement_url,
)
- assert discovery_refs == [refused_retarget[4]]
- assert refused_retarget[4] in adapter.revoked
-
- committed = client.patch(
- f"/api/models/sources/{source['id']}",
- json={
- "base_url": replacement_url,
- "force": True,
- "would_remove_hops": refusal["would_remove_hops"],
- "would_interrupt": refusal["would_interrupt"],
- },
- headers=headers,
- base_url=origin,
- ).get_json()
-
assert committed["source"]["base_url"] == replacement_url
- committed_retarget = adapter.retargeted_credentials[1]
- assert committed_retarget[:4] == refused_retarget[:4]
assert committed["source"]["credential_ref"] == committed_retarget[4]
- assert discovery_refs == [refused_retarget[4], committed_retarget[4]]
+ assert discovery_refs == [committed_retarget[4]]
assert old_credential_ref in adapter.revoked
- assert committed["removed_hops"] == refusal["would_remove_hops"]
- assert committed["interrupted"] == refusal["would_interrupt"]
+ assert committed_retarget[4] not in adapter.revoked
+ assert committed["removed_hops"] == []
+ assert committed["interrupted"] == []
assert store.config.sources[0].base_url == replacement_url
- removed_identities = {
- (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"]) for hop in committed["removed_hops"]
+ assert store.config.agents["claude"].to_payload()["routes"] == before_routes
+ assert service.agent_chain("claude", "claude-opus-4-6")["current"] == {
+ "source_id": source["id"], "model_id": "claude-opus-4-6"
}
- assert all(
- (backend, menu_model, hop.source_id, hop.model_id) not in removed_identities
- for backend, agent in store.config.agents.items()
- for menu_model, route in agent.routes.items()
- for hop in route.hops
- )
def test_base_url_retarget_cancellation_revokes_only_the_uncommitted_ref(
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 061f5c278..a11eab7df 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -106,7 +106,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():
def test_unsaved_observation_schema_closes_all_terminal_shapes():
schema = _schema("observation-result.schema.json")
- assert schema["properties"]["contract_version"]["const"] == 8
+ assert schema["properties"]["contract_version"]["const"] == 9
assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(
member.value for member in ObservationOutcome
)
@@ -130,7 +130,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
def payload(observation: SourceObservation) -> dict:
return {
- "contract_version": 8,
+ "contract_version": 9,
"outcome": observation.outcome.value,
"reachable": observation.reachable,
"authenticated": (
@@ -384,7 +384,7 @@ def test_opencode_persisted_rows_use_bare_canonical_ids_and_require_native_proto
payload = ModelHubConfig().to_payload()
source = copy.deepcopy(_schema("source.schema.json")["examples"][1])
payload["sources"] = [source]
- codex_route = next(iter(payload["agents"]["codex"]["routes"].values()))
+ codex_route = payload["agents"]["codex"]["routes"].setdefault("gpt-5.6", {"hops": []})
codex_route["hops"] = [
{
"source_id": source["id"],
@@ -650,37 +650,13 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():
assert required in ac_54
-def test_per_model_route_put_does_not_consume_stored_source_order():
- api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
- model_hub_plan = (CONTRACTS.parent / "model-hub.md").read_text(encoding="utf-8")
-
- route_row = next(
- line
- for line in api_contract.splitlines()
- if line.startswith("| PUT `/api/models/agents/<backend>/chain?model=<id>`")
- )
- assert "handler never reads `sources.order`" in route_row
- assert "submitted `hops` carry no Source-order semantics" in route_row
-
- source_order_contract = api_contract.split("## Per-backend source order", 1)[1].split(
- "### Direct-to-Gateway native adoption", 1
- )[0]
- assert "only server-side post-creation" in source_order_contract
- assert "implicitly reads and applies the stored Source order" in source_order_contract
-
- exact_route_contract = api_contract.split("### Exact Route-chain configuration", 1)[1].split(
- "## Source creation outcome", 1
- )[0]
- assert "per-model PUT persists the explicit submitted order" in exact_route_contract
- assert "never reads `sources.order`" in exact_route_contract
- assert "request still carries only explicit `hops`" in exact_route_contract
-
- section_42 = model_hub_plan.split("### 4.2 Gateway strategy", 1)[1].split("### 4.3 Runtime resolution", 1)[0]
- section_46 = model_hub_plan.split("### 4.6 Configured-chain storage and mutation", 1)[1].split("### 4.7", 1)[0]
- for authority in (section_42, section_46):
- assert "server" in authority
- assert "per-model" in authority
- assert "does not read `sources.order`" in authority or "never reads `sources.order`" in authority
+def test_sparse_override_contract_has_one_default_order_owner():
+ contract = (CONTRACTS.parent / "model-hub-routing-modes.md").read_text(encoding="utf-8")
+ assert "sources.order` is the sole backend-default" in contract
+ assert "Key absence means automatic" in contract
+ assert "Restoring automatic deletes the key" in contract
+ assert "Never reorder manual arrays" in contract
+ assert "no inference from array equality" in contract
def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
@@ -709,7 +685,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
route_refusal = {
"ok": False,
- "contract_version": 8,
+ "contract_version": 9,
"error": "source_in_route_chain",
"detail": "modelHub.errors.source_in_route_chain",
"would_remove_hops": [hop],
@@ -725,7 +701,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
}
candidate_refusal = {
"ok": False,
- "contract_version": 8,
+ "contract_version": 9,
"error": "candidate_suppliers_changed",
"detail": "modelHub.errors.candidate_suppliers_changed",
"changed": {
@@ -795,7 +771,7 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():
},
"supply_status": "ok",
"menu": None,
- "model_supply": [{"model_id": "claude-opus-4-5", "chain_length": 1}],
+ "model_supply": [{"model_id": "claude-opus-4-5", "chain_length": 1, "route_origin": "automatic"}],
"builtin_models": ["claude-opus-4-5"],
"named_agents": [],
}
@@ -807,7 +783,7 @@ def test_v8_mirror_registry_is_executable_and_complete():
registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
schemas = _mirror_schemas(registry)
- assert registry["contract_version"] == 8
+ assert registry["contract_version"] == 9
ids = [entry["id"] for entry in registry["entries"]]
assert ids
assert len(ids) == len(set(ids))
@@ -895,6 +871,20 @@ def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():
assert declared is not None
assert int(declared.group(1)) == terminal
+ ui_types = Path("ui/src/components/settings/models/types.ts").read_text(encoding="utf-8")
+ persisted_versions = re.search(
+ r"export const PERSISTED_TURN_CONTRACT_VERSIONS\s*=\s*(\[[^\]]*\])\s+as const;",
+ ui_types,
+ )
+ assert persisted_versions is not None
+ provenance_schema = json.loads((CONTRACTS / "turn-provenance.schema.json").read_text(encoding="utf-8"))
+ assert json.loads(persisted_versions.group(1)) == provenance_schema["properties"]["contract_version"]["enum"]
+ assert re.search(
+ r"export type TurnProvenance\s*=\s*\{\s*contract_version:\s*"
+ r"\(typeof PERSISTED_TURN_CONTRACT_VERSIONS\)\[number\];",
+ ui_types,
+ )
+
def test_contracts_readme_indexes_every_file_beside_it():
# The index is what a reader consults to learn a contract exists at all, so a
@@ -1025,8 +1015,8 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp
"kind": "contract_version_schema_drift",
"domain": "V1",
"file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",
- "values": [6, 7, 8],
- "expected": [5, 6, 7, 8],
+ "values": [6, 7, 8, 9],
+ "expected": [5, 6, 7, 8, 9],
} in result["findings"]
@@ -1313,15 +1303,17 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
chain_validator = Draft7Validator(chain_schema)
for example in chain_schema["examples"]:
chain_validator.validate(example)
- for waiting in chain_schema["examples"][:2]:
+ for waiting in (example for example in chain_schema["examples"] if example["supply_state"] == "waiting"):
interrupted = copy.deepcopy(waiting)
interrupted["supply_state"] = "interrupted"
with pytest.raises(ValidationError):
chain_validator.validate(interrupted)
exact_hop = {
- "contract_version": 8,
+ "contract_version": 9,
"backend": "claude",
"model_id": "claude-opus-4-6",
+ "manual_override": None,
+ "route_origin": "automatic",
"chain": [
{
"source_id": "src_claudepro1",
@@ -1352,6 +1344,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
"model_id": "claude-opus-4-6",
"chain_length": 0,
"has_runnable_hop": False,
+ "route_origin": None,
}
model_supply_validator.validate(empty_model_supply)
with pytest.raises(ValidationError):
@@ -1880,7 +1873,8 @@ def test_config_reload_spells_route_hops_like_the_inventory_they_name(monkeypatc
]
current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
current["model_hub"]["sources"] = [source]
- menu_model, route = next(iter(current["model_hub"]["agents"]["claude"]["routes"].items()))
+ menu_model = "claude-opus-4-6"
+ route = current["model_hub"]["agents"]["claude"]["routes"].setdefault(menu_model, {"hops": []})
route["hops"] = [{"source_id": source["id"], "model_id": model["id"]} for model in source["models"]]
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(current, ensure_ascii=False), encoding="utf-8")
@@ -1917,7 +1911,8 @@ def test_loading_a_persisted_config_yields_one_this_product_can_load_again(monke
]
current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
current["model_hub"]["sources"] = [source]
- menu_model, route = next(iter(current["model_hub"]["agents"]["claude"]["routes"].items()))
+ menu_model = "claude-opus-4-6"
+ route = current["model_hub"]["agents"]["claude"]["routes"].setdefault(menu_model, {"hops": []})
route["hops"] = [{"source_id": source["id"], "model_id": spelling} for spelling in (padded.strip(), padded)]
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(current, ensure_ascii=False), encoding="utf-8")
@@ -2969,7 +2964,7 @@ def test_recommended_order_is_backend_native_then_created_at_and_id():
]
-def test_persisted_hub_config_requires_explicit_complete_route_rows():
+def test_persisted_hub_config_requires_sparse_override_object():
payload = ModelHubConfig().to_payload()
missing = json.loads(json.dumps(payload))
@@ -2982,10 +2977,8 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():
with pytest.raises(ValueError, match="routes.*object"):
ModelHubConfig.from_payload(non_object)
- incomplete = json.loads(json.dumps(payload))
- incomplete["agents"]["claude"]["routes"].pop("claude-opus-4-6")
- with pytest.raises(ValueError, match="missing menu model"):
- ModelHubConfig.from_payload(incomplete)
+ sparse = ModelHubConfig.from_payload(payload)
+ assert sparse.agents["claude"].routes == {}
extra = json.loads(json.dumps(payload))
extra["agents"]["claude"]["routes"]["claude-hidden-model"] = {"hops": []}
@@ -3015,8 +3008,7 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():
}
]
dynamic["agents"]["opencode"]["routes"] = {}
- with pytest.raises(ValueError, match="missing menu model 'model'"):
- ModelHubConfig.from_payload(dynamic)
+ assert ModelHubConfig.from_payload(dynamic).agents["opencode"].routes == {}
dormant = json.loads(json.dumps(payload))
dormant["agents"]["opencode"]["routes"]["dormant-model"] = {"hops": []}
@@ -3033,10 +3025,11 @@ def test_backend_model_modalities_match_the_contract_directions():
ModelHubBackendModelConfig.from_payload({"id": "custom-model", "output_modalities": ["pdf"]})
-def test_config_reload_adds_bundled_routes_without_discarding_legacy_models(tmp_path):
+def test_config_reload_preserves_legacy_routes_without_seeding_missing_models(tmp_path):
payload = api.config_to_payload(default_config())
claude = payload["model_hub"]["agents"]["claude"]
- original_ids = tuple(claude["routes"])
+ original_ids = tuple(model["id"] for model in claude["models"])
+ claude["routes"] = {model_id: {"hops": []} for model_id in original_ids}
removed_id = original_ids[0]
stale_id = "claude-catalog-removed-after-save"
routes = claude["routes"]
@@ -3050,8 +3043,8 @@ def test_config_reload_adds_bundled_routes_without_discarding_legacy_models(tmp_
migrated_routes = loaded.model_hub.agents["claude"].routes
migrated_models = loaded.model_hub.agents["claude"].models
- assert set(migrated_routes) == {*original_ids, stale_id}
- assert migrated_routes[removed_id].hops == ()
+ assert set(migrated_routes) == ({*original_ids, stale_id} - {removed_id})
+ assert removed_id not in migrated_routes
assert migrated_routes[stale_id].hops == ()
assert next(model for model in migrated_models if model.id == stale_id).origin == "manual"
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 955490a20..b112101e2 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -1147,7 +1147,9 @@ class ProbeAdapter:
self.capability_queries.append(credential_ref)
return credential_ref in self.refreshable_credential_refs
- async def invoke(self, source_id, model_id, request, _stream, origin):
+ async def invoke(self, source_id, model_id, request, _stream, origin, *, on_admitted=None):
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id, origin))
self.requests.append(request)
if self.live_handles:
@@ -2781,7 +2783,7 @@ def test_gateway_no_candidate_projects_live_exact_hop_blockers(
{
"source_id": source.id,
"model_id": "removed-model",
- "reason": "model_unsupported",
+ "reason": "credential_revoked",
}
]
_assert_valid("turn-provenance.schema.json", record)
@@ -2907,10 +2909,12 @@ def test_gateway_exhaustion_uses_no_time_copy_when_an_earlier_hop_recovers(
request,
stream,
origin,
+ *,
+ on_admitted=None,
):
if source_id == second.id:
clock["now"] = NOW + timedelta(minutes=10)
- return await invoke(source_id, model_id, request, stream, origin)
+ return await invoke(source_id, model_id, request, stream, origin, on_admitted=on_admitted)
service.adapter.invoke = advance_during_later_attempt
gateway = ModelHubTurnGateway(service)
@@ -3020,6 +3024,8 @@ def test_gateway_streamed_fallback_settles_source_before_rendering_next_current(
"channel": "hub",
"reason": "stream_interrupted",
"stream_started": True,
+ "http_status": 200,
+ "upstream_error_code": None,
}
_assert_valid("turn-provenance.schema.json", record)
@@ -4070,6 +4076,7 @@ def test_resolver_settles_a_bodyless_attempt_that_beats_cancellation(
invoke = service.adapter.invoke
async def blocked_invoke(*args, **kwargs):
+ kwargs.pop("on_admitted")()
invoke_started.set()
await release_invoke.wait()
return await invoke(*args, **kwargs)
@@ -4121,6 +4128,7 @@ def test_resolver_meters_an_observed_stream_that_beats_cancellation(
invoke = service.adapter.invoke
async def blocked_invoke(*args, **kwargs):
+ kwargs.pop("on_admitted")()
invoke_started.set()
await release_invoke.wait()
return await invoke(*args, **kwargs)
@@ -4673,6 +4681,8 @@ def test_gateway_localizes_terminal_permission_denial_without_switching(
"channel": "hub",
"reason": "invalid_parameter",
"stream_started": False,
+ "http_status": 403,
+ "upstream_error_code": "permission_error",
}
_assert_valid("turn-provenance.schema.json", record)
@@ -5698,7 +5708,7 @@ def test_opencode_overlay_identity_is_stable_under_runtime_perturbations(
assert projected_content() == baseline
-def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: Path) -> None:
+def test_opencode_overlay_uses_exact_manual_target_missing_from_inventory(tmp_path: Path) -> None:
source = _source(
"src_overlay03",
"Overlay",
@@ -5733,7 +5743,7 @@ def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: Path
overlay = asyncio.run(router.prepare_opencode_overlay())
assert overlay is not None
- assert [launch.target_model for launch in overlay.launches] == ["supported-model"]
+ assert [launch.target_model for launch in overlay.launches] == ["stale-model"]
def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop(
@@ -5776,8 +5786,8 @@ def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop(
}
}
assert overlay.checked_identifiers == ("menu-model",)
- assert overlay.available_identifiers == ()
- assert overlay.launches == ()
+ assert overlay.available_identifiers == ("menu-model",)
+ assert [launch.target_model for launch in overlay.launches] == ["stale-model"]
def test_production_adapter_retargets_api_keys_without_exposing_or_mutating_them(
@@ -6434,7 +6444,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
_assert_valid(
"observation-result.schema.json",
{
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -8053,6 +8063,7 @@ def test_model_discovery_adds_standard_v1_path_to_a_bare_origin() -> None:
def test_blocked_exact_hop_emits_one_supply_interruption(tmp_path: Path) -> None:
source = _source("src_blocked01", "Blocked")
+ source.models.append(ModelHubModelConfig(id="removed-model", provenance="discovered", retired=True))
service = _service(tmp_path, sources=[source])
service.store.config.agents["claude"].routes["shared-model"] = ModelHubRouteConfig(
hops=(ModelHubRouteHopConfig(source.id, "removed-model"),)
@@ -8559,7 +8570,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:
probe = asyncio.run(service.probe_agent("codex", "shared-model"))
assert probe == {
- "contract_version": 8,
+ "contract_version": 9,
"backend": "codex",
"channel": "native_cli",
"reachable": True,
diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.py
new file mode 100644
index 000000000..b0c768d23
--- /dev/null
+++ b/tests/test_model_hub_provenance.py
@@ -0,0 +1,210 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+from core.handlers.model_hub.classification import UPSTREAM_MACHINE_ERROR_CODES, classify_outcome
+from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH
+from core.handlers.model_hub.provenance import BoundedProvenanceStore, TurnCorrelationRegistry
+from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+from core.handlers.model_hub.service import ModelHubError
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from tests.test_model_hub_resolution import _service
+from tests.test_model_hub_routing_modes import MODEL, _loaded_catalog_config, _sparse_config
+from tests.ui_server_test_helpers import csrf_headers
+from vibe import model_hub_client, ui_server
+
+
+def _record(turn_id, *, backend="claude", model=MODEL, outcome="failed_terminal"):
+ identity = {"source_id": "src_deleted01", "configured_model_id": "unknown-model", "channel": "hub"}
+ return {
+ "contract_version": 9,
+ "turn_id": turn_id,
+ "ts": "2026-09-06T00:00:00Z",
+ "agent": backend,
+ "requested_model_id": model,
+ "outcome": outcome,
+ "failed_attempts": [],
+ "served": identity if outcome == "served" else None,
+ "terminal_error": {**identity, "reason": "invalid_parameter", "stream_started": False}
+ if outcome == "failed_terminal"
+ else None,
+ "canceled_attempt": None,
+ "model_supply_state": None,
+ "blockers": [],
+ }
+
+
+def test_latest_record_is_backend_model_isolated_bounded_and_not_latest_error(tmp_path):
+ path = tmp_path / "provenance.json"
+ store = BoundedProvenanceStore(path, max_entries=3)
+ assert store.latest_for_model("claude", MODEL) is None
+ assert not path.exists()
+ first = _record("first")
+ store.put(first)
+ store.put(_record("other-backend", backend="codex"))
+ store.put(_record("other-model", model="claude-other"))
+ assert store.latest_for_model("claude", MODEL) == first
+ before = path.read_bytes()
+ assert BoundedProvenanceStore(path).latest_for_model("claude", MODEL) == first
+ assert path.read_bytes() == before
+ success = _record("later-success", outcome="served")
+ success["ts"] = "2025-01-01T00:00:00Z"
+ store.put(success)
+ assert store.latest_for_model("claude", MODEL) == success
+ assert store.get("first") is None
+ assert len(json.loads(path.read_text())) == 3
+
+
[email protected]("status,expected_status", [(404, 404), (True, None), (99, None), (600, None), (None, None)])
+ "code,expected_code", [("model_not_found", "model_not_found"), ("arbitrary credential=secret", None), (None, None)]
+)
+def test_new_terminal_records_retain_only_safe_recognized_error_metadata(
+ tmp_path, status, expected_status, code, expected_code
+):
+ store = BoundedProvenanceStore(tmp_path / "records.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "fixture", "turn-error")
+ turn_id = registry.begin_gateway_request(backend="claude", token=token, requested_model_id=MODEL)
+ registry.begin_attempt(
+ turn_id, source_id="src_deleted01", resolved_model_id="unknown-model", channel="hub", via_mapping=False
+ )
+ outcome = RawCallOutcome(
+ kind=RawOutcomeKind.HTTP_ERROR,
+ http_status=status,
+ error_code=code,
+ redacted_message="model not found; arbitrary upstream text",
+ stream_started=False,
+ model_id="unknown-model",
+ source_id="src_deleted01",
+ )
+ registry.finish_attempt(turn_id, outcome=outcome, decision=classify_outcome(outcome))
+ registry.settle("turn-error", settled_by=SETTLED_BY_TERMINAL_RESULT)
+ record = store.latest_for_model("claude", MODEL)
+ assert record["terminal_error"] == {
+ "source_id": "src_deleted01",
+ "configured_model_id": "unknown-model",
+ "channel": "hub",
+ "reason": "invalid_parameter",
+ "stream_started": False,
+ "http_status": expected_status,
+ "upstream_error_code": expected_code,
+ }
+ serialized = store.path.read_text()
+ assert "arbitrary" not in serialized
+ assert "credential" not in serialized
+
+
+def test_model_history_read_preserves_legacy_records_and_current_route_state(tmp_path):
+ service, store, adapter = _service(tmp_path, _sparse_config())
+ legacy = _record("legacy")
+ legacy["contract_version"] -= 1
+ service.provenance.put(legacy)
+ before = store.config.to_payload()
+ history_bytes = service.provenance.path.read_bytes()
+ assert service.get_model_provenance("claude", MODEL) == legacy
+ assert service.get_turn_provenance("legacy") == legacy
+ assert store.config.to_payload() == before
+ assert service.provenance.path.read_bytes() == history_bytes
+ assert adapter.synced == []
+
+
+def test_terminal_diagnostic_schema_uses_the_production_machine_code_authority():
+ schema = json.loads(
+ (Path(__file__).parents[1] / "docs/plans/model-hub-contracts/turn-provenance.schema.json").read_text()
+ )
+ enum = schema["properties"]["terminal_error"]["properties"]["upstream_error_code"]["enum"]
+ assert set(enum) - {None} == UPSTREAM_MACHINE_ERROR_CODES
+ assert "engine_down" not in enum
+
+
+ "error_type,expected_code,expected_error",
+ [
+ ("invalid_request_error", "model_not_found", "upstream_request_invalid"),
+ ("permission_error", "permission_error", "request_incompatible"),
+ ("arbitrary credential=secret", "model_not_found", "upstream_request_invalid"),
+ ],
+)
+def test_specific_model_diagnostic_does_not_rerank_classification(tmp_path, error_type, expected_code, expected_error):
+ store = BoundedProvenanceStore(tmp_path / "records.json")
+ registry = TurnCorrelationRegistry(store)
+ token = registry.credentials("claude", "fixture", "turn-error")
+ turn_id = registry.begin_gateway_request(backend="claude", token=token, requested_model_id=MODEL)
+ registry.begin_attempt(
+ turn_id, source_id="src_deleted01", resolved_model_id="unknown-model", channel="hub", via_mapping=False
+ )
+ outcome = RawCallOutcome(
+ kind=RawOutcomeKind.HTTP_ERROR,
+ http_status=404,
+ error_code="model_not_found",
+ error_type=error_type,
+ redacted_message="arbitrary credential=secret",
+ stream_started=False,
+ model_id="unknown-model",
+ source_id="src_deleted01",
+ )
+ decision = classify_outcome(outcome)
+ assert decision.error_code == expected_error
+ registry.finish_attempt(turn_id, outcome=outcome, decision=decision)
+ registry.settle("turn-error", settled_by=SETTLED_BY_TERMINAL_RESULT)
+ assert store.get("turn-error")["terminal_error"]["upstream_error_code"] == expected_code
+ assert classify_outcome(outcome) == decision
+ assert "arbitrary" not in store.path.read_text()
+
+
+ "backend,model", [("unknown", MODEL), ("claude", " unknown "), ("claude", "not-in-catalog"), ("claude", None)]
+)
+def test_model_history_validates_backend_and_canonical_catalog_id(tmp_path, backend, model):
+ service, _, _ = _service(tmp_path, _sparse_config())
+ with pytest.raises(ModelHubError):
+ service.get_model_provenance(backend, model)
+
+
[email protected]("backend", ["claude", "codex"])
+def test_latest_history_reads_exact_persisted_legacy_catalog_identity(tmp_path, backend):
+ legacy = "legacy-" + "x" * MODEL_ID_MAX_LENGTH
+ service, store, adapter = _service(tmp_path, _loaded_catalog_config(backend, legacy))
+ before = store.config.to_payload()
+ assert service.get_model_provenance(backend, legacy) is None
+ record = _record("legacy-long", backend=backend, model=legacy)
+ service.provenance.put(record)
+ assert service.get_model_provenance(backend, legacy) == record
+ with pytest.raises(ModelHubError):
+ service.get_model_provenance(backend, f" {legacy} ")
+ with pytest.raises(ModelHubError):
+ service.get_model_provenance(backend, "new-" + "x" * MODEL_ID_MAX_LENGTH)
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
+def test_model_history_client_rpc_http_share_nullable_read_only_result(monkeypatch, tmp_path):
+ service, store, adapter = _service(tmp_path, _sparse_config())
+ before = store.config.to_payload()
+
+ def rpc(operation, payload=None):
+ return asyncio.run(dispatch_model_hub_rpc(service, operation, payload or {}))
+
+ monkeypatch.setattr(model_hub_client, "_rpc_sync", rpc)
+ remote = model_hub_client.ModelHubRemoteService()
+ assert remote.get_model_provenance("claude", MODEL) is None
+ record = _record("latest")
+ service.provenance.put(record)
+ assert remote.get_model_provenance("claude", MODEL) == record
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: remote)
+ client = ui_server.app.test_client()
+ origin = "http://127.0.0.1:15131"
+ response = client.get(
+ f"/api/models/agents/claude/provenance?model={MODEL}", headers=csrf_headers(client, origin), base_url=origin
+ )
+ assert response.status_code == 200
+ assert response.get_json() == {"ok": True, "contract_version": 9, "provenance": record}
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 0b70e7d26..4893f189d 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -264,7 +264,9 @@ class FakeAdapter:
models=tuple(DiscoveredModel(id=model_id) for model_id in self.discovered),
)
- async def invoke(self, source_id, model_id, request, stream, origin):
+ async def invoke(self, source_id, model_id, request, stream, origin, *, on_admitted=None):
+ if on_admitted is not None:
+ on_admitted()
self.invocations.append((source_id, model_id))
self.invocation_requests.append(request)
outcome = self.outcomes.popleft()
@@ -301,6 +303,8 @@ def _config(sources: list[ModelHubSourceConfig], *, model: str = "claude-opus-4-
for backend in ("claude", "codex", "opencode")
}
for backend, agent in agents.items():
+ # Existing persisted routes remain explicit, including old empty seeds.
+ agent.routes = {entry.id: ModelHubRouteConfig() for entry in agent.models}
eligible = [source.id for source in sources if ModelHubConfig.source_eligible_for_backend(source, backend)]
agent.sources.order = eligible
agents["claude"].routes[model] = ModelHubRouteConfig(
@@ -1143,18 +1147,19 @@ def test_runtime_does_not_alias_unpersisted_claude_request():
assert resolution.supply_status == "interrupted"
-def test_resolution_marks_stale_exact_hop_unsupported():
+def test_resolution_preserves_unlisted_manual_target():
source = _source("src_stale001", ("other-model",))
config = _config([source], model="stale-model")
resolution = resolve_model_hub_turn(config, "claude", "stale-model")
assert resolution.matching_sources == (source,)
- assert resolution.candidates == ()
- assert resolution.unsupported_source_ids == (source.id,)
+ assert resolution.candidates == (source,)
+ assert resolution.unsupported_source_ids == ()
assert resolution.projectable_hops == resolution.inspected_hops
-def test_launch_failure_reports_unsupported_exact_hop():
- source = _source("src_launch001", ("other-model",))
+def test_launch_failure_reports_retired_exact_hop():
+ source = _source("src_launch001", ("stale-model",))
+ source.models[0].retired = True
config = _config([source], model="stale-model")
resolution = resolve_model_hub_turn(config, "claude", "stale-model")
@@ -1194,7 +1199,7 @@ def test_exact_hop_inspection_is_the_single_identity_and_supply_authority():
assert inspected.reason is None
-def test_exact_hop_inspection_rejects_wrong_identity_and_empty_route():
+def test_exact_hop_inspection_distinguishes_missing_inventory_from_empty_route():
source = _source("src_exact002", ("actual-model",), vendor="openai")
config = _config([source], model="menu-model")
@@ -1207,9 +1212,9 @@ def test_exact_hop_inspection_rejects_wrong_identity_and_empty_route():
empty = inspect_exact_hop(config, "opencode", "menu-model", None)
assert wrong.inventory_member is False
- assert wrong.supply_eligible is False
- assert wrong.runnable is False
- assert wrong.reason == "model_unsupported"
+ assert wrong.supply_eligible is True
+ assert wrong.runnable is True
+ assert wrong.reason is None
assert empty.identity == ("opencode", "menu-model", None, None)
assert empty.reason == "route_unconfigured"
@@ -1334,12 +1339,13 @@ def test_refresh_ignores_preexisting_unrelated_interruption(tmp_path):
assert result["interrupted"] == []
-def test_engine_binding_excludes_empty_inventory(tmp_path):
+def test_engine_binding_preserves_empty_inventory(tmp_path):
source = _source("src_empty01", (), vendor="openai")
config = _config([source], model="requested")
service, _store, _ = _service(tmp_path, config)
- assert service._bindings(config) == []
+ assert len(service._bindings(config)) == 1
+ assert service._bindings(config)[0].model_ids == ()
def test_agent_chain_projects_exact_hops_and_blockers(tmp_path):
@@ -1353,13 +1359,13 @@ def test_agent_chain_projects_exact_hops_and_blockers(tmp_path):
"model_id": "stale-model",
"channel": "hub",
"health": "healthy",
- "runnable": False,
- "reason": "model_unsupported",
+ "runnable": True,
+ "reason": None,
"retry_at": None,
}
]
- assert payload["current"] is None
- assert payload["supply_state"] == "interrupted"
+ assert payload["current"] == {"source_id": source.id, "model_id": "stale-model"}
+ assert payload["supply_state"] == "ok"
def test_set_agent_chain_returns_guarded_exact_route(tmp_path):
@@ -1388,7 +1394,7 @@ def test_set_agent_chain_returns_guarded_exact_route(tmp_path):
assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]
-def test_set_agent_chain_reports_complete_removed_hops_without_syncing(tmp_path):
+def test_set_agent_chain_reports_removed_hops_and_syncs_transport_targets(tmp_path):
menu_model = "claude-opus-4-6"
first = _source("src_chain006", (menu_model,))
second = _source("src_chain007", (menu_model,))
@@ -1415,7 +1421,8 @@ def test_set_agent_chain_reports_complete_removed_hops_without_syncing(tmp_path)
"position": 2,
}
]
- assert adapter.synced == []
+ assert len(adapter.synced) == 1
+ assert adapter.synced[0][1].route_model_ids == ()
def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):
@@ -1452,7 +1459,8 @@ def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):
)
assert result["interrupted"] == []
- assert adapter.synced == []
+ assert len(adapter.synced) == 1
+ assert adapter.synced[0][-1].route_model_ids == ("other",)
assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]
@@ -1590,7 +1598,6 @@ def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):
native_protocol="openai_responses",
)
]
- opencode.routes["gpt-5.6"] = ModelHubRouteConfig()
adapter = FakeAdapter(discovered=("gpt-5.6",))
service, store, _ = _service(tmp_path, config, adapter)
@@ -1762,7 +1769,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):
)
assert result["observation"] == {
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -1793,7 +1800,7 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):
assert exc.value.code == "discovery_failed"
assert exc.value.detail == "modelHub.errors.adapter_error"
assert exc.value.data["observation"] == {
- "contract_version": 8,
+ "contract_version": 9,
"outcome": "adapter_error",
"reachable": None,
"authenticated": "unknown",
@@ -2068,7 +2075,7 @@ def test_manual_model_delete_ignores_preexisting_unrelated_gap(tmp_path):
]
-def test_manual_model_delete_requires_the_exact_guard_plan(tmp_path):
+def test_manual_model_delete_preserves_explicit_route(tmp_path):
menu_model = "claude-opus-4-6"
source = _source("src_manual003")
source.models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))
@@ -2078,31 +2085,10 @@ def test_manual_model_delete_requires_the_exact_guard_plan(tmp_path):
)
service, store, _ = _service(tmp_path, config)
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(service.delete_custom_model(source.id, "manual-model"))
-
- assert exc.value.code == "source_model_in_route_chain"
- assert store.load().to_payload() == config.to_payload()
- with pytest.raises(ModelHubError) as unconfirmed:
- asyncio.run(
- service.delete_custom_model(
- source.id,
- "manual-model",
- force=True,
- )
- )
- assert unconfirmed.value.data == exc.value.data
- result = asyncio.run(
- service.delete_custom_model(
- source.id,
- "manual-model",
- force=True,
- confirmed_remove_hops=exc.value.data["would_remove_hops"],
- confirmed_interruptions=exc.value.data["would_interrupt"],
- )
- )
- assert result["removed_hops"] == exc.value.data["would_remove_hops"]
- assert store.load().agents["claude"].routes[menu_model].hops == ()
+ result = asyncio.run(service.delete_custom_model(source.id, "manual-model"))
+ assert result["removed_hops"] == []
+ assert store.load().agents["claude"].routes[menu_model].hops == config.agents["claude"].routes[menu_model].hops
+ assert service.agent_chain("claude", menu_model)["current"]["model_id"] == "manual-model"
def test_delete_unused_source_ignores_preexisting_unrelated_gap(tmp_path):
@@ -2189,20 +2175,10 @@ def test_refresh_source_uses_guarded_success_shape(tmp_path):
config = _config([source], model=menu_model)
adapter = FakeAdapter(discovered=("new-model",))
service, store, _ = _service(tmp_path, config, adapter)
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(service.refresh_source(source.id))
- assert exc.value.code == "source_model_in_route_chain"
- result = asyncio.run(
- service.refresh_source(
- source.id,
- force=True,
- confirmed_remove_hops=exc.value.data["would_remove_hops"],
- confirmed_interruptions=exc.value.data["would_interrupt"],
- )
- )
+ result = asyncio.run(service.refresh_source(source.id))
assert set(result) == {"source", "removed_hops", "interrupted"}
- assert result["removed_hops"][0]["model_id"] == menu_model
- assert store.load().agents["claude"].routes[menu_model].hops == ()
+ assert result["removed_hops"] == []
+ assert store.load().agents["claude"].routes[menu_model].hops == config.agents["claude"].routes[menu_model].hops
@pytest.mark.parametrize(
@@ -2261,37 +2237,13 @@ def test_inventory_mutations_share_the_successful_discovery_finalizer(
assert store.load().to_payload() == before
return
- if inventory_case == "empty":
- with pytest.raises(ModelHubError) as refusal:
- asyncio.run(mutation())
- confirmed = {
- "force": True,
- "would_remove_hops": refusal.value.data["would_remove_hops"],
- "would_interrupt": refusal.value.data["would_interrupt"],
- }
- if operation == "refresh":
- confirmed = {
- "force": True,
- "confirmed_remove_hops": refusal.value.data[
- "would_remove_hops"
- ],
- "confirmed_interruptions": refusal.value.data[
- "would_interrupt"
- ],
- }
- result = asyncio.run(mutation(confirmed))
- else:
- result = asyncio.run(mutation())
+ result = asyncio.run(mutation())
persisted = store.load().sources[0]
response_source = result["source"]
assert [model["retired"] for model in response_source["models"]] == [
False
] * len(discovered)
- assert response_source["adopted_by"] == (
- [{"backend": "claude", "menu_model": "claude-opus-4-6"}]
- if inventory_case == "normal"
- else []
- )
+ assert response_source["adopted_by"] == [{"backend": "claude", "menu_model": "claude-opus-4-6"}]
persisted_projection = {
key: value
for key, value in response_source.items()
@@ -2316,7 +2268,8 @@ def test_all_interruption_guards_use_the_shared_baseline_comparator():
)
direct_baseline_guards = {
"delete_source",
- "set_agent_chain",
+ "_write_agent_chain",
+ "set_agent_sources",
"delete_custom_model",
}
inventory_guards = {
@@ -2397,7 +2350,9 @@ def test_credential_target_and_refresh_capability_have_single_service_consumers(
assert "credential_supports_refresh" in calls(
methods["_classify_credential_outcome"]
)
- assert "_classify_source_outcome" in calls(methods["probe_agent"])
+ assert "_probe_agent_once" in calls(methods["probe_agent"])
+ assert "_classify_source_outcome" in calls(methods["_probe_agent_once"])
+ assert "_invoke_admitted" in calls(methods["_probe_agent_once"])
assert "_classify_source_outcome" in calls(methods["resolve"])
capability_callers = {
name
diff --git a/tests/test_model_hub_routing_modes.py b/tests/test_model_hub_routing_modes.py
new file mode 100644
index 000000000..02e4dbe79
--- /dev/null
+++ b/tests/test_model_hub_routing_modes.py
@@ -0,0 +1,604 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import asdict, replace
+from pathlib import Path
+
+import pytest
+
+from config.v2_config import (
+ ModelHubBackendModelConfig,
+ ModelHubConfig,
+ ModelHubModelConfig,
+ ModelHubRouteConfig,
+ ModelHubRouteHopConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind, SourceBinding
+from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH
+from core.handlers.model_hub.resolver import effective_model_route, resolve_model_hub_turn
+from core.handlers.model_hub.service import ModelHubError
+from scripts.check_model_hub_authorities import AuthorityInput, _typescript_string_union
+from tests.test_model_hub_resolution import _service, _source
+from vibe.model_hub_runtime.config import _append_source
+from vibe.model_hub_runtime.state import EngineStateStore, SourceRecord
+
+
+MODEL = "claude-opus-4-6"
+
+
+def _sparse_config(*sources):
+ config = ModelHubConfig(sources=list(sources))
+ agent = config.agents["claude"]
+ agent.mode = "hub"
+ agent.models = [ModelHubBackendModelConfig(id=MODEL)]
+ agent.sources.order = [source.id for source in sources]
+ return config
+
+
+def _pairs(plan):
+ return [(hop.source_id, hop.model_id) for hop in plan.hops]
+
+
+def test_sparse_matching_tier_excludes_speculation_and_survives_health_changes():
+ absent = _source("src_absent001", ())
+ known = _source("src_known001")
+ config = _sparse_config(absent, known)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.manual_override is None
+ assert plan.route_origin == "automatic"
+ assert _pairs(plan) == [(known.id, MODEL)]
+
+ known.state = ModelHubSourceStateConfig(
+ status="needs_action", detail_key="models.source.needs_action.oauth_expired"
+ )
+ blocked = resolve_model_hub_turn(config, "claude", MODEL)
+ assert blocked.route_origin == "automatic"
+ assert blocked.candidates == ()
+ assert [hop.source_id for hop in blocked.inspected_hops] == [known.id]
+ assert effective_model_route(config, "claude", MODEL) == plan
+ assert config.agents["claude"].routes == {}
+
+
+def test_no_matching_inventory_forwards_exact_id_to_all_defaults():
+ first = _source("src_first001", ())
+ second = _source("src_second001", ("other-model",))
+ config = _sparse_config(first, second)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.route_origin == "passthrough"
+ assert _pairs(plan) == [(first.id, MODEL), (second.id, MODEL)]
+ resolution = resolve_model_hub_turn(config, "claude", MODEL)
+ assert resolution.source is first
+ assert resolution.target_model == MODEL
+ assert all(not hop.inventory_member and hop.runnable for hop in resolution.inspected_hops)
+
+
+def test_manual_inventory_is_matching_evidence_and_retirement_is_not():
+ first = _source("src_first001", ())
+ second = _source("src_second001", ())
+ second.models = [ModelHubModelConfig(id=MODEL, provenance="manual")]
+ config = _sparse_config(first, second)
+ assert _pairs(effective_model_route(config, "claude", MODEL)) == [(second.id, MODEL)]
+ second.models = [ModelHubModelConfig(id=MODEL, provenance="discovered", retired=True)]
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.route_origin == "passthrough"
+ assert _pairs(plan) == [(first.id, MODEL)]
+ config.agents["claude"].routes[MODEL] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(second.id, MODEL),))
+ blocked = resolve_model_hub_turn(config, "claude", MODEL)
+ assert blocked.route_origin == "manual"
+ assert not blocked.candidates
+ assert blocked.inspected_hops[0].reason == "model_unsupported"
+
+
+def test_native_alias_tier_is_chosen_before_hub_transport_filter():
+ native = _source("src_native001", (), kind="subscription", channel="native_cli", credential_ref=None)
+ native.models = [ModelHubModelConfig(id="claude-opus-4-6-20260115", provenance="manual")]
+ api = _source("src_api00001", ())
+ config = _sparse_config(api, native)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.route_origin == "automatic"
+ assert _pairs(plan) == [(native.id, "claude-opus-4-6-20260115")]
+ resolution = resolve_model_hub_turn(config, "claude", MODEL, supply_channel="hub")
+ assert resolution.route_origin == "automatic"
+ assert not resolution.candidates
+ assert [hop.source_id for hop in resolution.inspected_hops] == [native.id]
+
+
+def test_absence_does_not_broaden_backend_model_admission():
+ config = _sparse_config(_source("src_first001", ()))
+ assert effective_model_route(config, "claude", "not-in-catalog").hops == ()
+ assert resolve_model_hub_turn(config, "claude", "not-in-catalog").source is None
+
+
[email protected]("channel", ["hub", "native_cli"])
+def test_subscriptions_do_not_gain_unknown_fallback_or_manual_admission(tmp_path, channel):
+ source = _source(
+ "src_subscription01",
+ (),
+ kind="subscription",
+ channel=channel,
+ credential_ref=None if channel == "native_cli" else "cred_source",
+ )
+ config = _sparse_config(source)
+ service, store, _ = _service(tmp_path, config)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.hops == ()
+ assert plan.route_origin is None
+ payload = {"hops": [{"source_id": source.id, "model_id": "unknown-target"}]}
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_chain("claude", MODEL, payload))
+ with pytest.raises(ModelHubError):
+ service.preview_agent_chain("claude", MODEL, {"manual_override": payload})
+ assert service._bindings(config) == []
+
+ # Historical stale intent remains editable, but never becomes runnable.
+ config.agents["claude"].routes[MODEL] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "unknown-target"),)
+ )
+ saved = asyncio.run(service.set_agent_chain("claude", MODEL, payload))
+ assert saved["chain"]["manual_override"] == payload
+ assert saved["chain"]["route_origin"] == "manual"
+ assert saved["chain"]["current"] is None
+ assert saved["chain"]["chain"][0]["reason"] == "model_unsupported"
+ assert store.config.agents["claude"].routes[MODEL].to_payload() == payload
+
+
+def test_subscription_match_suppresses_unknown_api_speculation(tmp_path):
+ api = _source("src_api00001", ())
+ subscription = _source("src_subscription01", kind="subscription")
+ config = _sparse_config(api, subscription)
+ service, _, _ = _service(tmp_path, config)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.route_origin == "automatic"
+ assert _pairs(plan) == [(subscription.id, MODEL)]
+ bindings = service._bindings(config)
+ assert all(binding.route_model_ids == () for binding in bindings)
+
+
+def test_mixed_unmatched_defaults_only_use_api_key_passthrough():
+ subscription = _source("src_subscription01", (), kind="subscription")
+ api = _source("src_api00001", ())
+ config = _sparse_config(subscription, api)
+ plan = effective_model_route(config, "claude", MODEL)
+ assert plan.route_origin == "passthrough"
+ assert _pairs(plan) == [(api.id, MODEL)]
+
+
+def test_equal_save_has_manual_provenance_and_empty_override_survives_changes(tmp_path):
+ source = _source("src_first001")
+ config = _sparse_config(source)
+ service, store, adapter = _service(tmp_path, config)
+ hops = [{"source_id": source.id, "model_id": MODEL}]
+ saved = asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": hops}))
+ assert saved["chain"]["route_origin"] == "manual"
+ assert saved["chain"]["manual_override"] == {"hops": hops}
+ with pytest.raises(ModelHubError) as guard:
+ asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": []}))
+ empty = asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": [], "force": True, **guard.value.data}))
+ assert empty["chain"]["manual_override"] == {"hops": []}
+ assert empty["chain"]["route_origin"] is None
+ asyncio.run(service.set_agent_sources("claude", {"order": []}))
+ store.config.sources[0].models.clear()
+ reloaded = ModelHubConfig.from_payload(store.config.to_payload())
+ assert reloaded.agents["claude"].routes[MODEL].hops == ()
+ assert effective_model_route(reloaded, "claude", MODEL).hops == ()
+ assert adapter.synced
+
+
+def test_preview_and_restore_use_same_plan_without_preview_side_effects(tmp_path):
+ source = _source("src_first001", ())
+ config = _sparse_config(source)
+ config.agents["claude"].routes[MODEL] = ModelHubRouteConfig()
+ service, store, adapter = _service(tmp_path, config)
+ before = store.config.to_payload()
+ writes = []
+ original_save = store.save
+ store.save = lambda updated: (writes.append(updated), original_save(updated))[-1]
+ draft = service.preview_agent_chain("claude", MODEL, {"manual_override": None})
+ assert draft["manual_override"] is None
+ assert draft["route_origin"] == "passthrough"
+ assert draft["current"] == {"source_id": source.id, "model_id": MODEL}
+ assert store.config.to_payload() == before
+ assert writes == adapter.synced == []
+ assert not (tmp_path / "events.json").exists()
+ restored = asyncio.run(service.delete_agent_chain("claude", MODEL))
+ assert restored["chain"] == draft
+ assert MODEL not in store.config.agents["claude"].routes
+ repeated = asyncio.run(service.delete_agent_chain("claude", MODEL))
+ assert repeated == restored
+ assert len(adapter.synced) == 1
+
+
+def test_restore_guards_effective_removal_and_accepts_only_exact_echo(tmp_path):
+ default = _source("src_default01")
+ manual = _source("src_manual001", ())
+ config = _sparse_config(default)
+ config.sources.append(manual)
+ config.agents["claude"].routes[MODEL] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(manual.id, "exact-unlisted"),)
+ )
+ service, store, _ = _service(tmp_path, config)
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.delete_agent_chain("claude", MODEL))
+ assert refusal.value.code == "source_in_route_chain"
+ assert refusal.value.data["would_interrupt"] == []
+ assert refusal.value.data["would_remove_hops"][0]["model_id"] == "exact-unlisted"
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.delete_agent_chain("claude", MODEL, {"force": True}))
+ result = asyncio.run(service.delete_agent_chain("claude", MODEL, {"force": True, **refusal.value.data}))
+ assert result["chain"]["route_origin"] == "automatic"
+ assert result["chain"]["current"] == {"source_id": default.id, "model_id": MODEL}
+ assert MODEL not in store.config.agents["claude"].routes
+
+
+def test_default_membership_guards_generated_removal_without_rewriting_manual(tmp_path):
+ first = _source("src_first001")
+ second = _source("src_second001")
+ config = _sparse_config(first, second)
+ service, store, adapter = _service(tmp_path, config)
+ asyncio.run(service.set_agent_sources("claude", {"order": [second.id, first.id]}))
+ assert adapter.synced == []
+ assert service.agent_chain("claude", MODEL)["chain"][0]["source_id"] == second.id
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.set_agent_sources("claude", {"order": [first.id]}))
+ assert refusal.value.data["would_remove_hops"][0]["source_id"] == second.id
+ assert refusal.value.data["would_interrupt"] == []
+ asyncio.run(service.set_agent_sources("claude", {"order": [first.id], "force": True, **refusal.value.data}))
+ asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": [{"source_id": second.id, "model_id": "exact"}]}))
+ original = store.config.agents["claude"].routes[MODEL].to_payload()
+ asyncio.run(service.set_agent_sources("claude", {"order": []}))
+ assert store.config.agents["claude"].routes[MODEL].to_payload() == original
+ assert service.agent_chain("claude", MODEL)["current"] == {"source_id": second.id, "model_id": "exact"}
+
+
+def test_engine_route_targets_are_deterministic_truthful_and_health_mode_independent(tmp_path):
+ source = _source("src_first001", ("inventory-only",))
+ config = _sparse_config(source)
+ agent = config.agents["claude"]
+ agent.models.append(ModelHubBackendModelConfig(id="claude-extra"))
+ agent.routes["claude-extra"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "unlisted"),))
+ service, _, _ = _service(tmp_path, config)
+ binding = service._bindings(config)[0]
+ assert binding.model_ids == ("inventory-only",)
+ assert binding.route_model_ids == (MODEL, "unlisted")
+ agent.mode = "direct"
+ source.state = ModelHubSourceStateConfig(
+ status="needs_action", detail_key="models.source.needs_action.oauth_expired"
+ )
+ assert service._bindings(config) == [binding]
+ source.models.clear()
+ empty_inventory = service._bindings(config)[0]
+ assert empty_inventory.model_ids == ()
+ assert empty_inventory.route_model_ids == binding.route_model_ids
+ assert source.models == []
+
+
+ "protocol,section",
+ [("anthropic", "claude-api-key"), ("openai_responses", "codex-api-key"), ("openai_chat", "openai-compatibility")],
+)
+def test_engine_compiler_registers_inventory_union_without_invented_reasoning(tmp_path, protocol, section):
+ store = EngineStateStore(tmp_path / "engine")
+ ref = store.store_api_key("fixture-key", vendor="custom", protocol=protocol, base_url="https://api.example/v1")
+ binding = SourceBinding(
+ source_id="src_first001",
+ vendor="custom",
+ protocol=protocol,
+ base_url="https://api.example/v1",
+ credential_ref=ref,
+ allowed_origins=(),
+ model_ids=("listed",),
+ model_reasoning_efforts=(("listed", ("low", "high")),),
+ route_model_ids=("listed", "unlisted"),
+ )
+ store.sync_sources([binding])
+ record = store.list_sources()[0]
+ assert record.model_ids == ("listed",)
+ assert record.route_model_ids == ("listed", "unlisted")
+ payload = {}
+ _append_source(payload, record, store)
+ assert payload[section][0]["models"] == [
+ {"name": "listed", "alias": "listed", "thinking": {"levels": ["high", "low"]}},
+ {"name": "unlisted", "alias": "unlisted"},
+ ]
+ store.sync_sources([replace(binding, model_ids=(), model_reasoning_efforts=())])
+ assert store.list_sources()[0].model_ids == ()
+
+
+def test_internal_engine_record_loads_old_shape_without_route_targets():
+ record = SourceRecord(
+ source_id="src_first001",
+ vendor="custom",
+ protocol="openai_chat",
+ base_url="https://api.example/v1",
+ credential_ref="cred_fixture",
+ allowed_origins=(),
+ model_ids=(),
+ prefix="avibe-fixture",
+ )
+ payload = asdict(record)
+ payload["model_ids"] = []
+ payload["model_reasoning_efforts"] = []
+ payload.pop("route_model_ids")
+ assert SourceRecord.from_payload(payload).route_model_ids == ()
+
+
+ "declaration",
+ [
+ 'export type RouteOrigin = "automatic" | "manual" | "passthrough" | null;',
+ "export type RouteOrigin =\n | 'automatic'\n | 'manual'\n | 'passthrough'\n | null;",
+ ],
+)
+def test_authority_extractor_reads_exported_nullable_string_union(monkeypatch, declaration):
+ source = AuthorityInput(Path.cwd())
+ monkeypatch.setattr(source, "text", lambda _: declaration)
+ assert _typescript_string_union(source, {"file": "fixture.ts", "name": "RouteOrigin"}) == {
+ "automatic",
+ "manual",
+ "passthrough",
+ }
+
+
+ "declaration",
+ [
+ 'type RouteOrigin = "manual";',
+ 'export type RouteOrigin = "manual" | string;',
+ 'export type RouteOrigin = "manual" |;',
+ "export type RouteOrigin = null;",
+ ],
+)
+def test_authority_extractor_rejects_missing_or_nonliteral_union(monkeypatch, declaration):
+ source = AuthorityInput(Path.cwd())
+ monkeypatch.setattr(source, "text", lambda _: declaration)
+ with pytest.raises(ValueError):
+ _typescript_string_union(source, {"file": "fixture.ts", "name": "RouteOrigin"})
+
+
+def _loaded_catalog_config(backend, requested, *sources):
+ config = ModelHubConfig(sources=list(sources))
+ agent = config.agents[backend]
+ agent.mode = "hub"
+ agent.models = [
+ ModelHubBackendModelConfig(
+ id=requested,
+ origin="manual",
+ native_protocol="openai_responses" if backend == "opencode" else None,
+ )
+ ]
+ agent.sources.order = [source.id for source in sources]
+ return ModelHubConfig.from_payload(config.to_payload())
+
+
[email protected]("backend", ["claude", "codex"])
[email protected]("state", ["automatic", "manual", "empty"])
[email protected]("operation", ["put", "preview", "restore_preview", "restore_save"])
+def test_persisted_legacy_catalog_identity_survives_route_consumers(tmp_path, backend, state, operation):
+ requested = "legacy-" + "x" * MODEL_ID_MAX_LENGTH
+ source = _source("src_legacy001", (requested,))
+ config = _loaded_catalog_config(backend, requested, source)
+ route = {"hops": [] if state == "empty" else [{"source_id": source.id, "model_id": "mapped-target"}]}
+ if state != "automatic":
+ config.agents[backend].routes[requested] = ModelHubRouteConfig.from_payload(route)
+ config = ModelHubConfig.from_payload(config.to_payload())
+ service, store, adapter = _service(tmp_path, config)
+ before = config.to_payload()
+ if operation == "put":
+ result = asyncio.run(service.set_agent_chain(backend, requested, route))["chain"]
+ assert result["manual_override"] == route
+ elif operation == "preview":
+ result = service.preview_agent_chain(backend, requested, {"manual_override": route})
+ assert result["manual_override"] == route
+ elif operation == "restore_preview":
+ result = service.preview_agent_chain(backend, requested, {"manual_override": None})
+ assert result["route_origin"] == "automatic"
+ assert result["current"] == {"source_id": source.id, "model_id": requested}
+ else:
+ if state == "manual":
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.delete_agent_chain(backend, requested))
+ assert refusal.value.code == "source_in_route_chain"
+ assert refusal.value.data["would_remove_hops"] == [
+ {
+ "backend": backend,
+ "menu_model": requested,
+ "source_id": source.id,
+ "model_id": "mapped-target",
+ "position": 1,
+ }
+ ]
+ assert store.config.to_payload() == before
+ result = asyncio.run(
+ service.delete_agent_chain(
+ backend,
+ requested,
+ {"force": True, **refusal.value.data},
+ )
+ )["chain"]
+ else:
+ result = asyncio.run(service.delete_agent_chain(backend, requested))["chain"]
+ assert result["manual_override"] is None
+ assert result["route_origin"] == "automatic"
+ assert requested not in store.config.agents[backend].routes
+ assert result["model_id"] == requested
+ assert [model.id for model in store.config.agents[backend].models] == [requested]
+ assert ModelHubConfig.from_payload(store.config.to_payload()).to_payload() == store.config.to_payload()
+ if "preview" in operation:
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
+def test_opencode_existing_loader_still_rejects_overlength_catalog_identity():
+ with pytest.raises(ValueError, match="models.id"):
+ _loaded_catalog_config("opencode", "x" * (MODEL_ID_MAX_LENGTH + 1))
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("kind", ["api_key", "subscription"])
[email protected]("evidence", ["override", "inventory"])
+def test_existing_long_target_identity_can_be_saved_and_reordered(tmp_path, backend, kind, evidence):
+ target = "legacy-target-" + "x" * MODEL_ID_MAX_LENGTH
+ source = _source("src_legacy001", (target,) if evidence == "inventory" else (), kind=kind)
+ other = _source("src_legacy002", ("other",), kind=kind)
+ config = _loaded_catalog_config(backend, MODEL, source, other)
+ hops = [{"source_id": source.id, "model_id": target}, {"source_id": other.id, "model_id": "other"}]
+ if evidence == "override":
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig.from_payload({"hops": hops})
+ config = ModelHubConfig.from_payload(config.to_payload())
+ service, store, _adapter = _service(tmp_path, config)
+ original_inventory = [source.to_payload()["models"] for source in config.sources]
+ for desired in (hops, list(reversed(hops))):
+ preview = service.preview_agent_chain(backend, MODEL, {"manual_override": {"hops": desired}})
+ assert preview["manual_override"] == {"hops": desired}
+ saved = asyncio.run(service.set_agent_chain(backend, MODEL, {"hops": desired}))["chain"]
+ assert saved["manual_override"] == {"hops": desired}
+ loaded = ModelHubConfig.from_payload(store.config.to_payload())
+ assert loaded.agents[backend].routes[MODEL].to_payload() == {"hops": desired}
+ assert [source.to_payload()["models"] for source in loaded.sources] == original_inventory
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("target_kind", ["new_long", "padded_known", "padded_long", "other_source_long"])
+def test_new_target_admission_cannot_reuse_legacy_identity_exceptions(tmp_path, backend, target_kind):
+ legacy = "legacy-" + "x" * MODEL_ID_MAX_LENGTH
+ source = _source("src_legacy001", ("known", legacy))
+ other = _source("src_legacy002", ())
+ config = _loaded_catalog_config(backend, MODEL, source, other)
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig.from_payload(
+ {
+ "hops": [{"source_id": source.id, "model_id": legacy}],
+ }
+ )
+ service, store, adapter = _service(tmp_path, ModelHubConfig.from_payload(config.to_payload()))
+ target = {
+ "new_long": "new-" + "x" * MODEL_ID_MAX_LENGTH,
+ "padded_known": " known ",
+ "padded_long": f" {legacy} ",
+ "other_source_long": legacy,
+ }[target_kind]
+ route = {"hops": [{"source_id": other.id if target_kind == "other_source_long" else source.id, "model_id": target}]}
+ before = store.config.to_payload()
+ with pytest.raises(ModelHubError):
+ service.preview_agent_chain(backend, MODEL, {"manual_override": route})
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_chain(backend, MODEL, route))
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+ "kind,existing,allowed",
+ [
+ ("api_key", False, False),
+ ("api_key", True, False),
+ ("subscription", False, False),
+ ("subscription", True, True),
+ ],
+)
+def test_legacy_target_retirement_keeps_existing_source_policy(tmp_path, backend, kind, existing, allowed):
+ target = "retired-" + "x" * MODEL_ID_MAX_LENGTH
+ source = _source("src_legacy001", (target,), kind=kind)
+ source.models[0].retired = True
+ config = _loaded_catalog_config(backend, MODEL, source)
+ route = {"hops": [{"source_id": source.id, "model_id": target}]}
+ if existing:
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig.from_payload(route)
+ service, store, adapter = _service(tmp_path, ModelHubConfig.from_payload(config.to_payload()))
+ before = store.config.to_payload()
+ if allowed:
+ preview = service.preview_agent_chain(backend, MODEL, {"manual_override": route})
+ assert preview["chain"][0]["runnable"] is False
+ assert asyncio.run(service.set_agent_chain(backend, MODEL, route))["chain"] == preview
+ else:
+ with pytest.raises(ModelHubError):
+ service.preview_agent_chain(backend, MODEL, {"manual_override": route})
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_chain(backend, MODEL, route))
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
+ "state", ["unknown", "known", "retired", "empty", "subscription_known", "subscription_unknown"]
+)
+def test_retained_opencode_route_registration_matches_resolver_without_inventing_catalog(tmp_path, state):
+ target, dormant, catalog = "dormant-target", "dormant-model", "catalog-model"
+ inventory = (catalog, target) if state in {"known", "retired", "subscription_known"} else (catalog,)
+ engine_store = EngineStateStore(tmp_path / "engine")
+ credential = engine_store.store_api_key(
+ "fixture-key", vendor="custom", protocol="openai_responses", base_url="https://api.example/v1"
+ )
+ source = _source("src_dormant01", inventory, vendor="custom", credential_ref=credential)
+ source.base_url = "https://api.example/v1"
+ if state.startswith("subscription"):
+ source.kind, source.billing = "subscription", "monthly"
+ source.vendor, source.base_url = "openai", None
+ if state == "retired":
+ source.models[-1].retired = True
+ config = _loaded_catalog_config("opencode", catalog, source)
+ config.agents["opencode"].routes[dormant] = ModelHubRouteConfig.from_payload(
+ {
+ "hops": [] if state == "empty" else [{"source_id": source.id, "model_id": target}],
+ }
+ )
+ path = tmp_path / "persisted-model-hub.json"
+ path.write_text(json.dumps(config.to_payload()))
+ config = ModelHubConfig.from_payload(json.loads(path.read_text()))
+ service, store, adapter = _service(tmp_path, config)
+ before = config.to_payload()
+ agent_before = before["agents"]["opencode"]
+ plan = effective_model_route(config, "opencode", dormant)
+ assert plan.route_origin == (None if state == "empty" else "manual")
+ expected_targets = (
+ ()
+ if state.startswith("subscription")
+ else tuple(sorted((catalog,) if state in {"retired", "empty"} else (catalog, target)))
+ )
+ binding = service._bindings(config)[0]
+ assert binding.route_model_ids == expected_targets
+ assert binding.model_ids == tuple(model.id for model in config.sources[0].models if not model.retired)
+ assert {item["model_id"] for item in service.agent_chains("opencode")} == {catalog, dormant}
+ if state != "empty":
+ assert {"backend": "opencode", "menu_model": dormant} in service._adopted_by(source.id)
+ assert any(item["menu_model"] == dormant for item in service._added_to(source.id))
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.delete_source(source.id))
+ assert any(item["menu_model"] == dormant for item in refusal.value.data["would_remove_hops"])
+ assert store.config.to_payload() == before
+ if not state.startswith("subscription"):
+ engine_store.sync_sources([binding])
+ compiled = {}
+ _append_source(compiled, engine_store.get_source(source.id), engine_store)
+ compiled_models = compiled["codex-api-key"][0]["models"]
+ assert {item["name"] for item in compiled_models} == set(binding.model_ids) | set(expected_targets)
+ assert all(set(item) == {"name", "alias"} for item in compiled_models)
+ if state == "unknown":
+ adapter.outcomes.append(
+ RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS,
+ http_status=200,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ source_id=source.id,
+ model_id=target,
+ )
+ )
+ probe = asyncio.run(service.probe_agent("opencode", dormant))
+ assert probe["reachable"] is True
+ assert adapter.invocations == [(source.id, target)]
+ assert adapter.synced[-1][0].route_model_ids == expected_targets
+ for mode in ("direct", "hub"):
+ for health in ("standby", "error"):
+ changed = ModelHubConfig.from_payload(before)
+ changed.agents["opencode"].mode = mode
+ changed.sources[0].state = ModelHubSourceStateConfig(status=health)
+ assert service._bindings(changed)[0].route_model_ids == expected_targets
+ loaded = ModelHubConfig.from_payload(store.config.to_payload())
+ assert loaded.agents["opencode"].to_payload() == agent_before
+ assert loaded.sources[0].to_payload()["models"] == before["sources"][0]["models"]
+ assert dormant not in {model.id for model in loaded.agents["opencode"].models}
+ assert loaded.agents["opencode"].menu.checked == [catalog]
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 6042cf3d8..6a81fb7b0 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -1293,7 +1293,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(
installer=manager,
state_store=EngineStateStore(tmp_path / "state"),
)
- projected = {"contract_version": 8, **supervisor.status()}
+ projected = {"contract_version": 9, **supervisor.status()}
schema = json.loads(
Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(
encoding="utf-8"
@@ -1731,8 +1731,8 @@ def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> Non
]
)
- with pytest.raises(EngineStateError, match="at least one model"):
- store.sync_sources([_binding(credential_ref, model_ids=())])
+ empty_inventory = store.sync_sources([_binding(credential_ref, model_ids=())])
+ assert empty_inventory[0].model_ids == ()
official_anthropic_ref = store.store_api_key(
"secret",
@@ -3126,9 +3126,11 @@ def test_adapter_uses_origin_protocol_for_engine_translation(
stream,
request_protocol=None,
request_headers=None,
+ on_transport_done=None,
):
self.request_protocol = request_protocol
self.request_headers = request_headers
+ on_transport_done()
return object()
class Supervisor:
@@ -3236,8 +3238,10 @@ def test_adapter_serializes_source_sync_with_new_invocations(tmp_path: Path) ->
stream,
request_protocol=None,
request_headers=None,
+ on_transport_done=None,
):
invoked_refs.append(source.credential_ref)
+ on_transport_done()
return object()
class Supervisor:
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 9aa7aedf6..46d38b7c5 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -457,7 +457,7 @@ def test_g3_settlement_returns_are_consumed() -> None:
def test_settlement_generations_are_reserved_only_at_attempt_start() -> None:
allowed_owners = {
- SERVICE: {"probe_agent", "resolve"},
+ SERVICE: {"admitted"},
ROUTER: {"resolve"},
}
for path, expected in allowed_owners.items():
@@ -474,6 +474,17 @@ def test_settlement_generations_are_reserved_only_at_attempt_start() -> None:
and _call_name(node) == "_reserve_settlement_generation"
}
assert owners == expected
+ if path == SERVICE:
+ admission_owners = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or _call_name(node) != "_reserve_settlement_generation":
+ continue
+ parent = parents[node]
+ while not isinstance(parent, ast.FunctionDef):
+ parent = parents[parent]
+ assert parent.name == "admitted"
+ admission_owners.add(_owner_name(parent, parents))
+ assert admission_owners == {"_probe_agent_once", "resolve"}
settlement_owner = _functions(_tree(SERVICE))["_settle_fallback_source"]
assert not any(
diff --git a/tests/test_model_hub_transport_leases.py b/tests/test_model_hub_transport_leases.py
new file mode 100644
index 000000000..60a49880f
--- /dev/null
+++ b/tests/test_model_hub_transport_leases.py
@@ -0,0 +1,306 @@
+from __future__ import annotations
+
+import asyncio
+import threading
+from contextlib import asynccontextmanager
+from dataclasses import replace
+
+import pytest
+from aiohttp import web
+
+from core.handlers.model_hub.adapter import RawOutcomeKind, SourceBinding
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.client import EngineClient, EngineConnection
+from vibe.model_hub_runtime.supervisor import EngineUnavailableError
+from vibe.model_hub_runtime.state import EngineStateStore
+
+
+FIRST = b'data: {"choices":[{"delta":{"content":"first"}}]}\n\n'
+LAST = b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n'
+
+
+class LeaseSupervisor:
+ def __init__(self, origin):
+ self.connection = EngineConnection(origin, "fixture-management", "fixture-token")
+ self.restart_started = threading.Event()
+ self.allow_restart = threading.Event()
+ self.allow_restart.set()
+ self.restart_count = 0
+ self.restore_count = 0
+ self.fail_restart = False
+
+ def client(self):
+ return EngineClient(self.connection)
+
+ def client_if_running(self):
+ return self.client()
+
+ def restart_if_running(self):
+ self.restart_count += 1
+ self.restart_started.set()
+ assert self.allow_restart.wait(3)
+ if self.fail_restart:
+ raise EngineUnavailableError("models.engine.health_failed")
+
+ def ensure_running(self):
+ self.restore_count += 1
+ return self.connection
+
+
+@asynccontextmanager
+async def _transport(tmp_path):
+ received = asyncio.Event()
+ finish = asyncio.Event()
+ requests = []
+
+ async def handler(request):
+ body = await request.json()
+ requests.append(body)
+ received.set()
+ if not body["stream"]:
+ await finish.wait()
+ return web.json_response({"choices": [{"message": {"content": "done"}, "finish_reason": "stop"}]})
+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
+ await response.prepare(request)
+ await response.write(FIRST)
+ await finish.wait()
+ try:
+ await response.write(LAST)
+ await response.write_eof()
+ except (ConnectionResetError, RuntimeError):
+ pass
+ return response
+
+ app = web.Application()
+ app.router.add_post("/v1/chat/completions", handler)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ site = web.TCPSite(runner, "127.0.0.1", 0)
+ await site.start()
+ origin = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}"
+ store = EngineStateStore(tmp_path / "engine")
+ ref = store.store_api_key("fixture-key", base_url="https://api.example/v1")
+ binding = SourceBinding(
+ source_id="src_lease0001",
+ vendor="custom",
+ protocol="openai_chat",
+ base_url="https://api.example/v1",
+ credential_ref=ref,
+ allowed_origins=(),
+ model_ids=("listed",),
+ route_model_ids=("unknown",),
+ )
+ store.sync_sources([binding])
+ supervisor = LeaseSupervisor(origin)
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)
+ try:
+ yield adapter, supervisor, binding, received, finish, requests
+ finally:
+ finish.set()
+ supervisor.allow_restart.set()
+ await runner.cleanup()
+
+
+async def _barrier_waiting(adapter, sync):
+ async with asyncio.timeout(2):
+ while not adapter._routing_lock.locked():
+ assert not sync.done()
+ await asyncio.sleep(0)
+ assert not sync.done()
+
+
[email protected]("stream", [False, True])
+def test_sync_waits_for_buffered_and_streaming_transport_not_service_settlement(tmp_path, stream):
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, received, finish, requests):
+ invoke = asyncio.create_task(adapter.invoke(binding.source_id, "unknown", {}, stream, "opencode"))
+ await asyncio.wait_for(received.wait(), 2)
+ handle = await invoke if stream else None
+ if handle is not None:
+ assert await anext(handle.stream) == FIRST
+ changed = replace(binding, route_model_ids=("unknown", "new"))
+ sync = asyncio.create_task(adapter.sync_sources([changed]))
+ await _barrier_waiting(adapter, sync)
+ later = asyncio.create_task(adapter.invoke(binding.source_id, "new", {}, False, "opencode"))
+ await asyncio.sleep(0)
+ assert not later.done()
+ assert supervisor.restart_count == 0
+ assert len(requests) == 1
+ # A service mutation lock can remain held during this drain. No
+ # outcome()/settlement call is needed to release the transport.
+ finish.set()
+ if handle is not None:
+ assert b"".join([part async for part in handle.stream]) == LAST
+ else:
+ handle = await asyncio.wait_for(invoke, 2)
+ await asyncio.wait_for(sync, 2)
+ assert supervisor.restart_count == 1
+ assert (await handle.outcome()).kind is RawOutcomeKind.SUCCESS
+ later_handle = await asyncio.wait_for(later, 2)
+ await handle.close_stream()
+ await later_handle.close_stream()
+ assert adapter._active_transports == 0
+ assert requests[1]["model"].endswith("/new")
+
+ asyncio.run(run())
+
+
[email protected]("finish_kind", ["unstarted_close", "started_close", "stream_cancel", "invoke_cancel"])
+def test_close_and_cancellation_release_transport_without_waiting_for_outcome(tmp_path, finish_kind):
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, received, _finish, _requests):
+ streaming = finish_kind != "invoke_cancel"
+ invoke = asyncio.create_task(adapter.invoke(binding.source_id, "unknown", {}, streaming, "opencode"))
+ await asyncio.wait_for(received.wait(), 2)
+ handle = await invoke if streaming else None
+ pending_read = None
+ if finish_kind in {"started_close", "stream_cancel"}:
+ assert await anext(handle.stream) == FIRST
+ if finish_kind == "stream_cancel":
+ pending_read = asyncio.create_task(anext(handle.stream))
+ await asyncio.sleep(0)
+ sync = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("new",))]))
+ await _barrier_waiting(adapter, sync)
+ assert supervisor.restart_count == 0
+ if handle is None:
+ invoke.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await invoke
+ elif pending_read is not None:
+ pending_read.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending_read
+ await handle.close_stream()
+ else:
+ await handle.close_stream()
+ await handle.close_stream()
+ await asyncio.wait_for(sync, 2)
+ assert supervisor.restart_count == 1
+ assert adapter._active_transports == 0
+ assert adapter._transports_idle.is_set()
+
+ asyncio.run(run())
+
+
+def test_cancelled_drain_does_not_cancel_active_request_or_leak_barrier(tmp_path):
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, _received, finish, _requests):
+ handle = await adapter.invoke(binding.source_id, "unknown", {}, True, "opencode")
+ assert await anext(handle.stream) == FIRST
+ before = adapter.state_store.list_sources()
+ sync = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("new",))]))
+ await _barrier_waiting(adapter, sync)
+ sync.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await sync
+ assert not adapter._routing_lock.locked()
+ assert adapter.state_store.list_sources() == before
+ assert adapter._active_transports == 1
+ assert supervisor.restart_count == 0
+ finish.set()
+ assert b"".join([part async for part in handle.stream]) == LAST
+ assert (await handle.outcome()).kind is RawOutcomeKind.SUCCESS
+ await adapter.sync_sources([binding])
+ assert adapter._active_transports == 0
+
+ asyncio.run(run())
+
+
[email protected]("fail_restart", [False, True])
+def test_cancelled_restart_retains_barrier_until_commit_or_rollback(tmp_path, fail_restart):
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, _received, finish, requests):
+ original = adapter.state_store.list_sources()
+ supervisor.allow_restart.clear()
+ supervisor.fail_restart = fail_restart
+ sync = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("changed",))]))
+ assert await asyncio.to_thread(supervisor.restart_started.wait, 2)
+ sync.cancel()
+ await asyncio.sleep(0)
+ assert not sync.done()
+ assert adapter._routing_lock.locked()
+ later = asyncio.create_task(adapter.invoke(binding.source_id, "listed", {}, False, "opencode"))
+ await asyncio.sleep(0)
+ assert requests == []
+ supervisor.allow_restart.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(sync, 2)
+ finish.set()
+ handle = await asyncio.wait_for(later, 2)
+ assert (await handle.outcome()).kind is RawOutcomeKind.SUCCESS
+ await handle.close_stream()
+ if fail_restart:
+ assert adapter.state_store.list_sources() == original
+ assert supervisor.restore_count == 1
+ else:
+ assert adapter.state_store.list_sources()[0].route_model_ids == ("changed",)
+ assert adapter._active_transports == 0
+ assert not adapter._routing_lock.locked()
+
+ asyncio.run(run())
+
+
+def test_two_concurrent_saves_are_serial_and_restart_failure_restores_projection(tmp_path):
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, _received, _finish, _requests):
+ original = adapter.state_store.list_sources()
+ supervisor.fail_restart = True
+ with pytest.raises(EngineUnavailableError):
+ await adapter.sync_sources([replace(binding, route_model_ids=("bad",))])
+ assert adapter.state_store.list_sources() == original
+ assert supervisor.restore_count == 1
+ supervisor.fail_restart = False
+ supervisor.restart_started.clear()
+ supervisor.allow_restart.clear()
+ first = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("first",))]))
+ assert await asyncio.to_thread(supervisor.restart_started.wait, 2)
+ second = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("second",))]))
+ await asyncio.sleep(0)
+ assert adapter.state_store.list_sources()[0].route_model_ids == ("first",)
+ supervisor.allow_restart.set()
+ await asyncio.wait_for(asyncio.gather(first, second), 2)
+ assert adapter.state_store.list_sources()[0].route_model_ids == ("second",)
+ assert supervisor.restart_count == 3
+ assert not adapter._routing_lock.locked()
+
+ asyncio.run(run())
+
+
+def test_service_save_drain_releases_before_settlement_can_acquire_mutation_lock(tmp_path):
+ from tests.test_model_hub_resolution import _service, _source
+ from tests.test_model_hub_routing_modes import MODEL, _sparse_config
+
+ async def run():
+ async with _transport(tmp_path) as (adapter, supervisor, binding, _received, finish, _requests):
+ source = _source(binding.source_id, (), vendor="custom", credential_ref=binding.credential_ref)
+ source.protocol = binding.protocol
+ source.base_url = binding.base_url
+ config = _sparse_config(source)
+ service, store, _ = _service(tmp_path / "service", config, adapter)
+ adapter.state_store.sync_sources(service._bindings(config))
+ handle = await adapter.invoke(source.id, MODEL, {}, True, "opencode")
+ assert await anext(handle.stream) == FIRST
+ save = asyncio.create_task(
+ service.set_agent_chain("claude", MODEL, {"hops": [{"source_id": source.id, "model_id": "new"}]})
+ )
+ await _barrier_waiting(adapter, save)
+ assert service._mutation_lock.locked()
+
+ async def settle():
+ async with service._mutation_lock:
+ return await handle.outcome()
+
+ settlement = asyncio.create_task(settle())
+ await asyncio.sleep(0)
+ assert not settlement.done()
+ assert supervisor.restart_count == 0
+ finish.set()
+ assert b"".join([part async for part in handle.stream]) == LAST
+ result, outcome = await asyncio.wait_for(asyncio.gather(save, settlement), 2)
+ assert result["chain"]["current"] == {"source_id": source.id, "model_id": "new"}
+ assert outcome.kind is RawOutcomeKind.SUCCESS
+ assert store.config.agents["claude"].routes[MODEL].hops[0].model_id == "new"
+ assert supervisor.restart_count == 1
+ assert adapter._active_transports == 0
+
+ asyncio.run(run())
diff --git a/ui/e2e/b-add-api-key.spec.ts b/ui/e2e/b-add-api-key.spec.ts
index 9a70b6aea..5212a1946 100644
--- a/ui/e2e/b-add-api-key.spec.ts
+++ b/ui/e2e/b-add-api-key.spec.ts
@@ -6,7 +6,7 @@
// here skips without one. The mock is reached ONLY over HTTP at
// `VIBE_E2E_MOCK_UPSTREAM_URL`, and its URL enters the product the same way a
// user's would: typed into the dialog's Base URL field.
-import type { HubApi, RouteHop } from './support/api';
+import type { HubApi } from './support/api';
import { hub as copy } from './support/copy';
import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';
import {
@@ -327,7 +327,7 @@ test.describe('B · add an API-key source', () => {
// The operator's chain only. The retry below deletes and recreates the
// precondition source, so a baseline carrying its hop would name a source id
// that no longer exists — and that refusal is not partial.
- const original: RouteHop[] = await captureAgentChain(api, gateway);
+ const original = await captureAgentChain(api, gateway);
try {
// The restoration boundary is entered BEFORE the arranged PUT (inside
// `arrange` below), not after it returns: a PUT whose response is lost
diff --git a/ui/e2e/d-routing.spec.ts b/ui/e2e/d-routing.spec.ts
index c071e848f..9845e7a4e 100644
--- a/ui/e2e/d-routing.spec.ts
+++ b/ui/e2e/d-routing.spec.ts
@@ -1,302 +1,165 @@
-// Suite D — the two surfaces that decide which source serves a request: a
-// model's own route chain, and the backend-wide priority order.
-//
-// Scenario IDs are from docs/plans/model-hub-e2e-test-plan.md §3.
-//
-// Both surfaces here are edited and then CANCELLED. That is not timidity: this
-// suite runs against a live instance whose routing may be real, and the
-// behaviour under test is what the editor does while you are editing it. The
-// commit path is scenario B7's subject, on a source this suite owns outright.
-import type { RouteHop } from './support/api';
-import { hub as copy, hubOrNull } from './support/copy';
+// Route editing and backend defaults have independent persistence owners.
+import { hub as copy } from './support/copy';
+import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';
import { requireMockUpstream, requireModelHub, requireRuntimeRunning } from './support/fixtures';
import { expect, test } from './support/gateway';
import { labelledButton } from './support/hub';
import { captureAgentChain, restoreAgentChain } from './support/restore';
-/** The product falls back to the raw backend id for a backend it has no label
- * for, so this does too rather than throwing on an id the bundle never named. */
-const backendLabel = (backend: string): string => hubOrNull(`backends.${backend}`) ?? backend;
-
-test.describe('D · route chains and priority order', () => {
+test.describe('D: inherited routes, manual editing, and default routing', () => {
test.beforeEach(async ({ api, mock }) => {
await requireModelHub(api);
await requireRuntimeRunning(api);
await requireMockUpstream(mock);
});
- test('D · a hop can be added, removed, and reordered by keyboard alone', async ({ hub, gateway, page }) => {
- await hub.goto();
- const row = hub.firstRouteRow(gateway.backend);
- await expect(row).toBeVisible();
- await row.click();
-
- const dialog = hub.routeDialog;
- await expect(dialog).toBeVisible();
- const hops = dialog.locator('.model-hub-route-hop');
- const before = await hops.count();
+ test('D: inherited inspection stays read-only until Edit route', async ({ api, hub, gateway }) => {
+ const original = await captureAgentChain(api, gateway);
+ try {
+ expect(await api.deleteAgentChain(gateway.backend, gateway.model)).toBe(true);
+ await hub.goto();
+ await hub.openRoute(gateway.backend, gateway.model);
+ const dialog = hub.routeDialog;
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true })).toHaveCount(0);
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.grip'), exact: true })).toHaveCount(0);
+ await labelledButton(dialog, copy('routing.editRoute')).click();
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true })).toBeVisible();
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.grip'), exact: true }).first()).toBeVisible();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ await labelledButton(dialog, copy('routeDialog.cancel')).click();
+ await expect(dialog).toHaveCount(0);
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ } finally {
+ await restoreAgentChain(api, gateway, original);
+ }
+ });
- // --- add (keyboard) -------------------------------------------------------
- // The whole scenario is a keyboard claim, so every step below drives focus
- // and keystrokes the way the claim's reader assumes it was driven: trigger,
- // candidate, confirm, and removal are all reached without a pointer.
- const addHop = dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true });
- const addOneHop = async (): Promise<void> => {
- // The trigger itself is key-activated too. It lives in the dialog, outside
- // the popover's cmdk panel — so Enter presses it (like the remove buttons
- // below); the Enter-swallowing rule only begins once the panel is open.
- await addHop.focus();
- await addHop.press('Enter');
- // The picker autofocuses its search box; cmdk's list takes ArrowDown to
- // move the selection and Enter to fire `onSelect`, which is the product's
- // own keyboard path for choosing a candidate.
+ test('D: manual add, reorder, Escape, and remove work by keyboard without committing the draft', async ({ api, hub, gateway, page }) => {
+ const original = await captureAgentChain(api, gateway);
+ const arranged = [{ source_id: gateway.sources[0].id, model_id: gateway.sources[0].models[0].id }];
+ try {
+ expect(await api.putAgentChain(gateway.backend, gateway.model, arranged)).toBe(true);
+ await hub.goto();
+ await hub.openRoute(gateway.backend, gateway.model);
+ const dialog = hub.routeDialog;
+ const hops = dialog.locator('.model-hub-route-hop');
+ await expect(hops).toHaveCount(1);
+ const add = dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true });
+ await add.focus();
+ await add.press('Enter');
const search = page.getByPlaceholder(copy('routeDialog.add.search'), { exact: true });
await expect(search).toBeFocused();
await search.press('ArrowDown');
await search.press('Enter');
- // The footer confirm is the next tabbable after the search box, and —
- // inside a cmdk panel — it answers Space, not Enter: cmdk's root handler
- // calls preventDefault() on every Enter that reaches it (Enter belongs to
- // the list there), which suppresses the button's native Enter activation.
- // Space is the activation that genuinely works, so Space is what a
- // keyboard user actually presses here.
await search.press('Tab');
const confirm = page.getByRole('button', { name: copy('routeDialog.add.confirm'), exact: true });
await expect(confirm).toBeFocused();
await confirm.press(' ');
- };
- test.skip(
- await addHop.isDisabled(),
- 'Every available source/model pair is already in this chain, so there is nothing left to add.',
- );
- await addOneHop();
- await expect(hops).toHaveCount(before + 1);
-
- // The reorder below is the other half of this spec, and a one-hop chain has
- // no order to change — which is exactly what an empty chain plus one add
- // is. So take a second hop while the instance still offers one, rather than
- // skipping the keyboard path on an arrangement this spec can fix itself.
- if (before + 1 < 2 && !(await addHop.isDisabled())) {
- await addOneHop();
- await expect(hops).toHaveCount(before + 2);
- }
-
- // --- keyboard reorder ---------------------------------------------------
- const added = await hops.count();
- test.skip(
- added < 2,
- 'A single-hop chain has no order to change; this instance offered only one candidate.',
- );
- const announcer = dialog.locator('[aria-live="polite"]');
- const firstGrip = hops.first().getByRole('button', { name: copy('routeDialog.grip'), exact: true });
- await firstGrip.focus();
- await firstGrip.press(' ');
- // The grab is announced, and the row says it is held — a sighted user sees
- // the lift, and this is the same fact stated for everyone else.
- await expect(announcer).toHaveText(copy('routeDialog.reorder.grabbed', { position: 1 }));
- await expect(firstGrip).toHaveAttribute('aria-grabbed', 'true');
-
- await firstGrip.press('ArrowDown');
- await expect(announcer).toHaveText(copy('routeDialog.reorder.position', { position: 2 }));
-
- // Space again drops what Space picked up, and says where it landed. The
- // OTHER way out of a grab — Escape, which should put the hop back — closes
- // the whole editor instead; see the fixme below.
- //
- // The drop is addressed by the row that reports itself held, not by
- // `hops.first()`: the move just made the first row a different hop, and a
- // locator re-resolves every time it is used.
- const heldGrip = dialog.locator('[aria-grabbed="true"]');
- await heldGrip.press(' ');
- await expect(announcer).toHaveText(copy('routeDialog.reorder.dropped', { position: 2 }));
- await expect(dialog.locator('[aria-grabbed="true"]')).toHaveCount(0);
-
- // --- remove (keyboard) ----------------------------------------------------
- // Back down to what was there before, one row at a time — the editor has to
- // give back everything it took, not just the last thing. The remove buttons
- // are roving-tabindex siblings of the grips, so each is focused directly and
- // pressed rather than clicked.
- for (let remaining = added; remaining > before; remaining -= 1) {
- const remove = hops.last().getByRole('button', { name: copy('routeDialog.removeHop'), exact: true });
- await remove.focus();
- await remove.press('Enter');
- await expect(hops).toHaveCount(remaining - 1);
- }
-
- // Cancel: this spec is about the editor, and the instance's real routing is
- // not this spec's to change.
- await labelledButton(dialog, copy('routeDialog.cancel')).click();
- await expect(dialog).toHaveCount(0);
- });
-
- test('D · Escape cancels a grab without discarding the chain edit', async ({ api, hub, gateway, page }) => {
- const original = await captureAgentChain(api, gateway);
- const arranged = gateway.sources.map((source) => ({
- source_id: source.id,
- model_id: source.models[0].id,
- }));
- try {
- expect(await api.putAgentChain(gateway.backend, gateway.model, arranged)).toBe(true);
- await hub.goto();
- const card = hub.agentCard(gateway.backend);
- const expand = card.locator('.model-hub-model-collapse').first();
- if (await expand.count()) await expand.click();
- await hub.routeRow(gateway.backend, gateway.model).click();
+ await expect(hops).toHaveCount(2);
- const dialog = hub.routeDialog;
- const hops = dialog.locator('.model-hub-route-hop');
const models = dialog.locator('.model-hub-route-hop-model');
+ const before = await models.allTextContents();
const announcer = dialog.locator('[aria-live="polite"]');
const gripName = copy('routeDialog.grip');
- const unsavedOrder = [arranged[1].model_id, arranged[0].model_id];
- const firstGrip = hops.first().getByRole('button', { name: gripName, exact: true });
-
- await firstGrip.focus();
- await firstGrip.press(' ');
- await firstGrip.press('ArrowDown');
- const heldGrip = dialog.locator('[aria-grabbed="true"]');
- await expect(heldGrip).toBeFocused();
- await heldGrip.press(' ');
- await expect(models).toHaveText(unsavedOrder);
- await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeEnabled();
-
- const unsavedGrip = hops.last().getByRole('button', { name: gripName, exact: true });
- await unsavedGrip.press(' ');
- await unsavedGrip.press('ArrowUp');
- await expect(dialog.locator('[aria-grabbed="true"]')).toBeFocused();
+ const grip = hops.first().getByRole('button', { name: gripName, exact: true });
+ await grip.focus();
+ await grip.press(' ');
+ await expect(announcer).toHaveText(copy('routeDialog.reorder.grabbed', { position: 1 }));
+ await grip.press('ArrowDown');
+ await expect(announcer).toHaveText(copy('routeDialog.reorder.position', { position: 2 }));
+ await dialog.locator('[aria-grabbed="true"]').press(' ');
+ await expect(announcer).toHaveText(copy('routeDialog.reorder.dropped', { position: 2 }));
+ await expect(models).toHaveText([...before].reverse());
+
+ const lastGrip = hops.last().getByRole('button', { name: gripName, exact: true });
+ await lastGrip.press(' ');
+ await lastGrip.press('ArrowUp');
await page.keyboard.press('Escape');
-
await expect(dialog).toBeVisible();
await expect(announcer).toHaveText(copy('routeDialog.reorder.cancelled', { position: 2 }));
await expect(dialog.locator('[aria-grabbed="true"]')).toHaveCount(0);
- await expect(models).toHaveText(unsavedOrder);
+ await expect(models).toHaveText([...before].reverse());
await expect(hops.last().getByRole('button', { name: gripName, exact: true })).toBeFocused();
await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeEnabled();
+ const remove = hops.last().getByRole('button', { name: copy('routeDialog.removeHop'), exact: true });
+ await remove.focus();
+ await remove.press('Enter');
+ await expect(hops).toHaveCount(1);
await labelledButton(dialog, copy('routeDialog.cancel')).click();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual({ hops: arranged });
} finally {
await restoreAgentChain(api, gateway, original);
}
});
- test('D · Reorder by Source order restates the chain, and says which it did', async ({ hub, gateway, api }) => {
- // Arranged, not hoped for. On a fresh hermetic instance the fixture's
- // `e2e-route-*` models do not match the backend menu, so this route begins
- // EMPTY — and an empty chain leaves the button with nothing to sort, so the
- // `unchanged` branch passes without the sorter ever running. The two hops
- // below are therefore the actual subject: deliberately opposite to Source
- // order, so the sort has a real permutation to perform.
- const supply = gateway.sources.flatMap((source) =>
- source.models.map((model) => ({ source_id: source.id, model_id: model.id })),
- );
- test.skip(
- supply.length < 2,
- 'This instance offers fewer than two source/model pairs, so no unsorted chain can be arranged.',
- );
- // The order of `gateway.sources` is the suite's own; the order the instance
- // routes by is Source order. Arranging route-b before route-a is opposite to
- // creation order only when creation order became priority order — which the
- // API call below establishes rather than assumes.
- const arrangeHops = [
- { source_id: gateway.sources[1].id, model_id: gateway.sources[1].models[0].id },
- { source_id: gateway.sources[0].id, model_id: gateway.sources[0].models[0].id },
- ];
- const original: RouteHop[] = await captureAgentChain(api, gateway);
+ test('D: Default routing saves its order without reordering manual routes', async ({ api, hub, gateway }) => {
+ const original = await captureAgentChain(api, gateway);
+ const originalOrder = await api.defaultSourceOrder(gateway.backend);
+ const order = gateway.sources.map((source) => source.id);
+ const manual = gateway.sources.map((source) => ({ source_id: source.id, model_id: gateway.model }));
try {
- // Entered BEFORE the arranged PUT, not after it succeeds: a PUT whose
- // response is lost or times out rejects that await with the chain
- // already replaced server-side, and a finally outside it would leave
- // the user's route swapped for the arrangement — then the fixture's
- // source sweep empties it entirely.
- expect(
- await api.putAgentChain(gateway.backend, gateway.model, arrangeHops),
- 'The instance refused the arranged route, so there is no chain to sort.',
- ).toBe(true);
-
+ expect(await api.putAgentChain(gateway.backend, gateway.model, manual)).toBe(true);
+ await api.setDefaultSourceOrder(gateway.backend, order);
await hub.goto();
- // The row for THIS model, not the card's first: the first row a card
- // shows is whichever model the supply ranks first — a different chain
- // than the one arranged above. And a collapsed card renders only its
- // first six models, so a selected model seventh-or-later has no row in
- // the DOM at all until the card is expanded.
- const card = hub.agentCard(gateway.backend);
- const expand = card.locator('.model-hub-model-collapse').first();
- if (await expand.count()) await expand.click();
- await hub.routeRow(gateway.backend, gateway.model).click();
- const dialog = hub.routeDialog;
- await expect(dialog).toBeVisible();
-
- const announcer = dialog.locator('[aria-live="polite"]');
- await dialog.getByRole('button', { name: copy('routeDialog.reorder.label'), exact: true }).click();
-
- // The announcement must say it sorted — the draft was arranged opposite
- // to Source order, so "already matches" would be the wrong claim.
- await expect(announcer).toHaveText(copy('routeDialog.reorder.sorted'));
- // And the hops must now BE in Source order, asserted by display name: the
- // name cell carries the id only for unjoined sources, so the display name
- // is the one observable every rendering shares. Each fixture source
- // contributes exactly one hop here, so name order IS hop order.
- const hops = dialog.locator('.model-hub-route-hop-name');
- await expect(hops).toHaveCount(2);
- await expect(hops.nth(0)).toHaveText(gateway.sources[0].display_name);
- await expect(hops.nth(1)).toHaveText(gateway.sources[1].display_name);
-
- await labelledButton(dialog, copy('routeDialog.cancel')).click();
- await expect(dialog).toHaveCount(0);
+ await hub.adjustPriorityButton(gateway.backend).click();
+ const drawer = hub.orderDrawer;
+ const ordered = drawer.locator('.model-hub-order-row--ordered');
+ await expect(ordered).toHaveCount(2);
+ await ordered.first().getByRole('button', { name: copy('routing.moveDown'), exact: true }).click();
+ await labelledButton(drawer, copy('order.save')).click();
+ await expect(drawer).toHaveCount(0);
+ expect(await api.defaultSourceOrder(gateway.backend)).toEqual([...order].reverse());
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual({ hops: manual });
+ await hub.openRoute(gateway.backend, gateway.model);
+ await expect(hub.routeDialog.locator('.model-hub-route-hop-name')).toHaveText(gateway.sources.map((source) => source.display_name));
+ await labelledButton(hub.routeDialog, copy('routeDialog.cancel')).click();
} finally {
- await restoreAgentChain(api, gateway, original);
+ try {
+ await api.setDefaultSourceOrder(gateway.backend, originalOrder);
+ } finally {
+ await restoreAgentChain(api, gateway, original);
+ }
}
});
- test('D · the priority drawer moves a source by keyboard and can be backed out of', async ({ hub, gateway, page }) => {
- await hub.goto();
- await hub.adjustPriorityButton(gateway.backend).click();
-
- const drawer = hub.orderDrawer;
- await expect(drawer).toBeVisible();
- await expect(drawer).toContainText(
- copy('order.title', { backend: backendLabel(gateway.backend) }),
- );
-
- const ordered = drawer.locator('.model-hub-order-row--ordered');
- const count = await ordered.count();
- test.skip(count < 2, 'Fewer than two sources are in this backend\'s order, so there is nothing to reorder.');
-
- const announcer = drawer.locator('[aria-live="polite"]');
- // The row's own name cell, not its first line: the row leads with its
- // position ordinal, so `innerText().split('\n')[0]` is "1" and the expected
- // announcement becomes "Grabbed 1, position 1 of 3."
- const firstName = (await ordered.first().locator('.model-hub-order-name').innerText()).trim();
- const grip = ordered.first().getByRole('button', { name: copy('order.reorder'), exact: true });
- await grip.focus();
- await grip.press(' ');
- await expect(announcer).toHaveText(
- copy('order.grabbed', { source: firstName, position: 1, count }),
- );
-
- await grip.press('ArrowDown');
- await expect(announcer).toHaveText(
- copy('order.moved', { source: firstName, position: 2, count }),
- );
-
- await page.keyboard.press('Escape');
- await expect(announcer).toHaveText(copy('order.grabCancelled', { source: firstName }));
- // Cancelling restored the position, so the first row is the one it started as.
- await expect(ordered.first()).toContainText(firstName);
-
- // Closed without saving: nothing this drawer did reaches the instance.
- await labelledButton(drawer, copy('order.cancel')).click();
- await expect(drawer).toHaveCount(0);
+ test('D: Default routing keyboard Escape and Cancel restore unsaved order', async ({ api, hub, gateway, page }) => {
+ const originalOrder = await api.defaultSourceOrder(gateway.backend);
+ try {
+ await api.setDefaultSourceOrder(gateway.backend, gateway.sources.map((source) => source.id));
+ await hub.goto();
+ await hub.adjustPriorityButton(gateway.backend).click();
+ const drawer = hub.orderDrawer;
+ const ordered = drawer.locator('.model-hub-order-row--ordered');
+ await expect(ordered).toHaveCount(2);
+ const firstName = gateway.sources[0].display_name;
+ const grip = ordered.first().getByRole('button', { name: copy('order.reorder'), exact: true });
+ await grip.focus();
+ await grip.press(' ');
+ await expect(drawer.locator('[aria-live="polite"]')).toHaveText(copy('order.grabbed', { source: firstName, position: 1, count: 2 }));
+ await grip.press('ArrowDown');
+ await page.keyboard.press('Escape');
+ await expect(drawer.locator('[aria-live="polite"]')).toHaveText(copy('order.grabCancelled', { source: firstName }));
+ await expect(ordered.first()).toContainText(firstName);
+ await labelledButton(drawer, copy('order.cancel')).click();
+ expect(await api.defaultSourceOrder(gateway.backend)).toEqual(gateway.sources.map((source) => source.id));
+ } finally {
+ await api.setDefaultSourceOrder(gateway.backend, originalOrder);
+ }
});
- // D1 — "a newly added source lands at the tail of the order rather than
- // displacing an existing one" — needs a SECOND source to arrive while a
- // non-trivial order already exists, and the plan's D1 states it for a
- // subscription source. A subscription source cannot be created from a browser
- // without a real OAuth provider, and this lane may not add a product test
- // hook, so the observable half is left to the pytest lane.
- test.fixme('D1 · a new source is appended to the priority order, not inserted', async () => {
- // Blocked on: no browser-reachable way to add a subscription source against
- // a mock. Reported to the orchestrator as a coverage gap, not a defect.
+ test('D1: a new API-key source appends to existing backend defaults', async ({ api, gateway }) => {
+ const before = await api.defaultSourceOrder(gateway.backend);
+ let added: string | undefined;
+ try {
+ const source = await api.createApiKeySource(E2E_SOURCE_PREFIX + 'default-tail', mockBaseUrl());
+ expect(source).not.toBeNull();
+ added = source!.id;
+ expect(await api.defaultSourceOrder(gateway.backend)).toEqual([...before, added]);
+ } finally {
+ if (added) await api.deleteSource(added);
+ await api.setDefaultSourceOrder(gateway.backend, before);
+ }
});
});
diff --git a/ui/e2e/g-guards-copy.spec.ts b/ui/e2e/g-guards-copy.spec.ts
index 853bb1e6e..bfa1f04d4 100644
--- a/ui/e2e/g-guards-copy.spec.ts
+++ b/ui/e2e/g-guards-copy.spec.ts
@@ -5,7 +5,6 @@
// Baseline discipline (§5a): `fix-first` scenarios land as `test.fixme` with
// the open decision named, never as red tests. Four of them do so below; each
// says what would have to change for it to become an assertion.
-import type { RouteHop } from './support/api';
import { hasCopy, hub as copy } from './support/copy';
import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';
import {
@@ -39,7 +38,7 @@ test.describe('G · supply guards and failure copy', () => {
// routing is not this spec's to keep. Real routing is also all it captures:
// the source deleted below may already be a hop here, and restoring a hop
// this spec is about to delete is how the whole restore gets refused.
- const original: RouteHop[] = await captureAgentChain(api, gateway);
+ const original = await captureAgentChain(api, gateway);
try {
// Entered BEFORE the arranged PUT, not after it succeeds: a response
// lost to a timeout or disconnect rejects that await with the chain
diff --git a/ui/e2e/model-recorded-turn.spec.ts b/ui/e2e/model-recorded-turn.spec.ts
new file mode 100644
index 000000000..36172580c
--- /dev/null
+++ b/ui/e2e/model-recorded-turn.spec.ts
@@ -0,0 +1,134 @@
+import { randomUUID } from 'node:crypto';
+
+import type { RecordedTurn, Source } from './support/api';
+import { routableModels } from './support/api';
+import { hub as copy } from './support/copy';
+import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';
+import { expect, requireMockUpstream, requireModelHub, requireRuntimeRunning, test } from './support/fixtures';
+import { labelledButton } from './support/hub';
+import { captureAgentChain, restoreAgentChain, restoreNativeSources } from './support/restore';
+
+// Additional live-browser evidence, not a Vitest scenario-catalog entry.
+test('MH-ROUTING-011 recorded request error is independent of current route and cleared by latest success', async ({ api, mock, hub, page }) => {
+ test.setTimeout(180_000);
+ const projectId = process.env.VIBE_E2E_TURN_PROJECT_ID?.trim();
+ test.skip(!projectId, 'Set VIBE_E2E_TURN_PROJECT_ID to a task-owned disposable project on the explicitly consented regression instance.');
+ await requireModelHub(api);
+ await requireRuntimeRunning(api);
+ await requireMockUpstream(mock);
+ const backend = 'codex';
+ const agent = (await api.agents()).find((entry) => entry.backend === backend);
+ test.skip(!agent?.cli_present, 'The recorded-turn scenario requires the real Codex CLI on the regression instance; OpenCode has no exact turn attribution.');
+ await api.read(`/api/projects/${encodeURIComponent(projectId!)}`);
+ const model = routableModels(agent!)[0];
+ expect(model).toBeDefined();
+ const originalRoute = await captureAgentChain(api, { backend, model });
+ const originalOrder = await api.defaultSourceOrder(backend);
+ const sourceIds = new Set((await api.sources()).map((entry) => entry.id));
+ const suffix = randomUUID().slice(0, 8);
+ const agentName = `e2e-recorded-${suffix}`;
+ const ownPrefix = `${E2E_SOURCE_PREFIX}${suffix}-`;
+ let sessionId: string | null = null;
+ let agentAttempted = false;
+ let modeAttempted = false;
+ let first: Source;
+ let second: Source;
+ try {
+ await mock.configure({ auth: 'ok', protocol: 'openai_responses', models_endpoint: 'ok', models: [], model_errors: {}, stream: 'healthy' });
+ const a = await api.createApiKeySource(`${ownPrefix}recorded-a`, `${mockBaseUrl()}/v1`);
+ const b = await api.createApiKeySource(`${ownPrefix}recorded-b`, `${mockBaseUrl()}/v1`);
+ expect(a).not.toBeNull();
+ expect(b).not.toBeNull();
+ first = a!;
+ second = b!;
+ expect(first.models).toEqual([]);
+ expect(second.models).toEqual([]);
+ if (agent!.mode !== 'hub') {
+ modeAttempted = true;
+ await api.setAgentMode(backend, 'hub');
+ }
+ await api.setDefaultSourceOrder(backend, [first.id]);
+ expect(await api.deleteAgentChain(backend, model)).toBe(true);
+ expect((await api.agentChain(backend, model)).manual_override).toBeNull();
+ const healthBefore = (await api.sources()).find((entry) => entry.id === first.id)!.state;
+ await mock.configure({ model_errors: { [model]: 'model_not_found' } });
+ agentAttempted = true;
+ await api.createTurnAgent(agentName, backend, model);
+ sessionId = await api.createTurnSession(projectId!, agentName, model);
+ await api.sendTurn(sessionId, 'Return the synthetic upstream response. Request: \u4e2d\u6587');
+ let failed: RecordedTurn | null = null;
+ await expect.poll(async () => {
+ failed = await api.latestRecordedTurn(backend, model);
+ return failed?.terminal_error?.source_id === first.id ? failed.terminal_error.upstream_error_code : null;
+ }, { timeout: 70_000 }).toBe('model_not_found');
+ const recorded = failed! as RecordedTurn;
+ expect(recorded.terminal_error).toMatchObject({ source_id: first.id, configured_model_id: model, http_status: 404 });
+ expect((await api.sources()).find((entry) => entry.id === first.id)!.state).toEqual(healthBefore);
+ expect((await api.agentChain(backend, model)).route_origin).toBe('passthrough');
+
+ // Changing today's route must not relabel the historical failing source.
+ expect(await api.putAgentChain(backend, model, [{ source_id: second.id, model_id: model }])).toBe(true);
+ await hub.goto();
+ await hub.openRoute(backend, model);
+ const dialog = hub.routeDialog;
+ const recordedPanel = dialog.locator('.model-hub-recorded-turn');
+ await expect(recordedPanel).toContainText(copy('routing.latestRecorded'));
+ await expect(recordedPanel).toContainText(copy('routing.modelNotFound'));
+ await expect(recordedPanel).toContainText('model_not_found');
+ await expect(recordedPanel).toContainText(first.id);
+ await expect(recordedPanel).toContainText(model);
+ await expect(recordedPanel.locator('time')).toHaveAttribute('datetime', recorded.ts);
+ await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText([second.display_name]);
+ expect(await api.latestRecordedTurn(backend, model)).toEqual(recorded);
+ await labelledButton(recordedPanel, copy('routing.errorDetails')).click();
+ const details = page.getByRole('dialog', { name: copy('routing.latestRecorded'), exact: true });
+ await expect(details).toBeVisible();
+ expect(JSON.parse(await details.locator('pre').innerText())).toEqual(recorded);
+ await details.press('Escape');
+ await expect(details).toHaveCount(0);
+ await labelledButton(dialog, copy('routeDialog.cancel')).click();
+
+ expect(await api.deleteAgentChain(backend, model)).toBe(true);
+ await mock.configure({ model_errors: {} });
+ await api.sendTurn(sessionId, 'Return the synthetic upstream response again.');
+ await expect.poll(async () => {
+ const latest = await api.latestRecordedTurn(backend, model);
+ return latest?.turn_id !== recorded.turn_id && latest?.served?.source_id === first.id && latest.terminal_error === null;
+ }, { timeout: 70_000 }).toBe(true);
+ await page.reload();
+ const historyRead = page.waitForResponse((response) => new URL(response.url()).pathname === `/api/models/agents/${backend}/provenance`);
+ await hub.openRoute(backend, model);
+ expect((await historyRead).ok()).toBe(true);
+ await expect(hub.routeDialog.locator('.model-hub-recorded-turn')).toHaveCount(0);
+ expect((await api.agentChain(backend, model)).route_origin).toBe('passthrough');
+ expect((await api.sources()).find((entry) => entry.id === first.id)!.state).toEqual(healthBefore);
+ } finally {
+ try {
+ if (agentAttempted) await api.removeTurnFixture(agentName, sessionId);
+ } finally {
+ try {
+ await restoreAgentChain(api, { backend, model }, originalRoute);
+ } finally {
+ try {
+ await api.setDefaultSourceOrder(backend, originalOrder);
+ } finally {
+ try {
+ if (modeAttempted) await api.setAgentMode(backend, agent!.mode);
+ } finally {
+ try {
+ if (modeAttempted) await restoreNativeSources(api, sourceIds);
+ } finally {
+ try {
+ for (const entry of await api.sources()) {
+ if (entry.display_name.startsWith(ownPrefix)) await api.deleteSource(entry.id);
+ }
+ } finally {
+ await mock.configure({ model_errors: {}, stream: 'healthy' });
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+});
diff --git a/ui/e2e/model-route-cleanup.spec.ts b/ui/e2e/model-route-cleanup.spec.ts
new file mode 100644
index 000000000..920fcc7fc
--- /dev/null
+++ b/ui/e2e/model-route-cleanup.spec.ts
@@ -0,0 +1,67 @@
+import { expect, test } from '@playwright/test';
+
+import type { AgentChain, HubApi } from './support/api';
+import { HubApi as HubApiClient } from './support/api';
+import { captureAgentChain, restoreAgentChain } from './support/restore';
+
+for (const override of [null, { hops: [] }, { hops: [{ source_id: 'src_operator', model_id: 'vendor/model' }] }]) {
+ test(`route cleanup preserves ${override === null ? 'absence' : override.hops.length ? 'manual hops' : 'explicit empty'}`, async () => {
+ let saved: AgentChain['manual_override'] = override;
+ const writes: string[] = [];
+ const api = {
+ sources: async () => [],
+ agentChain: async () => ({ manual_override: saved, chain: [{ source_id: 'src_generated', model_id: 'generated' }] }),
+ putAgentChain: async (_backend: string, _model: string, hops: NonNullable<AgentChain['manual_override']>['hops']) => {
+ writes.push('PUT');
+ saved = { hops };
+ return true;
+ },
+ deleteAgentChain: async () => {
+ writes.push('DELETE');
+ saved = null;
+ return true;
+ },
+ } as unknown as HubApi;
+ const route = { backend: 'claude', model: 'menu-model' };
+ const snapshot = await captureAgentChain(api, route);
+ expect(snapshot.manual_override).toEqual(override);
+ saved = { hops: [{ source_id: 'src_test', model_id: 'test-target' }] };
+ await restoreAgentChain(api, route, snapshot);
+ expect(saved).toEqual(override);
+ expect(writes).toEqual([override === null ? 'DELETE' : 'PUT']);
+ });
+}
+
+test('route cleanup rejects successful responses whose persisted intent was not restored', async () => {
+ const api = {
+ deleteAgentChain: async () => true,
+ agentChain: async () => ({ manual_override: { hops: [] } }),
+ } as unknown as HubApi;
+ await expect(restoreAgentChain(api, { backend: 'claude', model: 'menu-model' }, { manual_override: null }))
+ .rejects.toThrow('Teardown must restore route intent');
+});
+
+test('route cleanup preserves existing fixture-source references verbatim', async () => {
+ const hops = [{ source_id: 'src_previous_fixture', model_id: 'vendor/model' }];
+ const api = {
+ sources: async () => [{ id: 'src_previous_fixture', display_name: 'e2e-playwright-from-earlier-run' }],
+ agentChain: async () => ({ manual_override: { hops } }),
+ } as unknown as HubApi;
+ const snapshot = await captureAgentChain(api, { backend: 'codex', model: 'menu-model' });
+ expect(snapshot.manual_override).toEqual({ hops });
+});
+
+test('gateway fixture cleanup keeps every source that preceded this test', async () => {
+ const removed: string[] = [];
+ const client = {
+ modelHubEnabled: async () => true,
+ sources: async () => [
+ { id: 'src_previous_fixture', display_name: 'e2e-playwright-from-earlier-run' },
+ { id: 'src_this_fixture', display_name: 'e2e-playwright-from-this-run' },
+ { id: 'src_operator', display_name: 'Operator source' },
+ ],
+ deleteSource: async (id: string) => { removed.push(id); },
+ } as unknown as HubApi;
+ await HubApiClient.prototype.removeSuiteSources.call(client, new Set(['src_previous_fixture', 'src_operator']));
+ expect(removed).toEqual(['src_this_fixture']);
+});
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
new file mode 100644
index 000000000..ec719b799
--- /dev/null
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -0,0 +1,55 @@
+import { hub as copy } from './support/copy';
+import { expect, test } from './support/gateway';
+import { labelledButton } from './support/hub';
+import { captureAgentChain, restoreAgentChain } from './support/restore';
+
+test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route intent', async ({ api, gateway, hub, page }) => {
+ const original = await captureAgentChain(api, gateway);
+ const manual = { hops: [{ source_id: gateway.sources[0].id, model_id: gateway.model }] };
+ try {
+ expect(await api.putAgentChain(gateway.backend, gateway.model, manual.hops)).toBe(true);
+ await hub.goto();
+ await hub.openRoute(gateway.backend, gateway.model);
+ const dialog = hub.routeDialog;
+ await expect(dialog).toBeVisible();
+ const mutations: string[] = [];
+ page.on('request', (request) => {
+ if (['PUT', 'DELETE'].includes(request.method()) && new URL(request.url()).pathname.endsWith('/chain')) {
+ mutations.push(request.method());
+ }
+ });
+ const restore = () => labelledButton(dialog, copy('routing.restoreAutomatic')).click();
+ await restore();
+ await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ await labelledButton(dialog, copy('routing.undoRestore')).click();
+ await expect(labelledButton(dialog, copy('routing.restoreAutomatic'))).toBeVisible();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ expect(mutations).toEqual([]);
+
+ await restore();
+ await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
+ await labelledButton(dialog, copy('routeDialog.cancel')).click();
+ await expect(dialog).not.toBeVisible();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ expect(mutations).toEqual([]);
+
+ await hub.openRoute(gateway.backend, gateway.model);
+ await restore();
+ await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
+ await labelledButton(dialog, copy('routeDialog.save')).click();
+ await expect.poll(async () => (
+ (await api.agentChain(gateway.backend, gateway.model)).manual_override === null
+ || await labelledButton(dialog, copy('guard.confirm.saveRoute')).isVisible()
+ )).toBe(true);
+ const confirm = labelledButton(dialog, copy('guard.confirm.saveRoute'));
+ if (await confirm.isVisible()) await confirm.click();
+ await expect.poll(async () => (await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ expect(mutations.length).toBeGreaterThan(0);
+ expect(new Set(mutations)).toEqual(new Set(['DELETE']));
+ await page.reload();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ } finally {
+ await restoreAgentChain(api, gateway, original);
+ }
+});
diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.ts
index 414a103aa..53ff38df3 100644
--- a/ui/e2e/support/api.ts
+++ b/ui/e2e/support/api.ts
@@ -93,6 +93,21 @@ export type Probe = {
error?: string | null;
};
+export type RecordedTurn = {
+ turn_id: string;
+ ts: string;
+ agent: string;
+ requested_model_id: string;
+ terminal_error: null | {
+ source_id: string;
+ configured_model_id: string;
+ reason: string;
+ http_status?: number | null;
+ upstream_error_code?: string | null;
+ };
+ served: null | { source_id: string; configured_model_id: string };
+};
+
export type Runtime = {
enabled: boolean;
status: {
@@ -190,6 +205,8 @@ const refusedPlan = (body: unknown): { would_remove_hops: unknown[]; would_inter
export type AgentChain = {
backend: string;
+ manual_override: { hops: RouteHop[] } | null;
+ route_origin: 'automatic' | 'manual' | 'passthrough' | null;
/** The menu model this chain routes. Named `model_id` on the wire — the
* server writes `{model_id, chain}`, so a reader keying on `model` finds
* nothing and quietly treats every existing route as empty. */
@@ -331,6 +348,56 @@ export class HubApi {
return (await this.read<{ agents: Agent[] }>('/api/models/agents')).agents ?? [];
}
+ async latestRecordedTurn(backend: string, model: string): Promise<RecordedTurn | null> {
+ const payload = await this.read<{ ok: boolean; contract_version: number; provenance: RecordedTurn | null }>(
+ `/api/models/agents/${backend}/provenance?model=${encodeURIComponent(model)}`,
+ );
+ if (payload.ok !== true || payload.contract_version !== 9 || !('provenance' in payload)) {
+ throw new Error('Latest recorded turn did not use the v9 provenance envelope');
+ }
+ return payload.provenance;
+ }
+
+ async createTurnAgent(name: string, backend: string, model: string): Promise<void> {
+ const result = await this.mutate('post', '/api/agents', {
+ name, backend, model, system_prompt: 'Return only the upstream fixture response. Do not use tools.',
+ });
+ if (!result.ok) throw new Error(`Create turn agent failed: ${JSON.stringify(result.body)}`);
+ }
+
+ async createTurnSession(projectId: string, agentName: string, model: string): Promise<string> {
+ const result = await this.mutate('post', '/api/sessions', { project_id: projectId, agent_name: agentName, model });
+ const body = result.body as { id?: string } | null;
+ if (!result.ok || !body?.id) throw new Error(`Create turn session failed: ${JSON.stringify(result.body)}`);
+ return body.id;
+ }
+
+ async sendTurn(sessionId: string, text: string): Promise<void> {
+ const result = await this.mutate('post', `/api/sessions/${sessionId}/messages`, { text });
+ if (result.status !== 202) throw new Error(`Send turn failed: ${JSON.stringify(result.body)}`);
+ }
+
+ async removeTurnFixture(agentName: string, sessionId: string | null): Promise<void> {
+ const failures: unknown[] = [];
+ try {
+ if (sessionId) {
+ const canceled = await this.mutate('post', `/api/sessions/${sessionId}/cancel`, {});
+ if (!canceled.ok) throw new Error(`Cancel fixture turn failed: ${JSON.stringify(canceled.body)}`);
+ const archived = await this.mutate('delete', `/api/sessions/${sessionId}`);
+ if (!archived.ok) throw new Error(`Archive fixture session failed: ${JSON.stringify(archived.body)}`);
+ }
+ } catch (error) {
+ failures.push(error);
+ }
+ try {
+ const removed = await this.mutate('delete', `/api/agents/${encodeURIComponent(agentName)}`);
+ if (!removed.ok && removed.status !== 404) throw new Error(`Remove fixture agent failed: ${JSON.stringify(removed.body)}`);
+ } catch (error) {
+ failures.push(error);
+ }
+ if (failures.length) throw new AggregateError(failures, 'Recorded-turn fixture cleanup failed');
+ }
+
/**
* Whether this instance answers the read the picker's built-in and provider
* groups are made of.
@@ -459,6 +526,38 @@ export class HubApi {
return (await this.read<{ chains: AgentChain[] }>(`/api/models/agents/${backend}/chains`)).chains ?? [];
}
+ async defaultSourceOrder(backend: string): Promise<string[]> {
+ return (await this.read<{ agent: { sources: { order: string[] } } }>(
+ `/api/models/agents/${backend}/sources`,
+ )).agent.sources.order;
+ }
+
+ async setDefaultSourceOrder(backend: string, order: string[]): Promise<void> {
+ const path = `/api/models/agents/${backend}/sources`;
+ const first = await this.mutate('put', path, { order });
+ if (!first.ok) {
+ const forced = await this.mutate('put', path, { order, force: true, ...refusedPlan(first.body) });
+ if (!forced.ok) throw new Error(`Default routing was not restored: ${JSON.stringify(forced.body)}`);
+ }
+ if (JSON.stringify(await this.defaultSourceOrder(backend)) !== JSON.stringify(order)) {
+ throw new Error('Default routing readback differs from the requested order');
+ }
+ }
+
+ async agentChain(backend: string, model: string): Promise<AgentChain> {
+ return (await this.read<{ chain: AgentChain }>(
+ `/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`,
+ )).chain;
+ }
+
+ async deleteAgentChain(backend: string, model: string): Promise<boolean> {
+ const path = `/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`;
+ const first = await this.mutate('delete', path, {});
+ if (first.ok) return true;
+ const forced = await this.mutate('delete', path, { force: true, ...refusedPlan(first.body) });
+ return forced.ok;
+ }
+
/** Replaces one model's chain outright. Used to arrange the preconditions a
* guard scenario needs — a source that supplies a live route cannot be
* removed without the guard, which is the whole point of the scenario. */
@@ -558,7 +657,7 @@ export class HubApi {
* `/api/models/*` to sweep, and that is the one case where nothing to clean is
* a fact about the instance rather than a failed read.
*/
- async removeSuiteSources(): Promise<void> {
+ async removeSuiteSources(preserveIds: ReadonlySet<string> = new Set()): Promise<void> {
if (!(await this.modelHubEnabled())) return;
// Every match is attempted before any failure is raised: the gateway
// fixture leaves two sources behind, and a first delete that throws used
@@ -567,7 +666,7 @@ export class HubApi {
// failure that already stopped this one.
const failures: string[] = [];
for (const source of await this.sources()) {
- if (!isSuiteSource(source)) continue;
+ if (!isSuiteSource(source) || preserveIds.has(source.id)) continue;
try {
await this.deleteSource(source.id);
} catch (error) {
diff --git a/ui/e2e/support/gateway.ts b/ui/e2e/support/gateway.ts
index 786332829..da2bae3f1 100644
--- a/ui/e2e/support/gateway.ts
+++ b/ui/e2e/support/gateway.ts
@@ -91,6 +91,7 @@ export const test = base.extend<{ hubSurface: void; gateway: Gateway }>({
await requireModelHub(api);
await requireMockUpstream(mock);
await requireRuntimeRunning(api);
+ const sourceIdsAtStart = new Set((await api.sources()).map((source) => source.id));
await mock.configure({
auth: 'ok',
protocol: 'anthropic',
@@ -204,7 +205,7 @@ export const test = base.extend<{ hubSurface: void; gateway: Gateway }>({
try {
if (sourcesBeforeSwitch) await restoreNativeSources(api, sourcesBeforeSwitch);
} finally {
- await api.removeSuiteSources();
+ await api.removeSuiteSources(sourceIdsAtStart);
}
}
}
diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.ts
index 81bdda84c..1df56c05a 100644
--- a/ui/e2e/support/hub.ts
+++ b/ui/e2e/support/hub.ts
@@ -132,6 +132,16 @@ export class ModelHubPage {
return this.page.locator(attr('data-route-backend', backend) + attr('data-route-model', model));
}
+ async openRoute(backend: string, model: string): Promise<void> {
+ await this.agentCard(backend).waitFor({ state: 'visible' });
+ const row = this.routeRow(backend, model);
+ if (!(await row.count())) {
+ const expand = this.agentCard(backend).locator('.model-hub-model-collapse').first();
+ if (await expand.count()) await expand.click();
+ }
+ await row.click();
+ }
+
/** The card collapses its model list, so a spec that just needs *a* route
* takes the first row the card actually shows rather than naming a model
* that may be hidden behind "N more models". */
diff --git a/ui/e2e/support/mock.ts b/ui/e2e/support/mock.ts
index 21ac8eb24..16387294e 100644
--- a/ui/e2e/support/mock.ts
+++ b/ui/e2e/support/mock.ts
@@ -17,10 +17,11 @@ export type MockModelsEndpoint = 'ok' | 'http_404' | 'http_500' | 'timeout' | 'm
export type MockConfig = {
auth?: MockAuthMode;
- stream?: 'healthy' | 'interrupt_after_first_output';
+ stream?: 'healthy' | 'interrupt_after_first_output' | 'pause_after_first_output';
models?: unknown[];
protocol?: MockProtocol;
models_endpoint?: MockModelsEndpoint;
+ model_errors?: Record<string, 'model_not_found'>;
};
export type CapturedRequest = {
diff --git a/ui/e2e/support/restore.ts b/ui/e2e/support/restore.ts
index 2e9529589..ec3f1b785 100644
--- a/ui/e2e/support/restore.ts
+++ b/ui/e2e/support/restore.ts
@@ -26,71 +26,42 @@
// what "running" IS. One declaration each, so a site cannot answer them
// differently, and so the next site added inherits the answer instead of
// picking one.
-import type { HubApi, RouteHop, Runtime } from './api';
-import { isSuiteSource } from './api';
+import type { AgentChain, HubApi, Runtime } from './api';
import { expect, runtimeIsRunning } from './fixtures';
-/**
- * Reads the baseline `restoreAgentChain` puts back: the OPERATOR's chain, which
- * is not the same thing as the chain that is there when a spec looks.
- *
- * Adding a source is not an inert act. `_apply_source_placement` walks every
- * backend's menu and appends the new source to each route whose model it
- * matches, so by the time a spec captures its baseline the gateway fixture's
- * own two sources may already be hops in it. Those hops are arrangement, not
- * state: the fixture's sweep deletes the sources that supply them, so they do
- * not outlive the spec either way.
- *
- * Restoring them is worse than pointless, because a spec may delete or rebuild
- * one of those sources mid-body — B7 deletes it to raise the supply guard, B6
- * deletes and recreates it to shake off a sticky cooldown — and `set_agent_chain`
- * rejects a PUT containing ANY unknown source id outright. So one stale
- * suite-owned hop takes every real hop down with it and the route the operator
- * had is gone.
- *
- * Hence the pair: capture and restore live together and are written once,
- * because the defect was capture being re-derived at each site while only the
- * restore was shared.
- */
+export type AgentChainSnapshot = Pick<AgentChain, 'manual_override'>;
+
+/** Capture persisted intent, not an effective chain that includes fixture sources. */
export const captureAgentChain = async (
api: HubApi,
route: { backend: string; model: string },
-): Promise<RouteHop[]> => {
- const ours = new Set((await api.sources()).filter(isSuiteSource).map((source) => source.id));
- const chain = (await api.chains(route.backend)).find((entry) => entry.model_id === route.model);
- return (chain?.chain ?? [])
- .filter((hop) => !ours.has(hop.source_id))
- .map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id }));
+): Promise<AgentChainSnapshot> => {
+ const chain = await api.agentChain(route.backend, route.model);
+ expect(chain).toHaveProperty('manual_override');
+ return {
+ manual_override: chain.manual_override === null ? null : {
+ hops: chain.manual_override.hops.map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id })),
+ },
+ };
};
-/**
- * Puts one model's route chain back to `original` — including back to EMPTY.
- *
- * Unconditional, where three copies of this used to guard on
- * `original.length`. That guard is the same proxy as the rest of this file: it
- * asks "was there a chain?" when the postcondition is "the chain is what it
- * was", and the one case it gets wrong is the spec that arranged hops onto a
- * route that had none — precisely the arrangement most worth removing. The
- * server treats clearing a route as a first-class mutation (it is what
- * `newly_empty_routes` in `set_agent_chain` exists for), so an empty `original`
- * is a request, not a no-op.
- *
- * A refusal is reported, never swallowed: nothing downstream can reconstruct a
- * displaced chain — the source sweep that follows only deletes rows — so a
- * silent `false` here leaves the instance's routing changed while teardown
- * reads clean.
- */
+/** Automatic absence and a persisted empty manual route are different states. */
export const restoreAgentChain = async (
api: HubApi,
route: { backend: string; model: string },
- original: RouteHop[],
+ original: AgentChainSnapshot,
): Promise<void> => {
- const restored = await api.putAgentChain(route.backend, route.model, original);
+ const restored = original.manual_override === null
+ ? await api.deleteAgentChain(route.backend, route.model)
+ : await api.putAgentChain(route.backend, route.model, original.manual_override.hops);
expect(
restored,
`Teardown failed to restore the original route chain for ${route.backend}/${route.model} — `
+ "the instance is left with the scenario's arrangement.",
).toBe(true);
+ const actual = await api.agentChain(route.backend, route.model);
+ expect(actual.manual_override, 'Teardown must restore route intent, not only effective hops')
+ .toEqual(original.manual_override);
};
/**
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index 50e9e4d65..7295dcf26 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -16,7 +16,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';
import type { AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 8,
+ contract_version: 9,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -45,7 +45,7 @@ const hubAgent: AgentSupply = {
backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', selected_model_id: 'claude-opus-4-6', selected_model_explicit: true,
sources: { order: ['src_a', 'src_b'], eligibility: [{ source_id: 'src_a', eligible: true }, { source_id: 'src_b', eligible: true }] },
routes: { 'claude-opus-4-6': { hops: [{ source_id: 'src_a', model_id: 'claude-opus-4-6' }, { source_id: 'src_b', model_id: 'claude-opus-4-6' }] } },
- supply_status: 'degraded', model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true }], named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'degraded' }], builtin_models: ['claude-opus-4-6'], menu: null,
+ supply_status: 'degraded', model_supply: [{ route_origin: "manual" as const, model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true }], named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'degraded' }], builtin_models: ['claude-opus-4-6'], menu: null,
};
const openCodeAgent: AgentSupply = {
backend: 'opencode',
@@ -77,7 +77,7 @@ describe('AgentCard', () => {
const agentWithRetainedRoute = {
...openCodeAgent,
routes: { [retainedModelId]: { hops: [{ source_id: 'src_a', model_id: 'gpt-5.6-luna' }] } },
- model_supply: [{ model_id: retainedModelId, chain_length: 1, has_runnable_hop: true }],
+ model_supply: [{ route_origin: "manual" as const, model_id: retainedModelId, chain_length: 1, has_runnable_hop: true }],
};
render(<I18nextProvider i18n={localeInstance('zh')}><AgentCard agents={[agentWithRetainedRoute]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
@@ -98,7 +98,7 @@ describe('AgentCard', () => {
...hubAgent,
backend,
routes: {},
- model_supply: ids.map((modelId) => ({ model_id: modelId, chain_length: 1, has_runnable_hop: true })),
+ model_supply: ids.map((modelId) => ({ route_origin: "manual" as const, model_id: modelId, chain_length: 1, has_runnable_hop: true })),
catalog_models: ids.map((id) => ({
id, display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null,
input_modalities: ['text'], output_modalities: ['text'], supports_tools: true, supports_reasoning: false,
@@ -134,7 +134,7 @@ describe('AgentCard', () => {
render(<I18nextProvider i18n={localeInstance('zh')}><AgentCard agents={[{
...openCodeAgent,
menu: { view: 'featured', checked: [modelId] },
- model_supply: [{ model_id: modelId, chain_length: 0, has_runnable_hop: false }],
+ model_supply: [{ route_origin: null, model_id: modelId, chain_length: 0, has_runnable_hop: false }],
}]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText('1 个模型')).toBeTruthy();
@@ -181,7 +181,7 @@ describe('AgentCard', () => {
['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],
] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 8, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.getByTitle(mappingCopy)).toBeTruthy();
expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();
@@ -198,8 +198,8 @@ describe('AgentCard', () => {
agents={[hubAgent]}
sources={[source('src_b', 'Backup source')]}
chains={{
- [key]: readyRegion({
- contract_version: 8,
+ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_b',model_id:'routed-opus'}]}, route_origin: "manual" as const,
+ contract_version: 9,
backend: 'claude',
model_id: 'claude-opus-4-6',
current: { source_id: 'src_b', model_id: 'routed-opus' },
@@ -221,14 +221,15 @@ describe('AgentCard', () => {
const routeButton = screen.getByRole('button', { name: accessibleName });
const mapping = screen.getByTitle(mappingCopy);
- expect(routeButton.contains(mapping)).toBe(true);
- expect(mapping.parentElement?.textContent).toContain(modeCopy);
+ expect(routeButton.parentElement?.contains(mapping)).toBe(true);
+ expect(mapping.parentElement?.textContent).toContain(lng === 'zh' ? '手动' : 'Manual');
+ expect(modeCopy).toBeTruthy();
expect(mapping.textContent).toBe(mappingCopy);
});
it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 8, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.queryByText(/takeover/i)).toBeNull();
});
@@ -236,18 +237,19 @@ describe('AgentCard', () => {
it('hides current and takeover projections while the runtime is stopped', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };
- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 8, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Backup/)).toBeNull();
expect(screen.queryByText(/takeover/i)).toBeNull();
- expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);
+ expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(1);
+ expect(screen.getByRole('button', { name: 'Manual' })).toBeTruthy();
});
it('hides gateway-owned catalog and supply actions in direct mode', () => {
const onOpenModels = vi.fn();
const key = modelChainKey('claude', 'claude-opus-4-6');
const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 8, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Adjust priority/i)).toBeNull();
expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();
expect(screen.queryByText(/Backup/)).toBeNull();
@@ -259,8 +261,8 @@ describe('AgentCard', () => {
});
it.each([
- ['en', 'Adjust priority', 'Switch to direct', 'Switch to gateway'],
- ['zh', '调整优先级', '切到直连', '切换到模型网关'],
+ ['en', 'Default routing', 'Switch to direct', 'Switch to gateway'],
+ ['zh', '默认路由', '切到直连', '切换到模型网关'],
] as const)('uses explicit gateway action labels and icons in %s', async (lng, orderCopy, directCopy, gatewayCopy) => {
const directAgent: AgentSupply = {
...hubAgent,
@@ -312,7 +314,7 @@ describe('AgentCard', () => {
render(<I18nextProvider i18n={i18n}><AgentCard agents={[{
...hubAgent,
builtin_models: models,
- model_supply: models.map((modelId) => ({ model_id: modelId, chain_length: 1, has_runnable_hop: true })),
+ model_supply: models.map((modelId) => ({ route_origin: "manual" as const, model_id: modelId, chain_length: 1, has_runnable_hop: true })),
routes: {},
}]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={onProbeSettled} /></I18nextProvider>);
@@ -336,7 +338,7 @@ describe('AgentCard', () => {
...hubAgent,
builtin_models: models,
routes: {},
- model_supply: models.map((modelId) => ({
+ model_supply: models.map((modelId) => ({ route_origin: "manual" as const,
model_id: modelId,
chain_length: 1,
has_runnable_hop: modelId !== pausedModel,
@@ -355,7 +357,7 @@ describe('AgentCard', () => {
const catalogued = (ids: string[]): AgentSupply => ({
...hubAgent,
routes: {},
- model_supply: ids.map((modelId) => ({ model_id: modelId, chain_length: 0, has_runnable_hop: false })),
+ model_supply: ids.map((modelId) => ({ route_origin: null, model_id: modelId, chain_length: 0, has_runnable_hop: false })),
catalog_models: ids.map((id) => ({
id, display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null,
input_modalities: ['text'], output_modalities: ['text'], supports_tools: true, supports_reasoning: false,
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index e1ef9cafb..299ce6f98 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -3,6 +3,8 @@ import { ArrowDownUp, Check, ChevronDown, ChevronRight, ChevronUp, ListChecks, P
import { useTranslation } from 'react-i18next';
import { Badge } from '@/components/ui/badge';
+import { RouteOriginBadge } from './RouteOriginBadge';
+import { modelRouteOrigin } from './modelRows';
import { Button } from '@/components/ui/button';
import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
@@ -67,11 +69,7 @@ const ModelRow: React.FC<{
const takeover = isTakeoverRead(read);
const supplyState = modelSupplyState(agent, modelId);
const resolved = read?.kind === 'ready' && current !== null;
- const mode = resolved
- ? current.channel === 'native_cli'
- ? t('settings.models.legend.native') as string
- : t('settings.models.gateway.group.mode.gateway') as string
- : '—';
+ const routeOrigin = modelRouteOrigin(agent, modelId);
const currentSource = resolved ? sourceName(sources, current.source_id) : '';
const currentCopy = supplyState === 'paused'
? t('settings.models.legend.unavailable') as string
@@ -88,18 +86,16 @@ const ModelRow: React.FC<{
? t('settings.models.routeDialog.openWithMapping', { model: modelId, mapping: currentCopy }) as string
: t('settings.models.routeDialog.open', { model: modelId }) as string;
return (
- <button
- type="button"
+ <div
data-route-backend={agent.backend}
data-route-model={modelId}
- onClick={(event) => onOpenRoute(agent, modelId, event.currentTarget)}
- aria-label={openRouteLabel}
- className="model-hub-model-row flex h-9 w-full min-w-0 items-center gap-2.5 overflow-hidden rounded-md border border-border px-3 text-left"
+ className="model-hub-model-row relative flex h-9 w-full min-w-0 items-center gap-2.5 rounded-md border border-border px-3 text-left"
>
- <span className="flex min-w-0 flex-1 items-center justify-between gap-2.5">
+ <button type="button" className="model-hub-model-open absolute inset-0 rounded-[inherit]" aria-label={openRouteLabel} onClick={(event) => onOpenRoute(agent, modelId, event.currentTarget)} />
+ <span className="pointer-events-none flex min-w-0 flex-1 items-center justify-between gap-2.5">
<span className="min-w-0 flex-1 truncate font-mono text-[12px] font-medium text-foreground" title={modelId}>{modelId}</span>
<span className="flex min-w-0 flex-1 items-center justify-end gap-[7px]">
- <span className="model-hub-pill model-hub-model-mode-chip shrink-0 border border-border text-muted">{mode}</span>
+ <span className="pointer-events-auto relative shrink-0"><RouteOriginBadge origin={routeOrigin} backend={agent.backend} /></span>
{hasCurrentMapping ? (
<span
className={cn('model-hub-model-current min-w-0 flex-1 truncate text-right text-[10.5px]', takeover && 'model-hub-model-current--takeover')}
@@ -113,8 +109,8 @@ const ModelRow: React.FC<{
)}
</span>
</span>
- <ChevronRight className="model-hub-overview-chevron size-[15px] shrink-0" aria-hidden="true" />
- </button>
+ <ChevronRight className="model-hub-overview-chevron pointer-events-none size-[15px] shrink-0" aria-hidden="true" />
+ </div>
);
};
diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
index 2856b5897..8879545a9 100644
--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
@@ -34,7 +34,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 8,
+ contract_version: 9,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
index 4bfac5c92..bfde134fe 100644
--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
@@ -10,7 +10,7 @@ import { modelsApi } from './modelsApi';
import type { RuntimeDependency } from './types';
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 8,
+ contract_version: 9,
manifest: {
name: 'cliproxyapi',
resolution: 'resolved',
diff --git a/ui/src/components/settings/models/RouteCandidatePopover.tsx b/ui/src/components/settings/models/RouteCandidatePopover.tsx
index 41fdfb827..31c210f8b 100644
--- a/ui/src/components/settings/models/RouteCandidatePopover.tsx
+++ b/ui/src/components/settings/models/RouteCandidatePopover.tsx
@@ -2,6 +2,8 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Field } from './dialogFields';
import {
Command,
CommandEmpty,
@@ -24,6 +26,7 @@ const candidateKey = (hop: RouteHop): string =>
export const RouteCandidatePopover: React.FC<{
candidates: RouteCandidate[];
+ sources: Source[];
confirmLabel: string;
initialHop?: RouteHop;
label: string;
@@ -33,6 +36,7 @@ export const RouteCandidatePopover: React.FC<{
width: "route" | "trigger";
}> = ({
candidates,
+ sources,
confirmLabel,
initialHop,
label,
@@ -45,6 +49,8 @@ export const RouteCandidatePopover: React.FC<{
const [open, setOpen] = React.useState(false);
const [query, setQuery] = React.useState("");
const [candidate, setCandidate] = React.useState<RouteCandidate | null>(null);
+ const [customModel, setCustomModel] = React.useState('');
+ const [customSource, setCustomSource] = React.useState('');
const searchRef = React.useRef<HTMLInputElement | null>(null);
const pendingCandidateRef = React.useRef<RouteCandidate | null>(null);
const term = query.trim().toLowerCase();
@@ -67,10 +73,17 @@ export const RouteCandidatePopover: React.FC<{
else result.push({ source: item.source, items: [item] });
return result;
}, []);
+ const typedSources = sources.filter((source) => source.kind === 'api_key');
+ const typedSource = typedSources.find((source) => source.id === customSource);
+ const typedCandidate: RouteCandidate | null = customModel && typedSource
+ && customModel === customModel.trim()
+ && !typedSource.models.some((model) => model.id === customModel && model.retired)
+ ? { source: typedSource, hop: { source_id: typedSource.id, model_id: customModel } } : null;
+ const selected = customModel ? typedCandidate : candidate;
const unchanged =
- candidate !== null &&
+ selected !== null &&
initialHop !== undefined &&
- candidateKey(candidate.hop) === candidateKey(initialHop);
+ candidateKey(selected.hop) === candidateKey(initialHop);
React.useEffect(() => {
if (!open) return;
@@ -99,6 +112,8 @@ export const RouteCandidatePopover: React.FC<{
open={open}
onOpenChange={(nextOpen) => {
if (nextOpen) {
+ setCustomModel('');
+ setCustomSource(typedSources.find((source) => source.id === initialHop?.source_id)?.id ?? typedSources[0]?.id ?? '');
setQuery("");
setCandidate(
(initialHop
@@ -182,7 +197,7 @@ export const RouteCandidatePopover: React.FC<{
<CommandItem
key={candidateKey(item.hop)}
value={candidateKey(item.hop)}
- onSelect={() => setCandidate(item)}
+ onSelect={() => { setCustomModel(''); setCandidate(item); }}
className="model-hub-route-candidate model-hub-route-selector-row text-foreground"
>
<span className="model-hub-route-candidate-source truncate">
@@ -196,14 +211,20 @@ export const RouteCandidatePopover: React.FC<{
</CommandGroup>
))}
</CommandList>
+ {typedSources.length > 0 && <div className="model-hub-route-custom border-t border-border">
+ <Field label={t('settings.models.routeDialog.add.source')}>{(id) => <select id={id} value={customSource} onChange={(event) => setCustomSource(event.target.value)}>
+ {typedSources.map((source) => <option key={source.id} value={source.id}>{source.display_name}</option>)}
+ </select>}</Field>
+ <Field label={t('settings.models.routing.exactModel')}>{(id) => <Input id={id} value={customModel} onChange={(event) => setCustomModel(event.target.value)} placeholder={t('settings.models.routing.exactModel')} />}</Field>
+ </div>}
<div className="model-hub-route-selector-foot flex shrink-0 items-center justify-end border-t border-border">
<Button
type="button"
className="model-hub-route-selector-confirm px-4"
- disabled={!candidate || unchanged}
+ disabled={!selected || unchanged}
onClick={() => {
- if (!candidate || unchanged) return;
- pendingCandidateRef.current = candidate;
+ if (!selected || unchanged) return;
+ pendingCandidateRef.current = selected;
setOpen(false);
setQuery("");
setCandidate(null);
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 7d93fda5b..178005a40 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -51,8 +51,8 @@ const sources: Source[] = [
models: [],
},
];
-const chain: AgentChain = {
- contract_version: 8,
+const chain: AgentChain = { manual_override: {hops:[{source_id:"src_a",model_id:"claude-opus-5"},{source_id:"src_b",model_id:"opus-5"}]}, route_origin: "manual" as const,
+ contract_version: 9,
backend: "claude",
model_id: "opus-5",
current: { source_id: "src_b", model_id: "opus-5" },
@@ -166,6 +166,7 @@ const renderDialog = (onCommitted = vi.fn(), onClose = vi.fn()) => {
};
beforeEach(() => {
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(null);
// cmdk observes its list box and scrolls the active row into view; jsdom
// implements neither.
vi.stubGlobal(
@@ -186,11 +187,211 @@ afterEach(() => {
});
describe("RouteChainDialog", () => {
- it("matches a suspended Direct attempt only by its exact ordered pairs", () => {
+ describe('manual edit capability from an empty inherited route', () => {
+ const inherited: AgentChain = {
+ ...chain,
+ manual_override: null,
+ route_origin: null,
+ current: null,
+ chain: [],
+ supply_state: 'interrupted',
+ };
+ const alternateSubscription: Source = {
+ ...sources[1],
+ models: [{ id: 'sonnet-5', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null }],
+ };
+ const renderEmptyRoute = (nextAgent: AgentSupply, nextSources: Source[], initial = inherited) => {
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(initial);
+ render(<I18nextProvider i18n={i18n}><RouteChainDialog
+ selection={{ agent: nextAgent, modelId: inherited.model_id, read: readyRegion(initial) }}
+ sources={nextSources}
+ onClose={vi.fn()}
+ onOpenDefaults={vi.fn()}
+ readAgents={vi.fn()}
+ readSources={vi.fn()}
+ /></I18nextProvider>);
+ };
+
+ it('selects another known subscription model and saves the exact manual mapping', async () => {
+ const user = userEvent.setup();
+ const hop = { source_id: alternateSubscription.id, model_id: 'sonnet-5' };
+ const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue(mutation({
+ ...chain, manual_override: { hops: [hop] }, current: hop, chain: [{ ...chain.chain[1], ...hop }],
+ }));
+ renderEmptyRoute({ ...agent, sources: {
+ order: [alternateSubscription.id], eligibility: [{ source_id: alternateSubscription.id, eligible: true }],
+ } }, [alternateSubscription]);
+
+ await user.click(await screen.findByRole('button', { name: 'Edit route' }));
+ await user.click(screen.getByRole('button', { name: 'Add a hop' }));
+ await user.click(screen.getByRole('option', { name: /sonnet-5/ }));
+ await user.click(screen.getByRole('button', { name: 'Add' }));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(put).toHaveBeenCalledWith('claude', 'opus-5', { hops: [hop] }));
+ });
+
+ it('allows an eligible API key outside defaults to save an exact unlisted target', async () => {
+ const user = userEvent.setup();
+ const hop = { source_id: sources[0].id, model_id: 'unlisted-model' };
+ const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue(mutation({
+ ...chain, manual_override: { hops: [hop] }, current: hop,
+ chain: [{ ...chain.chain[0], ...hop, health: 'healthy', runnable: true, retry_at: null }],
+ }));
+ renderEmptyRoute({ ...agent, sources: {
+ order: [], eligibility: [{ source_id: sources[0].id, eligible: true }],
+ } }, [sources[0]]);
+
+ await user.click(await screen.findByRole('button', { name: 'Edit route' }));
+ await user.click(screen.getByRole('button', { name: 'Add a hop' }));
+ await user.type(screen.getByLabelText('Exact model ID'), hop.model_id);
+ await user.click(screen.getByRole('button', { name: 'Add' }));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(put).toHaveBeenCalledWith('claude', 'opus-5', { hops: [hop] }));
+ expect(sources[0].models).toEqual([]);
+ });
+
+ it.each([
+ { name: 'no sources', available: [], eligible: true },
+ { name: 'an eligible subscription with no known models', available: [sources[1]], eligible: true },
+ { name: 'an eligible subscription with only retired models', available: [{ ...alternateSubscription, models: alternateSubscription.models.map((model) => ({ ...model, retired: true })) }], eligible: true },
+ { name: 'ineligible API-key and subscription sources', available: [sources[0], alternateSubscription], eligible: false },
+ ])('keeps the unconfigured view without Edit for $name', async ({ available, eligible }) => {
+ renderEmptyRoute({ ...agent, sources: {
+ order: [], eligibility: available.map((source) => ({ source_id: source.id, eligible })),
+ } }, available);
+
+ await screen.findByRole('button', { name: 'Configure default routing' });
+ expect(screen.queryByRole('button', { name: 'Edit route' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Restore automatic' })).toBeNull();
+ });
+
+ it('retains restore and undo for a saved manual-empty route without admissible targets', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain').mockResolvedValue(mutation(inherited));
+ const put = vi.spyOn(modelsApi, 'putAgentChain');
+ renderEmptyRoute({ ...agent, sources: { order: [], eligibility: [] } }, [], {
+ ...inherited, manual_override: { hops: [] },
+ });
+
+ await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
+ await user.click(await screen.findByRole('button', { name: 'Undo restore' }));
+ expect(screen.queryByRole('button', { name: 'Edit route' })).toBeNull();
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
+ await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
+ await screen.findByRole('button', { name: 'Undo restore' });
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(restore).toHaveBeenCalledWith('claude', 'opus-5', undefined));
+ expect(put).not.toHaveBeenCalled();
+ });
+ });
+
+ it('refreshes inherited routing after returning from Default routing', async () => {
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
+ const next: AgentChain = { ...inherited, chain: [chain.chain[1]] };
+ const read = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValueOnce(inherited).mockResolvedValue(next);
+ const props = { selection: { agent, modelId: 'opus-5', read: readyRegion(inherited) }, sources, onClose: vi.fn(), readAgents: vi.fn(), readSources: vi.fn() };
+ const view = (covered: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog {...props} covered={covered} /></I18nextProvider>;
+ const { rerender } = render(view(false));
+ await screen.findByRole('button', { name: 'Edit route' });
+ rerender(view(true));
+ rerender(view(false));
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(1));
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ });
+
+ it('refreshes restore preview without losing the earlier manual draft', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValueOnce(inherited).mockResolvedValue({ ...inherited, chain: [chain.chain[0]] });
+ const props = { selection: { agent, modelId: 'opus-5', read: readyRegion(chain) }, sources, onClose: vi.fn(), readAgents: vi.fn(), readSources: vi.fn() };
+ const view = (covered: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog {...props} covered={covered} /></I18nextProvider>;
+ const { rerender } = render(view(false));
+ await screen.findAllByRole('button', { name: 'Remove hop' });
+ await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
+ await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
+ await screen.findByRole('button', { name: 'Undo restore' });
+ rerender(view(true));
+ rerender(view(false));
+ await waitFor(() => expect(preview).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(1));
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('claude-opus-5');
+ await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ });
+
+ it('previews restore, undoes to the unsaved manual draft, and cancels without writing', async () => {
+ const user = userEvent.setup();
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'passthrough' };
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
+ const put = vi.spyOn(modelsApi, 'putAgentChain');
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
+ const close = vi.fn();
+ renderDialog(vi.fn(), close);
+ await screen.findAllByRole('button', { name: 'Remove hop' });
+ await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
+ await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
+ await screen.findByText('After restore: original-name passthrough');
+ expect(preview).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: null });
+ expect(screen.queryByRole('button', { name: 'Remove hop' })).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(1);
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ await user.click(screen.getAllByRole('button', { name: 'Cancel' }).at(-1)!);
+ expect(close).toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ expect(restore).not.toHaveBeenCalled();
+ });
+
+ it('saves restored intent with DELETE even when automatic hops equal the manual hops', async () => {
+ const user = userEvent.setup();
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
+ vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain').mockResolvedValue(mutation(inherited));
+ const put = vi.spyOn(modelsApi, 'putAgentChain');
+ renderDialog();
+ await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
+ await screen.findByRole('button', { name: 'Undo restore' });
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(restore).toHaveBeenCalledWith('claude', 'opus-5', undefined));
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it('saving an explicit edit of identical inherited hops creates manual intent', async () => {
+ const user = userEvent.setup();
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
+ renderDialog();
+ vi.mocked(modelsApi.getAgentChain).mockResolvedValue(inherited);
+ // Reopen on a fresh mount so the initial read observes inherited intent.
+ cleanup();
+ const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue(mutation(chain));
+ render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(inherited) }} sources={[]} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
+ await user.click(await screen.findByRole('button', { name: 'Edit route' }));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(put).toHaveBeenCalledWith('claude', 'opus-5', { hops: chain.manual_override!.hops }));
+ });
+
+ it('accepts an exact unlisted API-key target without creating inventory', async () => {
+ const user = userEvent.setup();
+ renderStockedDialog();
+ await user.click(await screen.findByRole('button', { name: 'Add a hop' }));
+ expect(screen.getByLabelText('Source').querySelectorAll('option')).toHaveLength(1);
+ await user.type(screen.getByLabelText('Exact model ID'), 'unlisted-model');
+ await user.click(screen.getByRole('button', { name: 'Add' }));
+ expect([...document.querySelectorAll('.model-hub-route-hop-model')].at(-1)?.textContent).toBe('unlisted-model');
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
+ });
+ it("matches a suspended Direct attempt by persisted intent and ordered pairs", () => {
const attempt = {
backend: "claude" as const,
modelId: "opus-5",
stage: "initial" as const,
+ manual_override: { hops: [{ source_id: "src_b", model_id: "opus-5" }, { source_id: "src_a", model_id: "claude-opus-5" }] },
submitted: [
{ source_id: "src_b", model_id: "opus-5" },
{ source_id: "src_a", model_id: "claude-opus-5" },
@@ -200,6 +401,7 @@ describe("RouteChainDialog", () => {
routeChainMatchesAttempt(
{
...chain,
+ manual_override: attempt.manual_override,
chain: [chain.chain[1], chain.chain[0]],
},
attempt,
@@ -456,6 +658,7 @@ describe("RouteChainDialog", () => {
const user = userEvent.setup();
const committedChain: AgentChain = {
...chain,
+ manual_override: { hops: [{ source_id: "src_b", model_id: "opus-5" }] },
current: { source_id: "src_b", model_id: "opus-5" },
chain: [chain.chain[1]],
};
@@ -482,6 +685,7 @@ describe("RouteChainDialog", () => {
const user = userEvent.setup();
const observed: AgentChain = {
...chain,
+ manual_override: { hops: [{ source_id: "src_a", model_id: "claude-opus-5" }] },
chain: [chain.chain[0]],
current: null,
supply_state: "interrupted",
@@ -521,6 +725,7 @@ describe("RouteChainDialog", () => {
const user = userEvent.setup();
const nonmatching: AgentChain = {
...chain,
+ manual_override: { hops: [{ source_id: "src_a", model_id: "claude-opus-5" }] },
chain: [chain.chain[0]],
current: null,
supply_state: "interrupted",
@@ -602,7 +807,7 @@ describe("RouteChainDialog", () => {
const refreshedSources = editableSources.map((source) =>
source.id === "src_a"
- ? { ...source, models: source.models.slice(0, 1) }
+ ? { ...source, models: source.models.map((model, index) => index === 0 ? model : { ...model, retired: true }) }
: source,
);
page.rerender(
@@ -634,7 +839,7 @@ describe("RouteChainDialog", () => {
await user.click(screen.getByRole("button", { name: "Add a hop" }));
- expect(screen.getByText("Source")).toBeTruthy();
+ expect(screen.getAllByText("Source").length).toBeGreaterThan(0);
expect(screen.getByText("Model")).toBeTruthy();
// Both halves of a candidate are legible: the model id AND which source
// supplies it. The source column is what a sizing rework once dropped, so
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index 831349f3a..33b98bf7f 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -7,6 +7,9 @@ import {
LoaderCircle,
Pencil,
Plus,
+ RefreshCw,
+ RotateCcw,
+ Undo2,
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -15,12 +18,15 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { GuardGapList } from "./GuardGapList";
import { RouteCandidatePopover } from "./RouteCandidatePopover";
+import { RouteOriginBadge } from "./RouteOriginBadge";
+import { RouteRecordedTurn } from './RouteRecordedTurn';
+import { eligibleSources } from "./eligibility";
import { equalHopIdentity, hopBelongsToSource } from "./hopIdentity";
import { apiFailure, modelsApi, type GuardConfirmation } from "./modelsApi";
import type { ModelChainRead } from "./modelRows";
import {
routeCandidates,
- reorderRouteDraft,
+ sameManualOverride,
sameRouteDraft,
validateRouteDraft,
type RouteCandidate,
@@ -36,6 +42,8 @@ import type {
RouteHop,
RouteHopRef,
Source,
+ ManualRouteOverride,
+ AgentChain,
} from "./types";
const sourceName = (sources: Source[], sourceId: string): string =>
@@ -85,6 +93,7 @@ export type SuspendedRouteAttempt = {
modelId: string;
stage: "initial" | "confirmed";
submitted: RouteHop[];
+ manual_override: ManualRouteOverride | null;
};
export const RouteChainDialog: React.FC<{
@@ -94,6 +103,8 @@ export const RouteChainDialog: React.FC<{
onCommitted?: (result: RouteReport) => void;
commitReconciliation?: RouteCommitReconciliation | null;
onObserved?: (chain: AgentChainMutation["chain"]) => void;
+ onOpenDefaults?: () => void;
+ covered?: boolean;
readAgents: () => Promise<RouteCollectionObservation<AgentSupply[]>>;
readSources: () => Promise<RouteCollectionObservation<Source[]>>;
onDirectMode?: (
@@ -107,6 +118,8 @@ export const RouteChainDialog: React.FC<{
onCommitted,
commitReconciliation,
onObserved,
+ onOpenDefaults,
+ covered = false,
readAgents,
readSources,
onDirectMode,
@@ -114,6 +127,14 @@ export const RouteChainDialog: React.FC<{
const { t } = useTranslation();
const [phase, setPhase] = React.useState<Phase>("loading");
const [origin, setOrigin] = React.useState<RouteHop[]>([]);
+ const [savedOverride, setSavedOverride] = React.useState<ManualRouteOverride | null>(null);
+ const [manualDraft, setManualDraft] = React.useState(false);
+ const [preview, setPreview] = React.useState<AgentChain | null>(null);
+ const [previewPending, setPreviewPending] = React.useState(false);
+ const [previewFailed, setPreviewFailed] = React.useState(false);
+ const previewGeneration = React.useRef(0);
+ const restoreUndo = React.useRef<RouteHop[] | null>(null);
+ const submittedOverride = React.useRef<ManualRouteOverride | null>(null);
const interactionRef = React.useRef(createRouteChainInteraction());
const [interaction, setInteraction] = React.useState(interactionRef.current);
const [chain, setChain] = React.useState<AgentChainMutation["chain"] | null>(
@@ -149,6 +170,7 @@ export const RouteChainDialog: React.FC<{
const openedIdentity = React.useRef<string | null>(null);
const invalidSignature = React.useRef("");
const generation = React.useRef(0);
+ React.useEffect(() => () => { generation.current += 1; previewGeneration.current += 1; }, []);
const agent = selection?.agent ?? null;
const modelId = selection?.modelId ?? "";
@@ -166,6 +188,9 @@ export const RouteChainDialog: React.FC<{
[],
);
const addCandidates = agent ? routeCandidates(agent, sources, draft) : [];
+ const targetSources = agent ? eligibleSources(sources, agent) : [];
+ const canEditRoute = draft.length > 0 || addCandidates.length > 0
+ || targetSources.some((source) => source.kind === 'api_key');
const backend = agent
? (t(`settings.models.backends.${agent.backend}`, {
defaultValue: agent.backend,
@@ -174,7 +199,8 @@ export const RouteChainDialog: React.FC<{
const valid = agent
? validateRouteDraft(agent, sources, origin, draft)
: { invalidIndexes: [], valid: false };
- const dirty = !sameRouteDraft(origin, draft);
+ const dirty = manualDraft ? savedOverride === null || !sameRouteDraft(savedOverride.hops, draft) : savedOverride !== null;
+ const draftOrigin = manualDraft ? (draft.length ? 'manual' : null) : (preview ?? chain)?.route_origin ?? null;
const announce = (key: string, params?: Record<string, unknown>) =>
setAnnouncement({ key, params });
const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {
@@ -193,6 +219,10 @@ export const RouteChainDialog: React.FC<{
model_id,
}));
setChain(next);
+ setSavedOverride(next.manual_override);
+ setManualDraft(next.manual_override !== null);
+ setPreview(null);
+ setPreviewFailed(false);
onObserved?.(next);
setOrigin(hops);
advanceInteraction({ type: "reset", draft: hops, focusIndex: 0 });
@@ -217,6 +247,11 @@ export const RouteChainDialog: React.FC<{
if (nextIdentity === openedIdentity.current) return;
openedIdentity.current = nextIdentity;
generation.current += 1;
+ previewGeneration.current += 1;
+ restoreUndo.current = null;
+ setPreview(null);
+ setPreviewPending(false);
+ setPreviewFailed(false);
setGuard(null);
setSubmitted(null);
setSubmittedStage("initial");
@@ -274,6 +309,7 @@ export const RouteChainDialog: React.FC<{
return;
}
if (phase !== "saving") {
+ previewGeneration.current += 1;
if (phase !== "impact" && phase !== "refreshing") {
generation.current += 1;
}
@@ -387,6 +423,10 @@ export const RouteChainDialog: React.FC<{
) => {
generation.current += 1;
setChain(nextReport.chain);
+ setSavedOverride(nextReport.chain.manual_override);
+ setManualDraft(nextReport.chain.manual_override !== null);
+ setPreview(null);
+ restoreUndo.current = null;
setReport(nextReport);
setOrigin(committedHops);
advanceInteraction({ type: "reset", draft: committedHops });
@@ -402,34 +442,35 @@ export const RouteChainDialog: React.FC<{
};
const submit = async (confirmation?: GuardState) => {
- if (!selection || !agent || phase === "saving" || !valid.valid || !dirty)
+ if (!selection || !agent || phase === "saving" || previewPending || (!manualDraft && previewFailed) || (manualDraft && !valid.valid) || !dirty)
return;
const hops = (confirmation ? (submitted ?? draft) : draft).map((hop) => ({
...hop,
}));
setSubmitted(hops);
+ if (!confirmation) submittedOverride.current = manualDraft ? { hops } : null;
setSubmittedStage(confirmation ? "confirmed" : "initial");
setPhase("saving");
setGuard(null);
requestAnimationFrame(() => savingStatusRef.current?.focus());
try {
- const result = await modelsApi.putAgentChain(agent.backend, modelId, {
- hops,
- ...(confirmation
+ const guardFields = confirmation
? {
force: true as const,
would_remove_hops: confirmation.hops,
would_interrupt: confirmation.gaps,
}
- : {}),
- });
+ : {};
+ const result = submittedOverride.current === null
+ ? await modelsApi.restoreAgentChain(agent.backend, modelId, confirmation ? guardFields as GuardConfirmation : undefined)
+ : await modelsApi.putAgentChain(agent.backend, modelId, { hops, ...guardFields });
beginCommitted(
{
chain: result.chain,
removed_hops: result.removed_hops,
interrupted: result.interrupted,
},
- hops,
+ result.chain.chain.map(({ source_id, model_id }) => ({ source_id, model_id })),
);
} catch (error) {
const failure = apiFailure(error);
@@ -441,14 +482,15 @@ export const RouteChainDialog: React.FC<{
modelId,
stage: confirmation ? "confirmed" : "initial",
submitted: hops,
+ manual_override: submittedOverride.current,
},
null,
);
return;
}
if (
- failure?.code === "source_last_supplier" &&
- failure.wouldInterrupt.length > 0
+ (failure?.code === "source_last_supplier" || failure?.code === 'source_in_route_chain') &&
+ (failure.wouldInterrupt.length > 0 || failure.wouldRemoveHops.length > 0)
) {
setGuard({
hops: failure.wouldRemoveHops,
@@ -508,6 +550,7 @@ export const RouteChainDialog: React.FC<{
modelId,
stage: submittedStage,
submitted,
+ manual_override: submittedOverride.current,
},
observedAgent ?? null,
);
@@ -527,7 +570,7 @@ export const RouteChainDialog: React.FC<{
const observedHops = chainAnswer.value.chain.map(
({ source_id, model_id }) => ({ source_id, model_id }),
);
- if (sameRouteDraft(observedHops, submitted)) {
+ if (sameManualOverride(chainAnswer.value.manual_override, submittedOverride.current)) {
beginCommitted(
{
chain: chainAnswer.value,
@@ -594,6 +637,7 @@ export const RouteChainDialog: React.FC<{
modelId,
stage: submittedStage,
submitted,
+ manual_override: submittedOverride.current,
},
observedAgent,
);
@@ -618,6 +662,44 @@ export const RouteChainDialog: React.FC<{
const next = advanceInteraction({ type: "append", hop: candidate.hop });
requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
};
+ const restoreAutomatic = React.useCallback(async () => {
+ if (!agent || previewPending || phase !== 'ready') return;
+ const token = ++previewGeneration.current;
+ const previousDraft = draft.map((hop) => ({ ...hop }));
+ setPreviewPending(true);
+ setPreviewFailed(false);
+ try {
+ const next = await modelsApi.previewAgentChain(agent.backend, modelId, { manual_override: null });
+ if (token !== previewGeneration.current) return;
+ if (manualDraft) restoreUndo.current = previousDraft;
+ setPreview(next);
+ setManualDraft(false);
+ advanceInteraction({ type: 'reset', draft: next.chain.map(({ source_id, model_id }) => ({ source_id, model_id })) });
+ setAnnouncement({ key: 'settings.models.routing.restorePending' });
+ } catch {
+ if (token === previewGeneration.current) setPreviewFailed(true);
+ } finally {
+ if (token === previewGeneration.current) setPreviewPending(false);
+ }
+ }, [advanceInteraction, agent, draft, manualDraft, modelId, phase, previewPending]);
+ const wasCovered = React.useRef(covered);
+ React.useEffect(() => {
+ const returning = wasCovered.current && !covered;
+ wasCovered.current = covered;
+ if (!returning || manualDraft) return;
+ // Defaults can change while this dialog is hidden; explicit drafts remain local.
+ if (restoreUndo.current) void restoreAutomatic();
+ else void readChain();
+ }, [covered, manualDraft, readChain, restoreAutomatic]);
+ const undoRestore = () => {
+ previewGeneration.current += 1;
+ setPreview(null);
+ setPreviewFailed(false);
+ setManualDraft(true);
+ advanceInteraction({ type: 'reset', draft: restoreUndo.current ?? origin });
+ restoreUndo.current = null;
+ announce('settings.models.routing.undoDone');
+ };
const renderHop = (hop: RouteHop, index: number) => {
const chainLink = chain?.chain.find((entry) =>
equalHopIdentity(entry, hop),
@@ -727,6 +809,7 @@ export const RouteChainDialog: React.FC<{
<RouteCandidatePopover
key={`edit:${selectorEpoch}:${index}`}
candidates={replacementCandidates}
+ sources={targetSources}
confirmLabel={t("settings.models.routeDialog.edit.confirm") as string}
initialHop={hop}
label={t("settings.models.routeDialog.editHop") as string}
@@ -939,20 +1022,38 @@ export const RouteChainDialog: React.FC<{
</div>
) : (
<div className="model-hub-route-body flex flex-col">
+ <div className="model-hub-route-origin-line">
+ <RouteOriginBadge origin={draftOrigin} backend={agent!.backend} interactive={false} />
+ <span>{t(manualDraft ? 'settings.models.routing.frozen' : 'settings.models.routing.follows', { backend })}</span>
+ </div>
+ {preview && <div className="model-hub-route-preview" data-origin={preview.route_origin ?? 'unconfigured'} role="status">
+ <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`)}</strong>
+ <span>{t('settings.models.routing.restorePending')}</span>
+ </div>}
<h3 className="model-hub-route-label font-bold">
- {t("settings.models.routeDialog.section")}
+ {t(preview ? 'settings.models.routing.afterSave' : "settings.models.routeDialog.section")}
</h3>
- <div className="model-hub-route-list flex flex-col border border-border bg-background">
+ <div inert={previewPending} className="model-hub-route-list flex flex-col border border-border bg-background">
{draft.length ? (
- draft.map(renderHop)
+ manualDraft ? draft.map(renderHop) : draft.map((hop, index) => (
+ <div key={`${hop.source_id}:${hop.model_id}`} className="model-hub-route-hop model-hub-fill-08 flex items-center border border-border">
+ <span className="model-hub-route-ordinal grid shrink-0 place-items-center font-mono" data-origin={draftOrigin ?? 'unconfigured'}>{index + 1}</span>
+ <span className="model-hub-route-hop-copy flex min-w-0 flex-1 flex-col">
+ <span className="model-hub-route-hop-name truncate font-semibold" title={sourceName(sources, hop.source_id)}>{sourceName(sources, hop.source_id)}</span>
+ <span className="model-hub-route-hop-model truncate font-mono text-muted" title={hop.model_id}>{hop.model_id}</span>
+ </span>
+ </div>
+ ))
) : (
<div className="model-hub-route-empty text-xs text-muted">
- {t("settings.models.routeDialog.empty")}
+ <p>{t(manualDraft ? 'settings.models.routing.manualEmpty' : 'settings.models.routing.noDefaults')}</p>
+ {!manualDraft && onOpenDefaults && <Button variant="outline" onClick={onOpenDefaults}><ListOrdered aria-hidden />{t('settings.models.routing.configureDefaults')}</Button>}
</div>
)}
- <RouteCandidatePopover
+ {manualDraft && <RouteCandidatePopover
key={`add:${selectorEpoch}`}
candidates={addCandidates}
+ sources={targetSources}
confirmLabel={t("settings.models.routeDialog.add.confirm") as string}
label={t("settings.models.routeDialog.addHop") as string}
width="trigger"
@@ -962,7 +1063,7 @@ export const RouteChainDialog: React.FC<{
<button
ref={addButtonRef}
type="button"
- disabled={addCandidates.length === 0}
+ disabled={targetSources.length === 0 || previewPending}
aria-describedby={
addCandidates.length === 0
? "model-hub-route-add-none"
@@ -974,25 +1075,13 @@ export const RouteChainDialog: React.FC<{
{t("settings.models.routeDialog.addHop")}
</button>
}
- />
+ />}
</div>
- <button
- ref={reseedButtonRef}
- type="button"
- onClick={() => {
- const sorted = reorderRouteDraft(agent as AgentSupply, draft);
- advanceInteraction({ type: "reset", draft: sorted });
- announce(
- sameRouteDraft(sorted, draft)
- ? "settings.models.routeDialog.reorder.unchanged"
- : "settings.models.routeDialog.reorder.sorted",
- );
- }}
- className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan-ink"
- >
+ {onOpenDefaults && <button type="button" disabled={previewPending} onClick={onOpenDefaults} className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan-ink">
<ListOrdered aria-hidden="true" />
- {t("settings.models.routeDialog.reorder.label")}
- </button>
+ {t('settings.models.routing.defaultRouting')}
+ <span className="text-muted">{(agent?.sources?.order ?? []).map((id) => sourceName(sources, id)).join(' → ')}</span>
+ </button>}
{addCandidates.length === 0 && (
<span className="sr-only" id="model-hub-route-add-none">
{t("settings.models.routeDialog.add.none")}
@@ -1001,9 +1090,10 @@ export const RouteChainDialog: React.FC<{
<p className="model-hub-route-hint flex items-start">
<Info aria-hidden="true" className="shrink-0" />
<span className="model-hub-route-hint-copy">
- {t("settings.models.routeDialog.hint")}
+ {t(manualDraft ? 'settings.models.routing.manualHint' : 'settings.models.routing.editHint')}
</span>
</p>
+ {previewFailed && <div role="alert" className="text-destructive-ink text-xs"><p>{t('settings.models.routing.previewFailed')}</p><Button variant="ghost" size="sm" disabled={previewPending} onClick={() => void restoreAutomatic()}><RefreshCw aria-hidden />{t('settings.models.routeDialog.retry')}</Button></div>}
{valid.invalidIndexes.length > 0 && (
<p
id="model-hub-route-invalid-summary"
@@ -1019,7 +1109,7 @@ export const RouteChainDialog: React.FC<{
);
return (
- <DialogPrimitive.Root open onOpenChange={(open) => !open && close()}>
+ <DialogPrimitive.Root open={!covered} onOpenChange={(open) => !open && close()}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="model-hub-route-overlay fixed inset-0 z-50" />
<DialogPrimitive.Content
@@ -1073,6 +1163,7 @@ export const RouteChainDialog: React.FC<{
</DialogPrimitive.Description>
</header>
{body}
+ <RouteRecordedTurn key={`${selectionBackend}:${modelId}`} backend={selectionBackend!} modelId={modelId} />
<footer className="model-hub-route-foot model-hub-fill-05 flex items-center justify-end gap-2 border-t border-border">
{phase === "impact" || phase === "refreshing" ? (
<Button
@@ -1113,6 +1204,10 @@ export const RouteChainDialog: React.FC<{
</span>
) : (
<>
+ {(manualDraft || restoreUndo.current) && <Button ref={reseedButtonRef} variant="outline" className="model-hub-dialog-action mr-auto" disabled={phase !== 'ready' || previewPending} onClick={() => restoreUndo.current ? undoRestore() : void restoreAutomatic()}>
+ {previewPending ? <LoaderCircle className="animate-spin" aria-hidden /> : restoreUndo.current ? <Undo2 aria-hidden /> : <RotateCcw aria-hidden />}
+ {t(restoreUndo.current ? 'settings.models.routing.undoRestore' : 'settings.models.routing.restoreAutomatic')}
+ </Button>}
<Button
ref={cancelButtonRef}
type="button"
@@ -1120,9 +1215,9 @@ export const RouteChainDialog: React.FC<{
className="model-hub-dialog-action"
onClick={close}
>
- {t("settings.models.routeDialog.cancel")}
+ {t(manualDraft || preview ? "settings.models.routeDialog.cancel" : 'settings.models.routing.close')}
</Button>
- <Button
+ {!manualDraft && !preview ? (canEditRoute && <Button variant="outline" className="model-hub-dialog-action" disabled={phase !== 'ready'} onClick={() => setManualDraft(true)}><Pencil aria-hidden />{t('settings.models.routing.editRoute')}</Button>) : <Button
ref={saveButtonRef}
type="button"
className="model-hub-dialog-action"
@@ -1136,11 +1231,11 @@ export const RouteChainDialog: React.FC<{
].join(" ")
: undefined
}
- disabled={phase !== "ready" || !dirty || !valid.valid}
+ disabled={phase !== "ready" || previewPending || (!manualDraft && previewFailed) || !dirty || (manualDraft && !valid.valid)}
onClick={() => void submit()}
>
{t("settings.models.routeDialog.save")}
- </Button>
+ </Button>}
</>
)}
</footer>
diff --git a/ui/src/components/settings/models/RouteOriginBadge.test.tsx b/ui/src/components/settings/models/RouteOriginBadge.test.tsx
new file mode 100644
index 000000000..388a0bf8f
--- /dev/null
+++ b/ui/src/components/settings/models/RouteOriginBadge.test.tsx
@@ -0,0 +1,23 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import { RouteOriginBadge } from './RouteOriginBadge';
+
+afterEach(cleanup);
+describe('route origin help', () => {
+ it('opens on focus, dismisses on Escape, and touch does not open the route', async () => {
+ const user = userEvent.setup();
+ const route = vi.fn();
+ render(<I18nextProvider i18n={i18n}><div onClick={route}><RouteOriginBadge origin="passthrough" backend="codex" /></div></I18nextProvider>);
+ await user.tab();
+ expect(await screen.findByText(/eligible API-key providers/)).toBeTruthy();
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByText(/eligible API-key providers/)).toBeNull());
+ fireEvent.click(screen.getByRole('button', { name: 'Passthrough' }));
+ expect(await screen.findByText(/eligible API-key providers/)).toBeTruthy();
+ expect(route).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/settings/models/RouteOriginBadge.tsx b/ui/src/components/settings/models/RouteOriginBadge.tsx
new file mode 100644
index 000000000..43f01280c
--- /dev/null
+++ b/ui/src/components/settings/models/RouteOriginBadge.tsx
@@ -0,0 +1,51 @@
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import type { AgentBackend, RouteOrigin } from './types';
+
+export function RouteOriginBadge({ origin, backend, interactive = true }: {
+ origin: RouteOrigin;
+ backend: AgentBackend;
+ interactive?: boolean;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = React.useState(false);
+ const pinned = React.useRef(false);
+ const dismissal = React.useRef<ReturnType<typeof setTimeout> | null>(null);
+ const trigger = React.useRef<HTMLButtonElement>(null);
+ const content = React.useRef<HTMLDivElement>(null);
+ const key = origin ?? 'unconfigured';
+ const label = t(`settings.models.routing.origin.${key}`);
+ const className = `model-hub-route-origin model-hub-route-origin--${key}`;
+ const cancelDismissal = () => { if (dismissal.current) clearTimeout(dismissal.current); };
+ React.useEffect(() => () => { if (dismissal.current) clearTimeout(dismissal.current); }, []);
+ if (!interactive) return <span className={className}>{label}</span>;
+ const close = () => { cancelDismissal(); pinned.current = false; setOpen(false); };
+ const leave = (event: React.PointerEvent) => {
+ if (event.pointerType !== 'mouse' || pinned.current) return;
+ const target = event.relatedTarget;
+ if (target instanceof Node && (trigger.current?.contains(target) || content.current?.contains(target))) return;
+ if (document.activeElement !== trigger.current) dismissal.current = setTimeout(() => setOpen(false), 120);
+ };
+ return (
+ <Popover open={open} onOpenChange={(next) => { if (!next) close(); }}>
+ <PopoverTrigger asChild>
+ <button ref={trigger} type="button" className={className} aria-label={label}
+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') { cancelDismissal(); setOpen(true); } }}
+ onPointerLeave={leave}
+ onFocus={() => setOpen(true)}
+ onBlur={() => { if (!pinned.current) setOpen(false); }}
+ onClick={(event) => { event.preventDefault(); event.stopPropagation(); pinned.current = !pinned.current; setOpen(pinned.current); }}
+ >{label}</button>
+ </PopoverTrigger>
+ <PopoverContent ref={content} className="model-hub-origin-help" sideOffset={6}
+ onPointerEnter={cancelDismissal}
+ onPointerLeave={leave}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ onEscapeKeyDown={(event) => { event.stopPropagation(); close(); }}
+ onClick={(event) => event.stopPropagation()}
+ >{t(`settings.models.routing.help.${key}`, { backend: t(`settings.models.backends.${backend}`) })}</PopoverContent>
+ </Popover>
+ );
+}
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
new file mode 100644
index 000000000..4911cfacb
--- /dev/null
+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import { modelsApi } from './modelsApi';
+import { RouteRecordedTurn } from './RouteRecordedTurn';
+import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';
+import type { TurnProvenance } from './types';
+
+const record: TurnProvenance = {
+ contract_version: 9, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
+ outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],
+ terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },
+};
+const view = (modelId = 'requested-model') => <I18nextProvider i18n={i18n}><RouteRecordedTurn backend="codex" modelId={modelId} /></I18nextProvider>;
+afterEach(() => { cleanup(); vi.restoreAllMocks(); });
+
+describe('recorded turn error', () => {
+ it('renders exact historical identity and opens that same structured record', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(record);
+ render(view());
+ expect(await screen.findByText(/Latest recorded turn.*Upstream returned model not found/)).toBeTruthy();
+ expect(screen.getByText('src_historical · historical-model')).toBeTruthy();
+ expect(document.querySelector('time')?.dateTime).toBe(record.ts);
+ await user.click(screen.getByRole('button', { name: 'View error details' }));
+ expect(screen.getByRole('dialog').querySelector('pre')?.textContent).toBe(JSON.stringify(record, null, 2));
+ });
+ it('reads old terminal errors without inventing model-not-found evidence', async () => {
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue({ ...record, contract_version: PERSISTED_TURN_CONTRACT_VERSIONS[0], terminal_error: { source_id: 'src_old', configured_model_id: 'old-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false } });
+ render(view());
+ expect(await screen.findByText(/Latest recorded turn.*Request parameters rejected/)).toBeTruthy();
+ expect(screen.queryByText(/model not found/)).toBeNull();
+ });
+ it.each(['served', 'canceled', null] as const)('does not show an old error when latest outcome is %s', async (outcome) => {
+ const read = vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(outcome ? { ...record, outcome, terminal_error: null } : null);
+ render(view());
+ await act(async () => { await read.mock.results[0].value; });
+ expect(document.querySelector('.model-hub-recorded-turn')).toBeNull();
+ });
+ it('retries a failed read and ignores a previous model read that resolves late', async () => {
+ const user = userEvent.setup();
+ let resolve!: (value: TurnProvenance) => void;
+ const read = vi.spyOn(modelsApi, 'getAgentProvenance')
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockReturnValueOnce(new Promise((done) => { resolve = done; }))
+ .mockResolvedValueOnce(null);
+ const page = render(view());
+ await user.click(await screen.findByRole('button', { name: 'Retry' }));
+ page.rerender(view('other-model'));
+ await waitFor(() => expect(read).toHaveBeenCalledWith('codex', 'other-model'));
+ await act(async () => resolve(record));
+ expect(screen.queryByText(/Latest recorded turn/)).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.tsx b/ui/src/components/settings/models/RouteRecordedTurn.tsx
new file mode 100644
index 000000000..a3a6f75de
--- /dev/null
+++ b/ui/src/components/settings/models/RouteRecordedTurn.tsx
@@ -0,0 +1,48 @@
+import * as React from 'react';
+import { FileText, RefreshCw } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
+import { modelsApi } from './modelsApi';
+import type { AgentBackend, TurnProvenance } from './types';
+
+export function RouteRecordedTurn({ backend, modelId }: { backend: AgentBackend; modelId: string }) {
+ const { t, i18n } = useTranslation();
+ const [record, setRecord] = React.useState<TurnProvenance | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const [attempt, setAttempt] = React.useState(0);
+ const [details, setDetails] = React.useState(false);
+ React.useEffect(() => {
+ let active = true;
+ setRecord(null);
+ setFailed(false);
+ setDetails(false);
+ void modelsApi.getAgentProvenance(backend, modelId).then((value) => {
+ if (active) setRecord(value);
+ }, () => { if (active) setFailed(true); });
+ return () => { active = false; };
+ }, [backend, modelId, attempt]);
+ if (failed) return <div className="model-hub-recorded-turn" role="alert">
+ <span>{t('settings.models.routing.historyFailed')}</span>
+ <Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}><RefreshCw aria-hidden />{t('settings.models.order.retry')}</Button>
+ </div>;
+ if (!record?.terminal_error || record.agent !== backend || record.requested_model_id !== modelId) return null;
+ const error = record.terminal_error;
+ const reason = error.upstream_error_code === 'model_not_found'
+ ? t('settings.models.routing.modelNotFound')
+ : t(`settings.models.routing.errorReason.${error.reason}`);
+ return <section className="model-hub-recorded-turn">
+ <strong>{t('settings.models.routing.latestRecorded')} · {reason}</strong>
+ <time dateTime={record.ts}>{new Date(record.ts).toLocaleString(i18n.language)}</time>
+ <span className="font-mono">{error.source_id ?? '—'} · {error.configured_model_id ?? '—'}</span>
+ {error.upstream_error_code && <span className="font-mono">{error.upstream_error_code}</span>}
+ <Button variant="ghost" size="sm" className="self-start text-cyan-ink" onClick={() => setDetails(true)}><FileText aria-hidden />{t('settings.models.routing.errorDetails')}</Button>
+ <Dialog open={details} onOpenChange={setDetails}>
+ <DialogContent className="max-h-[85dvh] overflow-y-auto">
+ <DialogTitle>{t('settings.models.routing.latestRecorded')}</DialogTitle>
+ <DialogDescription>{record.turn_id}</DialogDescription>
+ <pre className="whitespace-pre-wrap break-words text-xs">{JSON.stringify(record, null, 2)}</pre>
+ </DialogContent>
+ </Dialog>
+ </section>;
+}
diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
index 6716d6a46..0f5757a33 100644
--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
@@ -31,7 +31,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 8,
+ contract_version: 9,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 84f22a0fa..29431b9a8 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -33,7 +33,7 @@ const manifest = {
} satisfies RuntimeManifest;
const runtime: RuntimeDependency = {
- contract_version: 8,
+ contract_version: 9,
manifest,
status: { installed_version: '1', verified: true, health: 'ok' },
};
@@ -77,14 +77,14 @@ const takeoverAgent: AgentSupply = {
sources: { order: ['src_head', 'src_relay'], eligibility: [] },
routes: { 'gpt-5.6-sol': { hops: [{ source_id: 'src_head', model_id: 'gpt-5.6-sol' }, { source_id: 'src_relay', model_id: 'gpt-5.6-sol' }] } },
supply_status: 'degraded',
- model_supply: [{ model_id: 'gpt-5.6-sol', chain_length: 2, has_runnable_hop: true }],
+ model_supply: [{ route_origin: "manual" as const, model_id: 'gpt-5.6-sol', chain_length: 2, has_runnable_hop: true }],
builtin_models: ['gpt-5.6-sol'],
named_agents: [],
menu: null,
};
-const takeoverChain: AgentChain = {
- contract_version: 8,
+const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head',model_id:'gpt-5.6-sol'},{source_id:'src_relay',model_id:'gpt-5.6-sol'}]}, route_origin: "manual" as const,
+ contract_version: 9,
backend: 'codex',
model_id: 'gpt-5.6-sol',
current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },
@@ -155,6 +155,7 @@ const closeSourceDetails = async () => {
};
beforeEach(() => {
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(null);
vi.spyOn(modelsApi, 'refreshAgentPresence').mockReturnValue(new Promise(() => {}));
});
@@ -176,7 +177,7 @@ describe('SettingsModelsPage surface branches', () => {
...takeoverAgent,
selected_model_id: modelIds[0] ?? null,
routes: {},
- model_supply: modelIds.map((modelId) => ({ model_id: modelId, chain_length: 0, has_runnable_hop: false })),
+ model_supply: modelIds.map((modelId) => ({ route_origin: null, model_id: modelId, chain_length: 0, has_runnable_hop: false })),
builtin_models: modelIds,
catalog_models: modelIds.map(model),
});
@@ -866,7 +867,7 @@ describe('SettingsModelsPage surface branches', () => {
const agent: AgentSupply = {
...takeoverAgent,
builtin_models: [takeoverChain.model_id, secondModel],
- model_supply: [takeoverChain.model_id, secondModel].map((model_id) => ({
+ model_supply: [takeoverChain.model_id, secondModel].map((model_id) => ({ route_origin: "manual" as const,
model_id,
chain_length: 2,
has_runnable_hop: true,
@@ -904,7 +905,7 @@ describe('SettingsModelsPage surface branches', () => {
}));
await waitFor(() => expect(exactRead).toHaveBeenCalledOnce());
expect(exactRead).toHaveBeenCalledWith('codex', 'gpt-5.6-sol');
- expect(screen.getByText(/Later Source order changes reorder its hops to match\.|以后调整供应商优先级时,其中的供应商会按新顺序重排。/i)).toBeTruthy();
+ expect(screen.getByText(/Changes to default routing do not overwrite|默认路由的调整不会覆盖/i)).toBeTruthy();
});
it('keeps a failed event read distinct from an empty history and retries it', async () => {
@@ -975,7 +976,7 @@ describe('SettingsModelsPage surface branches', () => {
selected_model_id: 'claude-opus-4-6',
sources: { order: [retainedSource.id], eligibility: [{ source_id: retainedSource.id, eligible: true }] },
routes: { 'claude-opus-4-6': { hops: [{ source_id: retainedSource.id, model_id: 'claude-opus-4-6' }] } },
- model_supply: [{ model_id: 'claude-opus-4-6', chain_length: 1, has_runnable_hop: true }],
+ model_supply: [{ route_origin: "manual" as const, model_id: 'claude-opus-4-6', chain_length: 1, has_runnable_hop: true }],
builtin_models: ['claude-opus-4-6'],
};
vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);
@@ -1011,11 +1012,11 @@ describe('SettingsModelsPage surface branches', () => {
eligibility: [{ source_id: retainedSource.id, eligible: true }],
},
routes: { [modelId]: { hops: [{ source_id: retainedSource.id, model_id: modelId }] } },
- model_supply: [{ model_id: modelId, chain_length: 1, has_runnable_hop: true }],
+ model_supply: [{ route_origin: "manual" as const, model_id: modelId, chain_length: 1, has_runnable_hop: true }],
builtin_models: [modelId],
};
- const affectedChain: AgentChain = {
- contract_version: 8,
+ const affectedChain: AgentChain = { manual_override: {hops:[{source_id:retainedSource.id,model_id:modelId}]}, route_origin: "manual" as const,
+ contract_version: 9,
backend: 'claude',
model_id: modelId,
current: { source_id: retainedSource.id, model_id: modelId },
@@ -1157,6 +1158,7 @@ describe('SettingsModelsPage surface branches', () => {
const pendingReconciliation = deferred<AgentSupply[]>();
const committedChain: AgentChain = {
...takeoverChain,
+ manual_override: { hops: [{ source_id: 'src_head', model_id: 'gpt-5.6-sol' }] },
current: { source_id: 'src_head', model_id: 'gpt-5.6-sol' },
chain: [{ ...takeoverChain.chain[0], health: 'healthy', runnable: true, retry_at: null }],
};
@@ -1210,7 +1212,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
- chain: { ...takeoverChain, chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0] },
+ chain: { ...takeoverChain, manual_override: { hops: [takeoverChain.chain[0]] }, chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0] },
removed_hops: [],
interrupted: [],
});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index ee92c7913..4f9ab818a 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1403,6 +1403,8 @@ export const SettingsModelsPage: React.FC = () => {
{menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} canReadSources={capabilities.can_manage_agents} sourceNames={sourceNames} onClose={() => setMenuBackend(null)} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}
<RouteChainDialog
selection={routeSelection}
+ covered={orderBackend !== null}
+ onOpenDefaults={() => { if (routeTarget) setOrderBackend(routeTarget.agent.backend); }}
sources={sources}
onClose={() => {
const target = routeTarget;
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
index 9ddce16ae..39bb8f684 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
import { createSourceCollectionReadAuthority } from './collectionReadAuthority';
-import { modelsApi } from './modelsApi';
+import { ApiCallError, modelsApi } from './modelsApi';
import { SourceOrderDrawer } from './SourceOrderDrawer';
import type { AgentSupply, Source } from './types';
@@ -65,18 +65,46 @@ afterEach(() => {
beforeEach(() => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValue(sources);
- vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(agent);
+ vi.spyOn(modelsApi, 'putAgentSources').mockResolvedValue(agent);
});
describe('SourceOrderDrawer keyboard ordering', () => {
+ it('echoes the exact effective-removal guard before saving default membership', async () => {
+ const user = userEvent.setup();
+ const hops = [{ backend: 'claude' as const, menu_model: 'model-a', position: 1, source_id: 'src_a', model_id: 'model-a' }];
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
+ const put = vi.spyOn(modelsApi, 'putAgentSources')
+ .mockRejectedValueOnce(new ApiCallError('source_in_route_chain', undefined, true, [], [], hops))
+ .mockResolvedValueOnce({ ...agent, sources: { ...agent.sources!, order: ['src_b'] } });
+ renderDrawer();
+ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));
+ await screen.findByText('Review affected routes');
+ expect(put).toHaveBeenCalledTimes(1);
+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));
+ await waitFor(() => expect(put).toHaveBeenLastCalledWith('claude', { order: ['src_b'], force: true, would_remove_hops: hops, would_interrupt: [] }));
+ });
+ it('reconciles an unknown order write without resubmitting the mutation', async () => {
+ const user = userEvent.setup();
+ const committed = { ...agent, sources: { ...agent.sources!, order: ['src_b'] } };
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValueOnce(agent).mockResolvedValueOnce(committed);
+ const put = vi.spyOn(modelsApi, 'putAgentSources').mockRejectedValueOnce(new TypeError('response lost'));
+ const onSaved = vi.fn();
+ renderDrawer({ onSaved });
+ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));
+ await user.click(await screen.findByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(committed));
+ expect(put).toHaveBeenCalledTimes(1);
+ });
it('grabs, moves, announces, and restores the pre-grab order on Escape', async () => {
const user = userEvent.setup();
vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
renderDrawer();
const handles = await screen.findAllByRole('button', { name: 'Reorder source' });
- expect(screen.getByRole('heading', { name: 'Claude Code · Global route priority' })).toBeTruthy();
- expect(screen.getByText("Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.")).toBeTruthy();
- expect(screen.getByText("These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route.")).toBeTruthy();
+ expect(screen.getByRole('heading', { name: 'Claude Code · Default routing' })).toBeTruthy();
+ expect(screen.getByText('Applies to automatic and passthrough routes. Saved manual routes stay unchanged.')).toBeTruthy();
+ expect(screen.getByText('Available for manual routes.')).toBeTruthy();
expect(handles[0].className).toContain('cursor-grab');
handles[0].focus();
@@ -109,33 +137,35 @@ describe('SourceOrderDrawer keyboard ordering', () => {
it('reads the current order on open and keeps the moved draft after a failed save', async () => {
const user = userEvent.setup();
const getAgentSources = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
- const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockRejectedValue(new Error('offline'));
+ const putAgentSources = vi.spyOn(modelsApi, 'putAgentSources').mockRejectedValue(new Error('offline'));
renderDrawer();
await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
await user.click(screen.getByRole('button', { name: 'Remove from order' }));
- await user.click(screen.getByRole('button', { name: 'Save order' }));
+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));
- await screen.findByText('The order was not saved');
+ await screen.findByText('Could not confirm the saved default routing. Retry to check.');
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
expect(screen.getByText('This order is empty. Add a source from below.')).toBeTruthy();
expect(getAgentSources).toHaveBeenCalledWith('claude');
- expect(reorderAgentChains).toHaveBeenCalledWith('claude', []);
+ expect(putAgentSources).toHaveBeenCalledWith('claude', { order: [] });
});
- it('applies the saved priority to existing route chains', async () => {
+ it('saves only default source membership through the source endpoint', async () => {
const user = userEvent.setup();
vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
- const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(agent);
+ const putAgentSources = vi.spyOn(modelsApi, 'putAgentSources').mockResolvedValue(agent);
+ const reorder = vi.spyOn(modelsApi, 'reorderAgentChains');
renderDrawer();
await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
- await user.click(screen.getByRole('button', { name: 'Save order' }));
+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));
- await waitFor(() => expect(reorderAgentChains).toHaveBeenCalledWith('claude', ['src_b']));
+ await waitFor(() => expect(putAgentSources).toHaveBeenCalledWith('claude', { order: ['src_b'] }));
+ expect(reorder).not.toHaveBeenCalled();
});
- it('allows reapplying an unchanged saved priority to existing route chains', async () => {
+ it('does not rewrite routes when default membership and order are unchanged', async () => {
const user = userEvent.setup();
const savedAgent: AgentSupply = {
...agent,
@@ -145,14 +175,14 @@ describe('SourceOrderDrawer keyboard ordering', () => {
},
};
vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(savedAgent);
- const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(savedAgent);
+ const putAgentSources = vi.spyOn(modelsApi, 'putAgentSources').mockResolvedValue(savedAgent);
renderDrawer({ agent: savedAgent });
- const save = await screen.findByRole('button', { name: 'Save order' });
- expect(save.hasAttribute('disabled')).toBe(false);
+ const save = await screen.findByRole('button', { name: 'Save default routing' });
+ expect(save.hasAttribute('disabled')).toBe(true);
await user.click(save);
- await waitFor(() => expect(reorderAgentChains).toHaveBeenCalledWith('claude', ['src_b', 'src_a']));
+ expect(putAgentSources).not.toHaveBeenCalled();
});
it('keeps a read failure inside the drawer and retries the collection read', async () => {
@@ -181,7 +211,7 @@ describe('SourceOrderDrawer keyboard ordering', () => {
renderDrawer({ agent: noEligible });
await screen.findByText('No source is available to this backend yet.');
- expect(screen.getByRole('button', { name: 'Save order' }).hasAttribute('disabled')).toBe(true);
+ expect(screen.getByRole('button', { name: 'Save default routing' }).hasAttribute('disabled')).toBe(true);
});
it('uses the source inventory read in the same generation as the Agent order', async () => {
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsx
index 42c681adf..245c03136 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx
@@ -1,20 +1,21 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { Reorder, useDragControls } from 'framer-motion';
-import { GripVertical, LoaderCircle, Minus, Plus, X } from 'lucide-react';
+import { ArrowUp, ArrowDown, GripVertical, LoaderCircle, Minus, Plus, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { ModelHubInfoHint } from './ModelHubInfoHint';
+import { PROTOCOL_COPY_KEYS } from './addApiKeyState';
import type { PendingWrite } from './asyncLifetime';
import type { CollectionReadAuthority } from './collectionReadAuthority';
-import { modelsApi } from './modelsApi';
+import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
+import { GuardGapList } from './GuardGapList';
+import { mayHaveWritten } from './repair';
import { movedOrder, sameIds } from './reorder';
import { combineSourceOrderReads } from './sourceOrderComposition';
-import { sourceDetail } from './sourcePresentation';
import type { AgentSupply, Source } from './types';
-import { ACCENT_PILL, sourceAccent } from './vendorMeta';
type OrderAnnouncement =
| { key: 'grabbed' | 'moved' | 'dropped'; source: string; position: number; count: number }
@@ -25,16 +26,16 @@ type ReadState = 'loading' | 'reconciling' | 'ready' | 'error';
const SourceIdentity: React.FC<{ source: Source }> = ({ source }) => {
const { t } = useTranslation();
- const detail = sourceDetail(source);
+ const inventory = source.models.length
+ ? t('settings.models.sources.modelCount', { count: source.models.length })
+ : t('settings.models.routing.inventoryNotProvided');
+ const detail = `${t(PROTOCOL_COPY_KEYS[source.protocol])} · ${inventory}`;
return (
<>
<span className="model-hub-order-identity">
<span className="model-hub-order-name truncate" title={source.display_name}>{source.display_name}</span>
{detail && <span className="model-hub-order-meta truncate" title={detail}>{detail}</span>}
</span>
- <span className={cn('model-hub-order-tag', ACCENT_PILL[sourceAccent(source)])}>
- {t(`settings.models.sourceKind.${source.kind}`)}
- </span>
</>
);
};
@@ -47,8 +48,9 @@ const OrderedRow: React.FC<{
grabbed: boolean;
handleRef: (node: HTMLButtonElement | null) => void;
onExclude: () => void;
+ onMove: (direction: -1 | 1) => void;
onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;
-}> = ({ source, index, count, busy, grabbed, handleRef, onExclude, onKeyDown }) => {
+}> = ({ source, index, count, busy, grabbed, handleRef, onExclude, onMove, onKeyDown }) => {
const { t } = useTranslation();
const controls = useDragControls();
const inert = count <= 1;
@@ -73,8 +75,10 @@ const OrderedRow: React.FC<{
</button>
<span className={cn('model-hub-order-ordinal', index === 0 && 'is-first')}>{index + 1}</span>
<SourceIdentity source={source} />
- <Button type="button" variant="outline" className="model-hub-order-row-action" disabled={busy} onClick={onExclude}>
- {t('settings.models.order.action.exclude')}
+ <Button type="button" variant="outline" size="icon" aria-label={t('settings.models.routing.moveUp')} disabled={busy || index === 0} onClick={() => onMove(-1)}><ArrowUp aria-hidden /></Button>
+ <Button type="button" variant="outline" size="icon" aria-label={t('settings.models.routing.moveDown')} disabled={busy || index === count - 1} onClick={() => onMove(1)}><ArrowDown aria-hidden /></Button>
+ <Button type="button" variant="outline" size="icon" aria-label={t('settings.models.order.action.exclude')} disabled={busy} onClick={onExclude}>
+ <Minus aria-hidden />
</Button>
</Reorder.Item>
);
@@ -95,9 +99,11 @@ export const SourceOrderDrawer: React.FC<{
const [readState, setReadState] = React.useState<ReadState>('loading');
const [order, setOrder] = React.useState<string[]>([]);
const [saveFailed, setSaveFailed] = React.useState(false);
+ const [guard, setGuard] = React.useState<GuardConfirmation | null>(null);
+ const [unknownWrite, setUnknownWrite] = React.useState(false);
const [grabbedId, setGrabbedId] = React.useState<string | null>(null);
const [announcement, setAnnouncement] = React.useState<OrderAnnouncement>(null);
- const saved = React.useRef<string[]>([]);
+ const [saved, setSaved] = React.useState<string[]>([]);
const grabbedFrom = React.useRef<string[]>([]);
const handles = React.useRef(new Map<string, HTMLButtonElement>());
const heldOutActions = React.useRef(new Map<string, HTMLButtonElement>());
@@ -108,9 +114,11 @@ export const SourceOrderDrawer: React.FC<{
const nextOrder = next.sources?.order ?? [];
setViewAgent(next);
setViewSources(nextSources);
- saved.current = nextOrder;
+ setSaved(nextOrder);
setOrder(nextOrder);
setSaveFailed(false);
+ setGuard(null);
+ setUnknownWrite(false);
setGrabbedId(null);
setAnnouncement(null);
setReadState(state);
@@ -226,17 +234,35 @@ export const SourceOrderDrawer: React.FC<{
}
};
- const save = () => {
- if (saving || readState !== 'ready' || available.length === 0) return;
+ const save = (confirmation?: GuardConfirmation) => {
+ if (saving || readState !== 'ready') return;
void orderWrite.track(async () => {
try {
- const echoed = await modelsApi.reorderAgentChains(agent.backend, order);
- saved.current = echoed.sources?.order ?? order;
- setOrder(saved.current);
+ if (unknownWrite) {
+ const observed = await modelsApi.getAgentSources(agent.backend);
+ if (sameIds(observed.sources?.order ?? [], order)) {
+ await onSaved(observed);
+ onClose();
+ return;
+ }
+ setUnknownWrite(false);
+ setSaveFailed(true);
+ return;
+ }
+ const echoed = await modelsApi.putAgentSources(agent.backend, { order, ...confirmation });
+ const nextOrder = echoed.sources?.order ?? order;
+ setSaved(nextOrder);
+ setOrder(nextOrder);
setSaveFailed(false);
await Promise.resolve(onSaved(echoed)).catch(() => {});
onClose();
- } catch {
+ } catch (error) {
+ const failure = apiFailure(error);
+ if (failure && (failure.wouldRemoveHops.length || failure.wouldInterrupt.length)) {
+ setGuard({ force: true, would_remove_hops: failure.wouldRemoveHops, would_interrupt: failure.wouldInterrupt });
+ return;
+ }
+ setUnknownWrite(mayHaveWritten(failure));
// F1: the request failed, not the user's draft. Keep every move and let
// the same primary retry the exact order.
setSaveFailed(true);
@@ -247,9 +273,9 @@ export const SourceOrderDrawer: React.FC<{
const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });
const title = t('settings.models.order.title', { backend });
const announcementText = announcement ? t(`settings.models.order.${announcement.key}`, announcement) : '';
- // Saving is also the explicit action for reapplying the stored priority to
- // routes that may have been edited independently since the last save.
- const saveEnabled = readState === 'ready' && available.length > 0;
+ const saveEnabled = readState === 'ready' && (!sameIds(saved, order) || saveFailed);
+ const manualCount = (viewAgent.model_supply ?? []).filter((model) => Object.hasOwn(viewAgent.routes ?? {}, model.model_id)).length;
+ const inheritedCount = (viewAgent.model_supply?.length ?? 0) - manualCount;
return (
<DialogPrimitive.Root open={open} onOpenChange={(next) => !next && !saving && onClose()}>
@@ -258,7 +284,10 @@ export const SourceOrderDrawer: React.FC<{
<DialogPrimitive.Content
className="model-hub-order-drawer fixed inset-y-0 right-0 z-50 flex flex-col overflow-hidden bg-surface outline-none"
onEscapeKeyDown={(event) => {
- if (grabbedId) {
+ if (guard) {
+ event.preventDefault();
+ setGuard(null);
+ } else if (grabbedId) {
event.preventDefault();
cancelGrab();
} else if (saving) event.preventDefault();
@@ -286,6 +315,11 @@ export const SourceOrderDrawer: React.FC<{
</header>
<div className="model-hub-order-body flex min-h-0 flex-1 flex-col overflow-y-auto">
+ {guard ? <div className="model-hub-order-section" role="alert">
+ <h3>{t('settings.models.routing.guardTitle')}</h3>
+ <ul className="model-hub-guard-list">{guard.would_remove_hops?.map((hop) => <li key={`${hop.backend}:${hop.menu_model}:${hop.position}`} className="model-hub-guard-hop"><span>{hop.menu_model} · {hop.model_id} · {hop.source_id}</span></li>)}</ul>
+ <GuardGapList gaps={guard.would_interrupt ?? []} />
+ </div> : <>
{readState === 'loading' && (
<div className="model-hub-order-state"><LoaderCircle className="model-hub-ink-mint size-4 animate-spin" />{t('common.loading')}</div>
)}
@@ -334,6 +368,7 @@ export const SourceOrderDrawer: React.FC<{
source={source}
index={index}
count={ordered.length}
+ onMove={(direction) => { persist(movedOrder(order, index, direction)); focusHandleAfterRender(source.id); }}
busy={saving}
grabbed={grabbedId === source.id}
handleRef={(node) => {
@@ -367,6 +402,8 @@ export const SourceOrderDrawer: React.FC<{
}}
type="button"
variant="outline"
+ size="icon"
+ aria-label={t('settings.models.order.action.include')}
className="model-hub-order-row-action"
disabled={saving}
onClick={() => {
@@ -375,7 +412,6 @@ export const SourceOrderDrawer: React.FC<{
}}
>
<Plus className="size-3.5" />
- {t('settings.models.order.action.include')}
</Button>
</div>
))}
@@ -384,18 +420,20 @@ export const SourceOrderDrawer: React.FC<{
</>
)}
<p aria-live="polite" className="sr-only">{announcementText}</p>
+ </>}
+ {readState === 'ready' && <p className="model-hub-default-counts">{t('settings.models.routing.counts', { inherited: inheritedCount, manual: manualCount })}</p>}
</div>
<footer className="model-hub-order-foot flex shrink-0 items-center justify-end border-t border-border">
{saveFailed && <span className="mr-auto text-[11px] text-destructive-ink">{t('settings.models.order.fail.save')}</span>}
- <Button type="button" variant="outline" className="model-hub-order-action" disabled={saving} onClick={onClose}>
+ <Button type="button" variant="outline" className="model-hub-order-action" disabled={saving} onClick={() => guard ? setGuard(null) : onClose()}>
{t('settings.models.order.cancel')}
</Button>
{readState === 'error'
? <Button type="button" variant="brand" className="model-hub-order-action" onClick={() => void read()}>{t('settings.models.order.retry')}</Button>
- : <Button type="button" variant="brand" className="model-hub-order-action" disabled={!saveEnabled || saving} onClick={save}>
+ : <Button type="button" variant="brand" className="model-hub-order-action" disabled={!saveEnabled || saving} onClick={() => save(guard ?? undefined)}>
{saving && <LoaderCircle className="size-3 animate-spin" />}
- {saveFailed ? t('settings.models.order.retry') : t('settings.models.order.save')}
+ {guard ? t('settings.models.routing.confirmDefaults') : saveFailed ? t('settings.models.order.retry') : t('settings.models.order.save')}
</Button>}
</footer>
</DialogPrimitive.Content>
diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.ts
index 627bbde2e..5990654c7 100644
--- a/ui/src/components/settings/models/SupplyGraph.test.ts
+++ b/ui/src/components/settings/models/SupplyGraph.test.ts
@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';
import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 8,
+ contract_version: 9,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -40,14 +40,14 @@ const agent: AgentSupply = {
sources: { order: ['native', 'relay', 'unused'], eligibility: [] },
routes: { 'model-a': { hops: [{ source_id: 'native', model_id: 'model-a' }, { source_id: 'relay', model_id: 'model-a' }, { source_id: 'unused', model_id: 'model-a' }] } },
supply_status: 'degraded',
- model_supply: [{ model_id: 'model-a', chain_length: 3, has_runnable_hop: true }],
+ model_supply: [{ route_origin: "manual" as const, model_id: 'model-a', chain_length: 3, has_runnable_hop: true }],
named_agents: [],
builtin_models: ['model-a'],
menu: null,
};
-const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({
- contract_version: 8,
+const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({ manual_override: {hops:[{source_id:'native',model_id:'model-a'},{source_id:'relay',model_id:'model-a'},{source_id:'unused',model_id:'model-a'}]}, route_origin: "manual" as const,
+ contract_version: 9,
backend: 'claude',
model_id: 'model-a',
current: { source_id: current, model_id: 'model-a' },
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
index a98e362a3..0d650bb2b 100644
--- a/ui/src/components/settings/models/apiFailure.test.ts
+++ b/ui/src/components/settings/models/apiFailure.test.ts
@@ -33,7 +33,7 @@ afterEach(() => {
describe('apiFailure — whether the route named the failure', () => {
it('posts installation to the dedicated runtime route', async () => {
const runtime = {
- contract_version: 8,
+ contract_version: 9,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },
status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },
} as const;
diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.ts
index a5873260d..73501654d 100644
--- a/ui/src/components/settings/models/gatewayAdoption.test.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts
@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({
});
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 8,
+ contract_version: 9,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
});
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 63c7f2f69..f9c997b9c 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -40,6 +40,8 @@
* general case is a re-implementation of the cascade.
*/
:root {
+ --route-manual-soft: color-mix(in srgb, var(--route-manual) 12%, transparent);
+ --route-manual-border: color-mix(in srgb, var(--route-manual) 25%, transparent);
/* Neutral wash channel: white over the dark frame. */
--model-hub-wash-channel: 255 255 255;
--model-hub-wash-03: rgb(var(--model-hub-wash-channel) / 1.2%);
@@ -190,7 +192,7 @@
/* Provider order drawer. */
--model-hub-order-row-height: 58px;
- --model-hub-order-row-radius: 9px;
+ --model-hub-order-row-radius: 8px;
--model-hub-order-grip-size: 14px;
--model-hub-order-grip-dim: var(--model-hub-wash-33);
--model-hub-order-meta-size: 10.5px;
@@ -509,7 +511,48 @@
--model-hub-upstream-detail-ink: var(--model-hub-muted-cc);
color: var(--model-hub-upstream-detail-ink);
}
+.model-hub-route-origin {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ min-width: 44px;
+ height: 23px;
+ padding: 0 11px;
+ border: 1px solid transparent;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 600;
+ white-space: nowrap;
+ color: var(--muted);
+}
+.model-hub-route-origin--automatic { color: var(--mint-ink); background: var(--model-hub-mint-1a); border-color: var(--model-hub-mint-4d); }
+.model-hub-route-origin--manual { color: var(--route-manual); background: var(--route-manual-soft); border-color: var(--route-manual-border); }
+.model-hub-route-origin--passthrough { color: var(--gold-ink); background: var(--model-hub-gold-1a); border-color: var(--model-hub-gold-4d); }
+.model-hub-route-origin:focus-visible { outline: 1px solid currentColor; outline-offset: 2px; }
+.model-hub-model-open:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
+.model-hub-model-row > span > span:first-child { flex: 0 1 28%; }
+.model-hub-origin-help { width: 340px; max-width: calc(100vw - 32px); white-space: pre-line; font-size: 12px; line-height: 1.6; }
+.model-hub-route-origin-line { display: flex; gap: 12px; align-items: center; color: var(--muted); font-size: 12px; }
+.model-hub-route-preview { display: flex; flex-direction: column; gap: 8px; padding: 16px; border-radius: 8px; background: var(--model-hub-mint-1a); color: var(--mint-ink); font-size: 12px; }
+.model-hub-route-preview[data-origin="passthrough"] { background: var(--model-hub-gold-1a); color: var(--gold-ink); }
+.model-hub-route-preview[data-origin="unconfigured"] { background: var(--model-hub-wash-08); color: var(--muted); }
+.model-hub-route-ordinal[data-origin="automatic"] { color: var(--mint-ink); background: var(--model-hub-mint-1a); }
+.model-hub-route-ordinal[data-origin="passthrough"] { color: var(--gold-ink); background: var(--model-hub-gold-1a); }
+.model-hub-route-custom { display: grid; grid-template-columns: minmax(80px, auto) minmax(0, 1fr); gap: 8px; align-items: center; padding: 12px; font-size: 12px; }
+.model-hub-route-custom select { min-width: 0; height: 32px; border: 1px solid var(--border); border-radius: 6px; background: var(--background); color: var(--foreground); padding: 0 8px; }
+.model-hub-default-counts { margin-top: auto; padding: 20px; font-size: 12px; color: var(--muted); }
+.model-hub-recorded-turn { display: flex; flex-direction: column; gap: 6px; margin: 0 20px 16px; padding: 12px; border-left: 2px solid var(--destructive-ink); font-size: 12px; overflow-wrap: anywhere; color: var(--muted); }
+.model-hub-recorded-turn strong { color: var(--destructive-ink); }
+@media (max-width: 640px) {
+ .model-hub-model-row { height: 72px; }
+ .model-hub-model-row > span { flex-wrap: wrap; padding-bottom: 24px; }
+ .model-hub-model-row > span > span:first-child { flex: 1; }
+ .model-hub-model-row .model-hub-model-current { position: absolute; left: 12px; right: 32px; bottom: 10px; text-align: left; }
+ .model-hub-route-foot { flex-wrap: wrap; min-height: var(--model-hub-dialog-foot-height); height: auto; }
+}
.model-hub-model-row {
+ border-radius: 8px;
--model-hub-model-row-fill: var(--model-hub-wash-05);
background: var(--model-hub-model-row-fill);
}
diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.ts
index 4e9c3ae5c..5bc8e6340 100644
--- a/ui/src/components/settings/models/modelRows.test.ts
+++ b/ui/src/components/settings/models/modelRows.test.ts
@@ -11,7 +11,7 @@ const baseModel: BackendModel = {
const agent: AgentSupply = {
backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', sources: { order: [], eligibility: [] },
- routes: { 'route-only': { hops: [] } }, builtin_models: ['builtin'], model_supply: [{ model_id: 'builtin', chain_length: 0, has_runnable_hop: false }],
+ routes: { 'route-only': { hops: [] } }, builtin_models: ['builtin'], model_supply: [{ route_origin: null, model_id: 'builtin', chain_length: 0, has_runnable_hop: false }],
selected_model_id: null, selected_model_explicit: false, supply_status: null, named_agents: [], menu: null,
};
@@ -56,7 +56,7 @@ describe('collapsedModelRows', () => {
...agent,
builtin_models: menu,
routes: {},
- model_supply: menu.map((modelId, index) => ({ model_id: modelId, chain_length: index < count ? 0 : 1, has_runnable_hop: index >= count })),
+ model_supply: menu.map((modelId, index) => ({ route_origin: "manual" as const, model_id: modelId, chain_length: index < count ? 0 : 1, has_runnable_hop: index >= count })),
});
it.each([0, 2, 5, menu.length])('shows at most the first six rows regardless of supply state (%i unsupplied)', (unsupplied) => {
@@ -73,7 +73,7 @@ describe('collapsedModelRows', () => {
it('keeps a nonempty but wholly unrunnable Route classified while folding it beyond the limit', () => {
const paused = {
...withEmptyRoutes(0),
- model_supply: menu.map((modelId, index) => ({
+ model_supply: menu.map((modelId, index) => ({ route_origin: "manual" as const,
model_id: modelId,
chain_length: 1,
has_runnable_hop: index !== menu.length - 1,
diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.ts
index 8442e5e66..bbf3e1549 100644
--- a/ui/src/components/settings/models/modelRows.ts
+++ b/ui/src/components/settings/models/modelRows.ts
@@ -1,7 +1,7 @@
import { catalogModelIds } from './backendCatalog';
import { eligibleSources } from './eligibility';
import type { RegionRead } from './regionRead';
-import type { AgentBackend, AgentChain, AgentSupply, Source } from './types';
+import type { AgentBackend, AgentChain, AgentSupply, Source, RouteOrigin } from './types';
export type ModelChainRead = RegionRead<AgentChain>;
@@ -60,6 +60,8 @@ export type CollapsedModelRows = {
};
export type ModelSupplyState = 'available' | 'paused' | 'unconfigured';
+export const modelRouteOrigin = (agent: AgentSupply, modelId: string): RouteOrigin =>
+ agent.model_supply?.find((row) => row.model_id === modelId)?.route_origin ?? null;
/** Structural emptiness wins before live runnability, exactly as the contract specifies. */
export function modelSupplyState(agent: AgentSupply, modelId: string): ModelSupplyState {
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 4ca587971..96f1e7823 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -10,6 +10,7 @@ import type {
AddedTo,
AgentBackend,
AgentChain,
+ TurnProvenance,
AgentChainMutation,
AgentChainPut,
AgentMode,
@@ -126,10 +127,13 @@ export type ModelsApi = {
reorderAgentChains(backend: AgentBackend, order?: string[]): Promise<AgentSupply>;
/** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */
getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;
+ getAgentProvenance(backend: AgentBackend, model: string): Promise<TurnProvenance | null>;
/** Complete overview chain projection for one Hub backend. */
getAgentChains(backend: AgentBackend): Promise<AgentChain[]>;
/** Total replacement of the exact stored chain. */
putAgentChain(backend: AgentBackend, model: string, body: AgentChainPut): Promise<AgentChainMutation>;
+ previewAgentChain(backend: AgentBackend, model: string, body: { manual_override: { hops: RouteHop[] } | null }): Promise<AgentChain>;
+ restoreAgentChain(backend: AgentBackend, model: string, body?: GuardConfirmation): Promise<AgentChainMutation>;
/** One real request through the chain. Hub mode only, same reason. */
probeAgent(backend: AgentBackend, model?: string): Promise<ProbeResult>;
setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;
@@ -596,8 +600,11 @@ export const modelsApi: ModelsApi = {
jsonInit('POST', order === undefined ? undefined : { order }),
).then((r) => r.agent),
getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),
+ getAgentProvenance: (backend, model) => call<{ provenance: TurnProvenance | null }>(`/api/models/agents/${backend}/provenance?model=${encodeURIComponent(model)}`).then((r) => r.provenance),
getAgentChains: (backend) => call<{ chains: AgentChain[] }>(`/api/models/agents/${backend}/chains`).then((r) => r.chains),
putAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('PUT', body)),
+ previewAgentChain: (backend, model, body) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain/preview?model=${encodeURIComponent(model)}`, jsonInit('POST', body)).then((r) => r.chain),
+ restoreAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('DELETE', body ?? {})),
probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),
setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),
putAgentModels: (backend, body) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/models`, jsonInit('PUT', body)).then((r) => (r.agent ?? r) as AgentSupply),
diff --git a/ui/src/components/settings/models/routeChainDraft.test.ts b/ui/src/components/settings/models/routeChainDraft.test.ts
index 10310d676..79e9c0fd7 100644
--- a/ui/src/components/settings/models/routeChainDraft.test.ts
+++ b/ui/src/components/settings/models/routeChainDraft.test.ts
@@ -45,6 +45,15 @@ const sources = [
];
describe("routeChainDraft", () => {
+ it('allows unknown API-key models while keeping subscription admission and retirement', () => {
+ const unknown = { source_id: 'src_a', model_id: 'unlisted' };
+ expect(validateRouteDraft(agent, sources, [], [unknown]).valid).toBe(true);
+ const subscription: Source = { ...sources[0], kind: 'subscription' };
+ expect(validateRouteDraft(agent, [subscription], [], [unknown]).valid).toBe(false);
+ expect(validateRouteDraft(agent, [subscription], [unknown], [unknown]).valid).toBe(true);
+ const retired: Source = { ...sources[0], models: [{ id: 'unlisted', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null, retired: true }] };
+ expect(validateRouteDraft(agent, [retired], [], [unknown]).valid).toBe(false);
+ });
it("builds eligible candidates without duplicate exact hops", () => {
const candidates = routeCandidates(agent, sources, [
{ source_id: "src_a", model_id: "model-a" },
diff --git a/ui/src/components/settings/models/routeChainDraft.ts b/ui/src/components/settings/models/routeChainDraft.ts
index 51c9a69f7..00c63671d 100644
--- a/ui/src/components/settings/models/routeChainDraft.ts
+++ b/ui/src/components/settings/models/routeChainDraft.ts
@@ -4,6 +4,7 @@ import type {
AgentChain,
AgentSupply,
RouteHop,
+ ManualRouteOverride,
Source,
} from "./types";
@@ -64,20 +65,19 @@ export function validateRouteDraft(
draft: RouteHop[],
): DraftValidation {
const unchanged = new Set(origin.map(identity));
- const available = new Set(
- eligibleSources(sources, agent).flatMap((source) =>
- source.models
- .filter((model) => model.retired !== true)
- .map((model) => `${source.id}\u0000${model.id}`),
- ),
- );
+ const available = new Map(eligibleSources(sources, agent).map((source) => [source.id, source]));
const counts = new Map<string, number>();
draft.forEach((hop) =>
counts.set(identity(hop), (counts.get(identity(hop)) ?? 0) + 1),
);
const allInvalidIndexes = draft.flatMap((hop, index) => {
const key = identity(hop);
- return counts.get(key)! > 1 || (!unchanged.has(key) && !available.has(key))
+ const source = available.get(hop.source_id);
+ const admitted = source && hop.model_id.trim().length > 0
+ && hop.model_id === hop.model_id.trim()
+ && (source.kind === 'api_key' || source.models.some((model) => model.id === hop.model_id))
+ && !source.models.some((model) => model.id === hop.model_id && model.retired === true);
+ return counts.get(key)! > 1 || (!unchanged.has(key) && !admitted)
? [index]
: [];
});
@@ -112,21 +112,22 @@ export const sameRouteDraft = (left: RouteHop[], right: RouteHop[]): boolean =>
left.length === right.length &&
left.every((hop, index) => identity(hop) === identity(right[index]));
+export const sameManualOverride = (left: ManualRouteOverride | null, right: ManualRouteOverride | null): boolean =>
+ left === null || right === null ? left === right : sameRouteDraft(left.hops, right.hops);
+
export const routeChainMatchesAttempt = (
chain: AgentChain,
attempt: {
backend: AgentBackend;
modelId: string;
submitted: RouteHop[];
+ manual_override: ManualRouteOverride | null;
},
): boolean => {
const { backend, model_id: menuModel } = chain;
return (
backend === attempt.backend &&
menuModel === attempt.modelId &&
- sameRouteDraft(
- chain.chain.map(({ source_id, model_id }) => ({ source_id, model_id })),
- attempt.submitted,
- )
+ sameManualOverride(chain.manual_override, attempt.manual_override)
);
};
diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.ts
index 3c1b8c00d..da5634c47 100644
--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts
+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts
@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({
});
const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({
- contract_version: 8,
+ contract_version: 9,
host_platform: 'darwin-arm64',
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.ts
index 9038d5884..e378b642b 100644
--- a/ui/src/components/settings/models/supply.test.ts
+++ b/ui/src/components/settings/models/supply.test.ts
@@ -211,8 +211,8 @@ describe('attribution (AC-9)', () => {
const agent = hubAgent({
named_agents: [{ name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' }],
model_supply: [
- { model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true },
- { model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false },
+ { route_origin: "manual" as const, model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true },
+ { route_origin: null, model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false },
],
});
expect(attribution(agent)).toEqual({
@@ -225,7 +225,7 @@ describe('attribution (AC-9)', () => {
it('never double-counts a model an Agent runs', () => {
const agent = hubAgent({
named_agents: [{ name: 'claude', effective_model_id: 'claude-haiku-4-5', supply_status: 'interrupted' }],
- model_supply: [{ model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false }],
+ model_supply: [{ route_origin: null, model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false }],
});
expect(attribution(agent)).toEqual({ interrupted: ['claude'], waiting: [], unassignedModels: [] });
});
diff --git a/ui/src/components/settings/models/suspendedRouteAttempts.test.ts b/ui/src/components/settings/models/suspendedRouteAttempts.test.ts
index c97803cbf..45ee92336 100644
--- a/ui/src/components/settings/models/suspendedRouteAttempts.test.ts
+++ b/ui/src/components/settings/models/suspendedRouteAttempts.test.ts
@@ -12,12 +12,14 @@ describe("suspended route attempts", () => {
backend: "claude" as const,
modelId: "claude-model",
stage: "initial" as const,
+ manual_override: { hops: [] },
submitted: [],
};
const codex = {
backend: "codex" as const,
modelId: "codex-model",
stage: "confirmed" as const,
+ manual_override: { hops: [] },
submitted: [],
};
const held = holdSuspendedRouteAttempt(
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 0f5bdfbfa..17bb5f341 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -10,7 +10,8 @@
// and the PR records the server implementation and feature-flag activation
// edge. The client never synthesizes a fallback payload shape.
-export const CONTRACT_VERSION = 8 as const;
+export const CONTRACT_VERSION = 9 as const;
+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9] as const;
export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;
export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;
@@ -362,6 +363,8 @@ export type RouteHopRef = RouteHop & {
export type AgentRoute = {
hops: RouteHop[];
};
+export type ManualRouteOverride = AgentRoute;
+export type RouteOrigin = 'automatic' | 'manual' | 'passthrough' | null;
/** Agent-level supply rollup (§4.5). `waiting` = every enabled source is
* cooling and one will come back; `interrupted` = nothing can serve the
@@ -386,6 +389,7 @@ export type NamedAgentSupply = {
* is the honest 「ticked but nothing supplies it」 state. */
export type ModelSupply = {
model_id: string;
+ route_origin: RouteOrigin;
chain_length: number;
has_runnable_hop: boolean;
};
@@ -407,7 +411,7 @@ export type AgentSupply = {
selected_model_explicit?: boolean;
/** Per-backend enabled subset + order. null when mode=direct. */
sources?: AgentSources | null;
- /** Exact configured Route for each menu model. Runtime reads this verbatim. */
+ /** Sparse persisted manual overrides. Missing keys follow default routing. */
routes?: Record<string, AgentRoute> | null;
/** Rollup over `sources.order` for the current selection. null in direct mode
* and whenever `selected_model_id` is null. This is not a backend-wide
@@ -548,6 +552,8 @@ export type AgentChain = {
contract_version: typeof AGENT_CHAIN_CONTRACT_VERSION;
backend: AgentBackend;
model_id: string;
+ manual_override: ManualRouteOverride | null;
+ route_origin: RouteOrigin;
current: RouteHop | null;
chain: AgentChainLink[];
/** v4 pins this to the array it summarises: `ok` iff some member is runnable,
@@ -555,6 +561,38 @@ export type AgentChain = {
supply_state: 'ok' | 'waiting' | 'interrupted';
};
+export type RecordedAttempt = {
+ source_id: string;
+ configured_model_id: string;
+ channel: SupplyChannel;
+ stripped_reasoning_efforts?: string[];
+ declared_reasoning_efforts?: string[];
+};
+export type TurnProvenance = {
+ contract_version: (typeof PERSISTED_TURN_CONTRACT_VERSIONS)[number];
+ turn_id: string;
+ ts: string;
+ agent: AgentBackend;
+ requested_model_id: string;
+ outcome: 'served' | 'exhausted' | 'failed_terminal' | 'no_candidate' | 'canceled';
+ failed_attempts: Array<RecordedAttempt & { reason: ResolutionReason }>;
+ served: RecordedAttempt | null;
+ canceled_attempt: RecordedAttempt | null;
+ terminal_error: {
+ source_id: string | null;
+ configured_model_id: string | null;
+ channel: SupplyChannel | null;
+ reason: 'invalid_parameter' | 'protocol_error' | 'tool_incompatible' | 'stream_interrupted' | 'engine_down';
+ stream_started: boolean;
+ http_status?: number | null;
+ upstream_error_code?: string | null;
+ stripped_reasoning_efforts?: string[];
+ declared_reasoning_efforts?: string[];
+ } | null;
+ model_supply_state: 'waiting' | 'interrupted' | null;
+ blockers: Array<RouteHop & { reason: ChainUnavailableReason; retry_at?: string | null }>;
+};
+
// ── probe-result.schema.json ────────────────────────────────────────────
/** v4 widened this beyond `state.detail_key`: the native_cli branch reports
* process unavailability, which no source-state key can express. */
@@ -857,7 +895,12 @@ export type SourcePatch = {
};
/** PUT /api/models/agents/<backend>/sources — replaces the complete order. */
-export type AgentSourcesPut = { order: string[] };
+export type AgentSourcesPut = {
+ order: string[];
+ force?: boolean;
+ would_remove_hops?: RouteHopRef[];
+ would_interrupt?: SupplyGap[];
+};
/** PUT /api/models/agents/<backend>/chain?model=<id> — replaces exact hops. */
export type AgentChainPut = {
diff --git a/ui/src/components/settings/models/vocabulary.test.ts b/ui/src/components/settings/models/vocabulary.test.ts
index 4fe2788bd..3c47bb066 100644
--- a/ui/src/components/settings/models/vocabulary.test.ts
+++ b/ui/src/components/settings/models/vocabulary.test.ts
@@ -13,16 +13,16 @@ const leaves = (node: unknown): string[] =>
describe('Models page vocabulary', () => {
it('contains none of the retired user-facing terms', () => {
const copy = leaves(zh.settings.models).join('\n');
- expect(copy).not.toMatch(/菜单固定|跟随推荐|中枢 Hub|按量\s*\$|映射|供给|来源|型号|上游|自定义顺序|已改为手动|恢复默认/);
+ expect(copy).not.toMatch(/菜单固定|跟随推荐|中枢 Hub|按量\s*\$|映射|供给|来源|型号|自定义顺序|已改为手动|恢复默认/);
expect(copy).not.toMatch(/按量(?!付费)/);
expect(zh.settings.models.billing.monthly).toBe('订阅');
expect(zh.settings.models.billing.metered).toBe('按量付费');
expect(en.settings.models.billing.monthly).toBe('Subscription');
expect(en.settings.models.billing.metered).toBe('Pay as you go');
- expect(zh.settings.models.order.subtitle).toBe('在每个模型已有路由中,排在前面的供应商优先使用;当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,模型网关会自动切换到下一优先级。');
- expect(en.settings.models.order.subtitle).toBe("Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.");
- expect(zh.settings.models.order.section['heldOut.note']).toBe('这些供应商仍保留在已有路由末尾。要从路由中移除,请编辑对应模型的路由。');
- expect(en.settings.models.order.section['heldOut.note']).toBe("These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route.");
+ expect(zh.settings.models.order.subtitle).toBe('作用于自动和透传路由,已保存的手动路由保持不变。');
+ expect(en.settings.models.order.subtitle).toBe('Applies to automatic and passthrough routes. Saved manual routes stay unchanged.');
+ expect(zh.settings.models.order.section['heldOut.note']).toBe('可用于手动路由。');
+ expect(en.settings.models.order.section['heldOut.note']).toBe('Available for manual routes.');
expect(zh.settings.models.supplyMode.fixHint).toBe('去「模型」页添加或启用供应商即可恢复。');
expect('policy' in zh.settings.models.agents).toBe(false);
});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 47b427a6d..6d561e448 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -908,8 +908,8 @@
"gateway": {
"heading": "Gateway routes",
"infoLabel": "What gateway routes are",
- "info": "Gateway routes decide which upstream source each Agent's model uses first among the sources already configured in its route. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.",
- "sourceOrder": "Adjust priority",
+ "info": "Models follow default routing unless they have a saved manual route. Matching providers take priority; unmatched models pass through to eligible API-key providers.",
+ "sourceOrder": "Default routing",
"manageModels": "Manage models",
"switchToGateway": "Switch to gateway",
"switchToDirect": "Switch to direct",
@@ -1170,16 +1170,54 @@
"reorder": "Reorder",
"oauthSignedOut": "CLI subscription is signed out"
},
+ "routing": {
+ "historyFailed": "Recorded turn could not be read.",
+ "latestRecorded": "Latest recorded turn",
+ "modelNotFound": "Upstream returned model not found",
+ "errorDetails": "View error details",
+ "errorReason": { "invalid_parameter": "Request parameters rejected", "protocol_error": "Protocol error", "tool_incompatible": "Tool incompatible", "stream_interrupted": "Stream interrupted", "engine_down": "Gateway unavailable" },
+ "origin": { "automatic": "Automatic", "manual": "Manual", "passthrough": "Passthrough", "unconfigured": "Unconfigured" },
+ "help": {
+ "automatic": "Matched by model name.\nSource order follows {{backend}} default routing.",
+ "manual": "This model has a saved, fixed route.\nDefault routing does not change it. Restore automatic in route settings to follow defaults.",
+ "passthrough": "No matching model was found in the provider lists.\nThe original model name is sent to eligible API-key providers in default order for the upstream to handle.",
+ "unconfigured": "No route is configured for this model. Open route settings to configure defaults or restore automatic routing."
+ },
+ "frozen": "This model uses a saved, fixed route",
+ "follows": "Follows {{backend}} default routing",
+ "manualHint": "Only this model. Changes to default routing do not overwrite these route entries.",
+ "editHint": "Editing and saving gives this model a manual route.",
+ "restoreAutomatic": "Restore automatic",
+ "undoRestore": "Undo restore",
+ "undoDone": "Previous manual draft restored.",
+ "restorePending": "Not saved yet. The saved route is still in use.",
+ "afterSave": "Route after saving",
+ "preview": { "automatic": "After restore: automatic matching", "passthrough": "After restore: original-name passthrough", "unconfigured": "After restore: unconfigured" },
+ "previewFailed": "Could not preview automatic routing. Your draft is unchanged. Try again.",
+ "manualEmpty": "This saved route is empty. Restore automatic to follow defaults.",
+ "noDefaults": "No default provider can route this model. Add a matching provider or an eligible API-key provider.",
+ "inventoryNotProvided": "Model list not provided",
+ "configureDefaults": "Configure default routing",
+ "defaultRouting": "Default routing",
+ "close": "Close",
+ "editRoute": "Edit route",
+ "exactModel": "Exact model ID",
+ "moveUp": "Move source up",
+ "moveDown": "Move source down",
+ "counts": "{{inherited}} models follow defaults · {{manual}} fixed routes",
+ "guardTitle": "Review affected routes",
+ "confirmDefaults": "Save default routing"
+ },
"order": {
- "title": "{{backend}} · Global route priority",
- "subtitle": "Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.",
- "infoLabel": "What global route priority is",
+ "title": "{{backend}} · Default routing",
+ "subtitle": "Applies to automatic and passthrough routes. Saved manual routes stay unchanged.",
+ "infoLabel": "About default routing",
"reorder": "Reorder source",
"section": {
- "ordered": "In this order",
- "ordered.note": "Drag to reorder",
- "heldOut": "Not in this order",
- "heldOut.note": "These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route."
+ "ordered": "Provider priority",
+ "ordered.note": "Match model names first; otherwise pass through to eligible API-key providers in this order.",
+ "heldOut": "Not in default routing",
+ "heldOut.note": "Available for manual routes."
},
"action": {
"include": "Add to order",
@@ -1190,10 +1228,10 @@
"ordered": "This order is empty. Add a source from below."
},
"cancel": "Cancel",
- "save": "Save order",
+ "save": "Save default routing",
"fail": {
"read": "The source list could not be read",
- "save": "The order was not saved"
+ "save": "Could not confirm the saved default routing. Retry to check."
},
"retry": "Retry",
"grabbed_one": "Grabbed {{source}}, position {{position}} of {{count}}.",
@@ -1292,7 +1330,7 @@
"modelCount_other": "{{count}} models",
"hubNoSupply": "On the gateway · no source enabled, the next turn will fail",
"directNote": "Uses the CLI's native configuration",
- "sourceOrder": "Source order",
+ "sourceOrder": "Default routing",
"modelListCount_one": "{{count}} model",
"modelListCount_other": "{{count}} models",
"enableManaged": "Manage centrally",
@@ -1368,7 +1406,7 @@
"retry": "Retry",
"empty": "This route chain is empty. Add a hop, or leave it unconfigured.",
"impact": { "title": "The route chain was saved", "detail": "These are the items this save actually removed or interrupted.", "refreshFail": "The route chain was saved, but the model surface could not be refreshed.", "done": "Done" },
- "hint": "This chain is stored configuration. Later Source order changes reorder its hops to match."
+ "hint": "This model has a saved, fixed route. Default routing changes do not overwrite it."
},
"recent": {
"title": "Recent switches",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 6b53d924f..5a6144fb9 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -908,8 +908,8 @@
"gateway": {
"heading": "路由",
"infoLabel": "什么是路由",
- "info": "路由决定每个 Agent 的模型优先使用哪个供应商;当前供应商不可用时,模型网关按优先级自动切换。",
- "sourceOrder": "调整优先级",
+ "info": "模型跟随默认路由,已保存手动路由的模型除外。优先使用匹配的供应商;未匹配时向符合条件的 API Key 供应商透传。",
+ "sourceOrder": "默认路由",
"manageModels": "管理模型",
"switchToGateway": "切换到模型网关",
"switchToDirect": "切到直连",
@@ -1170,16 +1170,54 @@
"reorder": "拖动排序",
"oauthSignedOut": "CLI 订阅未登录"
},
+ "routing": {
+ "historyFailed": "暂时无法读取已记录回合。",
+ "latestRecorded": "最近已记录回合",
+ "modelNotFound": "上游返回模型不存在",
+ "errorDetails": "查看错误详情",
+ "errorReason": { "invalid_parameter": "请求参数被拒绝", "protocol_error": "协议错误", "tool_incompatible": "工具不兼容", "stream_interrupted": "响应中断", "engine_down": "模型网关不可用" },
+ "origin": { "automatic": "自动", "manual": "手动", "passthrough": "透传", "unconfigured": "未配置" },
+ "help": {
+ "automatic": "已按模型名自动匹配。\n供应商顺序跟随 {{backend}} 的默认路由。",
+ "manual": "此模型已保存固定路由。\n不随默认路由调整,可在路由设置中恢复自动。",
+ "passthrough": "未在供应商列表中匹配到此模型。\n按默认顺序向符合条件的 API Key 供应商透传原模型名,由上游处理。",
+ "unconfigured": "此模型暂无路由。可在路由设置中配置默认路由或恢复自动。"
+ },
+ "frozen": "此模型使用已保存的固定路由",
+ "follows": "跟随 {{backend}} 的默认路由",
+ "manualHint": "仅此模型。默认路由的调整不会覆盖这些路由项。",
+ "editHint": "编辑并保存后,此模型将使用手动路由。",
+ "restoreAutomatic": "恢复自动",
+ "undoRestore": "撤销恢复",
+ "undoDone": "已恢复之前的手动草稿。",
+ "restorePending": "尚未保存,当前仍使用已保存的路由。",
+ "afterSave": "保存后的路由",
+ "preview": { "automatic": "恢复后:自动匹配", "passthrough": "恢复后:原名透传", "unconfigured": "恢复后:未配置" },
+ "previewFailed": "自动路由预览暂时不可用,草稿保持不变。请重试。",
+ "manualEmpty": "此模型已保存空路由。恢复自动后可跟随默认路由。",
+ "noDefaults": "暂无可路由此模型的默认供应商。请加入匹配的供应商或符合条件的 API Key 供应商。",
+ "inventoryNotProvided": "模型列表未提供",
+ "configureDefaults": "设置默认路由",
+ "defaultRouting": "默认路由",
+ "close": "关闭",
+ "editRoute": "编辑路由",
+ "exactModel": "准确模型 ID",
+ "moveUp": "上移供应商",
+ "moveDown": "下移供应商",
+ "counts": "{{inherited}} 个模型跟随默认路由 · {{manual}} 个固定路由",
+ "guardTitle": "确认受影响的路由",
+ "confirmDefaults": "保存默认路由"
+ },
"order": {
- "title": "{{backend}} · 供应商优先级",
- "subtitle": "在每个模型已有路由中,排在前面的供应商优先使用;当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,模型网关会自动切换到下一优先级。",
- "infoLabel": "什么是供应商优先级",
+ "title": "{{backend}} · 默认路由",
+ "subtitle": "作用于自动和透传路由,已保存的手动路由保持不变。",
+ "infoLabel": "关于默认路由",
"reorder": "调整供应商顺序",
"section": {
- "ordered": "当前顺序",
- "ordered.note": "拖动排序",
- "heldOut": "未加入当前顺序",
- "heldOut.note": "这些供应商仍保留在已有路由末尾。要从路由中移除,请编辑对应模型的路由。"
+ "ordered": "供应商优先级",
+ "ordered.note": "先匹配同名模型;无匹配时按此顺序向符合条件的 API Key 供应商透传。",
+ "heldOut": "未加入默认路由",
+ "heldOut.note": "可用于手动路由。"
},
"action": {
"include": "排进来",
@@ -1190,10 +1228,10 @@
"ordered": "当前顺序为空。把下面的供应商加入顺序。"
},
"cancel": "取消",
- "save": "保存顺序",
+ "save": "保存默认路由",
"fail": {
"read": "供应商列表暂时不可用",
- "save": "顺序没保存上"
+ "save": "暂时无法确认默认路由是否保存。请重试检查。"
},
"retry": "重试",
"grabbed_one": "已抓取 {{source}},当前位置 {{position}} / {{count}}。",
@@ -1292,7 +1330,7 @@
"modelCount_other": "{{count}} 个模型",
"hubNoSupply": "已使用模型网关 · 没有启用任何供应商,下一个回合会失败",
"directNote": "使用 Agent 自己的配置",
- "sourceOrder": "供应商优先级",
+ "sourceOrder": "默认路由",
"modelListCount_one": "{{count}} 个模型",
"modelListCount_other": "{{count}} 个模型",
"enableManaged": "模型网关",
@@ -1368,7 +1406,7 @@
"retry": "重试",
"empty": "这条路由是空的。添加一个路由项,或保持为空。",
"impact": { "title": "路由已保存", "detail": "以下是这次保存实际移除或中断的项目。", "refreshFail": "路由已保存,但模型页面暂时无法刷新。", "done": "完成" },
- "hint": "这是当前保存的路由。以后调整供应商优先级时,其中的供应商会按新顺序重排。"
+ "hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。"
},
"recent": {
"title": "最近切换",
diff --git a/ui/src/index.css b/ui/src/index.css
index fb9e8e914..cd6e9b0d2 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -244,6 +244,7 @@
--ring: rgba(91, 255, 160, 0.6);
--mint: #5bffa0;
+ --route-manual: #8bb4ff;
--mint-soft: rgba(91, 255, 160, 0.16);
--mint-ink: #5bffa0;
--mint-hover: #6fffab;
@@ -376,6 +377,7 @@
there by the owner decision of 2026-08-14 above. The washes below mix
from the fill, which is why they carry the fill's hex. */
--mint: #10b981;
+ --route-manual: #245bcd;
--mint-soft: rgba(16, 185, 129, 0.14);
--mint-ink: #10b981;
--mint-hover: #0ea372;
@@ -480,6 +482,7 @@
--ring: rgba(16, 185, 129, 0.5);
--mint: #10b981;
+ --route-manual: #245bcd;
--mint-soft: rgba(16, 185, 129, 0.14);
--mint-ink: #10b981;
--mint-hover: #0ea372;
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 11621ea61..9ce038e09 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -159,10 +159,24 @@ class ModelHubRemoteService:
{"backend": backend, "sources": sources},
)
- async def reorder_agent_chains(self, backend: str, order: object = _REORDER_ORDER_UNSET) -> dict:
+ async def reorder_agent_chains(
+ self,
+ backend: str,
+ order: object = _REORDER_ORDER_UNSET,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
+ ) -> dict:
payload = {"backend": backend}
if order is not _REORDER_ORDER_UNSET:
payload["order"] = order
+ if force:
+ payload["force"] = force
+ if confirmed_remove_hops is not None:
+ payload["would_remove_hops"] = confirmed_remove_hops
+ if confirmed_interruptions is not None:
+ payload["would_interrupt"] = confirmed_interruptions
return await _rpc("reorder_agent_chains", payload)
async def set_agent_mode(self, backend: str, mode: object) -> dict:
@@ -201,6 +215,16 @@ class ModelHubRemoteService:
{"backend": backend, "model_id": model_id, "chain": chain},
)
+ async def delete_agent_chain(self, backend: str, model_id: str, chain: object = None) -> dict:
+ return await _rpc(
+ "delete_agent_chain", {"backend": backend, "model_id": model_id, "chain": chain},
+ )
+
+ def preview_agent_chain(self, backend: str, model_id: str, chain: object) -> dict:
+ return _rpc_sync(
+ "preview_agent_chain", {"backend": backend, "model_id": model_id, "chain": chain},
+ )
+
async def add_custom_model(self, source_id: object, payload: dict) -> dict:
return await _rpc(
"add_custom_model",
@@ -272,6 +296,9 @@ class ModelHubRemoteService:
def get_turn_provenance(self, turn_id: str) -> dict:
return _rpc_sync("get_turn_provenance", {"turn_id": turn_id})
+ def get_model_provenance(self, backend: str, model_id: str) -> dict | None:
+ return _rpc_sync("get_model_provenance", {"backend": backend, "model_id": model_id})
+
async def oauth_start(self, payload: dict) -> dict:
return await _rpc("oauth_start", {"oauth": payload})
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 99aa09f60..0c2090523 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -34,6 +34,7 @@ from core.handlers.model_hub.adapter import (
make_source_observation,
)
from core.handlers.model_hub.errors import ModelDiscoveryError
+from core.handlers.model_hub.async_owner import run_owned_in_thread
from vibe.model_hub_runtime.client import (
_OFFICIAL_BASE_URLS,
EngineClient,
@@ -916,6 +917,9 @@ class CLIProxyEngineAdapter:
self.supervisor = supervisor or get_engine_supervisor()
self.state_store = state_store or self.supervisor.state_store
self._routing_lock = asyncio.Lock()
+ self._active_transports = 0
+ self._transports_idle = asyncio.Event()
+ self._transports_idle.set()
self._installation_lock = asyncio.Lock()
self._install_task: asyncio.Task[None] | None = None
self._install_admission: asyncio.Future[EngineStatus] | None = None
@@ -1258,7 +1262,8 @@ class CLIProxyEngineAdapter:
reason = str(install.get("reason") or "engine_install_failed")
raise self._install_failure(reason)
if install.get("changed"):
- await asyncio.to_thread(self.supervisor.restart_if_running)
+ await self._transports_idle.wait()
+ await run_owned_in_thread(self.supervisor.restart_if_running)
return EngineEnsureResult(
status=await self.status(),
changed=bool(install.get("changed")),
@@ -1350,24 +1355,46 @@ class CLIProxyEngineAdapter:
async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None:
async with self._routing_lock:
- try:
- previous = await asyncio.to_thread(self.state_store.list_sources)
- except EngineStateError:
- previous = []
- was_running = await asyncio.to_thread(self.supervisor.client_if_running) is not None
- await asyncio.to_thread(self.state_store.sync_sources, bindings)
- try:
- await asyncio.to_thread(self.supervisor.restart_if_running)
- except Exception:
- await asyncio.to_thread(self.state_store.replace_sources, previous)
- if was_running:
- try:
- await asyncio.to_thread(self.supervisor.ensure_running)
- except Exception as restore_error:
- raise EngineStateError(
- "source sync failed and the previous engine state could not be restored"
- ) from restore_error
- raise
+ await self._transports_idle.wait()
+ # Cancellation must retain the barrier until the finite transaction
+ # has either restarted or restored the prior projection.
+ await run_owned_in_thread(self._sync_sources_transaction, tuple(bindings))
+
+ def _sync_sources_transaction(self, bindings: Sequence[SourceBinding]) -> None:
+ try:
+ previous = self.state_store.list_sources()
+ except EngineStateError:
+ previous = []
+ was_running = self.supervisor.client_if_running() is not None
+ self.state_store.sync_sources(bindings)
+ try:
+ self.supervisor.restart_if_running()
+ except Exception:
+ self.state_store.replace_sources(previous)
+ if was_running:
+ try:
+ self.supervisor.ensure_running()
+ except Exception as restore_error:
+ raise EngineStateError(
+ "source sync failed and the previous engine state could not be restored"
+ ) from restore_error
+ raise
+
+ def _acquire_transport(self) -> Callable[[], None]:
+ self._active_transports += 1
+ self._transports_idle.clear()
+ released = False
+
+ def release() -> None:
+ nonlocal released
+ if released:
+ return
+ released = True
+ self._active_transports -= 1
+ if self._active_transports == 0:
+ self._transports_idle.set()
+
+ return release
async def provision_credential(
self,
@@ -1942,6 +1969,8 @@ class CLIProxyEngineAdapter:
request: Mapping[str, Any],
stream: bool,
origin: str,
+ *,
+ on_admitted: Callable[[], None] | None = None,
) -> EngineInvokeHandle:
async with self._routing_lock:
source = await asyncio.to_thread(self.state_store.get_source, source_id)
@@ -1963,18 +1992,30 @@ class CLIProxyEngineAdapter:
source_id=source_id,
)
)
- request_protocol = {
- "claude": "anthropic",
- "codex": "openai_responses",
- }.get(origin, getattr(request, "protocol", None) or source.protocol)
- return await client.invoke(
- source,
- model_id,
- request,
- stream=stream,
- request_protocol=request_protocol,
- request_headers=getattr(request, "headers", None),
- )
+ release = self._acquire_transport()
+ try:
+ if on_admitted is not None:
+ on_admitted()
+ except BaseException:
+ release()
+ raise
+ try:
+ request_protocol = {
+ "claude": "anthropic",
+ "codex": "openai_responses",
+ }.get(origin, getattr(request, "protocol", None) or source.protocol)
+ return await client.invoke(
+ source,
+ model_id,
+ request,
+ stream=stream,
+ request_protocol=request_protocol,
+ request_headers=getattr(request, "headers", None),
+ on_transport_done=release,
+ )
+ except BaseException:
+ release()
+ raise
async def _complete_oauth(self, flow: _OAuthFlow, client: EngineClient) -> None:
flow.grant_write_possible = True
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 5e2b34ef8..95e01f845 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -358,6 +358,7 @@ class EngineClient:
stream: bool,
request_protocol: str | None = None,
request_headers: Mapping[str, str] | None = None,
+ on_transport_done: Callable[[], None] | None = None,
) -> EngineInvokeHandle:
request_protocol = request_protocol or source.protocol
endpoint = _endpoint_for_protocol(request_protocol)
@@ -388,6 +389,7 @@ class EngineClient:
first_received = False
model_output_started = False
ownership_transferred = False
+ transport_transferred = False
prelude: _StreamPrelude | None = None
# Held here rather than inside the prelude reader so every way out of this
# call can still see what the wire already reported. A stream that reports
@@ -557,12 +559,17 @@ class EngineClient:
protocol=request_protocol,
outcome_future=outcome_future,
wire_state=wire_state,
+ on_transport_done=on_transport_done,
)
async def close_response_stream() -> None:
prelude.close()
response.close()
- await session.close()
+ try:
+ await session.close()
+ finally:
+ if on_transport_done is not None:
+ on_transport_done()
outcome = _observed_stream_terminal_outcome(
wire_state,
source,
@@ -579,6 +586,7 @@ class EngineClient:
observed=wire_state,
)
ownership_transferred = True
+ transport_transferred = True
return handle
except asyncio.TimeoutError:
if response is not None:
@@ -622,12 +630,16 @@ class EngineClient:
)
)
finally:
- if not ownership_transferred:
- if prelude is not None:
- prelude.close()
- if response is not None:
- response.close()
- await session.close()
+ try:
+ if not ownership_transferred:
+ if prelude is not None:
+ prelude.close()
+ if response is not None:
+ response.close()
+ await session.close()
+ finally:
+ if not transport_transferred and on_transport_done is not None:
+ on_transport_done()
def _request_json(
self,
@@ -1312,6 +1324,7 @@ async def _response_stream(
protocol: str,
outcome_future: asyncio.Future[RawCallOutcome],
wire_state: ProtocolSSEState,
+ on_transport_done: Callable[[], None] | None = None,
) -> AsyncIterator[bytes]:
outcome: RawCallOutcome | None = None
try:
@@ -1382,7 +1395,11 @@ async def _response_stream(
)
prelude.close()
response.close()
- await session.close()
+ try:
+ await session.close()
+ finally:
+ if on_transport_done is not None:
+ on_transport_done()
if outcome is not None and not outcome_future.done():
outcome_future.set_result(outcome)
diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.py
index fe959d75a..a2b93dbad 100644
--- a/vibe/model_hub_runtime/config.py
+++ b/vibe/model_hub_runtime/config.py
@@ -75,7 +75,7 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineS
api_key = store.read_api_key(source.credential_ref)
reasoning_by_model = dict(source.model_reasoning_efforts)
models = []
- for model in source.model_ids:
+ for model in dict.fromkeys((*source.model_ids, *source.route_model_ids)):
entry: dict[str, Any] = {"name": model, "alias": model}
reasoning_efforts = reasoning_by_model.get(model, ())
if reasoning_efforts:
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index 21fa639ed..62e779c87 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -44,6 +44,7 @@ class SourceRecord:
model_ids: tuple[str, ...]
prefix: str
model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()
+ route_model_ids: tuple[str, ...] = ()
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> SourceRecord:
@@ -57,6 +58,12 @@ class SourceRecord:
if not isinstance(raw_model_ids, list):
raise EngineStateError("invalid engine source state")
model_ids = tuple(str(model) for model in raw_model_ids)
+ route_model_ids = payload.get("route_model_ids", [])
+ if not isinstance(route_model_ids, list) or any(
+ not isinstance(model, str) or not model or model != model.strip()
+ for model in route_model_ids
+ ) or len(set(route_model_ids)) != len(route_model_ids):
+ raise EngineStateError("invalid engine route model state")
parsed_reasoning_efforts: list[tuple[str, tuple[str, ...]]] = []
seen_reasoning_models: set[str] = set()
for item in raw_reasoning_efforts:
@@ -84,6 +91,7 @@ class SourceRecord:
model_ids=model_ids,
prefix=str(payload["prefix"]),
model_reasoning_efforts=tuple(parsed_reasoning_efforts),
+ route_model_ids=tuple(route_model_ids),
)
@@ -249,10 +257,11 @@ class EngineStateStore:
raise EngineStateError("OAuth source requires at least one allowed origin")
previous = existing.get(source_id)
model_ids = tuple(dict.fromkeys(str(model).strip() for model in binding.model_ids))
- if not model_ids:
- raise EngineStateError("source requires at least one model id")
if any(not model for model in model_ids):
raise EngineStateError("model id cannot be empty")
+ route_model_ids = tuple(binding.route_model_ids)
+ if any(not isinstance(model, str) or not model or model != model.strip() for model in route_model_ids):
+ raise EngineStateError("invalid route model id")
reasoning_by_model: dict[str, tuple[str, ...]] = {}
for model_id, efforts in binding.model_reasoning_efforts:
normalized_model_id = str(model_id).strip()
@@ -275,6 +284,7 @@ class EngineStateStore:
credential_ref=credential_ref,
allowed_origins=allowed_origins,
model_ids=model_ids,
+ route_model_ids=tuple(sorted(set(route_model_ids))),
prefix=(
str(credential["prefix"])
if credential.get("prefix")
@@ -495,6 +505,7 @@ class EngineStateStore:
**asdict(source),
"allowed_origins": list(source.allowed_origins),
"model_ids": list(source.model_ids),
+ "route_model_ids": list(source.route_model_ids),
"model_reasoning_efforts": [
[model_id, list(efforts)]
for model_id, efforts in source.model_reasoning_efforts
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ac00ff7b4..27d34de56 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4625,12 +4625,17 @@ async def model_hub_agent_chains_reorder_post(backend):
if request.has_body:
raise ModelHubError("invalid_source_order")
payload = {}
- if not isinstance(payload, dict) or set(payload) - {"order"}:
+ if not isinstance(payload, dict) or set(payload) - {"order", "force", "would_remove_hops", "would_interrupt"} or (
+ "force" in payload and not isinstance(payload["force"], bool)
+ ):
raise ModelHubError("invalid_source_order")
if "order" in payload:
agent = await _model_hub_service().reorder_agent_chains(
backend,
payload["order"],
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
else:
agent = await _model_hub_service().reorder_agent_chains(backend)
@@ -4858,6 +4863,35 @@ async def model_hub_agent_chain_put(backend):
return _model_hub_error(exc)
[email protected]("/api/models/agents/<backend>/chain", methods=["DELETE"])
+async def model_hub_agent_chain_delete(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ model_id = str(request.args.get("model") or "").strip()
+ result = await _model_hub_service().delete_agent_chain(
+ backend, model_id,
+ _model_hub_json_object("mapping_target_unavailable") if request.has_body else {},
+ )
+ return _model_hub_success(**result)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/agents/<backend>/chain/preview", methods=["POST"])
+def model_hub_agent_chain_preview(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ model_id = str(request.args.get("model") or "").strip()
+ chain = _model_hub_service().preview_agent_chain(
+ backend, model_id, _model_hub_json_object("mapping_target_unavailable"),
+ )
+ return _model_hub_success(chain=chain)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
@app.route("/api/models/agents/<backend>/probe", methods=["POST"])
async def model_hub_agent_probe_post(backend):
from core.handlers.model_hub import ModelHubError
@@ -4890,6 +4924,17 @@ def model_hub_turn_provenance_get(turn_id):
return _model_hub_error(exc)
[email protected]("/api/models/agents/<backend>/provenance", methods=["GET"])
+def model_hub_model_provenance_get(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ provenance = _model_hub_service().get_model_provenance(backend, request.args.get("model"))
+ return _model_hub_success(provenance=provenance)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
@app.route("/api/models/oauth/start", methods=["POST"])
async def model_hub_oauth_start():
from core.handlers.model_hub import ModelHubError