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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): add turn provenance and channel-aware probes (#1100)
Call White05f72ae55108
diff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.pyindex f5da47edf..c018e7971 100644--- a/core/handlers/model_hub/classification.py+++ b/core/handlers/model_hub/classification.py@@ -9,7 +9,18 @@ from typing import Literal, Optionalfrom .adapter import RawCallOutcome, RawOutcomeKindResolutionAction = Literal["return", "surface", "refresh", "fallback"]-ResolutionReason = Literal["quota_exhausted", "rate_limited", "server_error", "network"]+ResolutionReason = Literal[+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "permission_denied",+ "unclassified_error",+]_SURFACE_PATTERNS = re.compile(r"(?:invalid[_ -]?(?:request|parameter)|validation[_ -]?error|context[_ -]?length|"@@ -17,11 +28,25 @@ _SURFACE_PATTERNS = re.compile(r"tool[_ -]?(?:compat|choice|schema|use)|malformed[_ -]?(?:request|schema))",re.IGNORECASE,)+_MODEL_SURFACE_PATTERNS = re.compile(+ r"(?:model[_ -]?(?:(?:is[_ -]?)?not[_ -]?(?:found|available|accessible)|"+ r"does[_ -]?not[_ -]?exist)|"+ r"unknown[_ -]?model|no[_ -]?such[_ -]?model)",+ re.IGNORECASE,+)+_MODEL_NOT_FOUND_ERROR_CODES = frozenset({"not_found_error"})+_REQUEST_SURFACE_ERROR_CODES = frozenset({"request_too_large"})+_REQUEST_FALLBACK_ERROR_CODES = frozenset({"permission_error"})_QUOTA_PATTERNS = re.compile(r"(?:quota[_ -]?(?:exhausted|exceeded)|insufficient[_ -]?(?:quota|credits)|"r"billing[_ -]?(?:limit|exhausted)|usage[_ -]?limit|credit[_ -]?balance)",re.IGNORECASE,)+_BANNED_PATTERNS = re.compile(+ r"(?:account[_ -]?(?:banned|suspended|disabled)|"+ r"(?:banned|suspended|disabled)[_ -]?account)",+ re.IGNORECASE,+)@dataclass(frozen=True)@@ -58,12 +83,31 @@ def classify_outcome(if outcome.http_status == 401:if refresh_attempted:- return ResolutionDecision("surface", error_code="upstream_unauthorized")+ return ResolutionDecision(+ "fallback",+ reason="credential_expired",+ )return ResolutionDecision("refresh")error_text = _error_text(outcome)- if _SURFACE_PATTERNS.search(error_text):+ if outcome.http_status == 402:+ return ResolutionDecision(+ "fallback",+ reason="balance_exhausted",+ )+ normalized_error_code = str(outcome.error_code or "").strip().lower()+ model_not_found = _MODEL_SURFACE_PATTERNS.search(error_text) or (+ outcome.http_status == 404+ and normalized_error_code in _MODEL_NOT_FOUND_ERROR_CODES+ )+ if (+ normalized_error_code in _REQUEST_SURFACE_ERROR_CODES+ or _SURFACE_PATTERNS.search(error_text)+ or model_not_found+ ):return ResolutionDecision("surface", error_code="upstream_request_invalid")+ if normalized_error_code in _REQUEST_FALLBACK_ERROR_CODES:+ return ResolutionDecision("fallback", reason="permission_denied")if _QUOTA_PATTERNS.search(error_text):return ResolutionDecision(@@ -71,6 +115,15 @@ def classify_outcome(reason="quota_exhausted",cooldown_seconds=300,)+ if outcome.http_status == 403:+ return ResolutionDecision(+ "fallback",+ reason=(+ "account_banned"+ if _BANNED_PATTERNS.search(error_text)+ else "credential_revoked"+ ),+ )if outcome.http_status == 429:return ResolutionDecision("fallback",@@ -83,4 +136,4 @@ def classify_outcome(reason="server_error",cooldown_seconds=30,)- return ResolutionDecision("surface", error_code="upstream_error")+ return ResolutionDecision("fallback", reason="unclassified_error")diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.pyindex ea0a3360a..098daab0e 100644--- a/core/handlers/model_hub/events.py+++ b/core/handlers/model_hub/events.py@@ -16,9 +16,56 @@ from typing import Literal, Optionalfrom vibe.i18n import t as i18n_tEventAgent = Literal["claude", "codex", "opencode", "system"]-EventKind = Literal["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"]-EventReason = Literal["quota_exhausted", "rate_limited", "server_error", "network", "recovery", "manual", "mapping"]+EventKind = Literal[+ "switch",+ "cooldown",+ "recover",+ "skip",+ "mapping_applied",+ "channel_switch",+ "needs_action",+ "supply_interrupted",+]+EventReason = Literal[+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ "recovery",+ "manual",+ "mapping",+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "permission_denied",+ "unclassified_error",+ "no_enabled_source",+ "no_eligible_source",+ "model_unsupported",+]BillingNote = Literal["entered_metered", "left_metered"]+EventSeverity = Literal["info", "action_required"]++_SELF_HEALING_REASONS = {+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+}+_NON_SELF_HEALING_REASONS = {+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "unclassified_error",+}+_REQUEST_SCOPED_REASONS = {"permission_denied"}+_STRUCTURAL_REASONS = {+ "no_enabled_source",+ "no_eligible_source",+ "model_unsupported",+}_CREDENTIAL_PATTERNS = (re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),@@ -48,13 +95,14 @@ class ResolutionEvent:ts: stragent: EventAgentkind: EventKind- model_id: str+ model_id: Optional[str]reason: EventReasonhuman_zh: strhuman_en: strfrom_source: Optional[str] = Noneto_source: Optional[str] = Nonebilling_note: Optional[BillingNote] = None+ severity: Optional[EventSeverity] = Nonedef to_payload(self) -> dict:return {@@ -67,6 +115,7 @@ class ResolutionEvent:"to_source": self.to_source,"reason": self.reason,"billing_note": self.billing_note,+ "severity": self.severity,"human_zh": self.human_zh,"human_en": self.human_en,}@@ -76,30 +125,89 @@ def build_resolution_event(*,agent: EventAgent,kind: EventKind,- model_id: str,+ model_id: Optional[str],reason: EventReason,from_source: Optional[str] = None,to_source: Optional[str] = None,from_label: Optional[str] = None,to_label: Optional[str] = None,billing_note: Optional[BillingNote] = None,+ severity: Optional[EventSeverity] = None,now: Optional[datetime] = None,) -> ResolutionEvent:+ action_required = kind in {"needs_action", "supply_interrupted"}+ expected_severity: EventSeverity = (+ "action_required" if action_required else "info"+ )+ severity = severity or expected_severity+ if severity != expected_severity:+ raise ValueError("Resolution event severity does not match its kind")+ if kind == "supply_interrupted":+ if (+ agent == "system"+ or model_id is None+ or from_source is not None+ or to_source is not None+ or reason not in _STRUCTURAL_REASONS+ ):+ raise ValueError("Invalid supply_interrupted event")+ elif reason in _STRUCTURAL_REASONS:+ raise ValueError("Structural reasons require supply_interrupted")+ if reason in _REQUEST_SCOPED_REASONS and kind != "switch":+ raise ValueError("Request-scoped reasons require a switch event")+ if kind == "needs_action" and (+ from_source is None+ or to_source is not None+ or reason not in _NON_SELF_HEALING_REASONS+ ):+ raise ValueError("Invalid needs_action event")+ if reason in _NON_SELF_HEALING_REASONS and kind in {"cooldown", "recover"}:+ raise ValueError("Non-self-healing reasons cannot cool down or recover")+ if kind == "cooldown" and reason not in _SELF_HEALING_REASONS:+ raise ValueError("Invalid cooldown reason")+ if kind == "channel_switch" and (+ from_source is None+ or to_source is None+ or from_source != to_source+ ):+ raise ValueError("Invalid channel_switch event")+ if kind == "switch" and (+ model_id is None or from_source is None or to_source is None+ ):+ raise ValueError("Invalid switch event")+ if kind in {"cooldown", "skip"} and (+ from_source is None or to_source is not None+ ):+ raise ValueError(f"Invalid {kind} event")+ if kind == "recover" and to_source is None:+ raise ValueError("Invalid recover event")+ if agent == "system" and kind not in {+ "cooldown",+ "recover",+ "skip",+ "needs_action",+ "channel_switch",+ }:+ raise ValueError("Invalid system event kind")+ if model_id is None and (+ agent != "system"+ or kind+ not in {"cooldown", "recover", "skip", "needs_action", "channel_switch"}+ ):+ raise ValueError("Null model_id requires a source-scoped system event")+safe_from = redact_credential_material(from_label or from_source or "")safe_to = redact_credential_material(to_label or to_source or "")def render(lang: str) -> str:- template = {- "switch": "switch",- "cooldown": "cooldown",- "recover": "recover",- }.get(kind, "status")+ template = kindreturn i18n_t(f"modelHub.events.{template}",lang,from_source=safe_from or i18n_t("modelHub.events.sourceFallback", lang),to_source=safe_to or i18n_t("modelHub.events.sourceFallback", lang),reason=i18n_t(f"modelHub.events.reason.{reason}", lang),+ model=model_id or "",)human_en = render("en")@@ -116,6 +224,7 @@ def build_resolution_event(from_source=from_source,to_source=to_source,billing_note=billing_note,+ severity=severity,)if contains_credential_material(event.to_payload()):raise ValueError("Resolution event contains credential material")diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pynew file mode 100644index 000000000..cedbe5201--- /dev/null+++ b/core/handlers/model_hub/provenance.py@@ -0,0 +1,798 @@+"""Exact-attribution turn provenance for process-scoped Model Hub traffic."""++from __future__ import annotations++import json+import os+import secrets+import tempfile+import threading+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Literal, Optional++from core.run_settlement import (+ SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_STOPPED,+ SETTLED_BY_TERMINAL_RESULT,+)++from .adapter import RawCallOutcome+from .classification import ResolutionDecision, ResolutionReason+++BackendName = Literal["claude", "codex", "opencode"]+SupplyChannel = Literal["native_cli", "hub"]+SupplyState = Literal["waiting", "interrupted"]+ScopeKey = tuple[BackendName, str]+++@dataclass(frozen=True)+class AttemptIdentity:+ source_id: str+ resolved_model_id: str+ channel: SupplyChannel+ via_mapping: bool++ def payload(self) -> dict:+ return {+ "source_id": self.source_id,+ "resolved_model_id": self.resolved_model_id,+ "channel": self.channel,+ "via_mapping": self.via_mapping,+ }+++@dataclass+class TurnTrace:+ turn_id: str+ agent: BackendName+ requested_model_id: str+ scope_key: ScopeKey+ failed_attempts: list[dict] = field(default_factory=list)+ served: Optional[dict] = None+ terminal_error: Optional[dict] = None+ pending_attempt: Optional[AttemptIdentity] = None+ model_supply_state: Optional[SupplyState] = None+ gateway_source_id: Optional[str] = None+ gateway_model_id: Optional[str] = None+ gateway_via_mapping: bool = False+ ambiguous: bool = False+++@dataclass+class ProcessScope:+ token: str+ active_turns: set[str] = field(default_factory=set)+ ambiguous_turns: set[str] = field(default_factory=set)+ untracked_use: bool = False+++class GatewayTurnTerminalizer:+ """One funnel for every exit after an exact gateway identity is prepared."""++ def __init__(+ self,+ registry: "TurnCorrelationRegistry",+ *,+ backend: str,+ token: str,+ ) -> None:+ self._registry = registry+ self._backend = backend+ self._token = token+ self.turn_id = registry._open_prepared_gateway_turn(+ backend=backend,+ token=token,+ )+ self._stream_started = False++ def __enter__(self) -> "GatewayTurnTerminalizer":+ return self++ def __exit__(self, _exc_type, _exc, _traceback) -> None:+ self._registry._terminalize_gateway_exit(+ self.turn_id,+ stream_started=self._stream_started,+ )++ def bind_request_model(self, model_id: str) -> Optional[str]:+ if self.turn_id is None:+ return None+ matched = self._registry.begin_gateway_request(+ backend=self._backend,+ token=self._token,+ requested_model_id=model_id,+ )+ if matched != self.turn_id:+ self.turn_id = None+ return self.turn_id++ def fail(+ self,+ reason: Literal["invalid_parameter", "protocol_error"],+ ) -> None:+ self._registry._terminalize_gateway_exit(+ self.turn_id,+ reason=reason,+ stream_started=self._stream_started,+ force=True,+ )++ def mark_no_candidate(self, supply_state: SupplyState) -> None:+ self._registry.mark_gateway_no_candidate(+ self.turn_id,+ supply_state,+ )++ def begin_attempt(+ self,+ *,+ source_id: str,+ resolved_model_id: str,+ channel: SupplyChannel,+ via_mapping: bool,+ ) -> None:+ self._registry.begin_attempt(+ self.turn_id,+ source_id=source_id,+ resolved_model_id=resolved_model_id,+ channel=channel,+ via_mapping=via_mapping,+ )++ def finish_attempt(+ self,+ *,+ outcome: RawCallOutcome,+ decision: ResolutionDecision,+ ) -> None:+ self._registry.finish_attempt(+ self.turn_id,+ outcome=outcome,+ decision=decision,+ )++ def mark_stream_started(self) -> None:+ self._stream_started = True+++def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++def _terminal_reason(decision: ResolutionDecision) -> str:+ code = decision.error_code or ""+ if code == "stream_interrupted":+ return "stream_interrupted"+ if code == "upstream_request_invalid":+ return "invalid_parameter"+ if code == "tool_incompatible":+ return "tool_incompatible"+ return "protocol_error"+++class BoundedProvenanceStore:+ """Atomic, bounded persistence for exact turn records."""++ def __init__(self, path: Path, *, max_entries: int = 500):+ self.path = path+ self.max_entries = max_entries+ self._lock = threading.RLock()++ @staticmethod+ def _read_path(path: Path) -> list[dict]:+ if not path.exists():+ return []+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return []+ if not isinstance(payload, list):+ return []+ return [item for item in payload if isinstance(item, dict)]++ def _read(self) -> list[dict]:+ return self._read_path(self.path)++ def _write_path(self, path: Path, records: list[dict]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ content = json.dumps(+ records[-self.max_entries :],+ ensure_ascii=False,+ separators=(",", ":"),+ )+ with tempfile.NamedTemporaryFile(+ "w",+ encoding="utf-8",+ dir=path.parent,+ delete=False,+ ) as tmp:+ tmp.write(content)+ tmp.flush()+ os.fsync(tmp.fileno())+ temporary_path = tmp.name+ os.chmod(temporary_path, 0o600)+ os.replace(temporary_path, path)++ def _write(self, records: list[dict]) -> None:+ self._write_path(self.path, records)++ def put(self, record: dict) -> None:+ turn_id = str(record.get("turn_id") or "")+ if not turn_id:+ raise ValueError("turn_id is required")+ with self._lock:+ records = [+ item+ for item in self._read()+ if str(item.get("turn_id") or "") != turn_id+ ]+ records.append(record)+ self._write(records)++ def get(self, turn_id: str) -> Optional[dict]:+ with self._lock:+ return next(+ (+ dict(item)+ for item in reversed(self._read())+ if item.get("turn_id") == turn_id+ ),+ None,+ )+++class TurnCorrelationRegistry:+ """Correlate process credentials to the existing Workbench turn token."""++ def __init__(self, store: BoundedProvenanceStore):+ self.store = store+ self._lock = threading.RLock()+ self._scopes: dict[ScopeKey, ProcessScope] = {}+ self._token_scopes: dict[str, ScopeKey] = {}+ self._turn_scopes: dict[str, set[ScopeKey]] = {}+ self._traces: dict[str, TurnTrace] = {}++ @staticmethod+ def _scope_key(backend: str, process_scope: str) -> ScopeKey:+ if backend not in {"claude", "codex", "opencode"}:+ raise ValueError("unsupported backend")+ normalized = str(process_scope or "").strip()+ if not normalized:+ raise ValueError("process scope is required")+ return backend, normalized # type: ignore[return-value]++ def credentials(+ self,+ backend: str,+ process_scope: str,+ turn_id: Optional[str],+ ) -> str:+ key = self._scope_key(backend, process_scope)+ normalized_turn_id = str(turn_id or "").strip() or None+ with self._lock:+ scope = self._scopes.get(key)+ if scope is None:+ scope = ProcessScope(token=secrets.token_urlsafe(32))+ self._scopes[key] = scope+ self._token_scopes[scope.token] = key++ # Frozen v3 has no discriminator for the shared OpenCode server.+ if normalized_turn_id is None or backend == "opencode":+ scope.untracked_use = True+ for active_turn_id in scope.active_turns:+ trace = self._traces.get(active_turn_id)+ if trace is not None:+ trace.ambiguous = True+ return scope.token++ if scope.active_turns - {normalized_turn_id}:+ overlapping = scope.active_turns | {normalized_turn_id}+ scope.ambiguous_turns.update(overlapping)+ for active_turn_id in overlapping:+ trace = self._traces.get(active_turn_id)+ if trace is not None:+ trace.ambiguous = True+ scope.active_turns.add(normalized_turn_id)+ self._turn_scopes.setdefault(normalized_turn_id, set()).add(key)+ return scope.token++ def authenticates(self, backend: str, token: str) -> bool:+ with self._lock:+ authorized = False+ for candidate, key in self._token_scopes.items():+ matches = secrets.compare_digest(candidate, token)+ authorized = authorized or (matches and key[0] == backend)+ return authorized++ def retire_scope(+ self,+ backend: str,+ process_scope: str,+ *,+ terminal_turn_id: Optional[str] = None,+ ) -> None:+ """Invalidate a process credential when its owning runtime is evicted."""++ key = self._scope_key(backend, process_scope)+ normalized_terminal_turn_id = str(terminal_turn_id or "").strip()+ with self._lock:+ scope = self._scopes.pop(key, None)+ if scope is None:+ return+ self._token_scopes.pop(scope.token, None)+ for turn_id in scope.active_turns:+ trace = self._traces.get(turn_id)+ terminal_is_exact = (+ turn_id == normalized_terminal_turn_id+ and trace is not None+ and not trace.ambiguous+ and not scope.untracked_use+ and scope.active_turns == {turn_id}+ and turn_id not in scope.ambiguous_turns+ and bool(trace.failed_attempts or trace.terminal_error)+ )+ if terminal_is_exact:+ turn_scopes = self._turn_scopes.get(turn_id)+ if turn_scopes is not None:+ turn_scopes.discard(key)+ elif trace is not None:+ trace.ambiguous = True++ def _exact_turn(self, backend: str, token: str) -> tuple[str, ScopeKey] | None:+ key = self._token_scopes.get(token)+ if key is None or key[0] != backend:+ return None+ scope = self._scopes[key]+ if scope.untracked_use or len(scope.active_turns) != 1:+ for turn_id in scope.active_turns:+ trace = self._traces.get(turn_id)+ if trace is not None:+ trace.ambiguous = True+ return None+ turn_id = next(iter(scope.active_turns))+ if turn_id in scope.ambiguous_turns:+ return None+ trace = self._traces.get(turn_id)+ if trace is not None and trace.ambiguous:+ return None+ return turn_id, key++ def begin_gateway_request(+ self,+ *,+ backend: str,+ token: str,+ requested_model_id: str,+ ) -> Optional[str]:+ with self._lock:+ exact = self._exact_turn(backend, token)+ if exact is None:+ return None+ turn_id, key = exact+ trace = self._traces.get(turn_id)+ if trace is None:+ trace = TurnTrace(+ turn_id=turn_id,+ agent=key[0],+ requested_model_id=requested_model_id,+ scope_key=key,+ )+ self._traces[turn_id] = trace+ elif (+ trace.gateway_model_id is not None+ and trace.gateway_model_id != requested_model_id+ ):+ trace.ambiguous = True+ self._scopes[key].ambiguous_turns.add(turn_id)+ return None+ return turn_id++ def prepare_gateway_turn(+ self,+ *,+ backend: str,+ token: str,+ requested_model_id: str,+ resolved_model_id: str,+ source_id: str,+ via_mapping: bool,+ ) -> None:+ """Retain the caller-facing model before the CLI rewrites its request."""++ with self._lock:+ exact = self._exact_turn(backend, token)+ if exact is None:+ return+ turn_id, key = exact+ trace = self._traces.setdefault(+ turn_id,+ TurnTrace(+ turn_id=turn_id,+ agent=key[0],+ requested_model_id=requested_model_id,+ scope_key=key,+ ),+ )+ if (+ trace.requested_model_id != requested_model_id+ or (+ trace.gateway_source_id is not None+ and trace.gateway_source_id != source_id+ )+ or (+ trace.gateway_model_id is not None+ and trace.gateway_model_id != resolved_model_id+ )+ ):+ trace.ambiguous = True+ self._scopes[key].ambiguous_turns.add(turn_id)+ return+ trace.gateway_source_id = source_id+ trace.gateway_model_id = resolved_model_id+ trace.gateway_via_mapping = via_mapping++ def gateway_terminalizer(+ self,+ *,+ backend: str,+ token: str,+ ) -> GatewayTurnTerminalizer:+ return GatewayTurnTerminalizer(+ self,+ backend=backend,+ token=token,+ )++ def _open_prepared_gateway_turn(+ self,+ *,+ backend: str,+ token: str,+ ) -> Optional[str]:+ with self._lock:+ exact = self._exact_turn(backend, token)+ if exact is None:+ return None+ turn_id, _ = exact+ trace = self._traces.get(turn_id)+ if (+ trace is None+ or trace.gateway_source_id is None+ or trace.gateway_model_id is None+ ):+ return None+ trace.pending_attempt = AttemptIdentity(+ source_id=trace.gateway_source_id,+ resolved_model_id=trace.gateway_model_id,+ channel="hub",+ via_mapping=trace.gateway_via_mapping,+ )+ return turn_id++ def _terminalize_gateway_exit(+ self,+ turn_id: Optional[str],+ *,+ reason: Literal["invalid_parameter", "protocol_error"] = "protocol_error",+ stream_started: bool,+ force: bool = False,+ ) -> None:+ if turn_id is None:+ return+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is None or trace.ambiguous:+ return+ if not force and (+ trace.served is not None+ or trace.terminal_error is not None+ or trace.model_supply_state is not None+ or (+ trace.pending_attempt is None+ and bool(trace.failed_attempts)+ )+ ):+ return+ identity = trace.pending_attempt+ if identity is None and (+ trace.gateway_source_id is not None+ and trace.gateway_model_id is not None+ ):+ identity = AttemptIdentity(+ source_id=trace.gateway_source_id,+ resolved_model_id=trace.gateway_model_id,+ channel="hub",+ via_mapping=trace.gateway_via_mapping,+ )+ if identity is None or identity.channel != "hub":+ return+ trace.pending_attempt = None+ trace.served = None+ trace.terminal_error = {+ **identity.payload(),+ "reason": reason,+ "stream_started": stream_started,+ }++ def begin_native_attempt(+ self,+ *,+ backend: str,+ process_scope: str,+ turn_id: Optional[str],+ requested_model_id: str,+ source_id: str,+ resolved_model_id: str,+ via_mapping: bool,+ ) -> None:+ token = self.credentials(backend, process_scope, turn_id)+ normalized_turn_id = str(turn_id or "").strip()+ if not normalized_turn_id:+ return+ with self._lock:+ exact = self._exact_turn(backend, token)+ if exact is None or exact[0] != normalized_turn_id:+ return+ trace = self._traces.setdefault(+ normalized_turn_id,+ TurnTrace(+ turn_id=normalized_turn_id,+ agent=exact[1][0],+ requested_model_id=requested_model_id,+ scope_key=exact[1],+ ),+ )+ trace.pending_attempt = AttemptIdentity(+ source_id=source_id,+ resolved_model_id=resolved_model_id,+ channel="native_cli",+ via_mapping=via_mapping,+ )++ def mark_no_candidate(+ self,+ *,+ backend: str,+ process_scope: str,+ turn_id: Optional[str],+ requested_model_id: str,+ supply_state: SupplyState,+ ) -> None:+ token = self.credentials(backend, process_scope, turn_id)+ normalized_turn_id = str(turn_id or "").strip()+ if not normalized_turn_id:+ return+ with self._lock:+ exact = self._exact_turn(backend, token)+ if exact is None or exact[0] != normalized_turn_id:+ return+ trace = self._traces.setdefault(+ normalized_turn_id,+ TurnTrace(+ turn_id=normalized_turn_id,+ agent=exact[1][0],+ requested_model_id=requested_model_id,+ scope_key=exact[1],+ ),+ )+ trace.model_supply_state = supply_state++ def mark_gateway_no_candidate(+ self,+ turn_id: Optional[str],+ supply_state: SupplyState,+ ) -> None:+ if turn_id is None:+ return+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is not None:+ trace.pending_attempt = None+ trace.served = None+ trace.terminal_error = None+ trace.model_supply_state = supply_state++ def begin_attempt(+ self,+ turn_id: Optional[str],+ *,+ source_id: str,+ resolved_model_id: str,+ channel: SupplyChannel,+ via_mapping: bool,+ ) -> None:+ if turn_id is None:+ return+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is None:+ return+ observed_via_mapping = via_mapping or (+ trace.gateway_via_mapping+ and trace.gateway_model_id == resolved_model_id+ )+ trace.pending_attempt = AttemptIdentity(+ source_id=source_id,+ resolved_model_id=resolved_model_id,+ channel=channel,+ via_mapping=observed_via_mapping,+ )++ def fail_native_attempt(+ self,+ turn_id: Optional[str],+ *,+ reason: ResolutionReason,+ ) -> None:+ """Convert an observed native terminal failure into a failed attempt."""++ normalized = str(turn_id or "").strip()+ if not normalized:+ return+ with self._lock:+ trace = self._traces.get(normalized)+ if (+ trace is None+ or trace.pending_attempt is None+ or trace.pending_attempt.channel != "native_cli"+ ):+ return+ identity = trace.pending_attempt+ trace.pending_attempt = None+ trace.served = None+ trace.terminal_error = None+ trace.failed_attempts.append(+ {**identity.payload(), "reason": reason}+ )++ def fail_hub_attempt(self, turn_id: Optional[str]) -> None:+ """Replace a gateway success rejected by the backend terminal result."""++ normalized = str(turn_id or "").strip()+ if not normalized:+ return+ with self._lock:+ trace = self._traces.get(normalized)+ if trace is None:+ return+ identity = trace.pending_attempt+ payload = (+ identity.payload()+ if identity is not None and identity.channel == "hub"+ else trace.served+ )+ if payload is None or payload.get("channel") != "hub":+ return+ trace.pending_attempt = None+ trace.served = None+ trace.terminal_error = {+ **payload,+ "reason": "protocol_error",+ "stream_started": True,+ }++ def finish_attempt(+ self,+ turn_id: Optional[str],+ *,+ outcome: RawCallOutcome,+ decision: ResolutionDecision,+ ) -> None:+ if turn_id is None:+ return+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is None or trace.pending_attempt is None:+ return+ identity = trace.pending_attempt+ trace.pending_attempt = None+ if decision.action == "return":+ trace.served = identity.payload()+ trace.terminal_error = None+ return+ if decision.action == "fallback" and decision.reason is not None:+ trace.failed_attempts.append(+ {**identity.payload(), "reason": decision.reason}+ )+ return+ if decision.action == "surface":+ trace.terminal_error = {+ **identity.payload(),+ "reason": _terminal_reason(decision),+ "stream_started": outcome.stream_started,+ }++ def settle(self, turn_id: str, *, settled_by: Optional[str], ts: Optional[str] = None) -> None:+ normalized_turn_id = str(turn_id or "").strip()+ if not normalized_turn_id:+ return+ with self._lock:+ trace = self._traces.pop(normalized_turn_id, None)+ scope_keys = self._turn_scopes.pop(normalized_turn_id, set())+ poisoned = False+ for key in scope_keys:+ scope = self._scopes.get(key)+ if scope is None:+ continue+ poisoned = poisoned or scope.untracked_use+ scope.active_turns.discard(normalized_turn_id)+ scope.ambiguous_turns.discard(normalized_turn_id)+ if trace is None or trace.ambiguous or poisoned:+ return++ served = trace.served+ terminal_error = trace.terminal_error+ canceled_attempt = None+ supply_state = None+ if settled_by == SETTLED_BY_STOPPED:+ outcome = "canceled"+ canceled_attempt = (+ trace.pending_attempt.payload()+ if trace.pending_attempt is not None+ else None+ )+ served = None+ terminal_error = None+ elif trace.model_supply_state is not None:+ outcome = "no_candidate"+ served = None+ terminal_error = None+ supply_state = trace.model_supply_state+ elif settled_by in {+ SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_BACKEND_REFRESH,+ }:+ interrupted_attempt = (+ trace.pending_attempt.payload()+ if trace.pending_attempt is not None+ else served+ )+ if terminal_error is None and interrupted_attempt is None:+ if not trace.failed_attempts:+ return+ outcome = "exhausted"+ else:+ outcome = "failed_terminal"+ served = None+ terminal_error = terminal_error or {+ **interrupted_attempt,+ "reason": "stream_interrupted",+ "stream_started": True,+ }+ elif (+ settled_by == SETTLED_BY_TERMINAL_RESULT+ and trace.pending_attempt is not None+ and trace.pending_attempt.channel == "native_cli"+ ):+ outcome = "served"+ served = trace.pending_attempt.payload()+ terminal_error = None+ elif terminal_error is not None:+ outcome = "failed_terminal"+ served = None+ elif served is not None:+ outcome = "served"+ elif trace.failed_attempts:+ outcome = "exhausted"+ else:+ return++ self.store.put(+ {+ "contract_version": 4,+ "turn_id": normalized_turn_id,+ "ts": ts or _utc_now_iso(),+ "agent": trace.agent,+ "requested_model_id": trace.requested_model_id,+ "outcome": outcome,+ "failed_attempts": list(trace.failed_attempts),+ "served": served,+ "terminal_error": terminal_error,+ "canceled_attempt": canceled_attempt,+ "model_supply_state": supply_state,+ }+ )diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 8f71738bf..d15606fc8 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -55,6 +55,15 @@ async def dispatch_model_hub_rpc(return await service.delete_custom_model(payload.get("source_id"), payload.get("model_id"))if operation == "list_events":return service.list_events(limit=payload.get("limit", 20), before=payload.get("before"))+ if operation == "get_agent_chain":+ return service.agent_chain(payload.get("backend"), payload.get("model_id"))+ if operation == "probe_agent":+ return await service.probe_agent(+ payload.get("backend"),+ payload.get("model_id"),+ )+ if operation == "get_turn_provenance":+ return service.get_turn_provenance(payload.get("turn_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.pyindex c48ce17b9..1f13d3942 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -4,12 +4,15 @@ from __future__ import annotationsimport asyncioimport logging+import timeimport uuidfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Literal, Mapping, Optional, Protocol, castfrom urllib.parse import parse_qsl, urlsplit+from sqlalchemy import func, select+from config import pathsfrom config.v2_config import (CONFIG_LOCK,@@ -25,6 +28,8 @@ from config.v2_config import (V2Config,)from core.services.settings import default_config+from storage.db import get_cached_sqlite_engine+from storage.models import agent_sessions, messagesfrom vibe.backend_model_catalog import backend_model_entries, load_bundled_catalogfrom .adapter import (@@ -35,6 +40,7 @@ from .adapter import (OAuthFlowState,OriginNotAllowedError,RawCallOutcome,+ RawOutcomeKind,SourceBinding,)from .classification import ResolutionDecision, classify_outcome@@ -66,6 +72,8 @@ from .oauth import (OAuthFlowRegistry,UnavailableNativeOAuthAdapter,)+from .provenance import BoundedProvenanceStore+from .request import ModelHubRequestfrom .resolver import (BackendName,ModelHubTurnResolution,@@ -74,10 +82,13 @@ from .resolver import (resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,+ source_runnable,)from .revocations import CredentialRevocationJournalCONTRACT_VERSION = 3+AGENT_CHAIN_CONTRACT_VERSION = 4+PROBE_RESULT_CONTRACT_VERSION = 4logger = logging.getLogger(__name__)_NATIVE_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}@@ -106,6 +117,7 @@ class ModelHubError(Exception):*,status: int = 400,detail: Optional[str] = None,+ supply_state: Optional[Literal["waiting", "interrupted"]] = None,data: Optional[Mapping[str, Any]] = None,):detail_key = detail or f"modelHub.errors.{code}"@@ -113,6 +125,7 @@ class ModelHubError(Exception):self.code = codeself.status = statusself.detail = detail_key+ self.supply_state = supply_stateself.data = dict(data or {})@@ -225,6 +238,19 @@ class ResolvedInvocation:supply_channel: Literal["native_cli", "hub"] = "hub"+AttemptObserver = Callable[+ [+ str,+ str,+ Literal["native_cli", "hub"],+ bool,+ Optional[RawCallOutcome],+ Optional[ResolutionDecision],+ ],+ None,+]++def _utc_now() -> datetime:return datetime.now(timezone.utc)@@ -379,6 +405,7 @@ class ModelHubService:store: ModelHubConfigStore,adapter: EngineAdapter,events: BoundedEventLog,+ provenance: Optional[BoundedProvenanceStore] = None,native_oauth_adapter: Optional[NativeOAuthAdapter] = None,oauth_flows: Optional[OAuthFlowRegistry] = None,revocations: Optional[CredentialRevocationJournal] = None,@@ -393,6 +420,9 @@ class ModelHubService:self.store = storeself.adapter = adapterself.events = events+ self.provenance = provenance or BoundedProvenanceStore(+ paths.get_state_dir() / "model_hub_turn_provenance.json"+ )self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()self.oauth_flows = oauth_flows or OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json")self.revocations = revocations or CredentialRevocationJournal(@@ -611,6 +641,16 @@ class ModelHubService:def _record_event(self, **event_fields: Any) -> None:try:+ source_ids = {+ source.id+ for source in self.store.load().sources+ }+ for field in ("from_source", "to_source"):+ source_id = event_fields.get(field)+ if source_id is not None and source_id not in source_ids:+ raise ValueError(+ f"Resolution event names unknown {field}"+ )self.events.append(build_resolution_event(**event_fields))except Exception:# Resolution telemetry is best effort and must never affect routing.@@ -1653,6 +1693,15 @@ class ModelHubService:detail_key="models.source.error.unclassified",)self.store.save(config)+ self._record_event(+ agent="system",+ kind="needs_action",+ model_id=None,+ reason="unclassified_error",+ from_source=source.id,+ from_label=source.display_name,+ now=self.now(),+ )raisesource.state = ModelHubSourceStateConfig(status="standby")await self._commit_synced(previous, config)@@ -1992,7 +2041,440 @@ class ModelHubService:return source.to_payload()def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:- return self.events.list(limit=limit, before=before)+ events = self.events.list(limit=limit, before=before)+ for event in events:+ if event.get("severity") is None:+ event["severity"] = (+ "action_required"+ if event.get("kind") in {"needs_action", "supply_interrupted"}+ else "info"+ )+ return events++ @staticmethod+ def _direct_mode_error() -> ModelHubError:+ return ModelHubError(+ "direct_mode",+ status=409,+ detail="models.hub.direct_mode",+ )++ @staticmethod+ def _chain_supply_state(chain: list[dict]) -> Literal["ok", "waiting", "interrupted"]:+ if any(item["runnable"] for item in chain):+ return "ok"+ if chain and all(+ item["health"] == "cooldown" and item["reason"] is None+ for item in chain+ ):+ return "waiting"+ return "interrupted"++ def _agent_chain(+ self,+ config: ModelHubConfig,+ backend: str,+ model_id: str,+ ) -> dict:+ agent = self._agent(config, backend)+ if agent.mode == "direct":+ raise self._direct_mode_error()+ now = self.now()+ unavailable = self._unavailable_native_sources(+ config,+ cast(BackendName, backend),+ )+ resolution = resolve_model_hub_turn(+ config,+ cast(BackendName, backend),+ model_id,+ now=now,+ unavailable_source_ids=unavailable,+ )+ chain: list[dict] = []+ for source in resolution.matching_sources:+ status = source.state.status+ health = (+ "healthy"+ if status in {"active", "standby"}+ else status+ )+ runnable = source_runnable(+ source,+ now=now,+ unavailable_source_ids=unavailable,+ )+ resolved_model = (+ resolution.target_model+ if resolution.mapping_applied or backend == "opencode"+ else None+ )+ chain.append(+ {+ "source_id": source.id,+ "channel": source.supply_channel,+ "via_mapping": resolution.mapping_applied,+ "resolved_model_id": resolved_model,+ "health": health,+ "runnable": runnable,+ "reason": (+ "native_cli_unavailable"+ if source.id in unavailable+ else None+ ),+ "retry_at": (+ source.state.retry_at+ if health == "cooldown"+ else None+ ),+ }+ )+ return {+ "contract_version": AGENT_CHAIN_CONTRACT_VERSION,+ "backend": backend,+ "model_id": resolution.requested_model or model_id,+ "chain": chain,+ "supply_state": self._chain_supply_state(chain),+ }++ def agent_chain(self, backend: str, model_id: object) -> dict:+ if backend not in MODEL_HUB_BACKENDS or not isinstance(model_id, str) or not model_id:+ raise ModelHubError("mapping_target_unavailable", status=409)+ return self._agent_chain(self.store.load(), backend, model_id)++ @staticmethod+ def _probe_request(+ source: ModelHubSourceConfig,+ model_id: str,+ backend: str,+ ) -> ModelHubRequest:+ # A probe enters the same translation seam as a live backend turn, so+ # its payload must be shaped in the backend's client protocol.+ request_protocol = {+ "claude": "anthropic",+ "codex": "openai_responses",+ }.get(backend, source.protocol)+ if request_protocol == "anthropic":+ payload = {+ "model": model_id,+ "max_tokens": 1,+ "messages": [{"role": "user", "content": "ping"}],+ }+ elif request_protocol == "openai_responses":+ payload = {+ "model": model_id,+ "max_output_tokens": 1,+ "input": "ping",+ }+ else:+ payload = {+ "model": model_id,+ "max_tokens": 1,+ "messages": [{"role": "user", "content": "ping"}],+ }+ return ModelHubRequest(payload, protocol=request_protocol)++ @staticmethod+ def _probe_failure(+ outcome: RawCallOutcome,+ decision: ResolutionDecision,+ ) -> tuple[str, Optional[EventReason]]:+ if decision.action == "surface":+ return "models.source.error.unclassified", None+ if decision.reason == "permission_denied":+ return "models.source.error.unclassified", None+ if outcome.kind == RawOutcomeKind.NETWORK_ERROR:+ return "models.source.cooldown.network", "network"+ if outcome.kind == RawOutcomeKind.TIMEOUT:+ return "models.source.cooldown.timeout", "network"+ text = " ".join(+ value+ for value in (outcome.error_code, outcome.redacted_message)+ if isinstance(value, str)+ ).lower()+ if outcome.http_status == 401:+ return "models.source.needs_action.oauth_expired", "credential_expired"+ if outcome.http_status == 402 or "balance" in text:+ return "models.source.needs_action.balance_exhausted", "balance_exhausted"+ if outcome.http_status == 403 and any(+ marker in text for marker in ("ban", "suspend", "disabled account")+ ):+ return "models.source.needs_action.account_banned", "account_banned"+ if outcome.http_status == 403:+ return "models.source.needs_action.credential_revoked", "credential_revoked"+ if decision.reason == "unclassified_error":+ return "models.source.error.unclassified", "unclassified_error"+ if decision.action == "fallback" and decision.reason is not None:+ return f"models.source.cooldown.{decision.reason}", cast(+ EventReason,+ decision.reason,+ )+ return "models.source.error.unclassified", "unclassified_error"++ async def _set_source_blocker(+ self,+ source_id: str,+ *,+ backend: BackendName,+ model_id: str,+ detail_key: str,+ reason: EventReason,+ ) -> None:+ async with self._mutation_lock:+ config = self.store.load()+ source = self._source(config, source_id)+ status: Literal["error", "needs_action"] = (+ "error"+ if reason == "unclassified_error"+ else "needs_action"+ )+ unchanged = (+ source.state.status == status+ and source.state.detail_key == detail_key+ )+ source.state = ModelHubSourceStateConfig(+ status=status,+ detail_key=detail_key,+ )+ self.store.save(config)+ if not unchanged:+ self._record_event(+ agent=cast(EventAgent, backend),+ kind="needs_action",+ model_id=model_id,+ reason=reason,+ from_source=source.id,+ from_label=source.display_name,+ now=self.now(),+ )++ async def probe_agent(self, backend: str, model_id: object = None) -> 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)+ candidate_payload = next(+ (item for item in chain_payload["chain"] if item["runnable"]),+ None,+ )+ if candidate_payload is None:+ supply_state = chain_payload["supply_state"]+ retry_at = min(+ (+ item["retry_at"]+ for item in chain_payload["chain"]+ if item["retry_at"]+ ),+ default=None,+ )+ raise ModelHubError(+ "probe_no_candidate",+ status=409,+ detail=f"models.probe.no_candidate.{supply_state}",+ data={+ "supply": {+ "supply_state": supply_state,+ "retry_at": retry_at,+ }+ },+ )+ source = self._source(config, candidate_payload["source_id"])+ resolved_model = (+ candidate_payload["resolved_model_id"]+ or chain_payload["model_id"]+ )+ if source.supply_channel == "native_cli":+ ready = self.native_source_ready(+ cast(BackendName, backend),+ source_after_cooldown_recovery(source, self.now()),+ )+ return {+ "contract_version": PROBE_RESULT_CONTRACT_VERSION,+ "backend": backend,+ "channel": "native_cli",+ "reachable": ready,+ "source_id": source.id,+ "model_id": resolved_model,+ "latency_ms": None,+ "via_mapping": bool(candidate_payload["via_mapping"]),+ "error": (+ None+ if ready+ else "models.probe.native_cli_unavailable"+ ),+ }++ await self._ensure_engine_synced()+ started_at = time.monotonic()+ handle = await self._engine_call(+ self.adapter.invoke(+ source.id,+ resolved_model,+ self._probe_request(source, resolved_model, backend),+ False,+ backend,+ )+ )+ if handle.stream is not None:+ async for _chunk in handle.stream:+ pass+ outcome = await self._engine_call(handle.outcome())+ decision = classify_outcome(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,+ )+ )+ if handle.stream is not None:+ async for _chunk in handle.stream:+ pass+ outcome = await self._engine_call(handle.outcome())+ decision = classify_outcome(outcome, refresh_attempted=True)+ elapsed_ms = max(0, round((time.monotonic() - started_at) * 1000))+ reachable = decision.action == "return"+ error_key: Optional[str] = None+ latency_ms: Optional[int] = elapsed_ms+ if not reachable:+ error_key, event_reason = self._probe_failure(outcome, decision)+ if error_key in {+ "models.source.cooldown.network",+ "models.source.cooldown.timeout",+ }:+ latency_ms = None+ if event_reason in {+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ }:+ await self._cooldown(+ source,+ decision,+ agent=cast(EventAgent, backend),+ model_id=resolved_model,+ detail_key=error_key,+ )+ elif event_reason is not None:+ await self._set_source_blocker(+ source.id,+ backend=cast(BackendName, backend),+ model_id=resolved_model,+ detail_key=error_key,+ reason=event_reason,+ )+ return {+ "contract_version": PROBE_RESULT_CONTRACT_VERSION,+ "backend": backend,+ "channel": "hub",+ "reachable": reachable,+ "source_id": source.id,+ "model_id": resolved_model,+ "latency_ms": latency_ms,+ "via_mapping": bool(candidate_payload["via_mapping"]),+ "error": error_key,+ }++ @staticmethod+ def note_turn_mode(+ turn_id: str,+ mode: Literal["direct", "hub"],+ ) -> None:+ """Store the mode on the message row whose lifetime defines the turn."""++ normalized = str(turn_id or "").strip()+ if not normalized:+ return+ with get_cached_sqlite_engine().begin() as conn:+ conn.execute(+ messages.update()+ .where(+ func.json_extract(+ messages.c.metadata_json,+ "$.turn_id",+ )+ == normalized+ )+ .values(+ metadata_json=func.json_set(+ messages.c.metadata_json,+ "$.model_hub_mode",+ mode,+ )+ )+ )++ @staticmethod+ def _known_turn(+ turn_id: str,+ ) -> tuple[Optional[str], Optional[Literal["direct", "hub"]]]:+ try:+ with get_cached_sqlite_engine().connect() as conn:+ row = conn.execute(+ select(+ agent_sessions.c.agent_backend.label("backend"),+ func.json_extract(+ messages.c.metadata_json,+ "$.model_hub_mode",+ ).label("mode"),+ )+ .select_from(+ messages.join(+ agent_sessions,+ messages.c.session_id == agent_sessions.c.id,+ )+ )+ .where(+ func.json_extract(+ messages.c.metadata_json,+ "$.turn_id",+ )+ == turn_id+ )+ .limit(1)+ ).mappings().first()+ except Exception:+ return None, None+ if row is None:+ return None, None+ mode = row["mode"]+ return (+ str(row["backend"]),+ mode if mode in {"direct", "hub"} else None,+ )++ def get_turn_provenance(self, turn_id: object) -> dict:+ normalized = str(turn_id or "").strip()+ if not normalized:+ raise ModelHubError("turn_not_found", status=404)+ record = self.provenance.get(normalized)+ if record is not None:+ return record+ backend, mode = self._known_turn(normalized)+ if backend is None:+ raise ModelHubError("turn_not_found", status=404)+ detail = (+ "models.provenance.direct_mode"+ if mode == "direct"+ else "models.provenance.attribution_ambiguous"+ )+ raise ModelHubError(+ "provenance_unavailable",+ status=409,+ detail=detail,+ )async def reauth_source(self, source_id: str, payload: object) -> dict:if (@@ -2366,6 +2848,7 @@ class ModelHubService:*,agent: EventAgent,model_id: str,+ detail_key: Optional[str] = None,) -> None:async with self._mutation_lock:config = self.store.load()@@ -2373,21 +2856,23 @@ class ModelHubService:current = self._source(config, source.id)except ModelHubError:return+ already_cooling = current.state.status == "cooldown"current.state = ModelHubSourceStateConfig(status="cooldown",retry_at=(self.now() + timedelta(seconds=decision.cooldown_seconds)).isoformat(),- detail_key=f"models.source.cooldown.{decision.reason}",+ detail_key=detail_key or f"models.source.cooldown.{decision.reason}",)self.store.save(config)- self._record_event(- agent=agent,- kind="cooldown",- model_id=model_id,- reason=cast(EventReason, decision.reason),- from_source=current.id,- from_label=current.display_name,- now=self.now(),- )+ if not already_cooling:+ self._record_event(+ agent=agent,+ kind="cooldown",+ model_id=model_id,+ reason=cast(EventReason, decision.reason),+ from_source=current.id,+ from_label=current.display_name,+ now=self.now(),+ )def _emit_switch(self,@@ -2440,6 +2925,7 @@ class ModelHubService:request: Mapping[str, Any],stream: bool = False,supply_channel: Literal["hub"] | None = None,+ attempt_observer: Optional[AttemptObserver] = None,) -> ResolvedInvocation:if backend not in {"claude", "codex", "opencode"}:raise ModelHubError("mapping_target_unavailable")@@ -2495,7 +2981,16 @@ class ModelHubService:)candidates = list(resolution.candidates)if not candidates:- raise ModelHubError("mapping_target_unavailable", status=409)+ supply_state = (+ "waiting"+ if resolution.supply_status == "waiting"+ else "interrupted"+ )+ raise ModelHubError(+ "mapping_target_unavailable",+ status=409,+ supply_state=supply_state,+ )failed_source: Optional[ModelHubSourceConfig] = Nonefailed_reason: Optional[EventReason] = None@@ -2517,6 +3012,15 @@ class ModelHubService:)if not engine_prepared:await self._ensure_engine_synced()+ if attempt_observer is not None:+ attempt_observer(+ source.id,+ target_model,+ "hub",+ resolution.mapping_applied,+ None,+ None,+ )handle, outcome = await self._invoke(source=source,model_id=target_model,@@ -2554,6 +3058,15 @@ class ModelHubService:)return ResolvedInvocation(source.id, target_model, handle, None)decision = classify_outcome(outcome, refresh_attempted=True)+ if attempt_observer is not None:+ attempt_observer(+ source.id,+ target_model,+ "hub",+ resolution.mapping_applied,+ outcome,+ decision,+ )if decision.action == "return":self._emit_switch(agent=event_agent,@@ -2573,9 +3086,36 @@ class ModelHubService:),)if decision.action == "fallback":- await self._cooldown(source, decision, agent=event_agent, model_id=target_model)+ event_reason = cast(EventReason, decision.reason)+ if event_reason in {+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ }:+ await self._cooldown(+ source,+ decision,+ agent=event_agent,+ model_id=target_model,+ )+ elif event_reason != "permission_denied":+ detail_key = {+ "credential_expired": "models.source.needs_action.oauth_expired",+ "credential_revoked": "models.source.needs_action.credential_revoked",+ "balance_exhausted": "models.source.needs_action.balance_exhausted",+ "account_banned": "models.source.needs_action.account_banned",+ "unclassified_error": "models.source.error.unclassified",+ }[event_reason]+ await self._set_source_blocker(+ source.id,+ backend=cast(BackendName, backend),+ model_id=target_model,+ detail_key=detail_key,+ reason=event_reason,+ )failed_source = source- failed_reason = cast(EventReason, decision.reason)+ failed_reason = event_reasoncontinueraise ModelHubError(decision.error_code or "engine_down", status=502)raise ModelHubError("engine_down", status=503)diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 98eb1e127..7f70736d2 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -4,13 +4,20 @@ from __future__ import annotationsimport asyncioimport json-import secretsimport socket-from typing import Final+from typing import Final, Optionalfrom aiohttp import web+from config import paths+from .adapter import RawCallOutcome, RawOutcomeKind+from .classification import classify_outcome+from .provenance import (+ BoundedProvenanceStore,+ GatewayTurnTerminalizer,+ TurnCorrelationRegistry,+)from .request import ModelHubRequestfrom .service import ModelHubError, ModelHubService, ResolvedInvocation@@ -40,23 +47,54 @@ _PROTOCOL_HEADERS: Final = frozenset(class ModelHubTurnGateway:"""Expose the controller-owned resolver to backend CLI HTTP clients."""- def __init__(self, service: ModelHubService) -> None:+ def __init__(+ self,+ service: ModelHubService,+ *,+ correlation: Optional[TurnCorrelationRegistry] = None,+ ) -> None:self.service = service- self._tokens = {- backend: secrets.token_urlsafe(32)- for backend in ("claude", "codex", "opencode")- }+ self.correlation = correlation or TurnCorrelationRegistry(+ getattr(+ service,+ "provenance",+ BoundedProvenanceStore(+ paths.get_state_dir() / "model_hub_turn_provenance.json"+ ),+ )+ )self._start_lock = asyncio.Lock()self._runner: web.AppRunner | None = Noneself._site: web.SockSite | None = Noneself._base_url: str | None = None- async def endpoint(self, backend: str) -> tuple[str, str]:+ async def endpoint(+ self,+ backend: str,+ *,+ process_scope: Optional[str] = None,+ turn_id: Optional[str] = None,+ requested_model_id: Optional[str] = None,+ resolved_model_id: Optional[str] = None,+ source_id: Optional[str] = None,+ via_mapping: bool = False,+ ) -> tuple[str, str]:if backend not in {"claude", "codex", "opencode"}:raise ModelHubError("mapping_target_unavailable", status=409)+ scope = str(process_scope or "").strip() or f"{backend}:untracked"+ token = self.correlation.credentials(backend, scope, turn_id)+ if requested_model_id and resolved_model_id and source_id:+ self.correlation.prepare_gateway_turn(+ backend=backend,+ token=token,+ requested_model_id=requested_model_id,+ resolved_model_id=resolved_model_id,+ source_id=source_id,+ via_mapping=via_mapping,+ )await self._ensure_started()assert self._base_url is not None- return f"{self._base_url}/{backend}", self._tokens[backend]+ return f"{self._base_url}/{backend}", tokenasync def close(self) -> None:runner = self._runner@@ -93,53 +131,92 @@ class ModelHubTurnGateway:self._site = siteself._base_url = f"http://127.0.0.1:{port}"- def _authorized(self, request: web.Request, backend: str) -> bool:- expected = self._tokens.get(backend)- if expected is None:- return False+ def _authorized_token(self, request: web.Request, backend: str) -> Optional[str]:authorization = request.headers.get("Authorization", "")bearer = authorization[7:] if authorization.lower().startswith("bearer ") else ""api_key = request.headers.get("x-api-key", "")- return secrets.compare_digest(bearer, expected) or secrets.compare_digest(api_key, expected)+ for candidate in (bearer, api_key):+ if candidate and self.correlation.authenticates(backend, candidate):+ return candidate+ return Noneasync def _handle_request(self, request: web.Request) -> web.StreamResponse:backend = request.match_info["backend"]- if not self._authorized(request, backend):+ token = self._authorized_token(request, backend)+ if token is None:return self._error_response(status=401, code="authentication_error")- endpoint = request.match_info["endpoint"].strip("/")- if backend not in {"claude", "codex", "opencode"} or endpoint not in _SUPPORTED_PATHS:- return self._error_response(status=404, code="not_found_error")- try:- payload = await request.json(loads=json.loads)- except (json.JSONDecodeError, UnicodeDecodeError):- return self._error_response(status=400, code="invalid_request_error")- if not isinstance(payload, dict):- return self._error_response(status=400, code="invalid_request_error")- model_id = payload.get("model")- stream = payload.get("stream", False)- if not isinstance(model_id, str) or not model_id or not isinstance(stream, bool):- return self._error_response(status=400, code="invalid_request_error")+ with self.correlation.gateway_terminalizer(+ backend=backend,+ token=token,+ ) as terminalizer:+ endpoint = request.match_info["endpoint"].strip("/")+ if backend not in {"claude", "codex", "opencode"} or endpoint not in _SUPPORTED_PATHS:+ terminalizer.fail("protocol_error")+ return self._error_response(status=404, code="not_found_error")+ try:+ payload = await request.json(loads=json.loads)+ except (json.JSONDecodeError, UnicodeDecodeError):+ terminalizer.fail("invalid_parameter")+ return self._error_response(status=400, code="invalid_request_error")+ if not isinstance(payload, dict):+ terminalizer.fail("invalid_parameter")+ return self._error_response(status=400, code="invalid_request_error")+ model_id = payload.get("model")+ stream = payload.get("stream", False)+ if not isinstance(model_id, str) or not model_id or not isinstance(stream, bool):+ terminalizer.fail("invalid_parameter")+ return self._error_response(status=400, code="invalid_request_error")+ terminalizer.bind_request_model(model_id)- try:- protocol_headers = {- name.lower(): value- for name, value in request.headers.items()- if name.lower() in _PROTOCOL_HEADERS- }- resolved = await self.service.resolve(- backend=backend,- model_id=model_id,- request=ModelHubRequest(- payload,- protocol=_REQUEST_PROTOCOLS[endpoint],- headers=protocol_headers,- ),+ def observe_attempt(+ source_id: str,+ resolved_model_id: str,+ channel: str,+ via_mapping: bool,+ outcome: Optional[RawCallOutcome],+ decision,+ ) -> None:+ if outcome is None or decision is None:+ terminalizer.begin_attempt(+ source_id=source_id,+ resolved_model_id=resolved_model_id,+ channel=channel,+ via_mapping=via_mapping,+ )+ return+ terminalizer.finish_attempt(+ outcome=outcome,+ decision=decision,+ )++ try:+ protocol_headers = {+ name.lower(): value+ for name, value in request.headers.items()+ if name.lower() in _PROTOCOL_HEADERS+ }+ resolved = await self.service.resolve(+ backend=backend,+ model_id=model_id,+ request=ModelHubRequest(+ payload,+ protocol=_REQUEST_PROTOCOLS[endpoint],+ headers=protocol_headers,+ ),+ stream=stream,+ supply_channel="hub",+ attempt_observer=observe_attempt,+ )+ except ModelHubError as exc:+ if exc.supply_state is not None:+ terminalizer.mark_no_candidate(exc.supply_state)+ return self._error_response(status=exc.status, code=exc.code)+ return await self._resolved_response(+ request,+ resolved,stream=stream,- supply_channel="hub",+ terminalizer=terminalizer,)- except ModelHubError as exc:- return self._error_response(status=exc.status, code=exc.code)- return await self._resolved_response(request, resolved, stream=stream)async def _resolved_response(self,@@ -147,6 +224,7 @@ class ModelHubTurnGateway:resolved: ResolvedInvocation,*,stream: bool,+ terminalizer: GatewayTurnTerminalizer,) -> web.StreamResponse:if resolved.supply_channel != "hub":return self._error_response(status=409, code="mode_switch_blocked")@@ -160,7 +238,17 @@ class ModelHubTurnGateway:payload = bytearray()async for chunk in handle.stream:payload.extend(chunk)- await handle.outcome()+ outcome = await handle.outcome()+ decision = classify_outcome(outcome)+ terminalizer.finish_attempt(+ outcome=outcome,+ decision=decision,+ )+ if decision.action != "return":+ return self._outcome_response(+ outcome,+ error_code=decision.error_code,+ )return web.Response(status=200,body=bytes(payload),@@ -180,20 +268,29 @@ class ModelHubTurnGateway:await response.prepare(request)try:async for chunk in handle.stream:+ terminalizer.mark_stream_started()await response.write(chunk)finally:- await handle.outcome()+ outcome = await handle.outcome()+ terminalizer.finish_attempt(+ outcome=outcome,+ decision=classify_outcome(outcome),+ )await response.write_eof()return response@staticmethod- def _outcome_response(outcome: RawCallOutcome) -> web.Response:+ def _outcome_response(+ outcome: RawCallOutcome,+ *,+ error_code: Optional[str] = None,+ ) -> web.Response:if outcome.kind == RawOutcomeKind.SUCCESS:return web.Response(status=200, body=b"{}", content_type="application/json")status = outcome.http_status if outcome.http_status and 400 <= outcome.http_status <= 599 else 502return ModelHubTurnGateway._error_response(status=status,- code=outcome.error_code or "api_error",+ code=error_code or outcome.error_code or "api_error",)@staticmethoddiff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 9f7da3b2c..a94881fae 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -203,7 +203,10 @@ class SessionHandler(BaseHandler):if getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint:logger.info("Recreating cached Claude SDK client because Model Hub channel changed")await self._wait_for_claude_session_idle(composite_key)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Nonenext_system_prompt = self._build_claude_system_prompt(@@ -219,7 +222,10 @@ class SessionHandler(BaseHandler):"Recreating cached Claude SDK client for %s because avibe system prompt changed",composite_key,)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Nonecaller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))@@ -228,7 +234,10 @@ class SessionHandler(BaseHandler):"Recreating cached Claude SDK client for %s because caller context env changed",composite_key,)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Nonegit_path_state = self._claude_git_path_state(working_path)if getattr(client, "_vibe_git_path_state", None) != git_path_state:@@ -236,7 +245,10 @@ class SessionHandler(BaseHandler):"Recreating cached Claude SDK client for %s because Git PATH changed",composite_key,)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Nonetry:@@ -273,7 +285,10 @@ class SessionHandler(BaseHandler):if getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint:logger.info("Recreating cached Claude subagent SDK client because Model Hub channel changed")await self._wait_for_claude_session_idle(composite_key)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Noneself.ensure_agent_session_id(context,@@ -287,7 +302,10 @@ class SessionHandler(BaseHandler):"Recreating cached Claude subagent SDK client for %s because caller context env changed",composite_key,)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Nonegit_path_state = self._claude_git_path_state(working_path)if getattr(client, "_vibe_git_path_state", None) != git_path_state:@@ -295,7 +313,10 @@ class SessionHandler(BaseHandler):"Recreating cached Claude subagent SDK client for %s because Git PATH changed",composite_key,)- await self.cleanup_session(composite_key)+ await self.cleanup_session(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )return Noneif desired_model:try:@@ -805,12 +826,23 @@ class SessionHandler(BaseHandler):if configured_agent_model and configured_agent_model.lower() not in ("inherit", ""):launch_model = configured_agent_modellaunch_model = launch_model or self.config.claude.default_model+ cached_base = (+ f"{base_session_id}:{effective_agent}"+ if effective_agent+ else None+ )+ cached_key = (+ f"{cached_base}:{working_path}"+ if cached_base is not None+ else None+ )from modules.agents.model_hub import bind_launch, resolve_model_hub_launchmodel_hub_launch = await resolve_model_hub_launch(self.controller,"claude",launch_model or "",+ process_scope=cached_key or composite_key,)bind_launch(context, model_hub_launch)runtime_model = model_hub_launch.runtime_model or launch_model@@ -835,8 +867,7 @@ class SessionHandler(BaseHandler):return clientif effective_agent:- cached_base = f"{base_session_id}:{effective_agent}"- cached_key = f"{cached_base}:{working_path}"+ assert cached_base is not None and cached_key is not Nonecached_session_id = self.sessions.get_agent_session_id(session_key,cached_base,@@ -1121,6 +1152,26 @@ class SessionHandler(BaseHandler):label="claude",)except Exception as exc:+ router = getattr(self.controller, "model_hub_runtime", None)+ record_failure = getattr(router, "record_native_failure", None)+ if callable(record_failure):+ try:+ await record_failure(context, str(exc))+ except Exception:+ logger.warning(+ "Failed to record Model Hub Claude startup failure",+ exc_info=True,+ )+ terminal_turn_id = str(+ (getattr(context, "platform_specific", None) or {}).get(+ "turn_token"+ )+ or ""+ ).strip()+ self._retire_model_hub_process_scope(+ composite_key,+ terminal_turn_id=terminal_turn_id or None,+ )stderr_text = "\n".join(claude_stderr_lines)match = CLAUDE_NO_CONVERSATION_RE.search(stderr_text) or CLAUDE_NO_CONVERSATION_RE.search(str(exc))if match:@@ -1404,10 +1455,36 @@ class SessionHandler(BaseHandler):return Falsereturn bool(agent and getattr(agent, "backend", None) == backend)- async def cleanup_session(self, composite_key: str, *, current_receiver_task=None):+ def _retire_model_hub_process_scope(+ self,+ composite_key: str,+ *,+ terminal_turn_id: Optional[str] = None,+ ) -> None:+ router = getattr(self.controller, "model_hub_runtime", None)+ retire = getattr(router, "retire_process_scope", None)+ if callable(retire):+ if terminal_turn_id is None:+ retire("claude", composite_key)+ else:+ retire(+ "claude",+ composite_key,+ terminal_turn_id=terminal_turn_id,+ )++ async def cleanup_session(+ self,+ composite_key: str,+ *,+ current_receiver_task=None,+ retire_model_hub_scope: bool = True,+ ):"""Clean up a specific session by composite key"""receiver_task = self.receiver_tasks.pop(composite_key, None)client = self.claude_sessions.pop(composite_key, None)+ if client is not None and retire_model_hub_scope:+ self._retire_model_hub_process_scope(composite_key)cleanup_from_receiver = receiver_task is not None and receiver_task is current_receiver_tasknative_session_id = getattr(client, "_vibe_native_session_id", None)keep_pid = get_claude_client_pid(client)diff --git a/core/session_turns.py b/core/session_turns.pyindex 7539c2bea..bcb0ca037 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -904,6 +904,67 @@ class SessionTurnManager:"""return {session_id for session_id in list(self.in_flight) if session_id}+ def model_hub_turn_id_for_task(+ self,+ task: Optional[asyncio.Task] = None,+ ) -> Optional[str]:+ """Return the existing FSM turn token owned by ``task``.++ Model Hub launch resolution runs inside the turn's dispatch task. IM and+ CLI calls do not enter this registry, so they intentionally return no id.+ """++ owner = task or asyncio.current_task()+ if owner is None:+ return None+ for turn in list(self.in_flight.values()):+ if turn.task is not owner or turn.task.done():+ continue+ token = str(+ (getattr(turn.context, "platform_specific", None) or {}).get(+ "turn_token"+ )+ or ""+ ).strip()+ return token or None+ return None++ def _settle_model_hub_turn(+ self,+ context: "MessageContext",+ settled_by: Optional[str],+ ) -> None:+ runtime = getattr(self.controller, "model_hub_runtime", None)+ settle = getattr(runtime, "settle_turn", None)+ turn_id = str(+ (getattr(context, "platform_specific", None) or {}).get("turn_token")+ or ""+ ).strip()+ if not turn_id or not callable(settle):+ return+ try:+ from modules.agents.model_hub import (+ launch_for_context,+ turn_mode_for_context,+ )++ launch = launch_for_context(context)+ mode = turn_mode_for_context(context)+ if mode is None and launch is not None:+ mode = "direct" if launch.channel == "direct" else "hub"+ settle(+ turn_id,+ settled_by=settled_by,+ ts=_utc_now_iso(),+ mode=mode,+ )+ except Exception:+ logger.warning(+ "Model Hub provenance settlement failed for turn=%s",+ turn_id,+ exc_info=True,+ )+def bind_context(self, build_context: Callable[[str], "MessageContext"]) -> None:"""Inject the routing-context builder (it lives in ``internal_server``) oncethe gate is built, so ``flush_queue`` can rebuild a queued follow-up's@@ -1161,6 +1222,7 @@ class SessionTurnManager:settled_by = (getattr(turn, "cancel_settled_by", None) if turn is not None else None) or SETTLED_BY_STOPPED+ self._settle_model_hub_turn(context, settled_by)# Converge the no-terminal-result outcome onto the OUTBOUND status# chokepoint. The normal path already emitted a terminal result;# only ``failed`` reaches here without one: dispatch raised beforediff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex c45d330cc..01b59155e 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,7 +1,10 @@# Model Hub — Interface Contracts-Status: **FROZEN v3** · 2026-07-29 · change only via orchestrator-Supersedes FROZEN v2 outright — no back-compat, no migration shims.+Status: **FROZEN v4 (targeted)** · 2026-07-30 · change only via orchestrator+Advances `agent-chain`, `probe-result`, and `turn-provenance` from contract+version 3 to 4. The same-assumption audit makes prose-only corrections in+`source` and `agent-supply`; the versionless `resolution-event` adds the+request-scoped `permission_denied` cause.Derived from: spec v2 (`../model-hub.md`), implementation plan(`../model-hub-implementation.md`),spike S1 engine survey (`docs/plans/model-hub-engine-survey.md`),@@ -53,6 +56,16 @@ Client-visible changes:- Resolution events remain single records. v3 adds neither affected-backend fan-outnor an attribution-grain marker.+## Targeted v4 process++Targeted revisions are orchestrator-authorized, evidence-pinned amendments: code+citations are required in the schema `$comment`s, and the revision is delivered as+a dedicated contract commit merged into the implementing lane's branch. Chat+messages alone never unfreeze a file. The first instance is this commit,+`docs(model-hub): amend channel-aware native CLI contracts v4`, consolidating+escalations #2+#3 as one class-level correction against master `807d1eee`; it remains+owner-vetoable.+## Resolved decision, carried forward from v1 (owner, 2026-07-23 10:33)**Hybrid supply by default + consent-gated experimental hub-held subscriptions.**@@ -86,10 +99,18 @@ order after any mutation; clients never compute partial reorders.`vibe/model_hub_runtime/state.py:135-166`, and owner-vetoable. It corrects onlythe hub-OAuth stable-ref repair invariant; chat messages alone did not unfreezethese files.+- **Targeted v4 process instance trail — entry 3 (v4c).** Review finding+ `3680338859` proved that the runtime-preserved `permission_error` machine code+ could be a model- or resource-scoped denial, while the classifier collapsed an+ otherwise redacted 403 into source-global `credential_revoked`. The+ orchestrator authorized this owner-vetoable amendment in L3 review round 11:+ `permission_denied` is an attempt failure, mirrored into provenance and legal+ only on a switch event; it has no Source-state `detail_key` and never mutates+ source health.- Contract tests (implementation plan §5) validate both directions againstthese schemas.-## Required-vs-optional discipline (v3)+## Required-vs-optional discipline (v4)Contracts land before implementation, so v2 fields describe a destination theshipped v1 serializers have not reached yet. The rule that keeps that honest:@@ -246,16 +267,17 @@ loads it and mutation-tests every comparable row.| # | Vocabulary | Home | Mirrors | Rule || --- | --- | --- | --- | --- |-| M1 | the ten `detail_key` values (5 cooldown + 4 needs_action + 1 error) | `source.schema.json` → `state`, across all three status branches — the `error` key is pinned as a `const`, which counts | `probe-result.schema.json` → `error` (minus null), and the `examples` list on the home field itself | `equality` |+| M1 | the ten `detail_key` values (5 cooldown + 4 needs_action + 1 error) | `source.schema.json` → `state`, across all three status branches — the `error` key is pinned as a `const`, which counts | `probe-result.schema.json` → `error` (minus null and its probe-local native readiness key), and the `examples` list on the home field itself | `equality` || M2 | source status → chain health | `source.schema.json` → `state.status` | `agent-chain.schema.json` → `chain[].health` | `projection` |-| M3 | attempt-failure causes | `resolution-event.schema.json` → `reason` | `turn-provenance.schema.json` → `failed_attempts[].reason` | `partition` |+| M3 | attempt-failure causes, including request-scoped `permission_denied` | `resolution-event.schema.json` → `reason` | `turn-provenance.schema.json` → `failed_attempts[].reason` | `partition` || M4 | non-self-healing cause ↔ blocking `detail_key` | `resolution-event.schema.json` → `reason` | `source.schema.json` → the `needs_action` and `error` `detail_key` branches | `bijection` || M5 | the supply-state taxonomy | `agent-supply.schema.json` → `supply_status` | `named_agents[].supply_status`; `agent-chain.schema.json` → `supply_state`; `turn-provenance.schema.json` → `model_supply_state` | `projection` || M6 | backend identifiers | `agent-supply.schema.json` → `backend` | `agent-chain.schema.json` and `probe-result.schema.json` → `backend`; `turn-provenance.schema.json` and `resolution-event.schema.json` → `agent` (`system` is the declared event-only extra) | `equality` |-| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; all four turn-provenance attempt slots | `equality` |+| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; `agent-chain.schema.json` → `chain[].channel`; `probe-result.schema.json` → `channel`; all four turn-provenance attempt slots | `equality` |+| M8 | native CLI process availability | `agent-chain.schema.json` → `chain[].reason` (`native_cli_unavailable`) | `probe-result.schema.json` → native not-ready `error` (`models.probe.native_cli_unavailable`) | `mapping` || N1 | source recommendation rule | `agent-supply.schema.json` → `sources.policy` | — | `none` |-What the rules mean, and why three of them are not equality:+What the rules mean, and why the non-equality rules differ:- **`equality`** — the sets are identical, in both directions. M6 carries one declaredsuperset: `resolution-event.agent` is the home set plus `system`, used for a@@ -274,6 +296,12 @@ What the rules mean, and why three of them are not equality:on the branch that pins `kind: supply_interrupted` — and `recovery`/`manual`/`mapping`are declared, because a resolution that is not a failure has no attempt to report. Anew `reason` fails the check until it is classified, which is the point.+ `permission_denied` belongs here because it describes the failed request+ attempt, but deliberately does not join M4: the preserved machine code does not+ prove a source-global credential or account state.+- **`mapping`** — M8 is one concept in two field conventions: a bare classifier in+ the chain and an i18n key in the probe error slot. The explicit one-to-one map is+ checked in both directions; adding a spelling on either side fails until paired.- **`bijection`** — M4 checks both sets and each explicit cause→detail-key pair;a permuted pairing therefore fails even when the two sets still match.- **`none`** — registered as non-comparable, with the reason. N1 is a pointer to a@@ -283,16 +311,16 @@ What the rules mean, and why three of them are not equality:| File | Consumers || --- | --- |-| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action` (+ mandatory `detail_key` there, enforced by an `if/then`), +immutable `created_at` (the sort key 跟随推荐 needs) with its **null placement now normative (07-29)** — absent sorts before every stamp, constant-epoch backfill, because a tie-break orders equals and cannot order null against a timestamp — +optional `usage.projected_exhaust_at`. No ordering field, ever. |-| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. Hub with no pinned selection keeps `selected_model_id`, `current`, and `supply_status` null; the server never invents `builtin_models[0]`. |-| `agent-chain.schema.json` | **New in v2.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain — cooling members included with `runnable: false` — and per-item `health` only; per-agent role is positional, never a copied `active`/`standby`. **+`supply_state` (07-29):** the three-class taxonomy at the (agent, model) grain, and the ONE field every model-scoped consumer reads (chain drill-in, the probe's `supply` sibling, turn record) so none of them consults the agent rollup for a model it does not describe. Its predicate is not restated here or there — spec §4.5 owns it, after round 3 found two files paraphrasing it into a different rule. |-| `probe-result.schema.json` | **New in v2.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. **07-29 round 3:** `reachable` now drives conditionals in both directions, so a reachable probe cannot carry null ids or an error; and `probe_no_candidate` moved its structured half out of `detail` into a typed `supply` sibling — the shipped clients declare `detail?: string`, so the object would have rendered as `[object Object]`. It reads the requested model's `supply_state`, never `supply_status`. |-| `turn-provenance.schema.json` | L2 API, L3 writer. v3 adds the FSM-truth `canceled` outcome and a reason-free `canceled_attempt` slot. Records exist only when attribution is exact; Direct and ambiguous absence are route errors in `api.md`. |-| `resolution-event.schema.json` | L2 emitter, L4 UI. v3 permits nullable `model_id` only for source-scoped system events, rejects `system` on backend-scoped interruption, and keeps one record with impact derived live. |+| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action`, immutable `created_at`, optional `usage.projected_exhaust_at`. Targeted v4 audit changes no shape: healthy source state and a lapsed `retry_at` do not assert process-local native CLI availability. No ordering field, ever. |+| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. Targeted v4 audit changes no shape: `supply_status` is derived from complete process-aware runnability, so unavailable native CLI supply is `interrupted`, not cooldown-only `waiting`. Hub with no pinned selection remains null throughout. |+| `agent-chain.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain and preserves visibility/order for blocked members. Each item now distinguishes source-global `health` from resolve-time channel availability: `runnable = health-permits AND process-available`; Hub availability is definitionally true, while an unavailable native CLI item at any health stays dimmed in place with `reason: native_cli_unavailable`. Cooldown plus unavailable is `interrupted`, not `waiting`. |+| `probe-result.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. The probe selects the first runnable item; unavailable chain items are skipped. Hub keeps v3's completed-request truth table. Native CLI re-verifies process readiness, never claims completion evidence, and pins `latency_ms: null` in both directions. It reads the requested model's `supply_state`, never `supply_status`. |+| `turn-provenance.schema.json` | L2 API, L3 writer. v4 adds request-scoped `permission_denied` to failed attempts without changing the exact-attribution rule. The FSM-truth `canceled` outcome keeps its reason-free `canceled_attempt` slot. Direct and ambiguous absence remain route errors in `api.md`. |+| `resolution-event.schema.json` | L2 emitter, L4 UI. The versionless feed adds `permission_denied` only for a model-scoped switch; it cannot describe cooldown, recovery, or needs-action source state. The record stays single-grained with impact derived live. || `oauth-flow.schema.json` | L2, L4 UI, L1 engine adapter || `migration-scan.schema.json` | L6, L5 UI. Unchanged by the v2 ruling — native-config import is an onboarding feature, not a priority mechanism. || `runtime-dependency.schema.json` | L1, L2 status API, L7 guards. **URL policy (orchestrator, 07-23 12:05):** the example URLs are placeholders; L1 ships with upstream release URLs + SHA256 integrity verification. Availability guard = L7/orchestrator deliverable BEFORE GA: mirror the pinned assets into Avibe-owned release storage (same manifest-verified backup/recovery pattern as Show Runtime, per repo release rules), then point the manifest at the mirror with upstream recorded as provenance. SHA256s never change (same bytes). L1 must NOT build the mirror or touch the Show Runtime guard. **Platform expansion (07-23 13:13):** linux-arm64 / darwin-x64 assets get pinned (+ schema platform-enum rev) together with the mirror work at L7; until then unsupported hosts fail closed, Direct = escape hatch (L1's `model_hub_engine_platform_unsupported` coverage is the intended behavior). **Cross-vendor note (07-29):** if the v2.1 cross-vendor spike (spec §10.4) concludes that a conversion pair needs a CPA plugin or a different engine build, that lands here as a pin + SHA256 revision with mirrored assets published before the manifest moves — never as user-facing configuration. |-| `api.md` | All route and envelope contracts. v3 defines Direct errors, named-Agent reads, repair acknowledgement/force, blocked-source re-test, the enabled-mapping guard, and durable pending revocations. |+| `api.md` | All route and envelope contracts. Targeted v4 keeps the shared envelope at v3 while documenting nested v4 chain/probe channel truth, orthogonal native availability, first-runnable probe selection, and stale readiness re-verification. The remaining route contracts are unchanged. || `opencode-overlay.md` | L3, L7 (identifier-stability tests). Identifiers stay stable across per-agent reordering — a source is never encoded into the provider segment. || `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). Dual-copy rule: both lanes copy VERBATIM to `core/handlers/model_hub/adapter.py` in their branches — byte-identical, merge is a no-op. Added 07-23 10:55 after L1 raised the ordering race; **v1.1 07-23 11:05**: +OAuth surface with deterministic source binding (`start_oauth(source_id)` → success carries `credential_ref`), +`allowed_origins`/`invoke(origin)`/`OriginNotAllowedError` (both from L1 review findings). Unchanged by v2: candidate walking and error classification stay Python-side, so moving ordering from global to per-agent needs no adapter or engine change (spec §8). |diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex ac58ee049..96480210b 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -2,12 +2,12 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/agent-chain.schema.json","title": "AgentChain",- "description": "v2 (2026-07-29): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by 'this source can supply this model, mapping applied'. For open menus the requested identifier carries a provider segment, and the vendor predicate is part of that filter: a `zhipuai/…` request is supplied only by zhipuai sources, never by whatever `custom/…` source happens to advertise the same bare model id (spec §4.3 step 2; the shipped resolver already enforces it). Deliberately NOT filtered by retry-readiness: a cooling source stays in the chain, dimmed, because the user needs to see it (frame V6 04). The RUNNABLE candidate list of spec §4.3 step 2 is this chain further filtered to `runnable: true`, evaluated per turn — so the two are one definition with one extra filter, not two independent lists. Closes v1's honesty gap: v1 showed one order per agent while N different chains ran underneath it, one per model. Read-only projection, computed per request, never persisted.",+ "description": "v4 (2026-07-29 targeted amendment): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by 'this source can supply this model, mapping applied'. For open menus the requested identifier carries a provider segment, and the vendor predicate is part of that filter: a `zhipuai/…` request is supplied only by zhipuai sources, never by whatever `custom/…` source happens to advertise the same bare model id (spec §4.3 step 2; the shipped resolver already enforces it). Deliberately NOT filtered by runnability: cooling, source-blocked and process-unavailable native_cli members stay at their positions, dimmed, because the user needs to see supply they own. The RUNNABLE candidate list is this chain further filtered to `runnable: true`, where runnable = health-permits AND process-available. Read-only projection, computed per request, never persisted.","type": "object","required": ["contract_version", "backend", "model_id", "chain", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 3 },+ "contract_version": { "const": 4 },"backend": { "enum": ["claude", "codex", "opencode"] },"model_id": {"type": "string",@@ -18,11 +18,11 @@"description": "Ordered, position 0 = highest in this backend's order. The next turn uses the FIRST item with `runnable: true`; role is positional and is never stored per source (a source can be serving one agent while merely standing by for another, so `active`/`standby` are not per-chain facts). Rendered with the same order-chip visuals as the agent row (frame V6 01). An EMPTY array is a first-class answer, not an error: the model is in the menu but no eligible source in this backend's order can supply it at all, so the UI flags 无来源可供 (spec §4.6) rather than offering a checkbox that silently fails. A non-empty chain with no `runnable` item is a different thing — `supply_state` on this object says which, at this model's grain. TWO STRUCTURAL INVARIANTS the schema cannot state, named here so they are enforced somewhere rather than assumed everywhere (07-29, review round 5): (1) `source_id` is UNIQUE across the chain — this is a FILTER over `sources.order`, which is itself `uniqueItems`, so a repeat means the projection double-counted; the damage is not cosmetic, since `chain.length` is what `AgentSupply.model_supply.chain_length` reports and 「2 个来源可供」 over one duplicated account is a false promise of redundancy, and a duplicate at the head would also make the resolver's fill-first retry the same cooling account twice before moving on. (2) The chain PRESERVES `sources.order` — a projection that filters must not reorder, or position 0 stops meaning 'spend first' and the drill-in shows a different order than the agent row it drilled in from. Draft-07 expresses neither: `uniqueItems` compares whole items, so two entries for one source with different `health` values are 'unique' to it, and no keyword can reference the ordering of another document. Both are therefore mechanical guards on the serializer (api.md → Serializer completeness), not schema keywords.","items": {"type": "object",- "required": ["source_id", "via_mapping", "resolved_model_id", "health", "runnable", "retry_at"],+ "required": ["source_id", "channel", "via_mapping", "resolved_model_id", "health", "runnable", "reason", "retry_at"],"additionalProperties": false,"allOf": [{- "$comment": "v2 (07-29, review round 4): health ⇒ runnability, as a conditional per health value. Round 3 stated the rule three times in prose — here, in spec §4.3 step 2's runnability filter, and in source.schema.json → retry_at — and enforced it nowhere, so an assembler regression could hand the resolver a `needs_action` source flagged `runnable: true` and pass contract validation. That is the one defect in this file that costs a real turn: the consumer takes the first runnable item, so a known-dead source at the head of the chain burns the turn AND suppresses the `interrupted` state that would have told the user to fix it. `needs_action` and `error` are pinned false and stampless; neither recovers unattended, so a `retry_at` on either would promise a recovery that is never coming.",+ "$comment": "v4 (07-29, escalations #2+#3): health that does not permit a turn pins runnability false. `needs_action` and `error` are stampless because neither recovers unattended. The orthogonal process-availability marker may still be present for an unavailable native_cli source; truth takes precedence over suppressing a redundant blocker.","if": {"properties": { "health": { "enum": ["needs_action", "error"] } },"required": ["health"]@@ -35,20 +35,72 @@}},{- "$comment": "v2 (07-29, review round 4): `healthy` is unconditionally runnable — there is no other filter left at this point in the pipeline (eligibility and capability are already applied to build the chain), so a healthy member flagged unrunnable would hide supply the user owns. Stampless for the same reason as above: nothing is being waited for.",+ "$comment": "v4 (07-29, escalations #2+#3): healthy ∧ hub ⇒ runnable. Hub process availability is definitionally true in v2, so round 4's assembler protection survives unchanged for this channel: a healthy hub member flagged unrunnable would hide supply the user owns. The old claim that no other filter remained was false only for native_cli. Evidence at master 807d1eee: core/handlers/model_hub/service.py:1223-1229 and modules/agents/model_hub.py:359-365 pass process-local unavailable_source_ids; core/handlers/model_hub/resolver.py:83-87 and 267-273 apply that filter after the capability chain is built.","if": {- "properties": { "health": { "const": "healthy" } },- "required": ["health"]+ "properties": {+ "health": { "const": "healthy" },+ "channel": { "const": "hub" }+ },+ "required": ["health", "channel"]},"then": {"properties": {"runnable": { "const": true },+ "reason": { "type": "null" },+ "retry_at": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v4 (07-29, escalations #2+#3): healthy ∧ native_cli pairs runnability with this process's CLI readiness. False requires the one closed reason; true requires null. Readiness is distinct from source-global health and is never persisted into it. Evidence at master 807d1eee: core/handlers/model_hub/resolver.py:252-273 keeps the source in matching_sources while excluding unavailable ids from candidates, and lines 95-116 classifies the resulting no-candidate state as interrupted rather than waiting.",+ "if": {+ "properties": {+ "health": { "const": "healthy" },+ "channel": { "const": "native_cli" },+ "runnable": { "const": false }+ },+ "required": ["health", "channel", "runnable"]+ },+ "then": {+ "required": ["reason"],+ "properties": {+ "reason": { "type": "string" },"retry_at": { "type": "null" }}}},{- "$comment": "v2 (07-29, review round 4): `cooldown` is the only health value with a stamp, and it always has one — mirroring source.schema.json → state.retry_at, where `cooldown` is defined as the self-healing status whose recovery time is known. `runnable` is deliberately left free here alone: it is exactly `retry_at` already in the past (the resolver retries a recovered source rather than waiting for a state flip), and a schema cannot compare a timestamp to now.",+ "if": {+ "properties": {+ "health": { "const": "healthy" },+ "channel": { "const": "native_cli" },+ "runnable": { "const": true }+ },+ "required": ["health", "channel", "runnable"]+ },+ "then": {+ "properties": {+ "reason": { "type": "null" },+ "retry_at": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v4 converse (corrected orchestrator ruling): a non-null availability marker is legal at every health and means this process cannot launch this native_cli source. It therefore always forces runnable false. Hub is definitionally process-available in v2, so the marker is impossible there. Together with the healthy native_cli branches above, this makes healthy ∧ native_cli ∧ runnable:false ⇔ reason=native_cli_unavailable total without collapsing process availability into source-global health.",+ "if": {+ "properties": { "reason": { "type": "string" } },+ "required": ["reason"]+ },+ "then": {+ "required": ["channel", "runnable"],+ "properties": {+ "channel": { "const": "native_cli" },+ "runnable": { "const": false }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4), availability-separated in v4: `cooldown` is the only health value with a stamp, and it always has one — mirroring source.schema.json → state.retry_at, where `cooldown` is the self-healing status whose recovery time is known. For an available item, `runnable` remains the v3 dynamic rule: true exactly when `retry_at` is already in the past, which a schema cannot compare to now. Process unavailability has precedence at every health, so a cooldown native_cli item may also carry the marker; the converse above then pins runnable false while retaining the health stamp.","if": {"properties": { "health": { "const": "cooldown" } },"required": ["health"]@@ -75,6 +127,10 @@],"properties": {"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "channel": {+ "enum": ["hub", "native_cli"],+ "description": "The source's serving channel. `hub` process availability is definitionally true in v2; `native_cli` is additionally gated by whether this serving process can launch the sanctioned CLI under its own login right now. The discriminator mirrors source.schema.json → supply_channel."+ },"via_mapping": {"type": "boolean","description": "true when this source supplies the model only because a per-agent mapping rewrote the requested id (spec §4.3 step 1). UI marks the chip 经映射."@@ -89,7 +145,14 @@},"runnable": {"type": "boolean",- "description": "Whether this candidate is usable right now: health `healthy`, OR health `cooldown` whose `retry_at` has already passed — the shipped resolver retries such a source rather than waiting for a state flip, so a contract reading `runnable == (health == healthy)` would understate what the next turn will do. ALWAYS false for `needs_action` and for `error`: the first cannot recover unattended, the second is a source already known to be broken, and retrying either burns a turn. Still shown in the chain, dimmed, in every one of those cases. This is exactly the retry-readiness filter of spec §4.3 step 2."+ "description": "Whether this candidate is usable right now: health permits the turn AND this process can serve the channel. Health permits `healthy`, or `cooldown` whose `retry_at` has already passed; process availability is definitionally true for `hub` and checked at resolve time for `native_cli`. ALWAYS false for `needs_action` and `error`. An unavailable native item stays visible at its original chain position, dimmed. This is the complete runnability filter used by the shipped resolver."+ },+ "reason": {+ "anyOf": [+ { "enum": ["native_cli_unavailable"] },+ { "type": "null" }+ ],+ "description": "The process-availability marker, orthogonal to source-global health. VOCABULARY HOME for `native_cli_unavailable`, the only unavailable state in v2. Non-null exactly when this process cannot launch the native_cli source, at any health; it forces runnable=false. Null means process-available. Hub is definitionally available and therefore always null. probe-result.schema.json mirrors this concept in its i18n-key error convention."},"retry_at": {"type": ["string", "null"],@@ -101,7 +164,7 @@},"supply_state": {"enum": ["ok", "waiting", "interrupted"],- "description": "v2 (07-29, review round 2): the MODEL-SCOPED supply state — the same three-class taxonomy as agent-supply `supply_status`, evaluated for THIS (agent, model) pair instead of the backend as a whole. The predicate is spec §4.5's, verbatim, and is stated once there: `ok` = at least one `runnable: true` item. Otherwise the chain is blocked, and the split is on whether the user owes an action — `interrupted` = the chain is empty, or AT LEAST ONE blocker needs the user (`needs_action` / `error`) — 「需处理」; `waiting` = chain non-empty and EVERY blocker is a cooldown, so it recovers unattended at the earliest `retry_at` — 「稍等即可」. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which left the mixed chain — one cooling source plus one revoked key — matching neither class, so the (agent, model) grain silently disagreed with `supply_status` (which had 'at least one' all along) and suppressed the action-required state for exactly the case that needs it most. `interrupted` is the OR-branch and `waiting` the AND-branch; in that order the two are total over every blocked chain, and a chain that needs the user is never reported as one that heals itself. Exists because the agent-level rollup answers only for the backend's CURRENT model: a user can inspect, probe, or request a model that is starved while the selected one is perfectly healthy, and consulting the rollup there reports `ok` for a chain that cannot run. Every consumer of a model-scoped answer reads this one field — the chain drill-in, `probe_no_candidate`'s typed `supply` sibling (api.md), and TurnProvenance `model_supply_state` — so 「稍等即可」 vs 「需处理」 has exactly one definition per grain."+ "description": "The MODEL-SCOPED supply state — the same three-class taxonomy as agent-supply `supply_status`, evaluated for THIS (agent, model) pair. The predicate is spec §4.5's: `ok` = at least one `runnable: true` item. Otherwise `waiting` iff the chain is non-empty and EVERY member is cooldown, not retry-ready, and process-available; `interrupted` = the chain is empty, or AT LEAST ONE blocker needs the user (`needs_action`, `error`, or process-unavailable native_cli at any health). v4 matches the shipped resolver's availability precedence: even cooldown plus native_cli_unavailable is interrupted, never waiting."}},"allOf": [@@ -127,13 +190,20 @@}},{- "$comment": "v2 (07-29, review round 4): and the waiting/interrupted split, which is where §4.5's asymmetry becomes checkable. `waiting` is the AND-branch — non-empty chain, EVERY blocker a cooldown — so a chain holding one revoked key cannot be reported as one that heals itself, which is exactly the suppressed action_required state the round-3 correction was about. `interrupted` is the OR-branch: empty chain, or at least one member the user has to fix. In that order the two are total over every blocked chain.",+ "$comment": "v4: waiting remains the AND-branch — non-empty chain and EVERY member a not-retry-ready cooldown that is process-available. The schema cannot compare retry_at to now, but the blocked-state conditional already forbids runnable members; requiring reason:null additionally excludes unavailable native_cli members. This matches core/handlers/model_hub/resolver.py:109-116 at master 807d1eee: waiting requires every source cooldown and not unavailable, otherwise no-candidate supply is interrupted.","if": { "properties": { "supply_state": { "const": "waiting" } }, "required": ["supply_state"] },"then": {"properties": {"chain": {"minItems": 1,- "not": { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } }+ "items": {+ "properties": {+ "health": { "const": "cooldown" },+ "runnable": { "const": false },+ "reason": { "type": "null" }+ },+ "required": ["health", "runnable", "reason"]+ }}}}@@ -145,7 +215,8 @@"chain": {"anyOf": [{ "maxItems": 0 },- { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } }+ { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } },+ { "contains": { "properties": { "reason": { "type": "string" } }, "required": ["reason"] } }]}}@@ -181,51 +252,93 @@],"examples": [{- "contract_version": 3,+ "contract_version": 4,"backend": "claude","model_id": "claude-opus-4-6","chain": [{"source_id": "src_claudepro1",+ "channel": "native_cli","via_mapping": false,"resolved_model_id": null,"health": "cooldown","runnable": false,+ "reason": null,"retry_at": "2026-07-29T04:00:00Z"},{"source_id": "src_anthkey01",+ "channel": "hub","via_mapping": false,"resolved_model_id": null,"health": "healthy","runnable": true,+ "reason": null,"retry_at": null}],"supply_state": "ok"},{- "contract_version": 3,+ "contract_version": 4,"backend": "claude","model_id": "claude-haiku-4-5","chain": [],"supply_state": "interrupted"},{- "contract_version": 3,+ "contract_version": 4,"backend": "codex","model_id": "gpt-5.3-codex","chain": [{"source_id": "src_codexplus1",+ "channel": "native_cli","via_mapping": false,"resolved_model_id": null,"health": "cooldown","runnable": false,+ "reason": null,"retry_at": "2026-07-29T09:15:00Z"}],"supply_state": "waiting"+ },+ {+ "contract_version": 4,+ "backend": "codex",+ "model_id": "gpt-5.6",+ "chain": [+ {+ "source_id": "src_chatgptplus",+ "channel": "native_cli",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "healthy",+ "runnable": false,+ "reason": "native_cli_unavailable",+ "retry_at": null+ }+ ],+ "supply_state": "interrupted"+ },+ {+ "contract_version": 4,+ "backend": "claude",+ "model_id": "claude-sonnet-4-5",+ "chain": [+ {+ "source_id": "src_claudecli1",+ "channel": "native_cli",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "cooldown",+ "runnable": false,+ "reason": "native_cli_unavailable",+ "retry_at": "2026-07-29T10:30:00Z"+ }+ ],+ "supply_state": "interrupted"}]}diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 5da00a74c..ce84b45af 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -112,7 +112,8 @@"supply_status": {"type": ["string", "null"],"enum": ["ok", "degraded", "waiting", "interrupted", null],- "description": "Derived health rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent`. ok = serving from the intended head; degraded = serving through fallback and/or with blocked members; waiting = no runnable member and every blocker is a cooldown; interrupted = no runnable member and at least one blocker needs action, or the capability chain is empty. null when mode=direct or when Hub has no pinned selection."+ "$comment": "Targeted v4 same-assumption audit (escalations #2+#3): this rollup is process-aware, not a health-only summary. Evidence at master 807d1eee: core/handlers/model_hub/service.py:1223-1229 supplies unavailable_source_ids to resolution; resolver.py:90-116 classifies waiting only when every blocked match is cooldown, not retry-ready, and not unavailable. Any unavailable member in a no-candidate chain therefore yields interrupted.",+ "description": "Derived supply rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent`. It reads the same complete runnability predicate as AgentChain: source-global health permits AND this process can serve the channel. ok = serving from the intended head; degraded = serving through fallback and/or with blocked members; waiting = no runnable member and every member is a not-retry-ready cooldown that is process-available; interrupted = no runnable member and at least one blocker needs action — including a native CLI unavailable in this process at any health — or the capability chain is empty. null when mode=direct or when Hub has no pinned selection."},"mappings": {"type": "array",@@ -158,7 +159,8 @@"chain_length": {"type": "integer","minimum": 0,- "description": "Length of the CAPABILITY chain — how many sources in this backend's order can supply this model at all, mapping applied — matching `AgentChain.chain`, cooling members included. Deliberately NOT a count of currently-runnable candidates: this drives a menu row's 「无来源可供」 flag, which is a structural fact about the model, and it must not flicker because an account is mid-cooldown. 0 ⇒ flag the row; transient unavailability is `supply_status` (waiting) instead."+ "$comment": "Targeted v4 audit: capability visibility is not candidate availability. core/handlers/model_hub/resolver.py:252-273 at master 807d1eee builds matching_sources before source_runnable filters unavailable ids into candidates, so an unavailable native source remains counted and ordered in this projection.",+ "description": "Length of the CAPABILITY chain — how many sources in this backend's order can supply this model at all, mapping applied — matching `AgentChain.chain`, including cooling and process-unavailable native CLI members. Deliberately NOT a count of currently-runnable candidates: this drives a menu row's 「无来源可供」 flag, which is structural and must not flicker with runtime state. 0 ⇒ flag the row; cooldown-only blocking appears as `supply_status: waiting`, while a native CLI unavailable in this process is `interrupted`."}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 1db26dedd..ad645fefb 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1,6 +1,6 @@# Model Hub — REST API contract-Status: **FROZEN v3**. All endpoints live under `/api/models/`.+Status: **FROZEN v4 (targeted)**. All endpoints live under `/api/models/`.Success envelope: `{ok: true, contract_version: 3, ...}`.Failure envelope:@@ -8,6 +8,10 @@ Failure envelope:`detail` is always a string. Structured error data lives in a named sibling.Authentication and CSRF rules are the existing UI-server rules.+The shared envelope remains v3. The targeted v4 amendment changes only the nested+`AgentChain` and `ProbeResult` objects, whose own `contract_version` is 4; untouched+schema objects and every unrelated route remain at version 3.+## Route table| Method and path | Request → response | Normative notes |@@ -327,9 +331,44 @@ Status and submit return the same terminal shape:## Chain and probeIn Hub mode, `AgentChain.chain` is the effective source order filtered by backend-eligibility and model support, with mapping applied. Cooling and other blocked members-stay in the chain; `runnable` is the retry-readiness filter used by the resolver.-An empty Hub chain is a valid `interrupted` chain.+eligibility and model support, with mapping applied. Cooling, source-blocked and+process-unavailable native CLI members stay in the chain at their original positions.+Each item carries `channel`, source-global `health`, process-aware `runnable`, and+nullable `reason`. The complete axiom is:++`runnable = health-permits AND process-available`.++Process availability is definitionally true for `channel: "hub"` in v2; there is no+configuration knob for it. For `native_cli`, `reason: "native_cli_unavailable"` is an+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`; `reason: null` means process-available. An empty Hub chain+remains a valid `interrupted` chain.++```json+{+ "ok": true,+ "contract_version": 3,+ "chain": {+ "contract_version": 4,+ "backend": "codex",+ "model_id": "gpt-5.6",+ "chain": [+ {+ "source_id": "src_chatgptplus",+ "channel": "native_cli",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "healthy",+ "runnable": false,+ "reason": "native_cli_unavailable",+ "retry_at": null+ }+ ],+ "supply_state": "interrupted"+ }+}+```In Direct mode both chain and probe refuse with:@@ -352,8 +391,9 @@ A successful probe nests its result:"ok": true,"contract_version": 3,"probe": {- "contract_version": 3,+ "contract_version": 4,"backend": "claude",+ "channel": "hub","reachable": false,"source_id": "src_relay9c1x","model_id": "glm-5.2",@@ -364,6 +404,43 @@ A successful probe nests its result:}```+The probe walks the same §4.3 chain order and selects the first runnable item;+items already marked unavailable are never probed. For `channel: "hub"`, that+candidate keeps v3's total request-result truth table verbatim. For+`channel: "native_cli"`, the probe re-verifies process readiness after selection;+the fact may have gone stale, so an available candidate can honestly return+not-ready. `reachable` is READINESS, not completion evidence: no upstream call is+timed, so `latency_ms` is null in both directions. Ready carries `error: null`;+not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.++```json+{+ "contract_version": 4,+ "backend": "codex",+ "channel": "native_cli",+ "reachable": true,+ "source_id": "src_chatgptplus",+ "model_id": "gpt-5.6",+ "latency_ms": null,+ "via_mapping": false,+ "error": null+}+```++```json+{+ "contract_version": 4,+ "backend": "codex",+ "channel": "native_cli",+ "reachable": false,+ "source_id": "src_chatgptplus",+ "model_id": "gpt-5.6",+ "latency_ms": null,+ "via_mapping": false,+ "error": "models.probe.native_cli_unavailable"+}+```+No candidate is an API error with a typed model-scoped state:```json@@ -437,11 +514,11 @@ contract harness and API-boundary tests enforce:| Guard | Boundary || --- | --- || every example validates and JSON round-trips | contract harness |-| mirror registry equality/projection/partition/bijection, including mutation probes | `mirror-registry.json` harness |+| mirror registry equality/projection/partition/bijection/mapping, including mutation probes | `mirror-registry.json` harness || every non-null `then` constraint has matching `required`, except a declared fail-safe legacy-example exception | contract harness || every `sources.order` id exists, is unique, and is eligible | config loader + source-order route || eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler |-| `AgentChain.chain` source ids are unique and preserve effective order | chain assembler |+| `AgentChain.chain` source ids are unique and preserve effective order, including process-unavailable native CLI items | 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 |diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex 029703726..ef483b243 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": 3,+ "contract_version": 4,"entries": [{"id": "M1",@@ -18,7 +18,8 @@{"schema": "probe-result.schema.json","paths": ["/properties/error"],- "exclude": [null]+ "exclude": [null],+ "extras": ["models.probe.native_cli_unavailable"]}]},@@ -161,6 +162,10 @@"schema": "agent-supply.schema.json","paths": ["/properties/current/properties/channel"]},+ {+ "schema": "agent-chain.schema.json",+ "paths": ["/properties/chain/items/properties/channel"]+ },{"schema": "turn-provenance.schema.json","paths": [@@ -169,9 +174,29 @@"/properties/terminal_error/properties/channel","/properties/canceled_attempt/properties/channel"]+ },+ {+ "schema": "probe-result.schema.json",+ "paths": ["/properties/channel"]}]},+ {+ "id": "M8",+ "vocabulary": "native CLI process availability",+ "rule": "mapping",+ "home": {+ "schema": "agent-chain.schema.json",+ "path": "/properties/chain/items/properties/reason/anyOf/0"+ },+ "target": {+ "schema": "probe-result.schema.json",+ "path": "/allOf/6/then/properties/error"+ },+ "mapping": {+ "native_cli_unavailable": "models.probe.native_cli_unavailable"+ }+ },{"id": "N1","vocabulary": "source recommendation rule",diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex 45061d35b..f0e66e1f2 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -2,31 +2,35 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/probe-result.schema.json","title": "ProbeResult",- "description": "v2 (2026-07-29): outcome of one dry-run request through an agent's current chain — 「试跑一次」 in the agent drawer footer (spec §10.1). Answers 'is this actually working right now' without making the user start a real turn, and replaces the session-level source pinning we explicitly do not build (spec §9). Inherits the resolution-event redaction invariant: classified outcomes only, never raw upstream error bodies. NOTE the outcome field is `reachable`, not `ok`: this object is nested under the standard envelope (`{ok: true, probe: ProbeResult}`), where `ok` already means 'the API call itself succeeded'. A probe that cleanly establishes the upstream is broken is a successful API call reporting `reachable: false` — the two must not share a name.",+ "description": "v4 (2026-07-29 targeted amendment): outcome of walking an agent's current chain in spec §4.3 order and selecting the first runnable source. An unavailable chain item is never probed. For channel=hub the selected source is probed upstream exactly as in v3. For channel=native_cli readiness is re-verified after selection, so an item that was available during resolution may honestly return not-ready if that process-local fact went stale. Readiness is not completion evidence: a native result never claims an upstream request ran or completed. Classified outcomes only, never raw diagnostics. `reachable` remains distinct from the envelope's `ok`.","type": "object",- "required": ["contract_version", "backend", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],+ "required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],"additionalProperties": false,"properties": {- "contract_version": { "const": 3 },+ "contract_version": { "const": 4 },"backend": { "enum": ["claude", "codex", "opencode"] },+ "channel": {+ "enum": ["hub", "native_cli"],+ "description": "The channel whose truth this result reports. Mirrors source.schema.json → supply_channel and agent-chain.schema.json → chain[].channel."+ },"reachable": {"type": "boolean",- "description": "Whether this source can serve a turn RIGHT NOW — request success, not transport reachability (definition corrected 07-29, review round 5). The round-4 wording was 'whether the upstream actually answered', which contradicted this file's own frozen example: a `balance_exhausted` is learned FROM a completed 402, so the upstream did answer, yet the example reports `reachable: false` and must — 「试跑一次」 asks 能不能用, and a source that answers only to refuse is not usable. An implementer following the old sentence would have emitted `reachable: true` with a required `error`, which the true branch forbids, leaving that probe with no valid representation at all. THE NAME IS RETAINED DELIBERATELY: it is load-bearing in api.md's explanation of why this field is not called `ok`, and the transport question it appears to ask is still answerable from this object without a second field — `latency_ms != null` means the attempt completed. So the two questions are separable: `reachable` = usable, `latency_ms` = completed. Never conflate either with the envelope's `ok`."+ "description": "Channel-scoped usability RIGHT NOW. For hub, true means the upstream request succeeded and false means the attempted source was not usable; latency says whether that attempt completed. For native_cli, this is readiness only: true means this process can launch the CLI under its own login now, false means it cannot. Native readiness is never completion evidence. Never conflate this field with the envelope's `ok`."},"source_id": {"type": "string","pattern": "^src_[a-z0-9]{8,}$",- "description": "The source that served (or failed) the probe — the first runnable candidate in this backend's chain for the probed model. NON-NULLABLE (07-29, review round 4): returning this object already means a candidate was resolved and attempted, because the no-candidate case is the separate `probe_no_candidate` error envelope. The v1 draft made it nullable 'for defensive serialization', which only bought the right to answer 「跑不通」 without saying what was tried — the one thing a probe exists to report."+ "description": "The first runnable chain source selected for checking. For hub it is attempted upstream. For native_cli its process readiness is re-verified without an upstream attempt and may have gone stale since selection; a source already marked unavailable in the chain is never selected. NON-NULLABLE; the no-candidate case remains the separate `probe_no_candidate` envelope."},"model_id": {"type": "string","minLength": 1,- "description": "The model actually sent upstream, mapping applied (the resolved id, not the menu identifier the caller passed in). Non-nullable for the same reason as `source_id`."+ "description": "The resolved model, mapping applied. Hub sends it upstream; native_cli would pass it to the CLI if readiness permits. Non-nullable for the same reason as `source_id`."},"latency_ms": {"type": ["integer", "null"],"minimum": 0,- "description": "Round trip of the minimal request. THE ONLY NULLABLE FIELD besides `error`, and deliberately so: it is the one value that depends on the attempt finishing. null means the attempt never completed — the UI renders 未完成, never 0 ms. WHICH failures completed is a total function of `error`, not an emitter judgement (07-29, review round 5): exactly two keys in the closed vocabulary are transport failures (`models.source.cooldown.network` / `.timeout`) and null is reserved for those two. Every other key — the whole needs_action family AND the response-based cooldowns (429 rate limit, cycle quota exhausted, upstream 5xx) — was learned FROM a completed upstream response, so it has a measured duration. Round 4 pinned only the needs_action half, which left a 429 free to report `latency_ms: null` and render a measured response as 未完成; the partition below closes the whole set in both directions."+ "description": "Hub round trip of the minimal upstream request. For hub, null means the attempt never completed and the existing error-key partition is total. For native_cli this is ALWAYS null in both readiness outcomes because no upstream request is timed; rendering a measured local check such as 12 ms would impersonate completion evidence."},"error": {"type": ["string", "null"],@@ -41,9 +45,10 @@"models.source.needs_action.balance_exhausted","models.source.needs_action.credential_revoked","models.source.needs_action.account_banned",- "models.source.error.unclassified"+ "models.source.error.unclassified",+ "models.probe.native_cli_unavailable"],- "description": "i18n key when reachable=false, mirroring the source `state.detail_key` vocabulary. Never raw upstream text. A CLOSED ENUM, not a prefix pattern (07-29, review round 5): round 4 used `^models\\.source\\.(cooldown|needs_action)\\..+` believing that enforced the redaction invariant, but `.+` accepts anything after a trusted-looking prefix — `models.source.cooldown.network: <raw upstream body>` matched it and would have carried an upstream payload into the API and the UI. A prefix check is a naming convention, not a boundary. The outcome set is finite and already enumerated (five self-healing causes, four that need the user, one unclassified), so the vocabulary is closed and a new cause is a contract change that comes here to declare its remedy. VOCABULARY HOME: `source.schema.json` → `state.detail_key` owns these keys — ALL THREE status families, cooldown + needs_action + the single `error` key it pins as a `const`; this is a mirror, because draft-07 has no cross-file `$ref` the contract test can resolve. `models.source.error.unclassified` was added here in round 7: round 6 introduced the `error` status and its key in `source.schema.json` alone, leaving a probe that hit an unmappable failure with no legal value for a REQUIRED field — the source could enter `error` but no probe could report why, and the mirror claim in this very sentence made the omission a documented self-contradiction rather than a gap. The lists must stay identical, and that is checked mechanically ACROSS files, not trusted — see the vocabulary mirror table in README.md and api.md → Serializer completeness. Explicitly null when reachable=true, so clients never distinguish absent from null."+ "description": "Closed i18n-key outcome, never raw text. For channel=hub the ten source-state keys mirror source.schema.json → state.detail_key. For channel=native_cli the only non-null value is `models.probe.native_cli_unavailable`, the i18n spelling of agent-chain.schema.json → reason `native_cli_unavailable`; that mapping is registered and mutation-tested in mirror-registry.json. Explicitly null on every reachable result."},"via_mapping": {"type": "boolean",@@ -53,7 +58,13 @@"allOf": [{"$comment": "v2 (07-29, review round 3): the nullability above was per-field and therefore too loose in combination — `reachable: true` with a null `source_id` and a non-null `error` validated, i.e. 'it answered, we don't know who, and here is why it didn't'. ROUND 4 moved the identity half UP to the type level: `source_id` / `model_id` / `via_mapping` are now plainly non-nullable, which is strictly stronger than pinning them in each branch and removes the branch bookkeeping entirely — a returned ProbeResult always identifies what was tested, in BOTH directions, and no future branch can reintroduce the hole. What is left here is genuinely conditional: `latency_ms` null means 'the attempt never completed', which a reachable probe contradicts by definition, so 未完成 belongs to the false branch alone.",- "if": { "properties": { "reachable": { "const": true } }, "required": ["reachable"] },+ "if": {+ "properties": {+ "channel": { "const": "hub" },+ "reachable": { "const": true }+ },+ "required": ["channel", "reachable"]+ },"then": {"properties": {"latency_ms": { "type": "integer" },@@ -63,13 +74,20 @@},{"$comment": "v2 (07-29, review round 3): the converse half. `error` is the field the UI renders instead of a latency, so an unreachable probe that carries no key leaves the drawer with nothing to say — the same 'required but nullable' gap, at the other end. `latency_ms` stays nullable on this branch on purpose: an attempted failure may or may not have completed.",- "if": { "properties": { "reachable": { "const": false } }, "required": ["reachable"] },+ "if": {+ "properties": {+ "channel": { "const": "hub" },+ "reachable": { "const": false }+ },+ "required": ["channel", "reachable"]+ },"then": { "properties": { "error": { "type": "string" } } }},{"$comment": "v2 (07-29, review round 4; made TOTAL in round 5): which failures completed is decided by the error key, not by the emitter. Round 4 pinned the needs_action family alone — every one of those is learned FROM a completed upstream response (402/401/403 telling us the balance is out, the key is revoked, the account is banned), so `latency_ms: null` there would render a completed billing answer as 未完成. But the cooldown family is MIXED, and round 4 treated it as if it were uniformly transport: `rate_limited` (429), `quota_exhausted` and `server_error` (5xx) are all completed responses too, so they were left free to report null and reproduce the exact defect one family over. The partition is by key, and only `network` / `.timeout` are transport. Listing the completed keys explicitly rather than negating the transport pair is deliberate: with a closed enum both forms are equivalent today, but an added key would silently inherit 'completed' from a negation, whereas this list forces the contract change to say which side it is on — and round 7 is that mechanism working as designed: `models.source.error.unclassified` joined the enum and had to declare a side here. It is COMPLETED. An unclassified failure is one the adapter could not map, which means something came back to be unmappable; a request that never finished is not unclassified at all, it is `network` or `timeout` by definition.","if": {"properties": {+ "channel": { "const": "hub" },"error": {"enum": ["models.source.cooldown.rate_limited",@@ -83,15 +101,22 @@]}},- "required": ["error"]+ "required": ["channel", "error"]},"then": { "properties": { "latency_ms": { "type": "integer" } } }},{"$comment": "v2 (07-29, review round 5): the converse, which is what makes the partition total instead of one-directional. Round 4's shape said 'these keys require a latency' and stopped, so 未完成 remained writable for anything not named — the open half is how the 429 case survived a round whose whole purpose was closing this class. Stated from the null side there is nothing left over: a probe that never completed MUST be one of the two transport failures, because those are the only two ways an attempt can fail to finish. Any other key with a null latency is now unrepresentable rather than merely discouraged. Round 5 also claimed this left 「no undefined combination in either direction」; that claim was false, and the branch below is the direction it missed.",- "if": { "properties": { "latency_ms": { "type": "null" } }, "required": ["latency_ms"] },+ "if": {+ "properties": {+ "channel": { "const": "hub" },+ "latency_ms": { "type": "null" }+ },+ "required": ["channel", "latency_ms"]+ },"then": {"properties": {+ "channel": { "const": "hub" },"error": {"enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]}@@ -102,19 +127,71 @@"$comment": "v2 (07-29, review round 9): transport failures require a NULL latency — the half round 5 thought it had closed. Both prior branches read from one side only: 'these eight completed keys need an integer' and 'a null latency must be transport'. Neither forbids `error: models.source.cooldown.timeout` with `latency_ms: 287`, so a request that never finished could validate carrying a measured round trip, and the drawer would render 超时 next to 287ms — a completed-looking answer for the one class of failure that by definition did not complete. Stated in both directions the pair is finally a partition: transport ⇔ null, the other eight keys ⇔ integer, `reachable: true` ⇔ integer with no error. No example changes; the transport example already carries null.","if": {"properties": {+ "channel": { "const": "hub" },"error": {"enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]}},- "required": ["error"]+ "required": ["channel", "error"]},"then": { "properties": { "latency_ms": { "type": "null" } } }+ },+ {+ "$comment": "v4 (07-29, escalations #2+#3): probe selection walks §4.3 order and touches the first runnable item; a source already present in unavailable_source_ids is excluded by core/handlers/model_hub/resolver.py:83-87,267-273 at master 807d1eee and is never probed. For a selected native_cli item, modules/agents/model_hub.py:323-348 re-verifies process-local readiness, which may have gone stale. reachable=true is readiness only — this process can launch the sanctioned CLI under its own login now. No upstream request ran, so readiness is not completion evidence and latency is null rather than a measured local check.",+ "if": {+ "properties": {+ "channel": { "const": "native_cli" },+ "reachable": { "const": true }+ },+ "required": ["channel", "reachable"]+ },+ "then": {+ "properties": {+ "latency_ms": { "type": "null" },+ "error": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v4 forward half: native_cli reachable=false is the same process-availability concept as agent-chain reason=native_cli_unavailable, spelled as a closed i18n key in this error slot. It is a readiness failure, not a completed CLI call, so latency is null.",+ "if": {+ "properties": {+ "channel": { "const": "native_cli" },+ "reachable": { "const": false }+ },+ "required": ["channel", "reachable"]+ },+ "then": {+ "required": ["error"],+ "properties": {+ "latency_ms": { "type": "null" },+ "error": { "enum": ["models.probe.native_cli_unavailable"] }+ }+ }+ },+ {+ "$comment": "v4 converse half: the native CLI readiness key cannot appear on a hub probe or a reachable result. Together with the two channel branches, this closes every channel × reachable × latency × error combination in both directions.",+ "if": {+ "properties": {+ "error": { "const": "models.probe.native_cli_unavailable" }+ },+ "required": ["error"]+ },+ "then": {+ "required": ["channel", "reachable", "latency_ms"],+ "properties": {+ "channel": { "const": "native_cli" },+ "reachable": { "const": false },+ "latency_ms": { "type": "null" }+ }+ }}],"examples": [{- "contract_version": 3,+ "contract_version": 4,"backend": "codex",+ "channel": "hub","reachable": true,"source_id": "src_chatgptplus","model_id": "gpt-5.6",@@ -123,8 +200,9 @@"via_mapping": false},{- "contract_version": 3,+ "contract_version": 4,"backend": "claude",+ "channel": "hub","reachable": false,"source_id": "src_relay9c1x","model_id": "glm-5.2",@@ -133,14 +211,37 @@"via_mapping": true},{- "contract_version": 3,+ "contract_version": 4,"backend": "claude",+ "channel": "hub","reachable": false,"source_id": "src_relay9c1x","model_id": "glm-5.2","latency_ms": null,"error": "models.source.cooldown.timeout","via_mapping": true+ },+ {+ "contract_version": 4,+ "backend": "codex",+ "channel": "native_cli",+ "reachable": true,+ "source_id": "src_chatgptplus",+ "model_id": "gpt-5.6",+ "latency_ms": null,+ "error": null,+ "via_mapping": false+ },+ {+ "contract_version": 4,+ "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",+ "via_mapping": false}]}diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.jsonindex 734ac2856..f1184b123 100644--- a/docs/plans/model-hub-contracts/resolution-event.schema.json+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/resolution-event.schema.json","title": "ResolutionEvent",- "description": "v3 source-resolution feed entry. Adapter-owned and redacted: ids, classified causes, and bounded human summaries only; never credential material or raw upstream error bodies. The record stays single-grained. Consumers derive current per-backend and per-Agent impact live instead of storing fan-out.",+ "description": "v4-targeted source-resolution feed entry. Adapter-owned and redacted: ids, classified causes, and bounded human summaries only; never credential material or raw upstream error bodies. The record stays single-grained. Consumers derive current per-backend and per-Agent impact live instead of storing fan-out.","type": "object","required": ["id", "ts", "agent", "kind", "model_id", "reason", "human_zh", "human_en"],"additionalProperties": false,@@ -52,12 +52,14 @@"credential_revoked","balance_exhausted","account_banned",+ "permission_denied","unclassified_error","no_enabled_source","no_eligible_source","model_unsupported"],- "description": "Adapter classification. The five non-self-healing source causes map bijectively to Source.state.detail_key: credential_expired→models.source.needs_action.oauth_expired; credential_revoked→models.source.needs_action.credential_revoked; balance_exhausted→models.source.needs_action.balance_exhausted; account_banned→models.source.needs_action.account_banned; unclassified_error→models.source.error.unclassified. The machine-readable mirror registry enforces the relation."+ "description": "Adapter classification. The five non-self-healing source causes map bijectively to Source.state.detail_key: credential_expired→models.source.needs_action.oauth_expired; credential_revoked→models.source.needs_action.credential_revoked; balance_exhausted→models.source.needs_action.balance_exhausted; account_banned→models.source.needs_action.account_banned; unclassified_error→models.source.error.unclassified. permission_denied is request-scoped and has no Source-state mirror. The machine-readable mirror registry enforces the attempt-failure relation.",+ "$comment": "Targeted v4c, review finding 3680338859: vibe/model_hub_runtime/client.py:21-44 preserves the exact permission_error machine code while redacting arbitrary bodies. core/handlers/model_hub/classification.py:98-125 previously collapsed every remaining 403 into credential_revoked, which claimed source-global knowledge the signal did not carry. permission_denied records only that this request attempt was denied."},"billing_note": {"enum": [null, "entered_metered", "left_metered"]@@ -113,6 +115,17 @@"properties": { "kind": { "const": "supply_interrupted" } }}},+ {+ "$comment": "Targeted v4c totality: request-scoped permission_denied can explain only a successful fallback switch. It cannot create source-global cooldown, recovery, skip, or needs_action state.",+ "if": {+ "properties": { "reason": { "const": "permission_denied" } },+ "required": ["reason"]+ },+ "then": {+ "required": ["kind"],+ "properties": { "kind": { "const": "switch" } }+ }+ },{"$comment": "A needs_action record is source-scoped and carries one of the five non-self-healing source causes.","if": {@@ -315,6 +328,20 @@"severity": "action_required","human_zh": "Relay 余额不足,需要处理","human_en": "Relay balance is exhausted and needs attention"+ },+ {+ "id": "evt_20260730c",+ "ts": "2026-07-30T05:55:00Z",+ "agent": "claude",+ "kind": "switch",+ "model_id": "claude-opus-4-6",+ "from_source": "src_primary01",+ "to_source": "src_backup001",+ "reason": "permission_denied",+ "billing_note": null,+ "severity": "info",+ "human_zh": "Primary:请求权限被拒绝 -> 已切到 Backup",+ "human_en": "Primary: request permission denied -> switched to Backup"}]}diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 11ca7c283..3505b0066 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -214,7 +214,8 @@"needs_action","error"],- "description": "Classified by whether the state heals itself (spec §4.5). cooldown = 暂不可用, self-healing, `retry_at` known; needs_action = 需处理, will NEVER recover unattended (v2, 2026-07-29) — the conditional above makes `detail_key` mandatory there, because a state whose whole point is 'the user must act' is unrenderable without naming the action; error = unclassified failure — and, pinned in round 6, a BLOCKER rather than a third class: its `retry_at` is null and nothing clears it unattended, so it counts WITH `needs_action` in the OR-branch that makes a chain `interrupted` (`agent-chain.schema.json`), and the interruption it causes is announced as `kind: needs_action`, `reason: unclassified_error`. 'We could not classify the failure' describes our knowledge of the cause, never a promise about recovery. active/standby are the two HEALTHY values and are a source-global DISPLAY ROLLUP, not a per-agent fact: active = 使用中, i.e. serving at least one agent right now; standby = 备用, healthy but currently serving nobody. A source can be at the head of Claude's order and third in Codex's, so per-agent role is read from position in `agent-chain.schema.json` and is never stored here. Health itself is genuinely source-global: quota and reachability are properties of the account, so one cooldown pool is shared across backends (core/handlers/model_hub/service.py::_cooldown). NOTE: `needs_action` is a v2 TARGET value — config/v2_config.py's loader whitelist still rejects it until the serializer PR lands it."+ "$comment": "Targeted v4 same-assumption audit (escalations #2+#3): source-global health cannot imply process-local native CLI availability. Evidence at master 807d1eee: core/handlers/model_hub/service.py:431-445 computes unavailable native sources independently of persisted health, then resolver.py:83-87 gives that process-local set precedence over active/standby and cooldown retry readiness.",+ "description": "Classified by whether the source-global state heals itself (spec §4.5). cooldown = 暂不可用, self-healing, `retry_at` known; needs_action = 需处理, will NEVER recover unattended; error = unclassified blocker with no unattended recovery. active/standby are the two HEALTHY persisted display values and both project to `health: healthy` in agent-chain.schema.json. Targeted v4 correction: neither healthy value asserts that this serving process can launch a native CLI right now. Process availability is a distinct resolve-time fact carried by chain `channel` / `runnable` / `reason`; a source may therefore remain globally healthy while one process reports `native_cli_unavailable`. Per-agent role is still positional and never stored here. Health itself remains source-global: quota and upstream reachability belong to the account and one cooldown pool is shared across backends (core/handlers/model_hub/service.py::_cooldown)."},"retry_at": {"type": [@@ -222,7 +223,8 @@"null"],"format": "date-time",- "description": "When a cooldown lapses. NON-NULL FOR EXACTLY ONE STATUS — `cooldown` — and null for the other four, by the conditionals above rather than by emitter discipline: `needs_action` and `error` never recover on a timer, and a healthy source has nothing to wait for. Same predicate as `retry_at` in agent-chain.schema.json, which mirrors this field per chain member."+ "$comment": "Targeted v4 same-assumption audit: retry_at belongs only to source-global cooldown. core/handlers/model_hub/resolver.py:83-87 at master 807d1eee still rejects an unavailable native source before evaluating source_retry_ready, so a health stamp never proves process availability.",+ "description": "When source-global cooldown health becomes retry-ready. NON-NULL FOR EXACTLY ONE STATUS — `cooldown` — and null for the other four. Targeted v4 correction: this timestamp says when health permits another try; it does not promise that a native CLI is available in this process. Process unavailability may coexist with cooldown before the stamp lapses and may still block the source after health recovers. agent-chain.schema.json mirrors the timestamp per member without collapsing those dimensions."},"detail_key": {"type": [@@ -568,4 +570,4 @@"masked_credential": "key …9c1"}]-}\ No newline at end of file+}diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 8d04da874..caa3728a2 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": "v3 debug record for one exactly attributed Hub turn. A record is written only when the turn FSM can attribute every included attempt to this turn; ambiguous attempts produce no provenance record. turn_id therefore remains required and no attribution-grain marker exists. The attempt sequence is failed_attempts followed by exactly one terminating slot when a source attempt terminated the turn: served, terminal_error, or canceled_attempt.",+ "description": "v4 debug record for one exactly attributed Hub turn. A record is written only when the turn FSM can attribute every included attempt to this turn; ambiguous attempts produce no provenance record. turn_id therefore remains required and no attribution-grain marker exists. The attempt sequence is failed_attempts followed by exactly one terminating slot when a source attempt terminated the turn: served, terminal_error, or canceled_attempt.","type": "object","required": ["contract_version",@@ -19,7 +19,7 @@],"additionalProperties": false,"properties": {- "contract_version": { "const": 3 },+ "contract_version": { "const": 4 },"turn_id": {"type": "string","description": "Opaque id in the existing turn/session id space."@@ -78,9 +78,11 @@"credential_revoked","balance_exhausted","account_banned",+ "permission_denied","unclassified_error"],- "description": "The attempt-failure partition of ResolutionEvent.reason. The mirror registry enforces totality."+ "description": "The attempt-failure partition of ResolutionEvent.reason. permission_denied records a request-scoped denial and does not imply source-global state. The mirror registry enforces totality.",+ "$comment": "Targeted v4c, review finding 3680338859: core/handlers/model_hub/classification.py:98-125 distinguishes the runtime-preserved permission_error code from source-global credential_revoked. The failed attempt remains useful turn evidence even though no Source state is mutated."}}}@@ -272,7 +274,7 @@],"examples": [{- "contract_version": 3,+ "contract_version": 4,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -298,7 +300,7 @@"model_supply_state": null},{- "contract_version": 3,+ "contract_version": 4,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -319,7 +321,7 @@"model_supply_state": null},{- "contract_version": 3,+ "contract_version": 4,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -332,7 +334,7 @@"model_supply_state": "waiting"},{- "contract_version": 3,+ "contract_version": 4,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -352,7 +354,7 @@"model_supply_state": null},{- "contract_version": 3,+ "contract_version": 4,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",@@ -368,6 +370,32 @@"via_mapping": false},"model_supply_state": null+ },+ {+ "contract_version": 4,+ "turn_id": "turn_01k9x6db",+ "ts": "2026-07-30T05:55:00Z",+ "agent": "claude",+ "requested_model_id": "claude-opus-4-6",+ "outcome": "served",+ "failed_attempts": [+ {+ "source_id": "src_primary01",+ "resolved_model_id": "claude-opus-4-6",+ "channel": "hub",+ "via_mapping": false,+ "reason": "permission_denied"+ }+ ],+ "served": {+ "source_id": "src_backup001",+ "resolved_model_id": "claude-opus-4-6",+ "channel": "hub",+ "via_mapping": false+ },+ "terminal_error": null,+ "canceled_attempt": null,+ "model_supply_state": null}]}diff --git a/docs/plans/model-hub-l3-correlation.md b/docs/plans/model-hub-l3-correlation.mdnew file mode 100644index 000000000..9c7449a08--- /dev/null+++ b/docs/plans/model-hub-l3-correlation.md@@ -0,0 +1,199 @@+# Model Hub L3 Turn Correlation++Status: implementation note for provenance v3 and the orchestrator-delivered,+channel-aware chain/probe v4. Contract files remain read-only to L3 authorship.++## Purpose++Turn provenance is useful only when every recorded attempt belongs to exactly+one Workbench turn. A plausible guess is worse than an explicit absence. This+design therefore uses the existing Workbench turn token as the only turn+identity and fails closed whenever a process-scoped gateway credential cannot+be attributed exactly.++## Runtime Facts++`SessionTurnManager` is the lifecycle authority for Workbench turns:++- `in_flight` owns one `Turn` per Avibe session id;+- the dispatch seam creates `context.platform_specific["turn_token"]`;+- the registered stream sink carries the same token and rejects duplicate+ registration;+- IM and CLI dispatches do not enter this FSM.++The token is therefore already bound to the turn that emits and settles. L3+does not mint another turn id.++Backend process scopes are:++| Backend | Credential scope | Runtime fact |+| --- | --- | --- |+| Claude | Claude composite client identity | One SDK client/process lane per main or agent-specific session identity |+| Codex | `(backend, normalized cwd)` | One app-server transport is reused by every session in that cwd |+| OpenCode | OpenCode server instance | `OpenCodeServerManager` is a singleton shared across all working directories and tracks multiple active sessions |++The OpenCode fact contradicts the requested server-per-session verification.+The shared-server evidence is `modules/agents/opencode/server.py:62-65`+(`OpenCodeServerManager` is a singleton shared across working directories) and+`modules/agents/opencode/caller_context.py:3-6` (the shared `opencode serve`+process multiplexes per-session context through a binding file). The+orchestrator confirmed that frozen v3 already represents this truth through+honest absence, so no targeted v4 is needed: OpenCode provenance is never+written in v2.++## Credential And Turn Registry++`ModelHubTurnGateway` owns one in-memory, process-lifetime registry. A key is+`(backend, process_scope)`, and its bearer token is minted on first use and+remains stable for the lifetime of that process scope. This replaces the+current per-backend token map without changing any backend process model,+gateway wire shape, or runtime fingerprint semantics.++The launch callers thread only the process identity already available at the+owned call sites:++- Claude passes the exact composite cache identity of the main or agent-specific+ SDK client;+- Codex passes its normalized cwd;+- OpenCode passes the singleton server scope.++`resolve_model_hub_launch` asks `SessionTurnManager` for the `Turn` whose+`task` is `asyncio.current_task()`. A match supplies the existing+`turn_token`; no match is an untracked use. This is the key reuse: the+correlator reads the FSM's token binding rather than constructing a parallel+session-to-turn map.++Each registry entry keeps:++- the stable bearer token;+- active tracked turn ids for the scope;+- a sticky ambiguity bit per overlapping tracked turn;+- a sticky `untracked_use` bit for the token lifetime;+- per-turn attempt traces while the turn is active.++The transition rules are:++1. A tracked launch registers its existing turn id under the process scope.+2. An IM/CLI launch has no FSM match and sets `untracked_use`.+3. A gateway request is attributable only when the scope has exactly one+ active tracked turn, no overlap has occurred for that turn, and+ `untracked_use` is false.+4. Two live tracked turns in one scope mark both turns ambiguous. Removing one+ later does not make either historical attempt exact.+5. An untracked use poisons the process-scope token for provenance. This is+ deliberately conservative: the stable credential carries no request field+ that could separate later tracked traffic from the untracked caller.+6. A request that fails the predicate is served normally but contributes no+ attempt to any provenance record.++The registry never serializes the bearer token or exposes it through an API.+When a Claude client cache entry or Codex cwd transport is evicted, its backend+lifecycle hook retires the matching registry scope and bearer token. A later+runtime for the same scope mints a new token. Retirement during a stuck active+turn marks that trace ambiguous before settlement, so eviction cannot turn+partial process traffic into an exact provenance record. In-process+replacement keeps the scope only when the replacement launch has already+registered the current turn against that same Claude session or Codex cwd.++## Attempt Capture And Settlement++The gateway records the classified `RawCallOutcome`, never raw response bodies+or credentials. The service contributes the selected source, resolved model,+channel, mapping flag, and supply state. Streaming attempts are finalized only+after their stream outcome is known.++For Hub launches, the registry also retains the caller-facing model and mapping+decision before the backend CLI replaces the request model with the resolved+target. The gateway accepts that request only when its model matches the+prepared target; a different-model request is untracked use and makes the turn+ineligible for a record. This preserves `requested_model_id` and `via_mapping`+without adding a wire field or a second correlator.++`SessionTurnManager` calls one additive settlement hook before retiring the+`Turn`. The hook receives the existing turn token and the FSM settlement:++| FSM / resolution fact | Provenance outcome |+| --- | --- |+| terminal result after a usable completion | `served` |+| all retryable candidates failed | `exhausted` |+| invalid parameter, protocol/tool failure, or dropped connection | `failed_terminal` |+| no runnable candidate at resolve time | `no_candidate` |+| `settled_by == stopped` | `canceled` |++A dropped connection settles as `no_terminal_result`, not `stopped`, and is+therefore never labeled `canceled`. A user Stop may have no upstream attempt;+in that case `canceled_attempt` is null. When Stop interrupts a known in-flight+attempt, `canceled_attempt` contains only its identity, as required by v3.++The writer emits a record only if all captured attempts passed the exactness+predicate. The timestamp is the FSM settlement time. Records use an atomic,+bounded state file beside the existing Model Hub event store. No placeholder,+coarse record, or attribution-grain field is written.++## Read-Time Absence++`GET /api/models/turns/<turn_id>/provenance` reads an exact record first. If no+record exists, it derives whether the turn is known from the Workbench session+store's persisted output metadata and reads a bounded turn-mode marker captured+from the bound launch at FSM settlement:++- known Direct turn: `provenance_unavailable` /+ `models.provenance.direct_mode`;+- known Hub turn without an exact record:+ `provenance_unavailable` /+ `models.provenance.attribution_ambiguous`;+- unknown id: `turn_not_found`.++The mode marker contains only `turn_id` and the turn-time `direct` / `hub` mode;+it is stored separately from v3 provenance records and never carries an attempt+identity. A known turn without a marker fails closed as+`attribution_ambiguous`. The read path never infers historical mode from mutable+current agent configuration. IM and CLI paths have no FSM turn id and write+neither a marker nor a provenance record.++## Pre-Launch Supply Failure Copy++The resolve boundary in `modules/agents/model_hub.py` is the single mapping+point, so Claude, Codex, and OpenCode inherit the same typed failure copy:++| State | Copy |+| --- | --- |+| self-healing retry | `下一回合已自动换线,直接重试即可` |+| waiting | `模型 {model} 暂时不可用,等待 {source} 于 {retry_at} 自动恢复。` |+| interrupted with blockers | `模型 {model} 当前不可用:{blockers}。请前往 Models 处理。` |+| no enabled source | `模型 {model} 没有已启用的来源。请前往 Models 配置。` |+| no eligible source | `模型 {model} 没有适用于 {backend} 的来源。请前往 Models 配置。` |+| unsupported model | `没有来源支持模型 {model}。请前往 Models 配置。` |++Successful fallback remains silent. Structural causes use+`no_enabled_source`, `no_eligible_source`, or `model_unsupported`; user-facing+text is selected through `vibe/i18n`. Persisted blocker detail keys are mapped+to the same closed ResolutionEvent reason vocabulary and translated before+interpolation; raw i18n keys never appear in launch copy.++## Verification++The acceptance suite contains separate fixtures for:++- two concurrent Web turns sharing one Codex cwd: neither record contains the+ ambiguous attempt;+- the same two turns run sequentially: both records are present;+- one tracked Web turn plus one untracked IM/CLI use in the same scope: the+ tracked record is absent;+- one known OpenCode turn: the shared server writes no record and the read API+ returns `provenance_unavailable` / `models.provenance.attribution_ambiguous`,+ never `turn_not_found`;+- one mapped Hub turn: the record retains the pre-mapping menu model and marks+ every matching attempt `via_mapping: true`; an unexpected request model+ makes the record absent;+- user Stop, dropped connection, and successful control settlements;+- every observed native CLI terminal failure classified before settlement+ (unknown diagnostics use `unclassified_error` without mutating source+ health), so a failed turn cannot be recorded as served;+- Direct, ambiguous-known, and unknown provenance route absences;+- source chain order and model-scoped supply state;+- Hub probe usable-completion, native CLI readiness, and their latency+ partitions;+- single-grain event emission and source referential integrity.++Healthy ambiguity emits no ResolutionEvent.diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 445ecfda4..2faca1623 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -183,6 +183,7 @@ class CodexAgent(BaseAgent):self.controller,"codex",requested_model or "",+ process_scope=request.working_path,)bind_launch(request.context, launch)await self._interrupt_active_turn_before_runtime_change(request, launch)@@ -402,9 +403,12 @@ class CodexAgent(BaseAgent):)except Exception:logger.warning("Failed to release Workbench turns during Codex refresh", exc_info=True)- transports = list(self._transports.values())+ transport_items = list(self._transports.items())+ transports = [transport for _, transport in transport_items]self._transports.clear()self._transport_last_activity.clear()+ for cwd, _ in transport_items:+ self._retire_model_hub_process_scope(cwd)for transport in transports:try:@@ -456,6 +460,7 @@ class CodexAgent(BaseAgent):self._transports.pop(working_path, None)self._transport_last_activity.pop(working_path, None)+ self._retire_model_hub_process_scope(working_path)self._session_mgr.invalidate_thread(base_session_id)self._turn_registry.clear_session(base_session_id)self._clear_thread_developer_instructions(base_session_id)@@ -469,10 +474,13 @@ class CodexAgent(BaseAgent):self._transport_locks = {}if not hasattr(self, "_session_locks"):self._session_locks = {}- transports = list(self._transports.values())+ transport_items = list(self._transports.items())+ transports = [transport for _, transport in transport_items]self._transports.clear()self._transport_last_activity.clear()self._transport_locks.clear()+ for cwd, _ in transport_items:+ self._retire_model_hub_process_scope(cwd)for transport in transports:try:@@ -566,6 +574,7 @@ class CodexAgent(BaseAgent):self._transports.pop(cwd, None)self._transport_last_activity.pop(cwd, None)self._cwd_inodes().pop(cwd, None)+ self._retire_model_hub_process_scope(cwd)for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):# A force-evicted stuck-active turn never emitted a terminal@@ -585,6 +594,13 @@ class CodexAgent(BaseAgent):return evicted+ def _retire_model_hub_process_scope(self, cwd: str) -> None:+ controller = getattr(self, "controller", None)+ router = getattr(controller, "model_hub_runtime", None)+ retire = getattr(router, "retire_process_scope", None)+ if callable(retire):+ retire("codex", cwd)+async def _settle_stuck_active_request(self, base_session_id: str) -> None:"""Settle a turn we are about to force-reap.@@ -746,6 +762,9 @@ class CodexAgent(BaseAgent):async with self._transport_locks[cwd]:# Double-check after acquiring lockexisting = self._transports.get(cwd)+ desired_fingerprint = launch.fingerprint if launch is not None else "direct"+ existing_fingerprint = getattr(existing, "runtime_fingerprint", "direct")+ runtime_changed = existing_fingerprint != desired_fingerprintif existing and existing.is_initialized:# Reuse only while the directory the app-server was spawned in# is still the SAME directory (#561): after a delete (+ possible@@ -753,8 +772,6 @@ class CodexAgent(BaseAgent):# thread/start fails. Untracked legacy entries reuse as before.spawned_ino = self._cwd_inodes().get(cwd)stale_cwd = spawned_ino is not None and self._cwd_inode(cwd) != spawned_ino- desired_fingerprint = launch.fingerprint if launch is not None else "direct"- runtime_changed = getattr(existing, "runtime_fingerprint", "direct") != desired_fingerprintif not stale_cwd and not runtime_changed:self._touch_transport_activity(cwd)return existing@@ -775,6 +792,12 @@ class CodexAgent(BaseAgent):# Stop stale transport if anyif existing:await existing.stop()+ if (+ runtime_changed+ and desired_fingerprint == "direct"+ and existing_fingerprint.startswith("hub:")+ ):+ self._retire_model_hub_process_scope(cwd)# The new app-server process won't know about threads/turns# from the old process. Invalidate only sessions bound to# this cwd so healthy sessions on other cwds are unaffected.diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex bd1792193..b72b7a9fe 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -7,6 +7,7 @@ import hashlibimport jsonimport osimport re+import shutilimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -26,12 +27,16 @@ from core.handlers.model_hub.resolver import (source_eligible_for_backend,)from core.handlers.model_hub.service import ModelHubError, ModelHubService, create_default_service+from core.services.settings import load_config_or_defaultfrom core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from vibe.i18n import t as i18n_tLaunchChannel = Literal["direct", "native_cli", "hub"]+TurnMode = Literal["direct", "hub"]_CONTEXT_LAUNCH_ATTR = "_vibe_model_hub_launch"+_CONTEXT_MODE_ATTR = "_vibe_model_hub_turn_mode"_CONTEXT_FAILURE_RECORDED_ATTR = "_vibe_model_hub_failure_recorded"_NATIVE_QUOTA_RE = re.compile(r"(?:quota|usage|credit|billing).{0,32}(?:exhaust|exceed|limit|deplet|insufficient)|"@@ -45,6 +50,18 @@ _NETWORK_ERROR_RE = re.compile(r"(?:timed?\s*out|timeout|connection (?:failed|reset|refused)|network (?:error|unreachable))",re.IGNORECASE,)+_SOURCE_DETAIL_EVENT_REASONS = {+ "models.source.cooldown.quota_exhausted": "quota_exhausted",+ "models.source.cooldown.rate_limited": "rate_limited",+ "models.source.cooldown.server_error": "server_error",+ "models.source.cooldown.network": "network",+ "models.source.cooldown.timeout": "network",+ "models.source.needs_action.oauth_expired": "credential_expired",+ "models.source.needs_action.credential_revoked": "credential_revoked",+ "models.source.needs_action.balance_exhausted": "balance_exhausted",+ "models.source.needs_action.account_banned": "account_banned",+ "models.source.error.unclassified": "unclassified_error",+}@dataclass(frozen=True)@@ -87,11 +104,28 @@ class OpenCodeOverlay:def bind_launch(context: Any, launch: ModelHubLaunch) -> None:try:setattr(context, _CONTEXT_LAUNCH_ATTR, launch)+ setattr(+ context,+ _CONTEXT_MODE_ATTR,+ "direct" if launch.channel == "direct" else "hub",+ )setattr(context, _CONTEXT_FAILURE_RECORDED_ATTR, False)except (AttributeError, TypeError):return+def bind_turn_mode(context: Any, mode: TurnMode) -> None:+ try:+ setattr(context, _CONTEXT_MODE_ATTR, mode)+ except (AttributeError, TypeError):+ return+++def turn_mode_for_context(context: Any) -> TurnMode | None:+ value = getattr(context, _CONTEXT_MODE_ATTR, None)+ return value if value in {"direct", "hub"} else None++def launch_for_context(context: Any) -> ModelHubLaunch | None:value = getattr(context, _CONTEXT_LAUNCH_ATTR, None)return value if isinstance(value, ModelHubLaunch) else None@@ -151,11 +185,29 @@ async def resolve_model_hub_launch(controller: Any,backend: BackendName,requested_model: str,+ *,+ process_scope: Optional[str] = None,) -> ModelHubLaunch:router = getattr(controller, "model_hub_runtime", None)resolver = getattr(router, "resolve", None)if callable(resolver):- return await resolver(backend, requested_model)+ manager = getattr(controller, "session_turns", None)+ turn_lookup = getattr(manager, "model_hub_turn_id_for_task", None)+ turn_id = turn_lookup() if callable(turn_lookup) else None+ try:+ return await resolver(+ backend,+ requested_model,+ process_scope=process_scope,+ turn_id=turn_id,+ )+ except ModelHubError as exc:+ raise _localized_launch_error(+ controller,+ backend,+ requested_model,+ exc,+ ) from Nonereturn ModelHubLaunch(backend=backend,channel="direct",@@ -173,10 +225,74 @@ async def resolve_opencode_overlay_launch(router = getattr(controller, "model_hub_runtime", None)resolver = getattr(router, "resolve_opencode_overlay_launch", None)if overlay is not None and callable(resolver):- return await resolver(overlay, requested_model)+ try:+ return await resolver(overlay, requested_model)+ except ModelHubError as exc:+ raise _localized_launch_error(+ controller,+ "opencode",+ requested_model,+ exc,+ ) from Nonereturn await resolve_model_hub_launch(controller, "opencode", requested_model)+def _localized_launch_error(+ controller: Any,+ backend: BackendName,+ requested_model: str,+ error: ModelHubError,+) -> ModelHubError:+ failure = error.data+ if not isinstance(failure, dict):+ return error+ language = str(+ getattr(getattr(controller, "config", None), "language", "en")+ or "en"+ )+ key = str(failure.get("copy_key") or "interrupted")+ raw_blockers = failure.get("blockers")+ if isinstance(raw_blockers, list):+ rendered_blockers = []+ for blocker in raw_blockers:+ if not isinstance(blocker, Mapping):+ continue+ source = str(blocker.get("source") or "")+ detail_key = str(blocker.get("detail_key") or "")+ blocker_reason = str(blocker.get("reason") or "")+ if blocker_reason == "native_cli_unavailable":+ detail = i18n_t(+ "modelHub.launch.native_cli_unavailable",+ language,+ )+ else:+ reason = _SOURCE_DETAIL_EVENT_REASONS.get(detail_key)+ detail = (+ i18n_t(f"modelHub.events.reason.{reason}", language)+ if reason is not None+ else str(blocker.get("status") or "")+ )+ rendered_blockers.append(f"{source}: {detail}")+ blockers = ", ".join(rendered_blockers)+ else:+ blockers = str(raw_blockers or "")+ return ModelHubError(+ error.code,+ status=error.status,+ detail=i18n_t(+ f"modelHub.launch.{key}",+ language,+ model=failure.get("model") or requested_model,+ backend=backend,+ source=failure.get("source") or "",+ retry_at=failure.get("retry_at") or "",+ blockers=blockers,+ ),+ supply_state=error.supply_state,+ data=error.data,+ )++def build_claude_hub_env(base_env: dict[str, str],launch: ModelHubLaunch,@@ -274,8 +390,9 @@ class ModelHubRuntimeRouter:self.native_cli_ready = native_cli_ready or self._default_native_cli_readyself.service.native_source_ready = self._native_source_readyself._last_launch: dict[tuple[BackendName, str], ModelHubLaunch] = {}- self._last_launch_mode: dict[- tuple[BackendName, str], Literal["hub", "direct"]+ self._last_supply_state: dict[+ tuple[BackendName, str],+ tuple[str, Optional[EventReason]],] = {}@staticmethod@@ -284,6 +401,14 @@ class ModelHubRuntimeRouter:*,verified_oauth: bool = False,) -> bool:+ runtime_config = getattr(load_config_or_default().agents, backend)+ cli_path = str(getattr(runtime_config, "cli_path", "") or "").strip()+ if (+ not bool(getattr(runtime_config, "enabled", False))+ or not cli_path+ or shutil.which(os.path.expanduser(cli_path)) is None+ ):+ return Falseif backend == "claude":from vibe.claude_config import read_claude_settings_env@@ -409,9 +534,27 @@ class ModelHubRuntimeRouter:return prefixraise ModelHubError("engine_down", status=503)- async def _gateway_credentials(self, backend: BackendName) -> tuple[str, str]:+ async def _gateway_credentials(+ self,+ backend: BackendName,+ *,+ process_scope: Optional[str],+ turn_id: Optional[str],+ requested_model_id: Optional[str] = None,+ resolved_model_id: Optional[str] = None,+ source_id: Optional[str] = None,+ via_mapping: bool = False,+ ) -> tuple[str, str]:if self.turn_gateway is not None:- return await self.turn_gateway.endpoint(backend)+ return await self.turn_gateway.endpoint(+ backend,+ process_scope=process_scope,+ turn_id=turn_id,+ requested_model_id=requested_model_id,+ resolved_model_id=resolved_model_id,+ source_id=source_id,+ via_mapping=via_mapping,+ )await self.service._ensure_engine_synced()status = await self.service._engine_call(self.service.adapter.start())if status.listen_port is None:@@ -494,14 +637,10 @@ class ModelHubRuntimeRouter:self,current: ModelHubLaunch,config: ModelHubConfig,- *,- configured_mode: Literal["hub", "direct"],) -> None:previous, failed_source, failed_reason = self._transition_context(current, config)route_key = self._route_key(current)- previous_mode = self._last_launch_mode.get(route_key)self._last_launch[route_key] = current- self._last_launch_mode[route_key] = configured_modecurrent_source = self._source_for_id(config, current.source_id)if (failed_source is not None@@ -517,50 +656,19 @@ class ModelHubRuntimeRouter:source=current_source,)if previous is None:- if configured_mode == "hub" and current.channel == "direct":- self.service._record_event(- agent=cast(EventAgent, current.backend),- kind="channel_switch",- model_id=current.target_model,- reason="manual",- to_source=None,- now=self.service.now(),- )returnif previous.channel == current.channel:- if (- current.channel == "direct"- and configured_mode == "hub"- and previous_mode == "direct"- ):- self.service._record_event(- agent=cast(EventAgent, current.backend),- kind="channel_switch",- model_id=current.target_model,- reason="manual",- to_source=None,- now=self.service.now(),- )returnif "direct" in {previous.channel, current.channel}:- if configured_mode != "hub":- return- previous_source = self._source_for_id(config, previous.source_id)- reason = failed_reason or "manual"- self.service._record_event(- agent=cast(EventAgent, current.backend),- kind="channel_switch",- model_id=current.target_model,- reason=reason,- from_source=previous.source_id,- to_source=current.source_id,- from_label=previous_source.display_name if previous_source else None,- to_label=current_source.display_name if current_source else None,- now=self.service.now(),- )returnif {previous.channel, current.channel} != {"native_cli", "hub"}:return+ if (+ previous.source_id is None+ or current.source_id is None+ or previous.source_id != current.source_id+ ):+ returnreason = failed_reason or ("recovery" if current.channel == "native_cli" else "manual")self.service._record_event(agent=cast(EventAgent, current.backend),@@ -568,11 +676,184 @@ class ModelHubRuntimeRouter:model_id=current.target_model,reason=reason,from_source=previous.source_id,- to_source=current.source_id,+ to_source=previous.source_id,+ from_label=current_source.display_name,+ to_label=current_source.display_name,now=self.service.now(),)- async def resolve(self, backend: BackendName, requested_model: str) -> ModelHubLaunch:+ @staticmethod+ def _supply_interruption_reason(+ config: ModelHubConfig,+ resolution: ModelHubTurnResolution,+ ) -> EventReason:+ order = config.effective_source_order(resolution.backend)+ sources_by_id = {source.id: source for source in config.sources}+ enabled_sources = [+ sources_by_id[source_id]+ for source_id in order+ if source_id in sources_by_id+ ]+ if not enabled_sources:+ if config.sources and not any(+ source_eligible_for_backend(source, resolution.backend)+ for source in config.sources+ ):+ return "no_eligible_source"+ return "no_enabled_source"+ if not any(+ source_eligible_for_backend(source, resolution.backend)+ for source in enabled_sources+ ):+ return "no_eligible_source"+ return "model_unsupported"++ @staticmethod+ def _launch_failure(+ config: ModelHubConfig,+ resolution: ModelHubTurnResolution,+ ) -> dict[str, Any]:+ model = resolution.requested_model or resolution.target_model+ if resolution.supply_status == "waiting":+ cooling = [+ source+ for source in resolution.matching_sources+ if source.state.status == "cooldown" and source.state.retry_at+ ]+ recovery = min(+ (source.state.retry_at or "" for source in cooling),+ default="",+ )+ return {+ "copy_key": "waiting",+ "model": model,+ "source": ", ".join(source.display_name for source in cooling),+ "retry_at": recovery,+ }+ if resolution.matching_sources:+ candidate_ids = {+ source.id for source in resolution.candidates+ }+ blockers = [+ {+ "source": source.display_name,+ "status": source.state.status,+ "detail_key": source.state.detail_key,+ "reason": (+ "native_cli_unavailable"+ if source.supply_channel == "native_cli"+ and source.state.status in {"active", "standby"}+ and source.id not in candidate_ids+ else None+ ),+ }+ for source in resolution.matching_sources+ ]+ return {+ "copy_key": "interrupted",+ "model": model,+ "blockers": blockers,+ }+ reason = ModelHubRuntimeRouter._supply_interruption_reason(config, resolution)+ return {+ "copy_key": reason,+ "model": model,+ }++ def _no_candidate_error(+ self,+ *,+ backend: BackendName,+ requested_model: str,+ config: ModelHubConfig,+ resolution: ModelHubTurnResolution,+ process_scope: Optional[str],+ turn_id: Optional[str],+ ) -> ModelHubError:+ supply_state = (+ "waiting"+ if resolution.supply_status == "waiting"+ else "interrupted"+ )+ normalized_scope = (+ str(process_scope or "").strip()+ or f"{backend}:untracked"+ )+ if self.turn_gateway is not None:+ self.turn_gateway.correlation.mark_no_candidate(+ backend=backend,+ process_scope=normalized_scope,+ turn_id=turn_id,+ requested_model_id=requested_model,+ supply_state=supply_state,+ )+ if not resolution.matching_sources:+ reason = self._supply_interruption_reason(config, resolution)+ supply_key = (backend, requested_model)+ current_state = ("interrupted", reason)+ if self._last_supply_state.get(supply_key) != current_state:+ self.service._record_event(+ agent=cast(EventAgent, backend),+ kind="supply_interrupted",+ model_id=requested_model,+ reason=reason,+ now=self.service.now(),+ )+ self._last_supply_state[supply_key] = current_state+ return ModelHubError(+ "mapping_target_unavailable",+ status=409,+ supply_state=supply_state,+ data=self._launch_failure(+ config,+ resolution,+ ),+ )++ def settle_turn(+ self,+ turn_id: str,+ *,+ settled_by: Optional[str],+ ts: str,+ mode: Optional[Literal["direct", "hub"]] = None,+ ) -> None:+ try:+ if mode is not None:+ self.service.note_turn_mode(turn_id, mode)+ finally:+ if self.turn_gateway is not None:+ self.turn_gateway.correlation.settle(+ turn_id,+ settled_by=settled_by,+ ts=ts,+ )++ def retire_process_scope(+ self,+ backend: BackendName,+ process_scope: str,+ *,+ terminal_turn_id: Optional[str] = None,+ ) -> None:+ if self.turn_gateway is not None:+ self.turn_gateway.correlation.retire_scope(+ backend,+ process_scope,+ terminal_turn_id=terminal_turn_id,+ )++ def turn_mode(self, backend: BackendName) -> TurnMode:+ return cast(TurnMode, self.service.store.load().agents[backend].mode)++ async def resolve(+ self,+ backend: BackendName,+ requested_model: str,+ *,+ process_scope: Optional[str] = None,+ turn_id: Optional[str] = None,+ ) -> ModelHubLaunch:requested_model = str(requested_model or "").strip()config = self.service.store.load()config, resolution = await self._resolve_turn(@@ -580,17 +861,19 @@ class ModelHubRuntimeRouter:backend,requested_model,)- configured_mode = config.agents[backend].modeif resolution.channel == "direct":launch = self._direct_launch(backend, requested_model)- self._emit_transition(- launch,- config,- configured_mode=configured_mode,- )+ self._emit_transition(launch, config)return launchif resolution.source is None:- raise ModelHubError("mapping_target_unavailable", status=409)+ raise self._no_candidate_error(+ backend=backend,+ requested_model=requested_model,+ config=config,+ resolution=resolution,+ process_scope=process_scope,+ turn_id=turn_id,+ )target_model = resolution.target_modelif resolution.mapping_applied:@@ -603,6 +886,7 @@ class ModelHubRuntimeRouter:now=self.service.now(),)source = resolution.source+ self._last_supply_state[(backend, requested_model)] = ("ok", None)if source.supply_channel == "native_cli":if self.service.revocations.list():try:@@ -618,8 +902,26 @@ class ModelHubRuntimeRouter:runtime_model=target_model,source_id=source.id,)+ if self.turn_gateway is not None:+ self.turn_gateway.correlation.begin_native_attempt(+ backend=backend,+ process_scope=str(process_scope or "").strip() or f"{backend}:untracked",+ turn_id=turn_id,+ requested_model_id=requested_model,+ source_id=source.id,+ resolved_model_id=target_model,+ via_mapping=resolution.mapping_applied,+ )else:- gateway_base_url, gateway_token = await self._gateway_credentials(backend)+ gateway_base_url, gateway_token = await self._gateway_credentials(+ backend,+ process_scope=str(process_scope or "").strip() or f"{backend}:untracked",+ turn_id=turn_id,+ requested_model_id=requested_model,+ resolved_model_id=target_model,+ source_id=source.id,+ via_mapping=resolution.mapping_applied,+ )runtime_model = target_modelif self.turn_gateway is None:prefix = await self._source_prefix(source.id)@@ -634,11 +936,7 @@ class ModelHubRuntimeRouter:gateway_base_url=gateway_base_url,gateway_token=gateway_token,)- self._emit_transition(- launch,- config,- configured_mode=configured_mode,- )+ self._emit_transition(launch, config)return launchasync def resolve_opencode_overlay_launch(@@ -653,13 +951,25 @@ class ModelHubRuntimeRouter:None,)if launch is None:+ config = self.service.store.load()+ config, resolution = await self._resolve_turn(+ config,+ "opencode",+ requested_model,+ supply_channel="hub",+ )+ if resolution.source is None:+ raise self._no_candidate_error(+ backend="opencode",+ requested_model=requested_model,+ config=config,+ resolution=resolution,+ process_scope="opencode:shared-server",+ turn_id=None,+ )raise ModelHubError("mapping_target_unavailable", status=409)config = self.service.store.load()- self._emit_transition(- launch,- config,- configured_mode=config.agents["opencode"].mode,- )+ self._emit_transition(launch, config)return launchasync def record_native_failure(self, context: Any, diagnostic: str) -> bool:@@ -672,10 +982,19 @@ class ModelHubRuntimeRouter:launch = launch_for_context(context)if launch is None or launch.channel not in {"native_cli", "hub"} or not launch.source_id:return False- if launch.channel == "hub" and self.turn_gateway is not None:- return Falseif getattr(context, _CONTEXT_FAILURE_RECORDED_ATTR, False):return False+ if launch.channel == "hub" and self.turn_gateway is not None:+ turn_id = str(+ (getattr(context, "platform_specific", None) or {}).get(+ "turn_token"+ )+ or ""+ ).strip()+ self.turn_gateway.correlation.fail_hub_attempt(turn_id)+ setattr(context, _CONTEXT_FAILURE_RECORDED_ATTR, True)+ return False+ decision: ResolutionDecision | Noneif _NATIVE_QUOTA_RE.search(diagnostic):decision = ResolutionDecision("fallback", reason="quota_exhausted", cooldown_seconds=300)elif _NATIVE_RATE_RE.search(diagnostic):@@ -685,6 +1004,23 @@ class ModelHubRuntimeRouter:elif _NETWORK_ERROR_RE.search(diagnostic):decision = ResolutionDecision("fallback", reason="network", cooldown_seconds=30)else:+ decision = None+ if launch.channel == "native_cli" and self.turn_gateway is not None:+ turn_id = str(+ (getattr(context, "platform_specific", None) or {}).get(+ "turn_token"+ )+ or ""+ ).strip()+ self.turn_gateway.correlation.fail_native_attempt(+ turn_id,+ reason=(+ decision.reason+ if decision is not None and decision.reason is not None+ else "unclassified_error"+ ),+ )+ if decision is None:return Falseconfig = self.service.store.load()source = next((item for item in config.sources if item.id == launch.source_id), None)@@ -708,7 +1044,11 @@ class ModelHubRuntimeRouter:if not checked:return None- gateway_base_url, gateway_token = await self._gateway_credentials("opencode")+ gateway_base_url, gateway_token = await self._gateway_credentials(+ "opencode",+ process_scope="opencode:shared-server",+ turn_id=None,+ )providers: dict[str, dict[str, Any]] = {}projected_identifiers: list[str] = []available_identifiers: list[str] = []diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex fb840ddc0..5035d254e 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -24,6 +24,7 @@ from modules.agents.model_hub import (ModelHubLaunch,OpenCodeOverlay,bind_launch,+ bind_turn_mode,opencode_model_for_overlay,persisted_launch_identity,resolve_opencode_overlay_launch,@@ -206,6 +207,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):session_id = Nonetry:model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)+ turn_mode = getattr(model_hub_runtime, "turn_mode", None)+ if callable(turn_mode):+ bind_turn_mode(+ request.context,+ turn_mode("opencode"),+ )prepare_overlay = getattr(model_hub_runtime, "prepare_opencode_overlay", None)if callable(prepare_overlay):model_hub_overlay = await prepare_overlay()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.pyindex de97d11e8..b9e57b1a5 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@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonfrom collections import dequefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone@@ -361,8 +362,10 @@ def test_mh_res_live_002_401_refreshes_once_in_live_turn(tmp_path: Path) -> Noneasyncio.run(exercise())-def test_mh_res_live_002_second_401_surfaces_without_fallback(tmp_path: Path) -> None:- """MH-RES-LIVE-002: a second 401 is terminal for the selected source."""+def test_mh_res_live_002_second_401_blocks_source_and_falls_back(+ tmp_path: Path,+) -> None:+ """MH-RES-LIVE-002: a second 401 leaves an actionable source blocker."""async def exercise() -> None:adapter = AdapterBoundaryFake(@@ -383,9 +386,22 @@ def test_mh_res_live_002_second_401_surfaces_without_fallback(tmp_path: Path) ->router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:status, _body = await _post_turn(await router.resolve("claude", "model-live"))- assert status == 401- assert [call[0] for call in adapter.invocations] == ["src_primary", "src_primary"]- assert store.load().sources[0].state.status == "standby"+ assert status == 200+ assert [call[0] for call in adapter.invocations] == [+ "src_primary",+ "src_primary",+ "src_backup",+ ]+ primary = store.load().sources[0]+ assert primary.state.status == "needs_action"+ assert (+ primary.state.detail_key+ == "models.source.needs_action.oauth_expired"+ )+ assert [+ event["kind"]+ for event in service.list_events(limit=10)+ ] == ["switch", "needs_action"]finally:await gateway.close()@@ -428,6 +444,42 @@ def test_mh_res_live_003_started_stream_never_retries(tmp_path: Path) -> None:asyncio.run(exercise())+def test_turn_gateway_nonstream_buffer_surfaces_terminal_failure(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ adapter = AdapterBoundaryFake(+ [+ AdapterResult(+ RawOutcomeKind.HTTP_ERROR,+ status=429,+ code="rate_limited",+ body=b'{"partial":',+ stream_started=True,+ ),+ ]+ )+ store = MemoryStore(_config(_source("src_primary")))+ service = _service(+ tmp_path,+ store,+ adapter,+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ status, body = await _post_turn(+ await router.resolve("claude", "model-live"),+ )+ assert status == 429+ assert json.loads(body)["error"]["code"] == "stream_interrupted"+ finally:+ await gateway.close()++ asyncio.run(exercise())++def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> None:async def exercise() -> None:adapter = AdapterBoundaryFake([AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')])@@ -525,8 +577,7 @@ def test_mh_evt_002_switch_events_survive_router_and_service_restart(tmp_path: Pfallback = await second_router.resolve("codex", "model-live")assert fallback.channel == "hub"persisted = BoundedEventLog(tmp_path / "events.json").list(limit=10)- assert [event["kind"] for event in persisted[:3]] == [- "channel_switch",+ assert [event["kind"] for event in persisted[:2]] == ["switch","cooldown",]diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex cbd07668e..9a9ed1aca 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -4,6 +4,7 @@ import asynciofrom dataclasses import dataclass, fieldfrom pathlib import Pathimport sys+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -732,6 +733,13 @@ def test_session_handler_does_not_resume_main_native_session_for_new_routing_submonkeypatch, tmp_path: Path) -> None:captured: dict[str, Any] = {"clients": []}+ from modules.agents import model_hub as model_hub_module++ original_resolve = model_hub_module.resolve_model_hub_launch++ async def capture_model_hub_scope(*args, **kwargs):+ captured["model_hub_process_scope"] = kwargs.get("process_scope")+ return await original_resolve(*args, **kwargs)class _SubagentSessions(_Sessions):@staticmethod@@ -770,6 +778,11 @@ def test_session_handler_does_not_resume_main_native_session_for_new_routing_submonkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)+ monkeypatch.setattr(+ model_hub_module,+ "resolve_model_hub_launch",+ capture_model_hub_scope,+ )controller = _Controller(tmp_path)controller.settings_manager = _RoutingSettingsManager()@@ -784,6 +797,7 @@ def test_session_handler_does_not_resume_main_native_session_for_new_routing_subclient = _run_session(handler, context)composite_key = f"slack_C123:reviewer:{tmp_path}"+ assert captured["model_hub_process_scope"] == composite_keyassert client.options.resume is Noneassert not hasattr(client, "_vibe_native_session_id")assert controller.claude_sessions[composite_key] is client@@ -1218,6 +1232,78 @@ def test_session_handler_surfaces_claude_missing_resume_session(monkeypatch, tmpassert captured["options"].resume == stale_session_id+def test_claude_startup_failure_is_recorded_before_scope_retirement(+ monkeypatch,+ tmp_path: Path,+) -> None:+ from modules.agents.model_hub import ModelHubLaunch++ events: list[tuple] = []++ class _StubClaudeSDKClient:+ def __init__(self, options):+ self.options = options++ async def connect(self) -> None:+ raise RuntimeError("startup failed")++ class _Runtime:+ async def resolve(self, backend, requested_model, **kwargs):+ return ModelHubLaunch(+ backend=backend,+ channel="native_cli",+ requested_model=requested_model,+ target_model="claude-opus",+ runtime_model="claude-opus",+ source_id="src_native01",+ )++ async def record_native_failure(self, context, diagnostic):+ events.append(("record", diagnostic))+ return False++ def retire_process_scope(+ self,+ backend,+ process_scope,+ *,+ terminal_turn_id=None,+ ):+ events.append(+ (+ "retire",+ backend,+ process_scope,+ terminal_turn_id,+ )+ )++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)++ controller = _Controller(tmp_path)+ controller.model_hub_runtime = _Runtime()+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="U123",+ channel_id="C123",+ platform_specific={"turn_token": "turn_startup_failure"},+ )++ with pytest.raises(RuntimeError, match="startup failed"):+ _run_session(handler, context)++ assert events == [+ ("record", "startup failed"),+ (+ "retire",+ "claude",+ f"slack_C123:{tmp_path}",+ "turn_startup_failure",+ ),+ ]++def test_session_handler_uses_scheduled_turn_source_for_dm_anchor(monkeypatch, tmp_path: Path) -> None:captured: dict[str, Any] = {}@@ -1785,6 +1871,48 @@ def test_cleanup_session_swallows_cancelled_receiver_task(monkeypatch, tmp_path:assert composite_key not in controller.claude_sessions+def test_cleanup_session_retires_model_hub_process_scope(+ monkeypatch,+ tmp_path: Path,+) -> None:+ class _StubClaudeSDKClient:+ def __init__(self, options):+ pass++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ return None++ monkeypatch.setattr(+ session_handler_module,+ "ClaudeAgentOptions",+ _StubClaudeAgentOptions,+ )+ monkeypatch.setattr(+ session_handler_module,+ "ClaudeSDKClient",+ _StubClaudeSDKClient,+ )++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")+ _run_session(handler, context)+ composite_key = f"slack_C123:{tmp_path}"+ retired: list[tuple[str, str]] = []+ controller.model_hub_runtime = SimpleNamespace(+ retire_process_scope=lambda backend, scope: retired.append(+ (backend, scope)+ )+ )++ asyncio.run(handler.cleanup_session(composite_key))++ assert retired == [("claude", composite_key)]++def test_cleanup_session_swallows_receiver_task_failure(monkeypatch, tmp_path: Path) -> None:events = []disconnected = asyncio.Event()diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex efb63c4e2..4866bed09 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -7,7 +7,7 @@ import typesimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import ANY, AsyncMock, Mock, patch+from unittest.mock import ANY, AsyncMock, Mock, call, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -313,6 +313,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):async def test_refresh_auth_state_stops_transports_and_invalidates_threads(self):agent = object.__new__(CodexAgent)stop_calls = []+ retire_scope = Mock()async def stop_a():stop_calls.append("a")@@ -337,7 +338,10 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):release_calls.append((backend, set(base_session_ids)))agent.controller = SimpleNamespace(- session_turns=SimpleNamespace(release_for_backend_refresh=release_for_backend_refresh)+ session_turns=SimpleNamespace(release_for_backend_refresh=release_for_backend_refresh),+ model_hub_runtime=SimpleNamespace(+ retire_process_scope=retire_scope,+ ),)await agent.refresh_auth_state()@@ -347,10 +351,18 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._transports, {})self.assertEqual(invalidated, ["session-1", "session-2"])self.assertEqual(cleared_sessions, ["session-1", "session-2"])+ self.assertEqual(+ retire_scope.call_args_list,+ [+ call("codex", "/tmp/a"),+ call("codex", "/tmp/b"),+ ],+ )async def test_prepare_resume_binding_restarts_unshared_transport(self):agent = object.__new__(CodexAgent)stop_calls = []+ retire_scope = Mock()async def stop_transport():stop_calls.append("stop")@@ -364,6 +376,11 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),)agent._turn_registry = SimpleNamespace(clear_session=lambda base_session_id: cleared_sessions.append(base_session_id))+ agent.controller = SimpleNamespace(+ model_hub_runtime=SimpleNamespace(+ retire_process_scope=retire_scope,+ )+ )await agent.prepare_resume_binding(base_session_id="session-1",@@ -376,6 +393,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._transport_last_activity, {})self.assertEqual(invalidated, ["session-1"])self.assertEqual(cleared_sessions, ["session-1"])+ retire_scope.assert_called_once_with("codex", "/tmp/work")async def test_prepare_resume_binding_skips_shared_transport(self):agent = object.__new__(CodexAgent)@@ -408,6 +426,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):stop_calls = []invalidated_sessions = []cleared_turns = []+ retire_scope = Mock()async def stop_transport():stop_calls.append("stop")@@ -425,6 +444,11 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):)agent._session_locks = {"session-1": asyncio.Lock()}agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())+ agent.controller = SimpleNamespace(+ model_hub_runtime=SimpleNamespace(+ retire_process_scope=retire_scope,+ )+ )with patch.object(_MODULE.time, "monotonic", return_value=1000.0):evicted = await agent.evict_idle_transports(600)@@ -437,6 +461,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._transports, {})self.assertIn("/tmp/work", agent._transport_locks)self.assertEqual(agent._transport_last_activity, {})+ retire_scope.assert_called_once_with("codex", "/tmp/work")async def test_evict_idle_transports_keeps_active_codex_runtime(self):agent = object.__new__(CodexAgent)diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex b896a07ac..30ba3b561 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -775,6 +775,26 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):)_assert_valid("agent-supply.schema.json", response.get_json()["agent"])+ response = client.get(+ "/api/models/agents/claude/chain?model=claude-native",+ base_url=base_url,+ )+ chain = response.get_json()["chain"]+ _assert_valid("agent-chain.schema.json", chain)+ assert chain["chain"][0]["source_id"] == source_id++ response = client.post(+ "/api/models/agents/claude/probe",+ json={"model": "claude-native"},+ headers=headers,+ base_url=base_url,+ )+ probe_body = response.get_json()+ assert "probe" in probe_body, probe_body+ probe = probe_body["probe"]+ _assert_valid("probe-result.schema.json", probe)+ assert probe["source_id"] == source_id+response = client.put("/api/models/agents/opencode/menu",json={"menu": {"view": "featured", "checked": ["anthropic/custom-model"]}},@@ -790,6 +810,13 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):base_url=base_url,)assert response.get_json()["agent"]["current"] is None+ response = client.get(+ "/api/models/agents/codex/chain?model=gpt-5",+ base_url=base_url,+ )+ assert response.status_code == 409+ assert response.get_json()["error"] == "direct_mode"+ assert response.get_json()["detail"] == "models.hub.direct_mode"agents = client.get("/api/models/agents", base_url=base_url).get_json()["agents"]assert len(agents) == 3@@ -808,7 +835,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):event_example = _schema("resolution-event.schema.json")["examples"][0]service.events.append(ResolutionEvent(**event_example))events = client.get("/api/models/events?limit=1", base_url=base_url).get_json()["events"]- assert events == [event_example]+ assert events == [{**event_example, "severity": "info"}]_assert_valid("resolution-event.schema.json", events[0])response = client.post(diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex f6e7c3fc2..d1a3ea019 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -189,11 +189,11 @@ def test_every_frozen_schema_example_is_valid_and_json_round_trips():assert _canonical(json.loads(_canonical(example))) == _canonical(example)-def test_v3_mirror_registry_is_executable_and_complete():+def test_v4_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"] == 3+ assert registry["contract_version"] == 4assert [entry["id"] for entry in registry["entries"]] == ["M1","M2",@@ -202,13 +202,14 @@ def test_v3_mirror_registry_is_executable_and_complete():"M5","M6","M7",+ "M8","N1",]for entry in registry["entries"]:_validate_mirror_entry(entry, schemas)-def test_v3_mirror_registry_mutation_probes_detect_every_comparable_drift():+def test_v4_mirror_registry_mutation_probes_detect_every_comparable_drift():registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))schemas = _mirror_schemas(registry)@@ -233,7 +234,53 @@ def test_v3_mirror_registry_mutation_probes_detect_every_comparable_drift():_validate_mirror_entry(entry, mutated)-def test_v3_shape_amendments_reject_the_false_states_they_replace():+def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():+ event_schema = _schema("resolution-event.schema.json")+ event_validator = Draft7Validator(event_schema)+ permission_event = next(+ example+ for example in event_schema["examples"]+ if example["reason"] == "permission_denied"+ )+ event_validator.validate(permission_event)++ invalid_cooldown = {+ **permission_event,+ "kind": "cooldown",+ "to_source": None,+ }+ with pytest.raises(ValidationError):+ event_validator.validate(invalid_cooldown)++ provenance_schema = _schema("turn-provenance.schema.json")+ assert provenance_schema["properties"]["contract_version"]["const"] == 4+ permission_record = next(+ example+ for example in provenance_schema["examples"]+ if any(+ attempt["reason"] == "permission_denied"+ for attempt in example["failed_attempts"]+ )+ )+ Draft7Validator(provenance_schema).validate(permission_record)++ registry = json.loads(+ (CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8")+ )+ schemas = _mirror_schemas(registry)+ failed_reasons = _json_pointer(+ schemas["turn-provenance.schema.json"],+ "/properties/failed_attempts/items/properties/reason",+ )["enum"]+ failed_reasons.remove("permission_denied")+ with pytest.raises(AssertionError):+ _validate_mirror_entry(+ next(entry for entry in registry["entries"] if entry["id"] == "M3"),+ schemas,+ )+++def test_v4_shape_amendments_reject_the_false_states_they_replace():supply_schema = _schema("agent-supply.schema.json")supply_validator = Draft7Validator(supply_schema)base_supply = {@@ -289,13 +336,62 @@ def test_v3_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):Draft7Validator(_schema("probe-result.schema.json")).validate(probe)- canceled = _schema("turn-provenance.schema.json")["examples"][-1]+ canceled = next(+ example+ for example in _schema("turn-provenance.schema.json")["examples"]+ if example["outcome"] == "canceled"+ )Draft7Validator(_schema("turn-provenance.schema.json")).validate(canceled)invented_failure = copy.deepcopy(canceled)invented_failure["canceled_attempt"]["reason"] = "server_error"with pytest.raises(ValidationError):Draft7Validator(_schema("turn-provenance.schema.json")).validate(invented_failure)+ chain_schema = _schema("agent-chain.schema.json")+ chain_validator = Draft7Validator(chain_schema)+ native_unavailable = copy.deepcopy(chain_schema["examples"][-1])+ chain_validator.validate(native_unavailable)++ unavailable_needs_action = copy.deepcopy(native_unavailable)+ unavailable_needs_action["chain"][0]["health"] = "needs_action"+ unavailable_needs_action["chain"][0]["retry_at"] = None+ chain_validator.validate(unavailable_needs_action)++ unmarked_healthy_unavailable = copy.deepcopy(chain_schema["examples"][-2])+ unmarked_healthy_unavailable["chain"][0]["reason"] = None+ with pytest.raises(ValidationError):+ chain_validator.validate(unmarked_healthy_unavailable)++ mislabeled_waiting = copy.deepcopy(native_unavailable)+ mislabeled_waiting["supply_state"] = "waiting"+ with pytest.raises(ValidationError):+ chain_validator.validate(mislabeled_waiting)++ unavailable_hub = copy.deepcopy(native_unavailable)+ unavailable_hub["chain"][0]["channel"] = "hub"+ with pytest.raises(ValidationError):+ chain_validator.validate(unavailable_hub)++ probe_schema = _schema("probe-result.schema.json")+ probe_validator = Draft7Validator(probe_schema)+ native_ready = copy.deepcopy(probe_schema["examples"][-2])+ probe_validator.validate(native_ready)+ native_ready["latency_ms"] = 12+ with pytest.raises(ValidationError):+ probe_validator.validate(native_ready)++ native_not_ready = copy.deepcopy(probe_schema["examples"][-1])+ probe_validator.validate(native_not_ready)+ native_not_ready_without_reason = copy.deepcopy(native_not_ready)+ native_not_ready_without_reason["error"] = None+ with pytest.raises(ValidationError):+ probe_validator.validate(native_not_ready_without_reason)++ timed_native_not_ready = copy.deepcopy(native_not_ready)+ timed_native_not_ready["latency_ms"] = 12+ with pytest.raises(ValidationError):+ probe_validator.validate(timed_native_not_ready)+def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 3a1199a6a..e5707a659 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -40,6 +40,7 @@ from modules.agents.model_hub import (opencode_model_for_overlay,overlay_identifier_bytes,persisted_launch_identity,+ resolve_model_hub_launch,resolve_opencode_overlay_launch,)from modules.agents.codex.agent import CodexAgent@@ -229,11 +230,108 @@ def test_mh_chan_001_native_quota_falls_back_then_recovers_next_turn(tmp_path: Precovered = asyncio.run(router.resolve("codex", "gpt-5"))assert (recovered.channel, recovered.source_id) == ("native_cli", native.id)kinds = [event["kind"] for event in reversed(service.events.list(limit=20))]- assert kinds == ["cooldown", "switch", "channel_switch", "recover", "channel_switch"]- assert [event["reason"] for event in service.events.list(limit=20) if event["kind"] == "channel_switch"] == [- "recovery",- "quota_exhausted",- ]+ assert kinds == ["cooldown", "switch", "recover"]+++def test_native_failure_is_forwarded_to_turn_correlation(+ tmp_path: Path,+) -> None:+ native = _source(+ "src_native01",+ kind="subscription",+ vendor="openai",+ protocol="openai_responses",+ channel="native_cli",+ model_ids=("gpt-5",),+ )+ service = _service(+ tmp_path,+ _hub_config(sources=[native], agents=_agents()),+ LaunchAdapter({}),+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),+ )+ correlation = Mock()+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(correlation=correlation),+ native_cli_ready=lambda _backend: True,+ )+ context = SimpleNamespace(+ platform_specific={"turn_token": "turn_native_failure"}+ )+ bind_launch(+ context,+ ModelHubLaunch(+ backend="codex",+ channel="native_cli",+ requested_model="gpt-5",+ target_model="gpt-5",+ runtime_model="gpt-5",+ source_id=native.id,+ ),+ )++ assert (+ asyncio.run(+ router.record_native_failure(+ context,+ "usage quota exceeded",+ )+ )+ is True+ )+ correlation.fail_native_attempt.assert_called_once_with(+ "turn_native_failure",+ reason="quota_exhausted",+ )++ correlation.fail_native_attempt.reset_mock()+ unclassified_context = SimpleNamespace(+ platform_specific={"turn_token": "turn_native_unclassified"}+ )+ native_launch = launch_for_context(context)+ assert native_launch is not None+ bind_launch(unclassified_context, native_launch)+ assert (+ asyncio.run(+ router.record_native_failure(+ unclassified_context,+ "provider rejected the local request",+ )+ )+ is False+ )+ correlation.fail_native_attempt.assert_called_once_with(+ "turn_native_unclassified",+ reason="unclassified_error",+ )++ hub_context = SimpleNamespace(+ platform_specific={"turn_token": "turn_hub_terminal"}+ )+ bind_launch(+ hub_context,+ ModelHubLaunch(+ backend="codex",+ channel="hub",+ requested_model="gpt-5",+ target_model="gpt-5",+ runtime_model="gpt-5",+ source_id="src_hub0001",+ ),+ )+ assert (+ asyncio.run(+ router.record_native_failure(+ hub_context,+ "backend rejected the completion",+ )+ )+ is False+ )+ correlation.fail_hub_attempt.assert_called_once_with(+ "turn_hub_terminal"+ )def test_mh_chan_001_hub_failure_cools_source_and_selects_backup(tmp_path: Path) -> None:@@ -317,8 +415,8 @@ def test_mh_chan_001_hub_to_native_switch_keeps_failure_reason(tmp_path: Path) -assert asyncio.run(router.record_native_failure(context, "usage quota exceeded")) is Trueassert asyncio.run(router.resolve("codex", "gpt-5")).channel == "native_cli"- channel_switch = next(event for event in service.events.list(limit=10) if event["kind"] == "channel_switch")- assert channel_switch["reason"] == "quota_exhausted"+ switch = next(event for event in service.events.list(limit=10) if event["kind"] == "switch")+ assert switch["reason"] == "quota_exhausted"def test_mh_chan_001_native_launch_replays_pending_revocations(tmp_path: Path) -> None:@@ -396,7 +494,153 @@ def test_mh_chan_001_unconfigured_hub_is_interrupted(tmp_path: Path) -> None:asyncio.run(_router(service).resolve("codex", "gpt-5"))assert exc_info.value.code == "mapping_target_unavailable"- assert service.events.list(limit=10) == []+ event = service.events.list(limit=10)[0]+ assert (event["kind"], event["reason"]) == (+ "supply_interrupted",+ "no_enabled_source",+ )+++def test_hub_with_only_ineligible_sources_names_structural_cause(+ tmp_path: Path,+) -> None:+ native_claude = _source(+ "src_claudenative",+ kind="subscription",+ vendor="anthropic",+ protocol="anthropic",+ channel="native_cli",+ model_ids=("gpt-5",),+ )+ service = _service(+ tmp_path,+ _hub_config(+ sources=[native_claude],+ order=[native_claude.id],+ agents=_agents(),+ ),+ LaunchAdapter({}),+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),+ )++ with pytest.raises(ModelHubError, match="mapping_target_unavailable"):+ asyncio.run(_router(service).resolve("codex", "gpt-5"))++ event = service.events.list(limit=10)[0]+ assert (event["kind"], event["reason"]) == (+ "supply_interrupted",+ "no_eligible_source",+ )++[email protected]("backend", ["claude", "codex", "opencode"])+def test_prelaunch_supply_failure_copy_is_shared_across_backends(+ tmp_path: Path,+ backend: str,+) -> None:+ service = _service(+ tmp_path,+ _hub_config(sources=[], order=[], agents=_agents()),+ LaunchAdapter({}),+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),+ )+ controller = SimpleNamespace(+ model_hub_runtime=_router(service),+ config=SimpleNamespace(language="zh"),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ resolve_model_hub_launch(+ controller,+ backend,+ "missing-model",+ )+ )++ assert str(exc_info.value) == (+ "模型 missing-model 没有已启用的来源。请前往 Models 配置。"+ )+ assert exc_info.value.data["copy_key"] == "no_enabled_source"+++def test_prelaunch_blocker_details_are_localized(+ tmp_path: Path,+) -> None:+ blocked = _source(+ "src_blocked01",+ kind="api_key",+ vendor="openai",+ protocol="openai_responses",+ channel="hub",+ model_ids=("gpt-5",),+ )+ blocked.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ )+ service = _service(+ tmp_path,+ _hub_config(sources=[blocked], agents=_agents()),+ LaunchAdapter({blocked.id: "route-blocked"}),+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),+ )+ controller = SimpleNamespace(+ model_hub_runtime=_router(service),+ config=SimpleNamespace(language="zh"),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ resolve_model_hub_launch(+ controller,+ "codex",+ "gpt-5",+ )+ )++ assert "凭证已过期" in str(exc_info.value)+ assert "models.source.needs_action.oauth_expired" not in str(+ exc_info.value+ )+++def test_native_unavailability_blocker_is_localized(+ tmp_path: Path,+) -> None:+ native = _source(+ "src_native01",+ kind="subscription",+ vendor="openai",+ protocol="openai_responses",+ channel="native_cli",+ model_ids=("gpt-5",),+ )+ service = _service(+ tmp_path,+ _hub_config(sources=[native], agents=_agents()),+ LaunchAdapter({}),+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),+ )+ controller = SimpleNamespace(+ model_hub_runtime=_router(+ service,+ native_cli_ready=lambda _backend: False,+ ),+ config=SimpleNamespace(language="zh"),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ resolve_model_hub_launch(+ controller,+ "codex",+ "gpt-5",+ )+ )++ assert "当前进程无法使用 CLI 登录" in str(exc_info.value)+ assert "src_native01:standby" not in str(exc_info.value)def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None:@@ -419,7 +663,11 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> Noneagents["codex"].mode = "hub"with pytest.raises(ModelHubError, match="mapping_target_unavailable"):asyncio.run(router.resolve("codex", "gpt-5"))- assert service.events.list(limit=10) == []+ event = service.events.list(limit=10)[0]+ assert (event["kind"], event["reason"]) == (+ "supply_interrupted",+ "no_enabled_source",+ )hub = _source("src_hub_after_direct",@@ -433,7 +681,8 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> Noneconfig.agents["codex"].sources.order.append(hub.id)adapter.prefixes[hub.id] = "route-hub"assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "hub"- assert service.events.list(limit=10)[0]["reason"] == "manual"+ assert len(service.events.list(limit=10)) == 1+ assert service.events.list(limit=10)[0]["reason"] == "no_enabled_source"def test_recovered_turn_uses_post_wait_mode_for_events(tmp_path: Path) -> None:@@ -492,11 +741,7 @@ def test_direct_to_healthy_hub_switch_is_manual(tmp_path: Path) -> None:assert (launch.channel, launch.source_id) == ("hub", hub.id)event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"], event["to_source"]) == (- "channel_switch",- "manual",- hub.id,- )+ assert (event["kind"], event["reason"]) == ("mapping_applied", "mapping")def test_mh_chan_001_other_backend_source_does_not_activate_hub(tmp_path: Path) -> None:@@ -554,7 +799,11 @@ def test_agent_projection_matches_interrupted_unmapped_fixed_backend(tmp_path: Passert projected["current"] is Noneassert projected["supply_status"] == "interrupted"assert adapter.starts == 0- assert service.events.list(limit=10) == []+ event = service.events.list(limit=10)[0]+ assert (event["kind"], event["reason"]) == (+ "supply_interrupted",+ "model_unsupported",+ )def test_agent_projection_uses_global_default_vibe_agent_model(tmp_path: Path) -> None:@@ -880,12 +1129,32 @@ def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(tmp_path: Path,config_path = codex_home / "config.toml"auth_path.write_text(json.dumps({"tokens": {"access_token": "fixture-token"}}))config_path.write_text("")+ codex_executable = tmp_path / "codex"+ codex_executable.write_text("#!/bin/sh\nexit 0\n")+ codex_executable.chmod(0o755)+ codex_runtime = SimpleNamespace(+ enabled=True,+ cli_path=str(codex_executable),+ )+ monkeypatch.setattr(+ "modules.agents.model_hub.load_config_or_default",+ lambda: SimpleNamespace(+ agents=SimpleNamespace(codex=codex_runtime),+ ),+ )monkeypatch.setenv("CODEX_HOME", str(codex_home))for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):monkeypatch.delenv(key, raising=False)assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is True+ codex_runtime.enabled = False+ assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False+ codex_runtime.enabled = True+ codex_runtime.cli_path = str(tmp_path / "missing-codex")+ assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False+ codex_runtime.cli_path = str(codex_executable)+config_path.write_text('model_provider = "relay"\n\n[model_providers.relay]\nbase_url = "https://relay.invalid/v1"\n')@@ -913,6 +1182,39 @@ def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(tmp_path: Path,)+def test_mh_chan_001_claude_native_runtime_requires_enabled_executable(+ tmp_path: Path,+ monkeypatch,+) -> None:+ claude_executable = tmp_path / "claude"+ claude_executable.write_text("#!/bin/sh\nexit 0\n")+ claude_executable.chmod(0o755)+ claude_runtime = SimpleNamespace(+ enabled=True,+ cli_path=str(claude_executable),+ )+ monkeypatch.setattr(+ "modules.agents.model_hub.load_config_or_default",+ lambda: SimpleNamespace(+ agents=SimpleNamespace(claude=claude_runtime),+ ),+ )+ monkeypatch.setattr(+ "vibe.claude_config.read_claude_settings_env",+ lambda: {},+ )+ for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"):+ monkeypatch.delenv(key, raising=False)++ assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is True++ claude_runtime.enabled = False+ assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is False+ claude_runtime.enabled = True+ claude_runtime.cli_path = str(tmp_path / "missing-claude")+ assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is False++def test_mh_chan_001_verified_codex_keyring_source_remains_routable(tmp_path: Path,monkeypatch,@@ -922,6 +1224,20 @@ def test_mh_chan_001_verified_codex_keyring_source_remains_routable(codex_home.mkdir()(codex_home / "auth.json").write_text("{}")(codex_home / "config.toml").write_text('cli_auth_credentials_store = "keyring"\n')+ codex_executable = tmp_path / "codex"+ codex_executable.write_text("#!/bin/sh\nexit 0\n")+ codex_executable.chmod(0o755)+ monkeypatch.setattr(+ "modules.agents.model_hub.load_config_or_default",+ lambda: SimpleNamespace(+ agents=SimpleNamespace(+ codex=SimpleNamespace(+ enabled=True,+ cli_path=str(codex_executable),+ )+ ),+ ),+ )monkeypatch.setenv("CODEX_HOME", str(codex_home))for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):monkeypatch.delenv(key, raising=False)@@ -1565,6 +1881,66 @@ def test_mh_inj_codex_runtime_change_waits_for_shared_active_turn(tmp_path: Pathasyncio.run(exercise())+def test_mh_inj_codex_hub_to_direct_retires_gateway_scope(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ agent = object.__new__(CodexAgent)+ old_transport = SimpleNamespace(+ is_initialized=True,+ runtime_fingerprint="hub:http://127.0.0.1:18443:token-hash",+ stop=AsyncMock(),+ )+ new_transport = SimpleNamespace(+ start=AsyncMock(),+ on_notification=Mock(),+ on_server_request=Mock(),+ pid=12345,+ )+ retire_scope = Mock()+ agent._transport_locks = {}+ agent._transports = {str(tmp_path): old_transport}+ agent._transport_last_activity = {}+ agent._transport_cwd_inodes = {}+ agent._session_mgr = SimpleNamespace(+ sessions_for_cwd=Mock(return_value=set()),+ invalidate_thread=Mock(),+ )+ agent._turn_registry = SimpleNamespace(clear_session=Mock())+ agent._clear_thread_developer_instructions = Mock()+ agent._on_notification = Mock()+ agent._on_server_request = AsyncMock()+ agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])+ agent.controller = SimpleNamespace(+ resource_governor=None,+ model_hub_runtime=SimpleNamespace(+ retire_process_scope=retire_scope,+ ),+ )+ launch = ModelHubLaunch(+ "codex",+ "direct",+ "gpt-5",+ "gpt-5",+ "gpt-5",+ )++ with (+ patch("modules.agents.codex.agent.CodexTransport", return_value=new_transport),+ patch(+ "modules.agents.codex.agent.governor_from_controller",+ return_value=SimpleNamespace(apply_to_pid=Mock()),+ ),+ ):+ assert await agent._get_or_create_transport(str(tmp_path), launch) is new_transport++ old_transport.stop.assert_awaited_once()+ new_transport.start.assert_awaited_once()+ retire_scope.assert_called_once_with("codex", str(tmp_path))++ asyncio.run(exercise())++def test_mh_inj_codex_runtime_change_interrupts_current_session_first() -> None:async def exercise() -> None:agent = object.__new__(CodexAgent)@@ -1725,7 +2101,10 @@ def test_mh_inj_claude_channel_change_waits_for_active_turn() -> None:handler.cleanup_session.assert_not_awaited()handler.active_sessions.clear()assert await task is None- handler.cleanup_session.assert_awaited_once_with(key)+ handler.cleanup_session.assert_awaited_once_with(+ key,+ retire_model_hub_scope=False,+ )asyncio.run(exercise())diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pynew file mode 100644index 000000000..459d177fe--- /dev/null+++ b/tests/test_model_hub_l3.py@@ -0,0 +1,1737 @@+from __future__ import annotations++import asyncio+import json+from collections import deque+from datetime import datetime, timedelta, timezone+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock, patch++import aiohttp+import pytest+from jsonschema import Draft7Validator, FormatChecker+from sqlalchemy import create_engine, delete, select++from config.v2_config import (+ ModelHubAgentSourcesConfig,+ ModelHubAgentSupplyConfig,+ ModelHubConfig,+ ModelHubModelConfig,+ ModelHubSourceConfig,+ ModelHubSourceStateConfig,+)+from core.handlers.model_hub.adapter import (+ EngineHealth,+ EngineStatus,+ RawCallOutcome,+ RawOutcomeKind,+)+from core.handlers.model_hub.classification import classify_outcome+from core.handlers.model_hub.events import (+ BoundedEventLog,+ build_resolution_event,+)+from core.handlers.model_hub.provenance import (+ BoundedProvenanceStore,+ TurnCorrelationRegistry,+)+from core.handlers.model_hub.request import ModelHubRequest+from core.handlers.model_hub.revocations import CredentialRevocationJournal+from core.handlers.model_hub.service import ModelHubError, ModelHubService+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.run_settlement import (+ SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_STOPPED,+ SETTLED_BY_TERMINAL_RESULT,+)+from core.services.dispatch import TurnDispatchOutcome+from core.session_turns import SessionTurnManager+from modules.agents.model_hub import (+ ModelHubLaunch,+ ModelHubRuntimeRouter,+ bind_launch,+ bind_turn_mode,+)+from storage.models import agent_sessions, messages, metadata+++CONTRACTS = Path(__file__).parents[1] / "docs" / "plans" / "model-hub-contracts"+NOW = datetime(2026, 7, 29, 12, 0, tzinfo=timezone.utc)+++def _assert_valid(schema_name: str, payload: dict) -> None:+ schema = json.loads((CONTRACTS / schema_name).read_text(encoding="utf-8"))+ errors = sorted(+ Draft7Validator(+ schema,+ format_checker=FormatChecker(),+ ).iter_errors(payload),+ key=lambda error: list(error.path),+ )+ assert not errors, [error.message for error in errors]+++class MemoryStore:+ def __init__(self, config: ModelHubConfig):+ self.config = config+ self.requested_models = {+ "claude": "shared-model",+ "codex": "shared-model",+ "opencode": "openai/shared-model",+ }++ def load(self) -> ModelHubConfig:+ return self.config++ def save(self, config: ModelHubConfig) -> None:+ self.config = config++ def requested_model(self, backend: str) -> str:+ return self.requested_models.get(backend, "")+++class InvokeHandle:+ def __init__(self, outcome: RawCallOutcome):+ self._outcome = outcome++ @property+ def stream(self):+ return None++ async def outcome(self) -> RawCallOutcome:+ return self._outcome+++class ProbeAdapter:+ def __init__(self, outcomes: list[RawCallOutcome]):+ self.outcomes = deque(outcomes)+ self.invocations: list[tuple[str, str, str]] = []+ self.requests: list[ModelHubRequest] = []++ async def sync_sources(self, _bindings) -> None:+ return None++ async def revoke_credential(self, _credential_ref: str) -> None:+ return None++ async def invoke(self, source_id, model_id, request, _stream, origin):+ self.invocations.append((source_id, model_id, origin))+ self.requests.append(request)+ return InvokeHandle(self.outcomes.popleft())++ async def status(self) -> EngineStatus:+ return EngineStatus(+ health=EngineHealth.OK,+ installed_version="test",+ verified=True,+ listen_host="127.0.0.1",+ listen_port=15220,+ last_check_iso=NOW.isoformat(),+ )+++def _source(+ source_id: str,+ label: str,+ *,+ channel: str = "hub",+ status: str = "standby",+ retry_at: str | None = None,+) -> ModelHubSourceConfig:+ return ModelHubSourceConfig(+ id=source_id,+ kind="subscription" if channel == "native_cli" else "api_key",+ vendor="openai",+ display_name=label,+ protocol="openai_responses",+ supply_channel=channel,+ billing="monthly" if channel == "native_cli" else "metered",+ state=ModelHubSourceStateConfig(+ status=status,+ retry_at=retry_at,+ detail_key=(+ "models.source.cooldown.rate_limited"+ if status == "cooldown"+ else None+ ),+ ),+ models=[+ ModelHubModelConfig(+ id="shared-model",+ provenance="discovered",+ )+ ],+ credential_ref=None if channel == "native_cli" else f"cred_{source_id}",+ )+++def _config(sources: list[ModelHubSourceConfig]) -> ModelHubConfig:+ agents = {+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")+ for backend in ("claude", "codex", "opencode")+ }+ for agent in agents.values():+ agent.sources = ModelHubAgentSourcesConfig(+ policy="custom",+ order=[source.id for source in sources],+ )+ agents["opencode"].menu.checked = ["openai/shared-model"]+ return ModelHubConfig(sources=sources, agents=agents)+++def _outcome(+ kind: RawOutcomeKind,+ *,+ status: int | None = None,+ code: str | None = None,+ message: str | None = None,+ source_id: str = "src_primary01",+) -> RawCallOutcome:+ return RawCallOutcome(+ kind=kind,+ http_status=status,+ error_code=code,+ redacted_message=message,+ stream_started=False,+ model_id="shared-model",+ source_id=source_id,+ )+++def _service(+ tmp_path: Path,+ *,+ sources: list[ModelHubSourceConfig],+ outcomes: list[RawCallOutcome] | None = None,+) -> ModelHubService:+ return ModelHubService(+ store=MemoryStore(_config(sources)),+ adapter=ProbeAdapter(outcomes or []),+ events=BoundedEventLog(tmp_path / "events.json"),+ provenance=BoundedProvenanceStore(tmp_path / "provenance.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ now=lambda: NOW,+ )+++def _begin_hub_attempt(+ registry: TurnCorrelationRegistry,+ *,+ turn_id: str,+ scope: str = "/repo",+) -> str | None:+ token = registry.credentials("codex", scope, turn_id)+ exact_turn = registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="shared-model",+ )+ registry.begin_attempt(+ exact_turn,+ source_id="src_primary01",+ resolved_model_id="shared-model",+ channel="hub",+ via_mapping=False,+ )+ return exact_turn+++def test_process_credentials_record_only_exact_turns(tmp_path: Path) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)++ token = registry.credentials("codex", "/repo", "turn_exact")+ assert token == registry.credentials("codex", "/repo", "turn_exact")+ assert token != registry.credentials("codex", "/other", "turn_other")+ assert registry.authenticates("codex", token) is True+ assert registry.authenticates("claude", token) is False+ assert registry.credentials("claude", "session-a", "turn_a") != registry.credentials(+ "claude",+ "session-b",+ "turn_b",+ )++ exact_turn = registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="shared-model",+ )+ registry.begin_attempt(+ exact_turn,+ source_id="src_primary01",+ resolved_model_id="shared-model",+ channel="hub",+ via_mapping=False,+ )+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )+ registry.settle(+ "turn_exact",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_exact")+ assert record is not None+ assert record["outcome"] == "served"+ _assert_valid("turn-provenance.schema.json", record)+++def test_retired_process_scope_revokes_token_and_fails_closed(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "retired-scope.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials("codex", "/repo", "turn_evicted")+ turn_id = registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="shared-model",+ )+ registry.begin_attempt(+ turn_id,+ source_id="src_primary01",+ resolved_model_id="shared-model",+ channel="hub",+ via_mapping=False,+ )++ registry.retire_scope("codex", "/repo")++ assert registry.authenticates("codex", token) is False+ replacement = registry.credentials("codex", "/repo", "turn_replacement")+ assert replacement != token+ assert registry.authenticates("codex", replacement) is True+ registry.settle(+ "turn_evicted",+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ assert store.get("turn_evicted") is None++ registry.settle(+ "turn_replacement",+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ registry.retire_scope("codex", "/repo")+ assert registry._scopes == {}+ assert registry._token_scopes == {}+++def test_terminal_failure_survives_exact_scope_retirement(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "terminal-retirement.json")+ registry = TurnCorrelationRegistry(store)+ registry.begin_native_attempt(+ backend="claude",+ process_scope="session:/repo",+ turn_id="turn_startup_failure",+ requested_model_id="claude-opus",+ source_id="src_native01",+ resolved_model_id="claude-opus",+ via_mapping=False,+ )+ registry.fail_native_attempt(+ "turn_startup_failure",+ reason="unclassified_error",+ )++ registry.retire_scope(+ "claude",+ "session:/repo",+ terminal_turn_id="turn_startup_failure",+ )+ registry.settle(+ "turn_startup_failure",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_startup_failure")+ assert record is not None+ assert record["outcome"] == "exhausted"+ assert record["failed_attempts"][0]["reason"] == "unclassified_error"+ _assert_valid("turn-provenance.schema.json", record)+++def test_terminal_retirement_does_not_restore_ambiguous_scope(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "ambiguous-retirement.json")+ registry = TurnCorrelationRegistry(store)+ registry.begin_native_attempt(+ backend="claude",+ process_scope="session:/repo",+ turn_id="turn_first",+ requested_model_id="claude-opus",+ source_id="src_native01",+ resolved_model_id="claude-opus",+ via_mapping=False,+ )+ registry.begin_native_attempt(+ backend="claude",+ process_scope="session:/repo",+ turn_id="turn_second",+ requested_model_id="claude-opus",+ source_id="src_native01",+ resolved_model_id="claude-opus",+ via_mapping=False,+ )+ registry.fail_native_attempt("turn_first", reason="unclassified_error")++ registry.retire_scope(+ "claude",+ "session:/repo",+ terminal_turn_id="turn_first",+ )+ registry.settle(+ "turn_first",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ assert store.get("turn_first") is None+++ ("path", "body", "status", "reason"),+ [+ ("responses", "{", 400, "invalid_parameter"),+ ("responses", "[]", 400, "invalid_parameter"),+ ("responses", '{"stream":false}', 400, "invalid_parameter"),+ ("unsupported", '{"model":"shared-model"}', 404, "protocol_error"),+ ],+)+def test_authenticated_gateway_validation_failure_is_correlated(+ tmp_path: Path,+ path: str,+ body: str,+ status: int,+ reason: str,+) -> None:+ async def exercise() -> None:+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ gateway = ModelHubTurnGateway(service)+ base_url, token = await gateway.endpoint(+ "codex",+ process_scope="/repo",+ turn_id="turn_invalid_gateway_request",+ requested_model_id="shared-model",+ resolved_model_id="shared-model",+ source_id="src_primary01",+ )+ try:+ async with aiohttp.ClientSession(trust_env=False) as client:+ response = await client.post(+ f"{base_url}/v1/{path}",+ data=body,+ headers={+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ },+ )+ assert response.status == status+ await response.read()+ finally:+ await gateway.close()++ gateway.correlation.settle(+ "turn_invalid_gateway_request",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ record = service.provenance.get("turn_invalid_gateway_request")+ assert record is not None+ assert record["outcome"] == "failed_terminal"+ assert record["terminal_error"] == {+ "source_id": "src_primary01",+ "resolved_model_id": "shared-model",+ "channel": "hub",+ "via_mapping": False,+ "reason": reason,+ "stream_started": False,+ }+ _assert_valid("turn-provenance.schema.json", record)++ asyncio.run(exercise())+++def test_gateway_terminalizer_records_pre_observer_engine_down_before_return(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )++ async def fail_sync(_bindings) -> None:+ raise RuntimeError("engine unavailable")++ service.adapter.sync_sources = fail_sync+ gateway = ModelHubTurnGateway(service)+ base_url, token = await gateway.endpoint(+ "codex",+ process_scope="/repo",+ turn_id="turn_pre_observer_engine_down",+ requested_model_id="shared-model",+ resolved_model_id="shared-model",+ source_id="src_primary01",+ )+ try:+ async with aiohttp.ClientSession(trust_env=False) as client:+ response = await client.post(+ f"{base_url}/v1/responses",+ json={+ "model": "shared-model",+ "input": "ping",+ "stream": False,+ },+ headers={"Authorization": f"Bearer {token}"},+ )+ assert response.status == 503+ await response.read()++ trace = gateway.correlation._traces[+ "turn_pre_observer_engine_down"+ ]+ assert trace.pending_attempt is None+ assert trace.terminal_error == {+ "source_id": "src_primary01",+ "resolved_model_id": "shared-model",+ "channel": "hub",+ "via_mapping": False,+ "reason": "protocol_error",+ "stream_started": False,+ }+ finally:+ await gateway.close()++ gateway.correlation.settle(+ "turn_pre_observer_engine_down",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ record = service.provenance.get("turn_pre_observer_engine_down")+ assert record is not None+ assert record["outcome"] == "failed_terminal"+ _assert_valid("turn-provenance.schema.json", record)++ asyncio.run(exercise())+++def test_gateway_provenance_retains_pre_mapping_model_identity(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials("codex", "/repo", "turn_mapped")+ registry.prepare_gateway_turn(+ backend="codex",+ token=token,+ requested_model_id="gpt-5",+ resolved_model_id="custom-gpt-5",+ source_id="src_primary01",+ via_mapping=True,+ )++ exact_turn = registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="custom-gpt-5",+ )+ registry.begin_attempt(+ exact_turn,+ source_id="src_primary01",+ resolved_model_id="custom-gpt-5",+ channel="hub",+ via_mapping=False,+ )+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )+ registry.settle(+ "turn_mapped",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_mapped")+ assert record is not None+ assert record["requested_model_id"] == "gpt-5"+ assert record["served"] == {+ "source_id": "src_primary01",+ "resolved_model_id": "custom-gpt-5",+ "channel": "hub",+ "via_mapping": True,+ }+ _assert_valid("turn-provenance.schema.json", record)+++def test_gateway_model_outside_prepared_turn_fails_closed(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials("codex", "/repo", "turn_expected")+ registry.prepare_gateway_turn(+ backend="codex",+ token=token,+ requested_model_id="gpt-5",+ resolved_model_id="custom-gpt-5",+ source_id="src_primary01",+ via_mapping=True,+ )++ assert (+ registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="untracked-model",+ )+ is None+ )+ registry.settle(+ "turn_expected",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ assert store.get("turn_expected") is None+++def test_native_terminal_failure_is_not_recorded_as_served(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "native-failure.json")+ registry = TurnCorrelationRegistry(store)+ registry.begin_native_attempt(+ backend="codex",+ process_scope="/repo",+ turn_id="turn_native_failure",+ requested_model_id="shared-model",+ source_id="src_primary01",+ resolved_model_id="shared-model",+ via_mapping=False,+ )++ registry.fail_native_attempt(+ "turn_native_failure",+ reason="quota_exhausted",+ )+ registry.settle(+ "turn_native_failure",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_native_failure")+ assert record is not None+ assert record["outcome"] == "exhausted"+ assert record["served"] is None+ assert record["failed_attempts"] == [+ {+ "source_id": "src_primary01",+ "resolved_model_id": "shared-model",+ "channel": "native_cli",+ "via_mapping": False,+ "reason": "quota_exhausted",+ }+ ]+ _assert_valid("turn-provenance.schema.json", record)+++def test_fsm_drop_overrides_a_completed_gateway_attempt(tmp_path: Path) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)+ exact_turn = _begin_hub_attempt(registry, turn_id="turn_drop")+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )++ registry.settle(+ "turn_drop",+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_drop")+ assert record is not None+ assert record["outcome"] == "failed_terminal"+ assert record["terminal_error"]["reason"] == "stream_interrupted"+ assert record["served"] is None+ _assert_valid("turn-provenance.schema.json", record)+++def test_backend_terminal_failure_overrides_gateway_success(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "backend-terminal.json")+ registry = TurnCorrelationRegistry(store)+ exact_turn = _begin_hub_attempt(+ registry,+ turn_id="turn_backend_terminal",+ )+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )++ registry.fail_hub_attempt("turn_backend_terminal")+ registry.settle(+ "turn_backend_terminal",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_backend_terminal")+ assert record is not None+ assert record["outcome"] == "failed_terminal"+ assert record["served"] is None+ assert record["terminal_error"]["reason"] == "protocol_error"+ _assert_valid("turn-provenance.schema.json", record)+++def test_lost_terminal_retains_completed_fallback_attempts(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "lost-terminal.json")+ registry = TurnCorrelationRegistry(store)+ exact_turn = _begin_hub_attempt(+ registry,+ turn_id="turn_lost_terminal",+ )+ failure = _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=429,+ )+ registry.finish_attempt(+ exact_turn,+ outcome=failure,+ decision=classify_outcome(failure),+ )++ registry.settle(+ "turn_lost_terminal",+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )++ record = store.get("turn_lost_terminal")+ assert record is not None+ assert record["outcome"] == "exhausted"+ assert record["failed_attempts"][0]["reason"] == "rate_limited"+ _assert_valid("turn-provenance.schema.json", record)+++def test_ambiguous_mixed_and_opencode_attempts_leave_no_record(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)++ first = _begin_hub_attempt(registry, turn_id="turn_first")+ assert first == "turn_first"+ registry.credentials("codex", "/repo", "turn_second")+ assert (+ registry.begin_gateway_request(+ backend="codex",+ token=registry.credentials("codex", "/repo", "turn_second"),+ requested_model_id="shared-model",+ )+ is None+ )+ registry.settle("turn_first", settled_by=SETTLED_BY_STOPPED)+ registry.settle("turn_second", settled_by=SETTLED_BY_TERMINAL_RESULT)+ assert store.get("turn_first") is None+ assert store.get("turn_second") is None++ mixed = _begin_hub_attempt(+ registry,+ turn_id="turn_mixed",+ scope="/mixed",+ )+ registry.credentials("codex", "/mixed", None)+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ mixed,+ outcome=success,+ decision=classify_outcome(success),+ )+ registry.settle("turn_mixed", settled_by=SETTLED_BY_TERMINAL_RESULT)+ assert store.get("turn_mixed") is None++ opencode_token = registry.credentials(+ "opencode",+ "opencode:shared-server",+ "turn_opencode",+ )+ assert (+ registry.begin_gateway_request(+ backend="opencode",+ token=opencode_token,+ requested_model_id="openai/shared-model",+ )+ is None+ )+ registry.settle("turn_opencode", settled_by=SETTLED_BY_TERMINAL_RESULT)+ assert store.get("turn_opencode") is None+++def test_fsm_cancel_drop_and_control_classification(tmp_path: Path) -> None:+ async def exercise(+ *,+ turn_id: str,+ mode: str,+ ) -> dict | None:+ store = BoundedProvenanceStore(tmp_path / f"{turn_id}.json")+ registry = TurnCorrelationRegistry(store)+ runtime = SimpleNamespace(+ settle_turn=lambda value, *, settled_by, ts, mode=None: registry.settle(+ value,+ settled_by=settled_by,+ ts=ts,+ )+ )+ controller = SimpleNamespace(+ model_hub_runtime=runtime,+ command_handler=SimpleNamespace(+ handle_stop=AsyncMock(return_value=True)+ ),+ set_agent_status=lambda _session_id, _status: None,+ )+ manager = SessionTurnManager(controller)+ manager.flush_queue = AsyncMock(return_value=False)+ started = asyncio.Event()+ hold = asyncio.Event()++ async def dispatch(_controller, _context, _text, **_kwargs):+ current_turn = manager.model_hub_turn_id_for_task()+ assert current_turn == turn_id+ exact_turn = _begin_hub_attempt(+ registry,+ turn_id=current_turn,+ )+ started.set()+ if mode == "cancel":+ await hold.wait()+ if mode == "served":+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )+ settlement = SETTLED_BY_TERMINAL_RESULT+ else:+ settlement = SETTLED_BY_NO_TERMINAL_RESULT+ return TurnDispatchOutcome(error=None, settled_by=settlement)++ context = SimpleNamespace(+ platform="avibe",+ platform_specific={+ "turn_token": turn_id,+ "agent_session_target": {"agent_backend": "codex"},+ },+ )+ with patch(+ "core.session_turns.dispatch_turn_with_outcome",+ side_effect=dispatch,+ ):+ await manager._run(turn_id, context, "test")+ task = manager.in_flight[turn_id].task+ await started.wait()+ if mode == "cancel":+ result = await manager.cancel(turn_id)+ assert result["status"] == "cancel_requested"+ await asyncio.gather(task, return_exceptions=True)+ return store.get(turn_id)++ async def run_cases() -> tuple[dict, dict, dict]:+ canceled = await exercise(turn_id="turn_cancel", mode="cancel")+ dropped = await exercise(turn_id="turn_drop", mode="drop")+ served = await exercise(turn_id="turn_control", mode="served")+ assert canceled is not None+ assert dropped is not None+ assert served is not None+ return canceled, dropped, served++ canceled, dropped, served = asyncio.run(run_cases())+ assert canceled["outcome"] == "canceled"+ assert canceled["canceled_attempt"]["source_id"] == "src_primary01"+ assert dropped["outcome"] == "failed_terminal"+ assert dropped["terminal_error"]["reason"] == "stream_interrupted"+ assert served["outcome"] == "served"+ for record in (canceled, dropped, served):+ _assert_valid("turn-provenance.schema.json", record)+++def test_fsm_settlement_persists_the_turn_time_mode() -> None:+ runtime = SimpleNamespace(settle_turn=Mock())+ manager = SessionTurnManager(+ SimpleNamespace(model_hub_runtime=runtime)+ )+ context = SimpleNamespace(+ platform_specific={"turn_token": "turn_direct"}+ )+ bind_launch(+ context,+ ModelHubLaunch(+ backend="codex",+ channel="direct",+ requested_model="gpt-5",+ target_model="gpt-5",+ runtime_model="gpt-5",+ ),+ )++ manager._settle_model_hub_turn(+ context,+ SETTLED_BY_TERMINAL_RESULT,+ )++ runtime.settle_turn.assert_called_once()+ assert runtime.settle_turn.call_args.kwargs["mode"] == "direct"+++def test_fsm_settlement_persists_model_less_direct_mode() -> None:+ runtime = SimpleNamespace(settle_turn=Mock())+ manager = SessionTurnManager(+ SimpleNamespace(model_hub_runtime=runtime)+ )+ context = SimpleNamespace(+ platform_specific={"turn_token": "turn_opencode_default"}+ )+ bind_turn_mode(context, "direct")++ manager._settle_model_hub_turn(+ context,+ SETTLED_BY_TERMINAL_RESULT,+ )++ runtime.settle_turn.assert_called_once()+ assert runtime.settle_turn.call_args.kwargs["mode"] == "direct"+++def test_settlement_retires_correlation_when_mode_persistence_fails(+ tmp_path: Path,+) -> None:+ correlation = Mock()+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ service.note_turn_mode = Mock(+ side_effect=OSError("mode store unavailable")+ )+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(correlation=correlation),+ )++ with pytest.raises(OSError, match="mode store unavailable"):+ router.settle_turn(+ "turn_mode_failure",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ mode="hub",+ )++ correlation.settle.assert_called_once_with(+ "turn_mode_failure",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+++def test_same_scope_concurrency_is_absent_and_sequential_control_is_present(+ tmp_path: Path,+) -> None:+ async def run() -> BoundedProvenanceStore:+ store = BoundedProvenanceStore(tmp_path / "concurrency.json")+ registry = TurnCorrelationRegistry(store)+ runtime = SimpleNamespace(+ settle_turn=lambda value, *, settled_by, ts, mode=None: registry.settle(+ value,+ settled_by=settled_by,+ ts=ts,+ )+ )+ controller = SimpleNamespace(+ model_hub_runtime=runtime,+ command_handler=SimpleNamespace(+ handle_stop=AsyncMock(return_value=True)+ ),+ set_agent_status=lambda _session_id, _status: None,+ )+ manager = SessionTurnManager(controller)+ manager.flush_queue = AsyncMock(return_value=False)+ started = {+ turn_id: asyncio.Event()+ for turn_id in ("turn_one", "turn_two", "turn_sequential")+ }+ release = {+ turn_id: asyncio.Event()+ for turn_id in ("turn_one", "turn_two", "turn_sequential")+ }++ async def dispatch(_controller, context, _text, **_kwargs):+ turn_id = manager.model_hub_turn_id_for_task()+ assert turn_id is not None+ exact_turn = _begin_hub_attempt(+ registry,+ turn_id=turn_id,+ scope="/shared-cwd",+ )+ started[turn_id].set()+ await release[turn_id].wait()+ success = _outcome(RawOutcomeKind.SUCCESS)+ registry.finish_attempt(+ exact_turn,+ outcome=success,+ decision=classify_outcome(success),+ )+ return TurnDispatchOutcome(+ error=None,+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ )++ def context(turn_id: str):+ return SimpleNamespace(+ platform="avibe",+ platform_specific={+ "turn_token": turn_id,+ "agent_session_target": {"agent_backend": "codex"},+ },+ )++ with patch(+ "core.session_turns.dispatch_turn_with_outcome",+ side_effect=dispatch,+ ):+ await manager._run("session-one", context("turn_one"), "one")+ first_task = manager.in_flight["session-one"].task+ await manager._run("session-two", context("turn_two"), "two")+ second_task = manager.in_flight["session-two"].task+ await started["turn_one"].wait()+ await started["turn_two"].wait()+ await manager.cancel("session-one")+ release["turn_two"].set()+ await asyncio.gather(+ first_task,+ second_task,+ return_exceptions=True,+ )++ assert store.get("turn_one") is None+ assert store.get("turn_two") is None++ await manager._run(+ "session-sequential",+ context("turn_sequential"),+ "sequential",+ )+ sequential_task = manager.in_flight["session-sequential"].task+ await started["turn_sequential"].wait()+ release["turn_sequential"].set()+ await asyncio.gather(sequential_task, return_exceptions=True)+ return store++ store = asyncio.run(run())+ sequential = store.get("turn_sequential")+ assert sequential is not None+ assert sequential["outcome"] == "served"+ _assert_valid("turn-provenance.schema.json", sequential)+++def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:+ cooling = _source(+ "src_cooling01",+ "Cooling",+ status="cooldown",+ retry_at=(NOW + timedelta(minutes=5)).isoformat(),+ )+ primary = _source("src_primary01", "Primary")+ service = _service(+ tmp_path,+ sources=[cooling, primary],+ outcomes=[_outcome(RawOutcomeKind.SUCCESS)],+ )++ chain = service.agent_chain("claude", "shared-model")+ assert [item["source_id"] for item in chain["chain"]] == [+ "src_cooling01",+ "src_primary01",+ ]+ assert chain["supply_state"] == "ok"+ assert all(item["channel"] == "hub" for item in chain["chain"])+ assert all(item["reason"] is None for item in chain["chain"])+ _assert_valid("agent-chain.schema.json", chain)++ probe = asyncio.run(service.probe_agent("claude", "shared-model"))+ assert probe["channel"] == "hub"+ assert probe["reachable"] is True+ assert probe["source_id"] == "src_primary01"+ assert isinstance(probe["latency_ms"], int)+ assert probe["error"] is None+ _assert_valid("probe-result.schema.json", probe)++ network_service = _service(+ tmp_path / "network",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[_outcome(RawOutcomeKind.NETWORK_ERROR)],+ )+ network = asyncio.run(+ network_service.probe_agent("claude", "shared-model")+ )+ assert network["reachable"] is False+ assert network["latency_ms"] is None+ assert network["error"] == "models.source.cooldown.network"+ _assert_valid("probe-result.schema.json", network)++ timeout_service = _service(+ tmp_path / "timeout",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[_outcome(RawOutcomeKind.TIMEOUT)],+ )+ timeout = asyncio.run(+ timeout_service.probe_agent("claude", "shared-model")+ )+ assert timeout["reachable"] is False+ assert timeout["latency_ms"] is None+ assert timeout["error"] == "models.source.cooldown.timeout"+ assert timeout_service.store.load().sources[0].state.detail_key == (+ "models.source.cooldown.timeout"+ )+ assert timeout_service.events.list(limit=10)[0]["reason"] == "network"+ _assert_valid("probe-result.schema.json", timeout)++ rate_service = _service(+ tmp_path / "rate",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=429,+ code="rate_limited",+ )+ ],+ )+ rate_limited = asyncio.run(+ rate_service.probe_agent("claude", "shared-model")+ )+ assert rate_limited["reachable"] is False+ assert isinstance(rate_limited["latency_ms"], int)+ assert rate_limited["error"] == "models.source.cooldown.rate_limited"+ _assert_valid("probe-result.schema.json", rate_limited)++ unclassified_service = _service(+ tmp_path / "unclassified",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=418,+ code="unexpected_upstream_failure",+ )+ ],+ )+ unclassified = asyncio.run(+ unclassified_service.probe_agent("claude", "shared-model")+ )+ assert unclassified["reachable"] is False+ assert isinstance(unclassified["latency_ms"], int)+ assert unclassified["error"] == "models.source.error.unclassified"+ assert (+ unclassified_service.store.load().sources[0].state.status+ == "error"+ )+ _assert_valid("probe-result.schema.json", unclassified)++ request_error_service = _service(+ tmp_path / "request-error",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=400,+ code="invalid_parameter",+ )+ ],+ )+ request_error = asyncio.run(+ request_error_service.probe_agent("claude", "shared-model")+ )+ assert request_error["reachable"] is False+ assert isinstance(request_error["latency_ms"], int)+ assert request_error["error"] == "models.source.error.unclassified"+ assert (+ request_error_service.store.load().sources[0].state.status+ == "standby"+ )+ assert request_error_service.events.list(limit=10) == []+ _assert_valid("probe-result.schema.json", request_error)++ anthropic_not_found = _service(+ tmp_path / "anthropic-not-found",+ sources=[_source("src_primary01", "Primary")],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=404,+ code="not_found_error",+ )+ ],+ )+ not_found = asyncio.run(+ anthropic_not_found.probe_agent("claude", "shared-model")+ )+ assert not_found["reachable"] is False+ assert (+ anthropic_not_found.store.load().sources[0].state.status+ == "standby"+ )+ assert anthropic_not_found.events.list(limit=10) == []+ _assert_valid("probe-result.schema.json", not_found)+++ ("backend", "source_protocol", "request_protocol", "request_keys"),+ [+ (+ "claude",+ source_protocol,+ "anthropic",+ {"model", "max_tokens", "messages"},+ )+ for source_protocol in (+ "anthropic",+ "openai_responses",+ "openai_chat",+ "openai_compatible",+ )+ ]+ + [+ (+ "codex",+ source_protocol,+ "openai_responses",+ {"model", "max_output_tokens", "input"},+ )+ for source_protocol in (+ "anthropic",+ "openai_responses",+ "openai_chat",+ "openai_compatible",+ )+ ]+ + [+ (+ "opencode",+ source_protocol,+ source_protocol,+ (+ {"model", "max_output_tokens", "input"}+ if source_protocol == "openai_responses"+ else {"model", "max_tokens", "messages"}+ ),+ )+ for source_protocol in (+ "anthropic",+ "openai_responses",+ "openai_chat",+ "openai_compatible",+ )+ ],+)+def test_probe_request_matches_live_backend_protocol_matrix(+ tmp_path: Path,+ backend: str,+ source_protocol: str,+ request_protocol: str,+ request_keys: set[str],+) -> None:+ source = _source("src_primary01", "Primary")+ source.protocol = source_protocol+ service = _service(+ tmp_path,+ sources=[source],+ outcomes=[_outcome(RawOutcomeKind.SUCCESS)],+ )++ result = asyncio.run(service.probe_agent(backend, "shared-model"))++ assert result["reachable"] is True+ assert service.adapter.invocations == [+ ("src_primary01", "shared-model", backend)+ ]+ request = service.adapter.requests[0]+ assert request.protocol == request_protocol+ assert set(request) == request_keys+++def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:+ native = _source(+ "src_nativecli1",+ "Native CLI",+ channel="native_cli",+ )+ service = _service(tmp_path, sources=[native])++ chain = service.agent_chain("codex", "shared-model")+ assert chain["chain"] == [+ {+ "source_id": native.id,+ "channel": "native_cli",+ "via_mapping": False,+ "resolved_model_id": None,+ "health": "healthy",+ "runnable": True,+ "reason": None,+ "retry_at": None,+ }+ ]+ assert chain["supply_state"] == "ok"+ _assert_valid("agent-chain.schema.json", chain)++ probe = asyncio.run(service.probe_agent("codex", "shared-model"))+ assert probe == {+ "contract_version": 4,+ "backend": "codex",+ "channel": "native_cli",+ "reachable": True,+ "source_id": native.id,+ "model_id": "shared-model",+ "latency_ms": None,+ "via_mapping": False,+ "error": None,+ }+ assert service.adapter.invocations == []+ _assert_valid("probe-result.schema.json", probe)+++def test_native_unavailability_is_orthogonal_to_health(+ tmp_path: Path,+) -> None:+ native = _source(+ "src_nativecli1",+ "Native CLI",+ channel="native_cli",+ status="cooldown",+ retry_at=(NOW + timedelta(minutes=5)).isoformat(),+ )+ service = _service(tmp_path, sources=[native])+ service.native_source_ready = lambda _backend, _source: False++ chain = service.agent_chain("codex", "shared-model")+ assert chain["chain"][0]["health"] == "cooldown"+ assert chain["chain"][0]["reason"] == "native_cli_unavailable"+ assert chain["chain"][0]["runnable"] is False+ assert chain["supply_state"] == "interrupted"+ _assert_valid("agent-chain.schema.json", chain)+++def test_native_probe_rechecks_readiness_after_selection(+ tmp_path: Path,+) -> None:+ native = _source(+ "src_nativecli1",+ "Native CLI",+ channel="native_cli",+ )+ service = _service(tmp_path, sources=[native])+ readiness = iter((True, False))+ service.native_source_ready = lambda _backend, _source: next(readiness)++ probe = asyncio.run(service.probe_agent("codex", "shared-model"))+ assert probe["channel"] == "native_cli"+ assert probe["reachable"] is False+ assert probe["latency_ms"] is None+ assert probe["error"] == "models.probe.native_cli_unavailable"+ assert service.adapter.invocations == []+ _assert_valid("probe-result.schema.json", probe)+++def test_probe_no_candidate_and_direct_mode_are_typed(tmp_path: Path) -> None:+ cooling = _source(+ "src_cooling01",+ "Cooling",+ status="cooldown",+ retry_at=(NOW + timedelta(minutes=5)).isoformat(),+ )+ service = _service(tmp_path, sources=[cooling])++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.probe_agent("claude", "shared-model"))+ assert exc_info.value.code == "probe_no_candidate"+ assert exc_info.value.detail == "models.probe.no_candidate.waiting"+ assert exc_info.value.data == {+ "supply": {+ "supply_state": "waiting",+ "retry_at": cooling.state.retry_at,+ }+ }++ service.store.config.agents["claude"].mode = "direct"+ with pytest.raises(ModelHubError) as chain_error:+ service.agent_chain("claude", "shared-model")+ with pytest.raises(ModelHubError) as probe_error:+ asyncio.run(service.probe_agent("claude", "shared-model"))+ for error in (chain_error.value, probe_error.value):+ assert error.code == "direct_mode"+ assert error.detail == "models.hub.direct_mode"+++def test_source_failure_event_is_single_grain_and_retained(tmp_path: Path) -> None:+ source = _source("src_primary01", "Shared paid source")+ service = _service(+ tmp_path,+ sources=[source],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=402,+ code="payment_required",+ message="balance exhausted",+ )+ ],+ )++ probe = asyncio.run(service.probe_agent("claude", "shared-model"))+ assert probe["reachable"] is False+ events = service.list_events(limit=20)+ failures = [event for event in events if event["kind"] == "needs_action"]+ assert len(failures) == 1+ event = failures[0]+ assert event["agent"] == "claude"+ assert event["from_source"] == source.id+ assert event["severity"] == "action_required"+ assert "Shared paid source" in event["human_en"]+ assert "Shared paid source" in event["human_zh"]+ _assert_valid("resolution-event.schema.json", event)++ agents = {+ item["backend"]: item+ for item in service.list_agents()+ }+ assert agents["claude"]["supply_status"] == "interrupted"+ assert agents["codex"]["supply_status"] == "interrupted"++ service.store.config.sources[0].state = ModelHubSourceStateConfig(+ status="standby"+ )+ recovered_agents = {+ item["backend"]: item+ for item in service.list_agents()+ }+ assert recovered_agents["claude"]["supply_status"] == "ok"+ assert recovered_agents["codex"]["supply_status"] == "ok"+ assert service.list_events(limit=20)[0] == event++ service.store.config.sources.clear()+ assert service.list_events(limit=20)[0] == event+++def test_mapping_and_channel_switch_copy_retain_human_subjects() -> None:+ mapping = build_resolution_event(+ agent="codex",+ kind="mapping_applied",+ model_id="target-model",+ reason="mapping",+ from_label="requested-model",+ now=NOW,+ )+ channel_switch = build_resolution_event(+ agent="system",+ kind="channel_switch",+ model_id=None,+ reason="manual",+ from_source="src_primary01",+ to_source="src_primary01",+ from_label="Primary source",+ to_label="Primary source",+ now=NOW,+ )++ for text in (mapping.human_en, mapping.human_zh):+ assert "requested-model" in text+ assert "target-model" in text+ for text in (channel_switch.human_en, channel_switch.human_zh):+ assert "Primary source" in text+++def test_shared_source_cooldown_emits_only_on_state_transition(+ tmp_path: Path,+) -> None:+ source = _source("src_primary01", "Shared source")+ service = _service(tmp_path, sources=[source])+ decision = classify_outcome(+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=429,+ code="rate_limited",+ )+ )++ async def cool_twice() -> None:+ await service._cooldown(+ source,+ decision,+ agent="claude",+ model_id="shared-model",+ )+ await service._cooldown(+ source,+ decision,+ agent="codex",+ model_id="shared-model",+ )++ asyncio.run(cool_twice())++ events = service.list_events(limit=20)+ assert len(events) == 1+ assert events[0]["kind"] == "cooldown"+ assert events[0]["agent"] == "claude"+++def test_event_emission_rejects_unknown_source_ids(tmp_path: Path) -> None:+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ service._record_event(+ agent="claude",+ kind="switch",+ model_id="shared-model",+ reason="manual",+ from_source="src_unknown01",+ to_source="src_primary01",+ now=NOW,+ )+ service._record_event(+ agent="claude",+ kind="switch",+ model_id="shared-model",+ reason="manual",+ from_source="src_primary01",+ to_source="src_unknown02",+ now=NOW,+ )+ assert service.list_events(limit=20) == []+++ "fields",+ [+ {+ "agent": "system",+ "kind": "supply_interrupted",+ "model_id": "shared-model",+ "reason": "no_enabled_source",+ },+ {+ "agent": "claude",+ "kind": "cooldown",+ "model_id": "shared-model",+ "reason": "credential_revoked",+ "from_source": "src_primary01",+ },+ {+ "agent": "claude",+ "kind": "needs_action",+ "model_id": "shared-model",+ "reason": "network",+ "from_source": "src_primary01",+ },+ {+ "agent": "claude",+ "kind": "switch",+ "model_id": "shared-model",+ "reason": "no_eligible_source",+ "from_source": "src_primary01",+ "to_source": "src_backup001",+ },+ ],+)+def test_event_builder_rejects_cross_grain_shapes(fields: dict) -> None:+ with pytest.raises(ValueError):+ build_resolution_event(**fields)+++def test_provenance_absence_codes_are_distinguishable(+ monkeypatch,+ tmp_path: Path,+) -> None:+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ monkeypatch.setattr(+ service,+ "_known_turn",+ lambda turn_id: (+ ("codex", "direct")+ if turn_id == "turn_direct"+ else (+ ("codex", "hub")+ if turn_id == "turn_ambiguous"+ else (None, None)+ )+ ),+ )++ service.store.config.agents["codex"].mode = "hub"+ with pytest.raises(ModelHubError) as direct:+ service.get_turn_provenance("turn_direct")+ assert direct.value.code == "provenance_unavailable"+ assert direct.value.detail == "models.provenance.direct_mode"++ service.store.config.agents["codex"].mode = "direct"+ with pytest.raises(ModelHubError) as ambiguous:+ service.get_turn_provenance("turn_ambiguous")+ assert ambiguous.value.code == "provenance_unavailable"+ assert (+ ambiguous.value.detail+ == "models.provenance.attribution_ambiguous"+ )++ with pytest.raises(ModelHubError) as unknown:+ service.get_turn_provenance("turn_unknown")+ assert unknown.value.code == "turn_not_found"+ assert unknown.value.status == 404+++def test_turn_mode_marker_is_deleted_with_its_turn_record(+ monkeypatch,+ tmp_path: Path,+) -> None:+ engine = create_engine(f"sqlite+pysqlite:///{tmp_path / 'state.db'}")+ metadata.create_all(engine)+ now = NOW.isoformat()+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id="ses_turn_mode",+ agent_backend="codex",+ agent_variant="codex",+ session_anchor="anchor",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ )+ )+ conn.execute(+ messages.insert().values(+ id="msg_turn_mode",+ session_id="ses_turn_mode",+ platform="avibe",+ author="user",+ type="user",+ source="user",+ content_json="{}",+ metadata_json=json.dumps({"turn_id": "turn_direct"}),+ created_at=now,+ updated_at=now,+ )+ )++ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ monkeypatch.setattr(+ "core.handlers.model_hub.service.get_cached_sqlite_engine",+ lambda: engine,+ )+ service.note_turn_mode("turn_direct", "direct")+ with engine.connect() as conn:+ stored_mode = conn.execute(+ select(+ messages.c.metadata_json,+ ).where(messages.c.id == "msg_turn_mode")+ ).scalar_one()+ assert json.loads(stored_mode)["model_hub_mode"] == "direct"++ with pytest.raises(ModelHubError) as unavailable:+ service.get_turn_provenance("turn_direct")+ assert unavailable.value.code == "provenance_unavailable"+ assert unavailable.value.detail == "models.provenance.direct_mode"++ with engine.begin() as conn:+ conn.execute(+ delete(messages).where(messages.c.id == "msg_turn_mode")+ )++ with pytest.raises(ModelHubError) as deleted:+ service.get_turn_provenance("turn_direct")+ assert deleted.value.code == "turn_not_found"+++def test_known_opencode_turn_is_fail_closed_but_not_unknown(+ monkeypatch,+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "opencode-provenance.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials(+ "opencode",+ "opencode:shared-server",+ "turn_opencode",+ )++ assert (+ registry.begin_gateway_request(+ backend="opencode",+ token=token,+ requested_model_id="openai/shared-model",+ )+ is None+ )+ registry.settle(+ "turn_opencode",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ )+ assert store.get("turn_opencode") is None++ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ service.provenance = store+ monkeypatch.setattr(+ service,+ "_known_turn",+ lambda turn_id: (+ ("opencode", None)+ if turn_id == "turn_opencode"+ else (None, None)+ ),+ )++ with pytest.raises(ModelHubError) as unavailable:+ service.get_turn_provenance("turn_opencode")+ assert unavailable.value.code == "provenance_unavailable"+ assert (+ unavailable.value.detail+ == "models.provenance.attribution_ambiguous"+ )diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 2c1efada8..36be54f9b 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -29,6 +29,7 @@ from core.handlers.model_hub.resolver import resolve_model_hub_turnfrom core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import ModelHubError, ModelHubService, _mask_credentialfrom vibe.i18n import t as i18n_t+from vibe.model_hub_runtime.client import _SAFE_ERROR_CODESfrom vibe.model_hub_runtime.state import EngineStateError@@ -235,12 +236,38 @@ def _assert_no_references_to(service, model_id: str) -> None:(_outcome(RawOutcomeKind.SUCCESS, status=200), False, "return", None),(_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"), False, "surface", None),(_outcome(RawOutcomeKind.HTTP_ERROR, status=422, code="tool_schema_error"), False, "surface", None),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found"), False, "surface", None),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=413, code="request_too_large"), False, "surface", None),+ (+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=403,+ message="The requested model is not accessible",+ ),+ False,+ "surface",+ None,+ ),(_outcome(RawOutcomeKind.HTTP_ERROR, status=401), False, "refresh", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), True, "surface", None),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), True, "fallback", "credential_expired"),(_outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"), False, "refresh", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"), True, "surface", None),+ (+ _outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"),+ True,+ "fallback",+ "credential_expired",+ ),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=402), False, "fallback", "balance_exhausted"),(_outcome(RawOutcomeKind.HTTP_ERROR, status=429), False, "fallback", "rate_limited"),(_outcome(RawOutcomeKind.HTTP_ERROR, status=403, code="quota_exhausted"), False, "fallback", "quota_exhausted"),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=403), False, "fallback", "credential_revoked"),+ (+ _outcome(RawOutcomeKind.HTTP_ERROR, status=403, code="account_suspended"),+ False,+ "fallback",+ "account_banned",+ ),+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=418), False, "fallback", "unclassified_error"),(_outcome(RawOutcomeKind.HTTP_ERROR, status=503), False, "fallback", "server_error"),(_outcome(RawOutcomeKind.NETWORK_ERROR), False, "fallback", "network"),(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True), False, "surface", None),@@ -252,6 +279,154 @@ def test_error_classification_table(outcome, refresh_attempted, action, reason):assert decision.reason == reason+def test_safe_error_code_family_is_exhaustively_classified_without_overclaim():+ dispositions = {+ "api_error": (500, False, "fallback", "server_error", None),+ "account_banned": (403, False, "fallback", "account_banned", None),+ "account_disabled": (403, False, "fallback", "account_banned", None),+ "account_suspended": (403, False, "fallback", "account_banned", None),+ "authentication_error": (401, False, "refresh", None, None),+ "billing_error": (402, False, "fallback", "balance_exhausted", None),+ "context_length_exceeded": (+ 400,+ False,+ "surface",+ None,+ "upstream_request_invalid",+ ),+ "insufficient_quota": (+ 429,+ False,+ "fallback",+ "quota_exhausted",+ None,+ ),+ "invalid_api_key": (401, False, "refresh", None, None),+ "invalid_request_error": (+ 400,+ False,+ "surface",+ None,+ "upstream_request_invalid",+ ),+ "model_not_found": (+ 404,+ False,+ "surface",+ None,+ "upstream_request_invalid",+ ),+ "not_found_error": (+ 404,+ False,+ "surface",+ None,+ "upstream_request_invalid",+ ),+ "overloaded_error": (529, False, "fallback", "server_error", None),+ "permission_error": (+ 403,+ False,+ "fallback",+ "permission_denied",+ None,+ ),+ "quota_exceeded": (+ 429,+ False,+ "fallback",+ "quota_exhausted",+ None,+ ),+ "rate_limit_error": (429, False, "fallback", "rate_limited", None),+ "rate_limit_exceeded": (429, False, "fallback", "rate_limited", None),+ "request_too_large": (+ 413,+ False,+ "surface",+ None,+ "upstream_request_invalid",+ ),+ "server_error": (500, False, "fallback", "server_error", None),+ }++ assert set(dispositions) == set(_SAFE_ERROR_CODES)+ for code, (+ status,+ refresh_attempted,+ action,+ reason,+ error_code,+ ) in dispositions.items():+ decision = classify_outcome(+ _outcome(RawOutcomeKind.HTTP_ERROR, status=status, code=code),+ refresh_attempted=refresh_attempted,+ )+ assert (+ decision.action,+ decision.reason,+ decision.error_code,+ ) == (action, reason, error_code), code+++def test_permission_denial_falls_back_without_mutating_source_health(tmp_path):+ adapter = FakeAdapter(+ [+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=403,+ code="permission_error",+ ),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ]+ )+ service = _service(tmp_path, adapter)++ resolved = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert resolved.source_id == "src_backup001"+ assert [source.state.status for source in service.store.load().sources] == [+ "standby",+ "standby",+ ]+ events = service.list_events(limit=10)+ assert len(events) == 1+ assert events[0]["kind"] == "switch"+ assert events[0]["reason"] == "permission_denied"+ assert events[0]["from_source"] == "src_primary01"+ assert events[0]["to_source"] == "src_backup001"+++def test_permission_denial_probe_does_not_block_the_source(tmp_path):+ service = _service(+ tmp_path,+ FakeAdapter(+ [+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=403,+ code="permission_error",+ )+ ]+ ),+ )++ result = asyncio.run(+ service.probe_agent("claude", "claude-opus-4-6")+ )++ assert result["reachable"] is False+ assert result["error"] == "models.source.error.unclassified"+ assert service.store.load().sources[0].state.status == "standby"+ assert service.list_events(limit=10) == []++def test_quota_failure_cools_source_switches_and_emits_redacted_events(tmp_path):"""Scenario: MH-RES-001."""@@ -339,6 +514,65 @@ def test_401_refreshes_exactly_once_before_returning(tmp_path):assert len(adapter.invocations) == 2+ ("outcomes", "reason", "detail_key"),+ [+ (+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=401),+ _outcome(RawOutcomeKind.HTTP_ERROR, status=401),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ],+ "credential_expired",+ "models.source.needs_action.oauth_expired",+ ),+ (+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=402),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ],+ "balance_exhausted",+ "models.source.needs_action.balance_exhausted",+ ),+ (+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=418),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ],+ "unclassified_error",+ "models.source.error.unclassified",+ ),+ ],+)+def test_non_self_healing_failure_blocks_source_then_falls_back(+ tmp_path,+ outcomes,+ reason,+ detail_key,+):+ service = _service(tmp_path, FakeAdapter(outcomes))++ result = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )++ assert result.source_id == "src_backup001"+ primary = service.store.load().sources[0]+ assert primary.state.status == (+ "error" if reason == "unclassified_error" else "needs_action"+ )+ assert primary.state.detail_key == detail_key+ events = service.list_events(limit=10)+ assert [event["kind"] for event in events] == ["switch", "needs_action"]+ assert events[0]["reason"] == events[1]["reason"] == reason+ assert events[0]["severity"] == "info"+ assert events[1]["severity"] == "action_required"++def test_refreshed_fallback_stream_emits_switch_event(tmp_path):async def stream_bytes():yield b"ok"@@ -371,6 +605,8 @@ def test_refreshed_fallback_stream_emits_switch_event(tmp_path):def test_parameter_error_and_started_stream_never_fallback(tmp_path):for outcome in (_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"),+ _outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found"),+ _outcome(RawOutcomeKind.HTTP_ERROR, status=413, code="request_too_large"),_outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True),):adapter = FakeAdapter([outcome])@@ -378,6 +614,7 @@ def test_parameter_error_and_started_stream_never_fallback(tmp_path):with pytest.raises(ModelHubError):asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}, stream=True))assert len(adapter.invocations) == 1+ assert service.store.load().sources[0].state.status == "standby"def test_mapping_is_scoped_to_the_requesting_backend(tmp_path):@@ -1095,6 +1332,7 @@ def test_resolution_event_copy_comes_from_backend_i18n(tmp_path):kind="cooldown",model_id="test-model",reason="network",+ from_source="src_primary01",from_label="Primary",)@@ -1519,6 +1757,35 @@ def test_existing_source_test_persists_safe_error_state_on_discovery_failure(assert service.store.load().sources[0].state.detail_key == ("models.source.error.unclassified")+ source_test_event = service.list_events(limit=10)[0]+ assert source_test_event["agent"] == "system"+ assert source_test_event["model_id"] is None++ turn_service = _service(+ tmp_path / "turn",+ FakeAdapter(+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=418),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ]+ ),+ )+ asyncio.run(+ turn_service.resolve(+ backend="claude",+ model_id="claude-opus-4-6",+ request={},+ )+ )+ turn_event = next(+ event+ for event in turn_service.list_events(limit=10)+ if event["kind"] == "needs_action"+ )+ fields = ("kind", "reason", "from_source", "severity")+ assert tuple(source_test_event[field] for field in fields) == tuple(+ turn_event[field] for field in fields+ )def test_existing_source_test_rejects_empty_discovery_before_recovery(tmp_path):@@ -1558,6 +1825,7 @@ def test_existing_source_test_preserves_health_on_engine_outage(tmp_path):assert exc_info.value.code == "engine_down"assert _serialized_config(service) == before+ assert service.list_events(limit=10) == []def test_mapping_write_rejects_disabled_unavailable_target(tmp_path):diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 0b6621e81..d5e567bff 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -25,6 +25,7 @@ from core.handlers.model_hub.adapter import (RawOutcomeKind,SourceBinding,)+from core.handlers.model_hub.classification import classify_outcomefrom core.handlers.model_hub.request import ModelHubRequestfrom vibe.model_hub_runtime import client as client_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter@@ -639,6 +640,18 @@ class Handler(BaseHTTPRequestHandler):if payload['model'].endswith('/unsafe-error-code'):self._json(400, {{'error': {{'type': 'invalid_key_upstream-secret'}}}})return+ if payload['model'].endswith('/account-banned'):+ self._json(403, {{'error': {{'type': 'account_banned', 'message': 'upstream-secret'}}}})+ return+ if payload['model'].endswith('/account-suspended'):+ self._json(403, {{'error': {{'code': 'account_suspended', 'message': 'upstream-secret'}}}})+ return+ if payload['model'].endswith('/account-disabled'):+ self._json(403, {{'error': {{'type': 'vendor_error', 'code': 'account_disabled', 'message': 'upstream-secret'}}}})+ return+ if payload['model'].endswith('/ban-token-in-message'):+ self._json(403, {{'error': {{'message': 'prefix account_banned suffix upstream-secret'}}}})+ returnif payload['model'].endswith('/redirected'):self.send_response(307)self.send_header('Location', 'https://example.test/credential-leak')@@ -818,7 +831,16 @@ def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> Non_binding(credential_ref,allowed_origins=("codex",),- model_ids=("model-a", "rate-limited", "unsafe-error-code", "redirected"),+ model_ids=(+ "model-a",+ "rate-limited",+ "unsafe-error-code",+ "account-banned",+ "account-suspended",+ "account-disabled",+ "ban-token-in-message",+ "redirected",+ ),)])@@ -848,6 +870,28 @@ def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> Nonassert "upstream-secret" not in (failure.redacted_message or "")unsafe_code = await adapter.invoke("src_fixture123", "unsafe-error-code", {}, False, "codex")assert (await unsafe_code.outcome()).error_code is None+ for model_id, error_code in (+ ("account-banned", "account_banned"),+ ("account-suspended", "account_suspended"),+ ("account-disabled", "account_disabled"),+ ):+ banned = await adapter.invoke("src_fixture123", model_id, {}, False, "codex")+ banned_outcome = await banned.outcome()+ assert banned_outcome.error_code == error_code+ assert banned_outcome.redacted_message == "upstream returned HTTP 403"+ assert classify_outcome(banned_outcome).reason == "account_banned"+ free_text = await adapter.invoke(+ "src_fixture123",+ "ban-token-in-message",+ {},+ False,+ "codex",+ )+ free_text_outcome = await free_text.outcome()+ assert free_text_outcome.error_code is None+ assert "account_banned" not in (free_text_outcome.redacted_message or "")+ assert "upstream-secret" not in (free_text_outcome.redacted_message or "")+ assert classify_outcome(free_text_outcome).reason == "credential_revoked"redirected = await adapter.invoke("src_fixture123", "redirected", {}, False, "codex")redirect_outcome = await redirected.outcome()assert redirect_outcome.kind is RawOutcomeKind.HTTP_ERRORdiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex d61c464b4..075d8cdf0 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1035,6 +1035,9 @@"opencode_api_key_only": "OpenCode can only be supplied by API-key sources","consent_required": "Needs your consent for experimental hub supply first"},+ "probe": {+ "native_cli_unavailable": "CLI login is not available in this process"+ },"source": {"cooldown": {"network": "Network unreachable",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b860b6f43..f56450537 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1035,6 +1035,9 @@"opencode_api_key_only": "OpenCode 只能由 API Key 来源供给","consent_required": "需要先同意实验性中枢供给"},+ "probe": {+ "native_cli_unavailable": "当前进程无法使用 CLI 登录"+ },"source": {"cooldown": {"network": "网络不通",diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 23e3c308f..5c4156369 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -535,7 +535,11 @@"switch": "{from_source}: {reason} -> switched to {to_source}","cooldown": "{from_source}: {reason}; cooling down","recover": "{to_source}: recovered and available",- "status": "{from_source}: {reason}",+ "skip": "{from_source}: {reason}; skipped",+ "mapping_applied": "{from_source} -> {model}: model mapping applied",+ "channel_switch": "{from_source}: supply channel changed",+ "needs_action": "{from_source}: {reason}; action required",+ "supply_interrupted": "{model}: {reason}; model supply interrupted","reason": {"quota_exhausted": "quota exhausted","rate_limited": "rate limited",@@ -543,8 +547,26 @@"network": "network unavailable","recovery": "recovered","manual": "manual change",- "mapping": "model mapping applied"+ "mapping": "model mapping applied",+ "credential_expired": "credential expired",+ "credential_revoked": "credential revoked",+ "balance_exhausted": "balance exhausted",+ "account_banned": "account unavailable",+ "permission_denied": "request permission denied",+ "unclassified_error": "unclassified source error",+ "no_enabled_source": "no source is enabled",+ "no_eligible_source": "no source is eligible",+ "model_unsupported": "no source supports this model"}+ },+ "launch": {+ "retry": "The next turn has already switched routes. Retry directly.",+ "waiting": "Model {model} is temporarily unavailable. Waiting for {source} to recover at {retry_at}.",+ "interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.",+ "native_cli_unavailable": "CLI login is not available in this process",+ "no_enabled_source": "Model {model} has no enabled source. Open Models to configure one.",+ "no_eligible_source": "Model {model} has no source eligible for {backend}. Open Models to configure one.",+ "model_unsupported": "No source supports model {model}. Open Models to configure one."}},"remote_access": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex ac688e7b8..78468f401 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -535,7 +535,11 @@"switch": "{from_source}:{reason} -> 已切到 {to_source}","cooldown": "{from_source}:{reason},暂时冷却","recover": "{to_source}:已恢复可用",- "status": "{from_source}:{reason}",+ "skip": "{from_source}:{reason},已跳过",+ "mapping_applied": "{from_source} -> {model}:已应用模型映射",+ "channel_switch": "{from_source}:供给通道已切换",+ "needs_action": "{from_source}:{reason},需要处理",+ "supply_interrupted": "{model}:{reason},模型供给已中断","reason": {"quota_exhausted": "额度用完","rate_limited": "请求受限",@@ -543,8 +547,26 @@"network": "网络暂不可用","recovery": "已恢复","manual": "手动调整",- "mapping": "已应用模型映射"+ "mapping": "已应用模型映射",+ "credential_expired": "凭证已过期",+ "credential_revoked": "凭证已撤销",+ "balance_exhausted": "余额不足",+ "account_banned": "账户不可用",+ "permission_denied": "请求权限被拒绝",+ "unclassified_error": "来源发生未分类错误",+ "no_enabled_source": "没有已启用的来源",+ "no_eligible_source": "没有适用的来源",+ "model_unsupported": "没有来源支持此模型"}+ },+ "launch": {+ "retry": "下一回合已自动换线,直接重试即可",+ "waiting": "模型 {model} 暂时不可用,等待 {source} 于 {retry_at} 自动恢复。",+ "interrupted": "模型 {model} 当前不可用:{blockers}。请前往 Models 处理。",+ "native_cli_unavailable": "当前进程无法使用 CLI 登录",+ "no_enabled_source": "模型 {model} 没有已启用的来源。请前往 Models 配置。",+ "no_eligible_source": "模型 {model} 没有适用于 {backend} 的来源。请前往 Models 配置。",+ "model_unsupported": "没有来源支持模型 {model}。请前往 Models 配置。"}},"remote_access": {diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 1a4576cd9..3e1f6c8ca 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -140,6 +140,25 @@ class ModelHubRemoteService:def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:return _rpc_sync("list_events", {"limit": limit, "before": before})+ def agent_chain(self, backend: str, model_id: str) -> dict:+ return _rpc_sync(+ "get_agent_chain",+ {"backend": backend, "model_id": model_id},+ )++ async def probe_agent(+ self,+ backend: str,+ model_id: Optional[str] = None,+ ) -> dict:+ return await _rpc(+ "probe_agent",+ {"backend": backend, "model_id": model_id},+ )++ def get_turn_provenance(self, turn_id: str) -> dict:+ return _rpc_sync("get_turn_provenance", {"turn_id": turn_id})+async def oauth_start(self, payload: dict) -> dict:return await _rpc("oauth_start", {"oauth": payload})diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 7776501fb..4addb443c 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -21,6 +21,11 @@ _MODEL_PROBE_BYTES = 4 * 1024 * 1024_SAFE_ERROR_CODES = frozenset({"api_error",+ # Closed mirror of classification._BANNED_PATTERNS account-status+ # tokens; the runtime preserves only exact machine codes.+ "account_banned",+ "account_disabled",+ "account_suspended","authentication_error","billing_error","context_length_exceeded",@@ -533,10 +538,12 @@ def _error_code(payload: bytes) -> str | None:return Noneerror = decoded.get("error")if isinstance(error, dict):- value = error.get("type") or error.get("code")- return _safe_error_code(value)- value = decoded.get("code")- return _safe_error_code(value)+ for value in (error.get("type"), error.get("code")):+ safe_value = _safe_error_code(value)+ if safe_value is not None:+ return safe_value+ return None+ return _safe_error_code(decoded.get("code"))def _safe_error_code(value: object) -> str | None:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 3240dd65e..ffbc65526 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3356,6 +3356,52 @@ def model_hub_events_get():return _model_hub_error(exc)[email protected]("/api/models/agents/<backend>/chain", methods=["GET"])+def model_hub_agent_chain_get(backend):+ from core.handlers.model_hub import ModelHubError++ try:+ model_id = str(request.args.get("model") or "").strip()+ if not model_id:+ raise ModelHubError("mapping_target_unavailable", status=409)+ chain = _model_hub_service().agent_chain(backend, model_id)+ return _model_hub_success(chain=chain)+ except ModelHubError as exc:+ return _model_hub_error(exc)++[email protected]("/api/models/agents/<backend>/probe", methods=["POST"])+async def model_hub_agent_probe_post(backend):+ from core.handlers.model_hub import ModelHubError++ try:+ payload = request.json+ if payload is None:+ payload = {}+ if not isinstance(payload, dict) or set(payload) - {"model"}:+ raise ModelHubError("mapping_target_unavailable")+ model_id = payload.get("model")+ if model_id is not None and (+ not isinstance(model_id, str) or not model_id.strip()+ ):+ raise ModelHubError("mapping_target_unavailable")+ probe = await _model_hub_service().probe_agent(backend, model_id)+ return _model_hub_success(probe=probe)+ except ModelHubError as exc:+ return _model_hub_error(exc)++[email protected]("/api/models/turns/<turn_id>/provenance", methods=["GET"])+def model_hub_turn_provenance_get(turn_id):+ from core.handlers.model_hub import ModelHubError++ try:+ provenance = _model_hub_service().get_turn_provenance(turn_id)+ 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