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
docs(model-hub): specify local gateway v3 (#1215)
Call Whiteceace07f06ba
diff --git a/config/v2_config.py b/config/v2_config.pyindex 317663773..7aebb583a 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -548,6 +548,7 @@ class AgentsConfig:class ModelHubModelConfig:id: strprovenance: Literal["discovered", "manual"]+ reasoning_efforts: list[str] = field(default_factory=list)display_name: Optional[str] = Nonediscovered_at: Optional[str] = None@@ -556,18 +557,26 @@ class ModelHubModelConfig:if not isinstance(payload, dict):raise ValueError("Config 'model_hub.sources.models' entries must be objects")model_id = payload.get("id")- provenance = payload.get("provenance")+ origin = payload.get("origin")+ reasoning_efforts = payload.get("reasoning_efforts", [])display_name = payload.get("display_name")discovered_at = payload.get("discovered_at")if not isinstance(model_id, str) or not model_id:raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")- if provenance not in {"discovered", "manual"}:- raise ValueError("Config 'model_hub.sources.models.provenance' is invalid")+ if origin not in {"discovered", "manual"}:+ raise ValueError("Config 'model_hub.sources.models.origin' is invalid")+ if (+ not isinstance(reasoning_efforts, list)+ or any(not isinstance(effort, str) or not effort for effort in reasoning_efforts)+ or len(set(reasoning_efforts)) != len(reasoning_efforts)+ ):+ raise ValueError("Config 'model_hub.sources.models.reasoning_efforts' must be a unique array of strings")if display_name is not None and not isinstance(display_name, str):raise ValueError("Config 'model_hub.sources.models.display_name' must be a string or null")return cls(id=model_id,- provenance=provenance,+ provenance=origin,+ reasoning_efforts=list(reasoning_efforts),display_name=display_name,discovered_at=_validate_optional_datetime(discovered_at,@@ -579,7 +588,8 @@ class ModelHubModelConfig:return {"id": self.id,"display_name": self.display_name,- "provenance": self.provenance,+ "origin": self.provenance,+ "reasoning_efforts": list(self.reasoning_efforts),"discovered_at": self.discovered_at,}@@ -685,7 +695,7 @@ class ModelHubSourceConfig:kind: Literal["subscription", "api_key"]vendor: strdisplay_name: str- protocol: Literal["anthropic", "openai_responses", "openai_chat", "openai_compatible"]+ protocol: Literal["anthropic", "openai_responses", "openai_chat"]supply_channel: Literal["native_cli", "hub"]billing: Literal["monthly", "metered"]state: ModelHubSourceStateConfig@@ -718,7 +728,7 @@ class ModelHubSourceConfig:raise ValueError("Config 'model_hub.sources.vendor' must be a non-empty string")if not isinstance(display_name, str) or not display_name or len(display_name) > 64:raise ValueError("Config 'model_hub.sources.display_name' is invalid")- if protocol not in {"anthropic", "openai_responses", "openai_chat", "openai_compatible"}:+ if protocol not in {"anthropic", "openai_responses", "openai_chat"}:raise ValueError("Config 'model_hub.sources.protocol' is invalid")if supply_channel not in {"native_cli", "hub"}:raise ValueError("Config 'model_hub.sources.supply_channel' is invalid")@@ -795,8 +805,6 @@ class ModelHubSourceConfig:}if self.usage is not None:payload["usage"] = self.usage.to_payload()- if self.experimental_consent_at is not None:- payload["experimental_consent_at"] = self.experimental_consent_atreturn payload@@ -1018,12 +1026,10 @@ class ModelHubConfig:)for backend in MODEL_HUB_BACKENDS}- for source in sources:- if source.kind == "subscription" and source.supply_channel == "hub":- if not experimental or not source.experimental_consent_at:- raise ValueError("Config hub-held subscription source requires recorded experimental consent")- elif source.experimental_consent_at is not None:- raise ValueError("Config experimental consent is only valid for hub-held subscription sources")+ # Consent and the experimental flag are retired product concepts. Older+ # in-memory callers may still carry these private attributes while the+ # final serialized Source shape omits them; loading a valid final Source+ # must therefore never require a retired stamp.config = cls(sources=sources,agents=agents,diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex a737142e4..aa5bc49ac 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -1,61 +1,11 @@-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.5 (2026-07-31).--v1.5 changelog (honest lazy-start health):-- ``EngineHealth.NOT_STARTED`` distinguishes an installed runtime that has not- been demanded in this service lifetime from one that started and went down.--v1.4 changelog (ref-keyed cleanup convergence):-- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an- already-converged cleanup, making journal replay idempotent across crashes.--v1.3 changelog (owner-approved channel class pass):-- ``OAuthFlowState.channel`` makes Hub and native CLI success semantics explicit:- Hub success carries an engine credential ref; native success never does.-- Hub flows expose a total five-way retained-material disposition for repair- decisions. Native flows pin that disposition to ``none`` because CLI-owned- login material never crosses this engine seam.-- Retained refs are exposed only for flow-owned or orphaned material. Foreign- and unknown placements deliberately expose no actionable handle.-- ``cleanup_orphaned_oauth_material`` is the ref-keyed retry seam: it confirms- both auth-file deletions before revoking the only retained handle.--v1.2 changelog (L1 implementation findings — credential & model lifecycle):-- Secret provisioning path closed: ``provision_credential`` moves an API-key- secret (transient parameter, never logged, never persisted by L2) into the- ENGINE-OWNED store and returns the opaque ``credential_ref``;- ``revoke_credential`` releases it on source deletion. L2's config persists- refs only. Flow: provision → discover (probe) → persist Source → sync.-- ``SourceBinding.model_ids`` added: the declared supply list (discovered +- manual custom entries) — required by the engine's generic/API-key config.-- ``discover_models`` re-signed as a PROBE (vendor/protocol/base_url/- credential_ref) so discovery works BEFORE registration; it no longer takes- a ``source_id``.--v1.1 changelog (L1 review findings, routed via orchestrator):-- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes- the pre-created (pending) ``source_id``; a Hub-channel ``success``- ``OAuthFlowState`` carries the resulting opaque ``credential_ref``. The- later native channel uses the same flow state without an engine ref.- Concurrent same-vendor flows can never cross-bind.-- Client binding made enforceable at the engine boundary:- ``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +- ``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters- first — defense in depth per README invariant 3).--Canonical text: docs/plans/model-hub-contracts/adapter-interface.py (this file).-Dual-copy rule: BOTH lane L1 and lane L2 copy this file VERBATIM to-``core/handlers/model_hub/adapter.py`` in their branches (byte-identical, so the-merge is a no-op). L2 owns the in-repo copy on master thereafter. Any change-routes through the orchestrator and bumps the version line above.--Seam semantics (from spike S1, binding):-- L1 implements this protocol (engine facade). L1 must NOT classify errors,- retry, or fall back across sources — per-source invocation only; the- engine's internal fallback and usage feed stay disabled/bypassed.-- L2 consumes it: picks exactly one source per call (priority resolution),- classifies ``RawCallOutcome`` into the canonical taxonomy, emits redacted- resolution events.-- No credential material may appear in any field defined here.+"""Model Hub EngineAdapter interface. FINAL CONTRACT v5 (2026-08-09).++This file is the canonical adapter boundary and must remain byte-identical to+``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:+credential custody, protocol observation, model discovery, OAuth, invocation,+and cleanup. It never chooses or reorders Route hops, classifies cross-Source+fallthrough, or exposes credential material. Contract changes route through the+orchestrator and land with every affected consumer on the same tested head."""from __future__ import annotations@@ -64,6 +14,8 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence+# authority-consumer: protocol anthropic openai_responses openai_chat+class EngineHealth(str, Enum):OK = "ok"@@ -89,7 +41,7 @@ class SourceBinding:source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "openai_compatible"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on this@@ -175,9 +127,8 @@ class OAuthFlowState:error_key: str | Noneexpires_at_iso: str | Nonecredential_ref: str | None- # Defaults preserve pre-v1.3 call sites until the follow-up service-consumer- # lane supplies the discriminator explicitly. Channel-aware producers MUST- # set all three fields.+ # Channel-aware producers set all three fields explicitly. Defaults keep the+ # dataclass construction total for presentation-only adapter implementations.channel: Literal["hub", "native_cli"] = "hub"retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONEretained_credential_ref: str | None = Nonediff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 9bea228e2..974956fa6 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -35,11 +35,11 @@ _CUSTOM_ENDPOINT_NOTE = "settings.models.source.customEndpoint"_NATIVE_SUPPLY_NOTE = "settings.models.source.nativeSupply"_OPENCODE_BUILTIN_PROTOCOLS: dict[str,- Literal["anthropic", "openai_compatible"],+ Literal["anthropic", "openai_chat"],] = {- "deepseek": "openai_compatible",+ "deepseek": "openai_chat","minimax": "anthropic",- "openrouter": "openai_compatible",+ "openrouter": "openai_chat",}_OPENCODE_UNSUPPORTED_NATIVE_IDS = {"alibaba-cn", "poe"}@@ -101,7 +101,6 @@ class NativeMigrationItem:"anthropic","openai_responses","openai_chat",- "openai_compatible",]display_name: strbase_url: Optional[str] = None@@ -372,7 +371,7 @@ def _opencode_protocol(provider_id: str,provider_config: dict[str, Any],catalog_provider: dict[str, Any],-) -> Optional[Literal["anthropic", "openai_responses", "openai_compatible"]]:+) -> Optional[Literal["anthropic", "openai_responses", "openai_chat"]]:if provider_id == "anthropic":return "anthropic"if provider_id == "openai":@@ -381,7 +380,7 @@ def _opencode_protocol(if custom_adapter == "anthropic-compatible":return "anthropic"if custom_adapter == "openai-compatible":- return "openai_compatible"+ return "openai_chat"builtin_protocol = _OPENCODE_BUILTIN_PROTOCOLS.get(provider_id)if builtin_protocol is not None:return builtin_protocol@@ -391,7 +390,7 @@ def _opencode_protocol(if npm == "@ai-sdk/openai":return "openai_responses"if npm in {"@ai-sdk/openai-compatible", "@openrouter/ai-sdk-provider"}:- return "openai_compatible"+ return "openai_chat"return Nonediff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex dc9b032ab..224675ae0 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -39,9 +39,8 @@ class AttemptIdentity:def payload(self) -> dict:return {"source_id": self.source_id,- "resolved_model_id": self.resolved_model_id,+ "configured_model_id": self.resolved_model_id,"channel": self.channel,- "via_mapping": self.via_mapping,}@@ -798,7 +797,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 4,+ "contract_version": 5,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,@@ -809,5 +808,6 @@ class TurnCorrelationRegistry:"terminal_error": terminal_error,"canceled_attempt": canceled_attempt,"model_supply_state": supply_state,+ "blockers": [],})diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 41b66f4ad..bd75d45db 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -50,9 +50,19 @@ async def dispatch_model_hub_rpc(if operation == "set_opencode_menu":return await service.set_opencode_menu(payload.get("menu"))if operation == "add_custom_model":- return await service.add_custom_model(payload.get("model"))+ return await service.add_custom_model(payload.get("source_id"), payload.get("model"))+ if operation == "update_model_reasoning_efforts":+ return await service.update_model_reasoning_efforts(+ payload.get("source_id"),+ payload.get("model_id"),+ payload.get("model"),+ )if operation == "delete_custom_model":- return await service.delete_custom_model(payload.get("source_id"), payload.get("model_id"))+ return await service.delete_custom_model(+ payload.get("source_id"),+ payload.get("model_id"),+ force=payload.get("force") is True,+ )if operation == "list_events":return service.list_events(limit=payload.get("limit", 20), before=payload.get("before"))if operation == "get_agent_chain":diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 6b7ca3115..6f362bf3f 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -88,8 +88,8 @@ from .resolver import (from .revocations import CredentialRevocationJournalCONTRACT_VERSION = 3-AGENT_CHAIN_CONTRACT_VERSION = 4-PROBE_RESULT_CONTRACT_VERSION = 4+AGENT_CHAIN_CONTRACT_VERSION = 5+PROBE_RESULT_CONTRACT_VERSION = 5logger = logging.getLogger(__name__)_NATIVE_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}@@ -321,7 +321,7 @@ def _default_protocol(vendor: str) -> str:return "anthropic"if vendor == "openai":return "openai_responses"- return "openai_compatible"+ return "openai_chat"def _binding(source: ModelHubSourceConfig) -> SourceBinding:@@ -370,7 +370,7 @@ def _runtime_payload(status: EngineStatus) -> dict:from vibe.model_hub_runtime.installer import EngineRuntimeManagerreturn {- "contract_version": 4,+ "contract_version": 5,"manifest": EngineRuntimeManager().contract_manifest(),"status": {"installed_version": status.installed_version,@@ -808,11 +808,22 @@ class ModelHubService:raise ModelHubError("discovery_failed", status=502)discovered_at = self.now().isoformat()manual_model_ids = {model.id for model in manual_models}- source.models = [- ModelHubModelConfig(id=model_id, provenance="discovered", discovered_at=discovered_at)- for model_id in discovered- if model_id not in manual_model_ids- ] + manual_models+ existing_by_id = {model.id: model for model in source.models}+ discovered_models = []+ for model_id in discovered:+ if model_id in manual_model_ids:+ continue+ existing = existing_by_id.get(model_id)+ discovered_models.append(+ ModelHubModelConfig(+ id=model_id,+ provenance="discovered",+ reasoning_efforts=list(existing.reasoning_efforts) if existing else [],+ display_name=existing.display_name if existing else None,+ discovered_at=discovered_at,+ )+ )+ source.models = discovered_models + manual_modelssource.last_discovered_at = discovered_atasync def _commit_new_source_locked(@@ -2109,7 +2120,6 @@ class ModelHubService:}sources = ({- "policy": agent.sources.policy,"order": config.effective_source_order(agent.backend),"eligibility": [{@@ -2161,8 +2171,10 @@ class ModelHubService:),})+ agent_payload = agent.to_payload()+ agent_payload.pop("mappings", None)return {- **agent.to_payload(),+ **agent_payload,"selected_by_agent": selected_by_agent,"selected_model_id": selected_model_id,"selected_model_explicit": selected_model_explicit,@@ -2254,11 +2266,28 @@ class ModelHubService:self.store.save(config)return self._agent_payload(config, agent)- async def add_custom_model(self, payload: dict) -> dict:+ @staticmethod+ def _validated_reasoning_efforts(+ model: ModelHubModelConfig,+ value: object,+ ) -> list[str]:+ try:+ validated = ModelHubModelConfig.from_payload(+ {+ **model.to_payload(),+ "reasoning_efforts": value,+ }+ )+ except ValueError:+ raise ModelHubError("mapping_target_unavailable") from None+ return validated.reasoning_efforts++ async def add_custom_model(self, source_id: object, payload: dict) -> dict:if not isinstance(payload, dict):raise ModelHubError("source_not_found", status=404)model_id = payload.get("model_id")display_name = payload.get("display_name")+ reasoning_efforts = payload.get("reasoning_efforts")if (not isinstance(model_id, str)or not model_id@@ -2272,39 +2301,79 @@ class ModelHubService:async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)- source = self._source(config, str(payload.get("source_id") or ""))+ source = self._source(config, str(source_id or ""))existing = next((model for model in source.models if model.id == model_id), None)if existing is None:- source.models.append(- ModelHubModelConfig(- id=model_id,- display_name=display_name,- provenance="manual",- discovered_at=None,- )+ model = ModelHubModelConfig(+ id=model_id,+ display_name=display_name,+ provenance="manual",+ discovered_at=None,)- elif existing.provenance == "manual":+ model.reasoning_efforts = self._validated_reasoning_efforts(+ model,+ reasoning_efforts,+ )+ source.models.append(model)+ elif existing.provenance == "discovered":+ raise ModelHubError("source_model_managed_upstream", status=409)+ else:existing.display_name = display_name+ existing.reasoning_efforts = self._validated_reasoning_efforts(+ existing,+ reasoning_efforts,+ )await self._commit_synced(previous, config)return source.to_payload()- async def delete_custom_model(self, source_id: object, model_id: object) -> dict:- if not isinstance(model_id, str) or not model_id:+ async def update_model_reasoning_efforts(+ self,+ source_id: object,+ model_id: object,+ payload: object,+ ) -> dict:+ if not isinstance(model_id, str) or not model_id or not isinstance(payload, dict):+ raise ModelHubError("mapping_target_unavailable")+ if set(payload) != {"reasoning_efforts"}:raise ModelHubError("mapping_target_unavailable")async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, str(source_id or ""))- manual = next(- (model for model in source.models if model.id == model_id and model.provenance == "manual"),- None,+ model = next((item for item in source.models if item.id == model_id), None)+ if model is None:+ raise ModelHubError("mapping_target_unavailable", status=404)+ model.reasoning_efforts = self._validated_reasoning_efforts(+ model,+ payload["reasoning_efforts"],)- if manual is not None and self._only_selected_model_supplier(config, source, model_id):+ await self._commit_synced(previous, config)+ return source.to_payload()++ async def delete_custom_model(+ self,+ source_id: object,+ model_id: object,+ *,+ force: bool = False,+ ) -> dict:+ if not isinstance(model_id, str) or not model_id:+ raise ModelHubError("mapping_target_unavailable")+ async with self._mutation_lock:+ previous = self.store.load()+ config = self._clone_config(previous)+ source = self._source(config, str(source_id or ""))+ model = next((item for item in source.models if item.id == model_id), None)+ if model is None:+ raise ModelHubError("mapping_target_unavailable", status=404)+ if model.provenance == "discovered":+ raise ModelHubError("source_model_managed_upstream", status=409)+ if not force and self._only_selected_model_supplier(config, source, model_id):raise ModelHubError("mode_switch_blocked", status=409)source.models = [- model- for model in source.models- if not (model.id == model_id and model.provenance == "manual")+ item+ for item in source.models+ if item.id != model_id]self._prune_unavailable_agent_references(config)await self._commit_synced(previous, config)diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 40feb7bc0..c7dde7079 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,401 +1,117 @@-# Model Hub — Interface Contracts--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. Later targeted-v4 amendments retain those pins while tightening-the channel-aware adapter seam and grafting derived truth onto the live-AgentSupply/source-creation projections. The 2026-07-31 source-refresh amendment-adds persisted discovery freshness and makes `/sources/<id>/refresh` the single-explicit refresh/recovery operation. The versionless `resolution-event`-includes 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`),-spike S2 ToS review (`docs/plans/model-hub-tos-review.md`).--## v2 ruling (owner, 2026-07-28/29)--**Ordering is a consumption property, not a supply property.** The single global-priority list was a product-model error: a source is an asset the user owns, and-how eagerly to spend it is a decision each agent backend makes for itself. So the-spend order moves onto the per-backend supply record — each backend owns an-**ordered subset** of the sources it is eligible for, plus a policy (`follow` =-跟随推荐, server-computed and auto-joining; `custom` = 自定义, user-owned and frozen).--v2 replaces v1 outright because the feature never GA'd (`VIBE_MODEL_HUB_ENABLED`-dormant by default, every backend defaults `direct`, PR #1019). Old config keys are-dropped on load rather than translated. Also folded in: server-authoritative-eligibility, a `needs_action` state class, per-agent `supply_status`, the capability-chain per (agent, model), a dry-run probe, a turn-provenance read contract, and-`adopted_by` on source create.--Cooldown and health stay **source-global**, deliberately: quota exhaustion and-network reachability are properties of the account, not of the agent that happened-to touch it (`core/handlers/model_hub/service.py::_cooldown`).--## v3 handoff notes (single freeze, orchestrator 2026-07-29)--v3 is the batch's only post-v2 contract state. L1 authors this freeze once; every-later lane treats `model-hub-contracts/**` as read-only and implements against it.-An implementation-proven mismatch is escalated for a targeted v4 rather than edited-in a later lane. No v3 term is deferred to v4.--Client-visible changes:--- `GET /api/models/agents` adds `named_agents`, with each enabled named Agent's- effective model and live `supply_status`.-- Hub with no explicit Agent model and no backend default reports a null selection,- null `current`, and null rollup. This is deliberate: no pinned selection means each- turn resolves the model carried by that request. Choosing `builtin_models[0]` would- invent state the user never selected, the same false-state class as a fabricated- source or recovery.-- Direct chain/probe calls and Direct or ambiguously unattributed provenance reads- return documented errors instead of fabricated Hub data.-- Turn provenance adds `outcome: canceled` and `canceled_attempt`; resolution events- allow `model_id: null` only for source-scoped system events.-- Canonical `src_` patterns, closed eligibility reasons, repair confirmations,- credential force, blocked-source re-test, enabled-mapping guard scope, and durable- revocation reconciliation are frozen in `api.md` and the schemas.-- Resolution events remain single records. v3 adds neither affected-backend fan-out- nor 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.--The 2026-07-31 source-refresh amendment is likewise orchestrator-authorized and-owner-vetoable. It reuses the existing discovery commit point: one timestamp now-stamps both the replacement discovered rows and their owning source, so a manual-only-inventory or a failed attempt cannot fabricate freshness. The canonical POST route-returns the updated `Source`; the UI uses that server echo before its sequenced-full-surface read-back.--## Resolved decision, carried forward from v1 (owner, 2026-07-23 10:33)--**Hybrid supply by default + consent-gated experimental hub-held subscriptions.**-Subscription sources default `supply_channel: "native_cli"` (per-turn channel-dispatch; the CLI's own sanctioned OAuth burns the quota); api_key sources are-`"hub"`. Additionally, subscription login INTO the engine (hub-held, incl.-Claude) ships as an **experimental feature behind-`subscription_hub_experimental`** with explicit ban-risk consent (copy: S2 §9)-and per-source opt-in — never enabled silently, always visibly marked. The-`allowed_origins`-style client binding applies to native_cli sources-(sanctioned client only) and to any experimental hub-held subscription.--Everything else reflects S1 findings: runtime-declared OAuth presentation-(S1 gap ③), adapter-owned redacted resolution events with the engine usage feed-disabled (S1 gap ② — the feed leaks inbound keys), model provenance + cooldown-fields, and a standalone managed-dependency manifest/status contract. The v1-freeze item "authoritative ordered priority" survives in v2 as **authoritative-ordered per-backend subset**: the server always re-echoes the full canonical-order after any mutation; clients never compute partial reorders.--## Freeze protocol--- The orchestrator commits these files with message- `docs(model-hub): freeze interface contracts v3` and announces the commit SHA- in every lane brief. From then on: lanes cite, never edit; changes go through- the orchestrator and bump `contract_version`.-- **Targeted v4 process instance trail — entry 2 (v4b).** Following v4a commit- `37285675`, the dedicated commit- `docs(model-hub): scope hub OAuth reauth rollback invariant v4b` is- orchestrator-authorized, evidence-pinned to review finding `3675168031` and- `vibe/model_hub_runtime/state.py:135-166`, and owner-vetoable. It corrects only- the hub-OAuth stable-ref repair invariant; chat messages alone did not unfreeze- these 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.-- **Targeted v4 process instance trail — entry 4 (channel class pass).** Owner- Plan A approval at 2026-07-30 09:47 authorized the class-level correction- proved necessary by the five-stop v4c evidence history, rooted in finding- `3675528561`. The earlier v4a audit missed `adapter-interface.py` and its- global success-implies-ref assertion; this dedicated commit repairs that- omission by splitting the seam per channel, carries the retained-material- discriminator into both producers, and audits every remaining contract file.- It is evidence-pinned, delivered into the implementing lane rather than by- chat, and remains owner-vetoable.-- **Targeted v4 process instance trail — entry 5 (engine health honesty).** The- 2026-07-31 restart incident proved that `runtime-dependency.status.health`- collapsed an installed runtime that had never been demanded into `down`. The- orchestrator authorized this owner-vetoable amendment: the nested runtime- object now carries `contract_version: 4`, adds `not_started`, and exposes a- CSRF-guarded explicit start route without making the status read mutate state.- Existing v3 clients with exhaustive health switches fall through their- unknown-value/default branch until upgraded; no boot-time eager start is added.-- Contract tests (implementation plan §5) validate both directions against- these schemas.--## Required-vs-optional discipline (v4)--Contracts land before implementation, so v2 fields describe a destination the-shipped v1 serializers have not reached yet. The rule that keeps that honest:--- **New contracts are fully required.** `agent-chain.schema.json`,- `probe-result.schema.json` and `turn-provenance.schema.json` describe surfaces- with no v1 implementation, so **every** field is in `required` — including- nullable ones such as `resolved_model_id`, `error` and `via_mapping`, where the- type allows `null` but omission is not permitted. That is the point: a client- reading these never has to distinguish "absent" from "null", and a server that- cannot compute a value has to say so explicitly.-- **Fields grafted onto a live v1 serializer are optional here and REQUIRED at the- API boundary once that serializer lands them.** That covers- `agent-supply.sources` / `supply_status` / `model_supply` / `named_agents` /- `selected_model_id`, `source.created_at`, `source.usage.projected_exhaust_at`- and `resolution-event.severity`. Each such property says so in its own- `description`; the implementation PR flips it to `required` in the same change- that makes it emit.-- **Request shapes are not response shapes.** `PUT …/agents/<backend>/sources`- takes `order` only under `policy: "custom"`, while the response object requires- both fields — spelled out in `api.md` rather than forced through one schema, so a- client never has to send an ignored field to express 跟随推荐.-- **Prefer an unwritable contradiction to a validated one** (added 07-29, review- round 2). Where an invariant can be designed out of the shape, it is: the served- attempt in `turn-provenance` lives in its own field instead of being flagged inside- the attempt array, so "two winners", "the winner is not last" and "the summary names- a source the array never mentions" stop being things a validator or a test has to- catch. Where the shape cannot carry it, a draft-07 conditional does —- `needs_action` requiring `detail_key`, `supply_interrupted` pinning `severity` and- nulling both source endpoints, `outcome` pinning which of `served` /- `failed_attempts` may be populated. Prose invariants are the last resort, and any- that remain name the assertion their implementing lane owes: this lane runs the- contract tests without editing them, so a new semantic test belongs to the- serializer PR that makes the payload real, not here.-- **Round 3 (07-29) applied that rule to the gaps round 2 left in prose.** The- pattern it kept finding was the same one twice: a constraint stated in a- `description` while the shape still permitted its negation. Now conditionals —- `kind: needs_action` pinning `severity: action_required` and its four causes- (a revoked key that validates as `info` is presented as self-healing);- `reachable: true` pinning non-null `source_id` / `model_id` /- `via_mapping` / `latency_ms` and a null `error` (「答了,但不知道是谁答的,另附失败原因」- was a valid probe); `outcome: failed_terminal` and the `terminal_error` slot- beside `served`; every `outcome` branch now pinning the slots it *forbids*, not- just the ones it uses. Two overlapping-vocabulary cases got a **normative- precedence** instead, since no shape can order them: the three- `supply_interrupted` reasons, and `interrupted` before `waiting`.-- **A predicate has exactly one home** (added 07-29, round 3). Round 2 restated the- `waiting`/`interrupted` split in three files and got it wrong in two — 「每个成员都- 需要用户处理」 instead of 「至少一个」 — which made a mixed chain match no value and- suppressed the action-required state. Likewise the 跟随推荐 recommendation rule,- paraphrased in `agent-supply.policy` in a way that excluded the hub-held- subscription the spec admits. Both now point at spec §4.5 / §4.2 and paraphrase- nothing. A determinism rule that two files describe differently is not one.-- **Rounds 4–5 (07-29) closed the shape that was generating the findings.** Round 4- finished what round 3 started: every prose invariant that could become a conditional- became one, some forty of them. Round 5 then found that the *form* of those- conditionals was itself a finding generator, and the mechanism is worth naming- because it is not obvious. Two properties make a one-directional conditional- self-replicating: `if A then B` always leaves `if B then A?` reviewable, and draft-07- `then: {properties: {…}}` **never enforces presence** — `properties` validates only- fields that are actually there, so a conditional constraining an optional field is- silently vacuous exactly when the field is missing. Nine of round 5's sixteen- findings were byproducts of that shape rather than of the design underneath it. So- the fix form is TOTAL, and it is the standard for anything added later: closed enums- instead of prefix patterns (`.+` after a trusted prefix is a naming convention, not a- redaction boundary — it happily matches `models.source.cooldown.network: <raw- upstream body>`); biconditionals instead of implications, or an explicit `$comment`- saying why the converse is deliberately left open; and `required` beside every- non-null `then` constraint. A mechanical presence check guards that last rule, with- two declared exceptions where a frozen v1 example forbids `required` — both- fail-safe absences, and both listed in `api.md` → mechanical guards, never silent.- Deliberate non-constraints go in a `$comment` so the next reader can tell a- judgement from an oversight.-- **Round 6 (07-29) was a different class: contract completeness.** The form fix- held — none of round 6's findings was a strictness byproduct. What it found instead- was prose promising an outcome the payload had no field to carry, and one sequence- the frozen adapter could not execute. Three shapes closed it. `SupplyGap`- (`{backend, model_id, agents}`) gives the (backend, model) starvation set a- declared form, under two keys that differ only in mood — `interrupted_pairs` for- what did happen, `would_interrupt` for what a refusal predicts — because one- predicate has one home even when two routes state it. `OAuthFlow.intent` makes the- terminal-success response a function of the payload rather than of which button the- client remembers pressing, so the add-source loop closes identically through both- creation paths. And `resolution-event.reason: unclassified_error` closes a taxonomy- hole: `state.status: error` is a blocker (`agent-chain` has always counted it with- `needs_action`), so an interruption caused by the last runnable source erroring had- no representable state event — the emitter had to misclassify or stay silent.- It became a fifth CAUSE rather than a ninth kind, which keeps the- reason↔`detail_key` correspondence a bijection and leaves the standing 「four causes- do not imply `kind: needs_action`」 ruling untouched. The sequencing finding is the- one worth remembering as a rule: **a documented sequence must be executable through- the frozen adapter surface.** Credential replacement now provisions a *replacement*- ref, discovers through it, and only then swaps atomically — because- `discover_models` consumes a ref only `provision_credential` can mint, so "validate- before you provision" was unimplementable no matter how much better it reads.-- **Round 7 (07-29) found that the sequence itself was the generator, and retired- it.** Round 6's closing sentence above — the provision → discover → swap ordering —- was correct and still bred four findings, because a step list invites the reader to- ask what happens between any two steps, and every answer is a new step. So the- credential section no longer states steps: it states six INVARIANTS against one- named commit point (atomicity, no revoked-credential window, failure preserves the- prior state, guard before commit, per-channel executability, recovery symmetry), and- the ordering survives as an explicitly **non-normative** illustrative sequence. The- rule generalizes: **where a step list would need a converse for every gap between- steps, write the properties the operation must satisfy and name the single point- where it becomes true.** Two definitions were also collapsed to one home each. The- DELETE guard and the repair guard now read the same 「The supply guard」 section —- computed in the MENU identifier namespace, over EFFECTIVE selections, against- post-change RUNNABLE supply, where "runnable" is the chain classifier's own field- and not `chain_length > 0` (round 6's structural test passed a chain holding one- revoked key). And `SupplyGap.agents` now names the Agents that would actually break- INCLUDING backend-default inheritors, which **reverses round 6's parenthetical** —- recorded as an orchestrator ruling open to owner veto, because round 6's rule- answered 「谁明确写了这个模型」 and therefore returned an empty list on a real- interruption, which is false reassurance where the product owes the user a named- cause and a named victim. The remaining finding was a GRAIN mismatch that default- naming had hidden: 「Agent」 on an event is a backend, while `named_agents` is a- live projection of named Vibe Agents. The two coincide only for a default Agent- whose name happens to equal its backend.-- **Round 7's other class was vocabulary blast radius, and it is now mechanical.**- Round 6 added one cause to two files and left the three other files that mirror that- vocabulary asserting an identity they no longer had — a required field with no legal- value, three times over, each one a documented self-contradiction rather than a gap.- Two mechanisms let it through and both are closed: comparison ran INSIDE each file,- so a third mirror had nothing watching it; and the checker collected `enum` only,- while the new key was pinned as a `const`, so the guard whose whole job was this- check passed vacuously. `const` is now read as an enum of cardinality one, every- shared vocabulary is a registered row in the table below, and the inverse direction- is enforced too: a field whose description names another contract file must appear in- that table or the harness fails. That inverse is the part that stops the class —- detection is by schema STEM, not by the `.schema.json` suffix and not by the word- "mirror", because round 7's own missed claim used neither.-- **Existing examples stay v1-shaped on purpose.** The byte-faithful round-trip- test (`tests/test_model_hub_config.py`) drives the shipped serializer through- every example in `source.schema.json` and `agent-supply.schema.json`, so a v2- field in those examples would assert that dormant v1 code already speaks v2.- Worked v2 payloads live in `api.md` instead, where they document the target- without lying about the present.-- Two v2 enum values (`source.state.status: needs_action`,- `resolution-event.kind: needs_action`) are likewise targets: today's loader- whitelist in `config/v2_config.py` rejects the former until the serializer PR- widens it. Called out inline in the schemas.--## Vocabulary mirrors and their blast radius--draft-07 has no cross-file `$ref` the contract test can resolve, so a vocabulary shared-by two contracts is duplicated by hand. Every such duplication is registered here with-a MECHANICAL RULE, and the harness evaluates the rule rather than trusting the prose —-including the inverse direction: **a field whose description names another contract file-must appear in this table.** Adding a value to a home field is therefore never a local-edit; this table is the list of files that edit reaches.-The executable source of this table is `mirror-registry.json`; the contract harness-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 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, 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`; `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`) | `agent-supply.schema.json` → `sources.eligibility[].process_availability_reason` (same bare token); `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 the non-equality rules differ:--- **`equality`** — the sets are identical, in both directions. M6 carries one declared- superset: `resolution-event.agent` is the home set plus `system`, used for a- source-scoped non-turn operation. A documented superset is checked as- `home ∪ {declared extras}`, so a fourth backend appearing there alone still fails.-- **`projection`** — the mirror is a stated function of the home, because the two live- at different grains. M2: `health` carries the health half only, so `active`/`standby`- collapse into `healthy`. M5: one taxonomy at two grains — the backend rollup adds- `degraded` (serving, but via fallback), and `model_supply_state` exists only for- `outcome: no_candidate`, where `ok` is unreachable by construction. Both projections- are executable, so widening the home without deciding where the new value lands fails.-- **`partition`** — M3 is not a subset relation but a total classification: every- `resolution-event.reason` must be either an attempt failure (mirrored) or in a- declared exclusion, and never both. Two exclusions exist. The three agent-scoped- causes are **derived from the schema**, not restated here — they are exactly the enum- 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. A- new `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 across two field conventions: the same bare- classifier in chain and AgentSupply inventory, plus an i18n key in the probe- error slot. Per-target one-to-one maps are checked in both directions; adding a- spelling at any of the three surfaces fails until the row binds it.-- **`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- rule, not a shared value set. A row with neither rule nor reason is itself a failure.+# Model Hub contracts++Status: **FINAL v5 shape, implementation-gated (2026-08-09)**.++These files describe the terminal contract for Model Hub before first release. There is+no v4-to-v5 data migration, compatibility reader, conversion transaction, or version+discriminator: Model Hub has not shipped. `contract_version` is 5 wherever a versioned+object exists.++The contracts and their consumers must coexist on one tested PR head before Model Hub+can be enabled. CI evaluates that head, not individual commits. A green intermediate+commit is not evidence that the complete final protocol has landed.++## Product model++- Sources are upstream assets. A Source never owns ordering.+- Gateway stores one explicit Source order per backend and one exact ordered Route chain+ per menu model. Neither has a `follow | custom` or other policy discriminator.+- Add Source runs the sole placement policy once and persists its positions. Runtime+ never repeats placement, model matching, vendor matching, or substitution.+- Runtime walks the stored Route hops verbatim, rechecking only whether each exact hop is+ runnable now and whether a failure permits fallthrough.+- A hop whose upstream `model_id` differs from its menu model is an explicit configured+ mapping. There is no separate mapping object or runtime mapping event.+- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat`.+ `base_url` already distinguishes official endpoints from relays and self-hosted+ gateways; no fourth protocol value is defined.+- Source health is global. Native CLI process availability and exact-hop integrity are+ live execution facts and never silently rewrite stored configuration.+- Supply state is pull-oriented. Successful fallback is silent; Gateway and Usage are+ the user-visible inspection surfaces.++Normative routing behavior lives only in `docs/plans/model-hub.md`: §4.2 owns Add-time+placement, §4.3 owns exact-chain execution and credential failures, §4.5 owns state,+turn copy, and guarded mutation envelopes, and §6 owns native-config import actions.+Contract prose points to those authorities and does not add branches.++## Invariants++1. Plaintext upstream credentials never appear in config, API payloads, events, logs,+ or Agent runtime configuration. Hub-held material is referenced by an opaque engine+ credential id; native credentials remain in the sanctioned CLI store.+2. Every persisted Source has a protocol proved by a real upstream response before+ commit. Vendor names, Base URLs, and manual hints may order probes but cannot create+ a saved protocol value.+3. Every Source/model reference is canonical and referentially valid at write time.+ Unchanged stale Route hops may be retained or reordered, but new or changed pairs+ must validate.+4. Source deletion atomically removes its id from every backend Source order and every+ exact Route chain, preserving survivor order. Serialization and reload reject a+ dangling Source id.+5. Given the same stored configuration and request, the selected Route hops are stable+ across time, quota, and health changes. Live runnability and current execution+ position may change; Route membership and order may not.+6. Every Source model id is unique within that Source. The final model item shape is+ `{id, origin, reasoning_efforts, display_name?, discovered_at?}`; effort lists are+ editable capability declarations, may be empty, and have no selected/default item.+7. A backend has at most one `native_cli` Source. Additional accounts are Hub-held+ Sources.+8. Direct mode and a Native hop are distinct. Direct bypasses Gateway for the backend;+ Native is one configured hop inside Gateway mode.++## Authority and mirror guard++`mirror-registry.json` is the executable index for closed vocabularies and decision+tables. The generated contract test reads the live schemas, specification, adapter+copies, and locale/type consumers in the same run. It enforces both directions:++- every registered contract or copy enum resolves to exactly one authority;+- every authority row has at least one registered consumer;+- cross-file vocabulary projections and mappings remain total;+- orphan values and orphan branches fail.++The gate does not accept a missing external snapshot. If a future consumer must use one,+the snapshot carries the current artifact fingerprint and a mismatch fails before any+comparison. A gate may not report success by comparing stale input with itself.++## Version closure++The terminal value 5 must coexist in these ten locations on the same tested head:++- `mirror-registry.json`+- `agent-chain.schema.json`+- `probe-result.schema.json`+- `runtime-dependency.schema.json`+- `turn-provenance.schema.json`+- `core/handlers/model_hub/service.py`+- `core/handlers/model_hub/provenance.py`+- `tests/test_model_hub_config.py`+- `tests/test_model_hub_api.py`+- `tests/test_model_hub_l3.py`++The three-value protocol closure includes `source.schema.json`, `adapter-interface.py`,+and the byte-identical `core/handlers/model_hub/adapter.py` on the same tested head.++After implementation lands, these contracts are read-only for downstream lanes. An+implementation-discovered mismatch is reported to the orchestrator for a targeted+revision; the discovering lane does not reinterpret or edit the contract in place.## Files-| File | Consumers |+| File | Authority and consumer role || --- | --- |-| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action`, immutable `created_at`, optional `usage.projected_exhaust_at`. Targeted v4 adds required-nullable `last_discovered_at`: the latest successful full inventory replacement, never a failed-attempt time. 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`. The channel class pass extends the complete eligibility inventory with current-chain membership and process availability, retaining non-members so one projection serves both the Agent row and all-sources drawer. |-| `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. Remains presentation-only: channel is public, while engine credential refs and retained-material disposition stay on the service seam because the UI never consumes them. |-| `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. Targeted v4 keeps the shared envelope at v3 while documenting channel truth, the five-way OAuth repair partition, complete AgentSupply source signals, explicit skipped custom orders, mapping/menu enrollment, and the single source refresh/recovery route. |-| `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). v1.3 makes OAuth flow success channel-aware and adds the total retained-material disposition. The contract and `core/handlers/model_hub/adapter.py` remain byte-identical by mechanical guard. |--## Full channel audit (owner Plan A)--The audit question was fixed: does this file assume every supply/login path is-Hub-engine-owned, or collapse source-global state into serving-process truth?--| File | Disposition |-| --- | --- |-| `README.md` | **Fixed.** Records the missed adapter seam, the owner authorization chain, M8's AgentSupply spelling, and this complete audit. |-| `adapter-interface.py` | **Fixed.** Replaces global success/ref semantics with Hub and native branches; adds the five retained-material placements. |-| `agent-chain.schema.json` | **Audited clean.** v4a already keeps channel, health, availability, and runnability orthogonal at every chain position. |-| `agent-supply.schema.json` | **Fixed.** Complete per-source inventory now carries current-chain membership plus the per-process native blocker without dropping non-members. |-| `api.md` | **Fixed.** Adds the five-arm repair consumer contract, source-signal grain, `skipped_by`, and mapping enrollment; existing probe text already says readiness is not completion. |-| `migration-scan.schema.json` | **Audited clean.** Each import item already declares `supply_channel`; scanning native config never claims engine ownership. |-| `mirror-registry.json` | **Fixed.** M8 binds chain, AgentSupply, and probe spellings as one process-availability concept. |-| `oauth-flow.schema.json` | **Fixed.** Pins the user-wire/service-seam exclusion and makes source binding channel-neutral; refs remain off the wire. |-| `opencode-overlay.md` | **Audited clean.** Provider/model identifiers remain source- and channel-independent, so no gateway ownership is implied. |-| `probe-result.schema.json` | **Audited clean.** Hub records completion evidence; native records readiness with null latency in both directions. |-| `resolution-event.schema.json` | **Audited clean.** Events classify observed attempts and state changes without deriving process availability from global health. |-| `runtime-dependency.schema.json` | **Audited clean.** It describes the optional managed Hub engine itself, not native CLI availability or login ownership. |-| `source.schema.json` | **Fixed.** The existing channel/ref and global-health boundaries hold; `oauth_expired` now explicitly covers unknown retained placement. |-| `turn-provenance.schema.json` | **Audited clean.** Every attempt-bearing slot already carries `channel`; exact attribution never assumes gateway execution. |-| `core/handlers/model_hub/adapter.py` | **Fixed mechanically.** Byte-identical v1.3 copy of the contract seam. |-| `core/handlers/model_hub/native_oauth.py` | **Fixed.** Every produced flow is tagged `native_cli`, carries no engine ref, and pins retained material to `none`. |-| `vibe/model_hub_runtime/adapter.py` | **Fixed.** Every Hub terminal path reports a proved disposition and cleanup retains the ref until both auth-file deletions are confirmed. |--## Security invariants (from S1/S2, non-negotiable)--1. No credential material ever appears in any payload defined here —- sources expose `credential_ref` only; events are adapter-redacted.- Clarified 07-23 12:10 (L4 finding): non-reversible display data IS- permitted — `account_label` (subscription identity from the sanctioned- auth surface) and `masked_credential` (≤7-char prefix + "…" + last 4,- computed once at provisioning, never re-derivable) exist precisely so- the UI never needs anything stronger.-2. The engine's own usage feed stays disabled; events originate from our- adapter (S1 gap ②). Extended in v2: `ProbeResult.error` and every- `detail_key` are i18n keys — classified outcomes only, never raw upstream- error bodies, on the probe path as much as the event path.-3. `allowed_origins`-style client binding is enforced in code: subscription- sources are never eligible for agents outside their sanctioned client- (S2; server-side enforcement exists for Claude anyway). In v2 this is the- same rule the server now publishes as `sources.eligibility` — one- implementation, projected to the UI, never re-derived there. **The binding is- keyed on vendor and holds in both channels**: `subscription_hub_experimental`- unlocks *how* a subscription is delivered, never *who* may consume it, so a- hub-held Anthropic subscription is eligible for Claude Code alone (spec §4.4- matrix, one row per vendor×channel precisely so this cannot be read loosely).+| `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. |+| `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |+| `agent-chain.schema.json` | Read projection of exact stored hops plus current runnability, blockers, retry metadata, and model supply state. |+| `probe-result.schema.json` | Saved recovery probes, Add-time connectivity/protocol observation, and route probes. |+| `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. |+| `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |+| `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |+| `migration-scan.schema.json` | Copy-only import of existing native CLI/provider configuration; not an internal contract migration. |+| `runtime-dependency.schema.json` | Managed local Gateway asset, lifecycle, and health. |+| `api.md` | Routes, envelopes, exact Source order and Route-chain writes, guards, OAuth/import results, provenance, and runtime status. |+| `opencode-overlay.md` | Stable OpenCode provider/model identifiers and exact configured-hop overlay behavior. |+| `adapter-interface.py` | Adapter protocol, observation, credential, discovery, invocation, cleanup, and classification boundary. |+| `mirror-registry.json` | Executable authority/mirror registry and terminal contract version. |+| `README.md` | This ownership, version-closure, and contract-index document. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex a737142e4..aa5bc49ac 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -1,61 +1,11 @@-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.5 (2026-07-31).--v1.5 changelog (honest lazy-start health):-- ``EngineHealth.NOT_STARTED`` distinguishes an installed runtime that has not- been demanded in this service lifetime from one that started and went down.--v1.4 changelog (ref-keyed cleanup convergence):-- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an- already-converged cleanup, making journal replay idempotent across crashes.--v1.3 changelog (owner-approved channel class pass):-- ``OAuthFlowState.channel`` makes Hub and native CLI success semantics explicit:- Hub success carries an engine credential ref; native success never does.-- Hub flows expose a total five-way retained-material disposition for repair- decisions. Native flows pin that disposition to ``none`` because CLI-owned- login material never crosses this engine seam.-- Retained refs are exposed only for flow-owned or orphaned material. Foreign- and unknown placements deliberately expose no actionable handle.-- ``cleanup_orphaned_oauth_material`` is the ref-keyed retry seam: it confirms- both auth-file deletions before revoking the only retained handle.--v1.2 changelog (L1 implementation findings — credential & model lifecycle):-- Secret provisioning path closed: ``provision_credential`` moves an API-key- secret (transient parameter, never logged, never persisted by L2) into the- ENGINE-OWNED store and returns the opaque ``credential_ref``;- ``revoke_credential`` releases it on source deletion. L2's config persists- refs only. Flow: provision → discover (probe) → persist Source → sync.-- ``SourceBinding.model_ids`` added: the declared supply list (discovered +- manual custom entries) — required by the engine's generic/API-key config.-- ``discover_models`` re-signed as a PROBE (vendor/protocol/base_url/- credential_ref) so discovery works BEFORE registration; it no longer takes- a ``source_id``.--v1.1 changelog (L1 review findings, routed via orchestrator):-- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes- the pre-created (pending) ``source_id``; a Hub-channel ``success``- ``OAuthFlowState`` carries the resulting opaque ``credential_ref``. The- later native channel uses the same flow state without an engine ref.- Concurrent same-vendor flows can never cross-bind.-- Client binding made enforceable at the engine boundary:- ``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +- ``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters- first — defense in depth per README invariant 3).--Canonical text: docs/plans/model-hub-contracts/adapter-interface.py (this file).-Dual-copy rule: BOTH lane L1 and lane L2 copy this file VERBATIM to-``core/handlers/model_hub/adapter.py`` in their branches (byte-identical, so the-merge is a no-op). L2 owns the in-repo copy on master thereafter. Any change-routes through the orchestrator and bumps the version line above.--Seam semantics (from spike S1, binding):-- L1 implements this protocol (engine facade). L1 must NOT classify errors,- retry, or fall back across sources — per-source invocation only; the- engine's internal fallback and usage feed stay disabled/bypassed.-- L2 consumes it: picks exactly one source per call (priority resolution),- classifies ``RawCallOutcome`` into the canonical taxonomy, emits redacted- resolution events.-- No credential material may appear in any field defined here.+"""Model Hub EngineAdapter interface. FINAL CONTRACT v5 (2026-08-09).++This file is the canonical adapter boundary and must remain byte-identical to+``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:+credential custody, protocol observation, model discovery, OAuth, invocation,+and cleanup. It never chooses or reorders Route hops, classifies cross-Source+fallthrough, or exposes credential material. Contract changes route through the+orchestrator and land with every affected consumer on the same tested head."""from __future__ import annotations@@ -64,6 +14,8 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence+# authority-consumer: protocol anthropic openai_responses openai_chat+class EngineHealth(str, Enum):OK = "ok"@@ -89,7 +41,7 @@ class SourceBinding:source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "openai_compatible"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on this@@ -175,9 +127,8 @@ class OAuthFlowState:error_key: str | Noneexpires_at_iso: str | Nonecredential_ref: str | None- # Defaults preserve pre-v1.3 call sites until the follow-up service-consumer- # lane supplies the discriminator explicitly. Channel-aware producers MUST- # set all three fields.+ # Channel-aware producers set all three fields explicitly. Defaults keep the+ # dataclass construction total for presentation-only adapter implementations.channel: Literal["hub", "native_cli"] = "hub"retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONEretained_credential_ref: str | None = Nonediff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex c4d19db5b..7e6fc0073 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": "v4 (2026-07-30 targeted amendment): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by the server's one per-source supply derivation. That derivation applies an explicit mapping first, otherwise resolves a vendor-native fixed-menu alias against discovered inventory only, then tests source capability. 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. 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.",+ "description": "Read projection of one stored per-model Route chain. Items preserve the exact configured Source/model pairs and order; runtime adds only live health, runnability, blocker, and retry annotations. Cooling, missing, model-unsupported, Source-blocked, and process-unavailable native_cli hops remain visible at their configured positions. Runtime never derives membership, resolves aliases, or substitutes a model.","type": "object","required": ["contract_version", "backend", "model_id", "chain", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 4 },+ "contract_version": { "const": 5 },"backend": { "enum": ["claude", "codex", "opencode"] },"model_id": {"type": "string",@@ -22,7 +22,7 @@"additionalProperties": false,"allOf": [{- "$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.",+ "$comment": "v5 (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,7 +35,7 @@}},{- "$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.",+ "$comment": "v5 (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" },@@ -52,7 +52,7 @@}},{- "$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.",+ "$comment": "v5 (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" },@@ -86,7 +86,7 @@}},{- "$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.",+ "$comment": "A non-null process-availability marker is legal at every Source health and means this process cannot launch the native_cli hop. It always forces runnable false. Hub hops are definitionally process-available, so the marker is impossible there.","if": {"properties": { "reason": { "type": "string" } },"required": ["reason"]@@ -100,7 +100,7 @@}},{- "$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.",+ "$comment": "v2 (07-29, review round 4), availability-separated in v5: `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"]@@ -164,7 +164,7 @@},"supply_state": {"enum": ["ok", "waiting", "interrupted"],- "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."+ "description": "The model-scoped supply state. `ok` means at least one configured hop is runnable. Otherwise `waiting` means the chain is non-empty and every hop is cooling, not retry-ready, and process-available; `interrupted` means the chain is empty or at least one blocker needs action, including process-unavailable native_cli at any Source health. Cooldown plus native_cli_unavailable is interrupted, never waiting."}},"allOf": [@@ -190,7 +190,7 @@}},{- "$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.",+ "$comment": "v5: 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": {@@ -232,7 +232,7 @@}},{- "$comment": "v4 (07-30 native-alias amendment): Codex has no built-in upstream-id rewrite today, so `via_mapping:false` still means byte-identical and therefore null for that backend. Claude differs: its fixed menu includes stable aliases that may resolve to a dated discovered id without becoming an explicit user mapping.",+ "$comment": "v5 (07-30 native-alias amendment): Codex has no built-in upstream-id rewrite today, so `via_mapping:false` still means byte-identical and therefore null for that backend. Claude differs: its fixed menu includes stable aliases that may resolve to a dated discovered id without becoming an explicit user mapping.","if": { "properties": { "backend": { "const": "codex" } }, "required": ["backend"] },"then": {"properties": {@@ -250,7 +250,7 @@}},{- "$comment": "v4 (07-30 native-alias amendment): a non-mapped Claude rewrite is legal only in the vendor-native Claude identifier family. The server additionally proves same-family/version selection against discovered inventory; JSON Schema cannot compare the requested model_id with each row or inspect the source inventory.",+ "$comment": "v5 (07-30 native-alias amendment): a non-mapped Claude rewrite is legal only in the vendor-native Claude identifier family. The server additionally proves same-family/version selection against discovered inventory; JSON Schema cannot compare the requested model_id with each row or inspect the source inventory.","if": { "properties": { "backend": { "const": "claude" } }, "required": ["backend"] },"then": {"properties": {@@ -279,7 +279,7 @@],"examples": [{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","model_id": "claude-opus-4-6","chain": [@@ -307,7 +307,7 @@"supply_state": "ok"},{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","model_id": "claude-opus-4-5","chain": [@@ -325,14 +325,14 @@"supply_state": "ok"},{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","model_id": "claude-haiku-4-5","chain": [],"supply_state": "interrupted"},{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","model_id": "gpt-5.3-codex","chain": [@@ -350,7 +350,7 @@"supply_state": "waiting"},{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","model_id": "gpt-5.6","chain": [@@ -368,7 +368,7 @@"supply_state": "interrupted"},{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","model_id": "claude-sonnet-4-5","chain": [diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 44cd46749..b28744fc1 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/agent-supply.schema.json","title": "AgentSupply",- "description": "Per-backend supply strategy and live status (spec §4.2, frames V6 01–04 / M01–M02). v3 keeps the spend order at the backend grain and adds the enabled named-Agent projection used to attribute model supply honestly.",+ "description": "Per-backend Gateway configuration and live supply projection. It exposes explicit Source order, menu metadata, model-supply state, and enabled named-Agent attribution without deriving Route membership.","type": "object","required": ["backend", "mode", "menu_kind"],"additionalProperties": false,@@ -10,7 +10,7 @@"backend": { "enum": ["claude", "codex", "opencode"] },"mode": {"enum": ["hub", "direct"],- "description": "中枢/直连. Existing users stay direct until they migrate; fresh installs default hub (plan §4). Under Option 1, hub mode for claude still consumes the subscription via the native channel per turn."+ "description": "Gateway or Direct. Existing installations start Direct until the user switches; fresh installations default Gateway. A native_cli Source is one configured Gateway hop and is distinct from Direct mode."},"menu_kind": { "enum": ["fixed", "open"] },"selected_by_agent": {@@ -26,30 +26,26 @@"selected_model_explicit": { "type": "boolean", "description": "TRUE iff `selected_model_id` originates from the user's explicit configuration request; FALSE means no explicit model selection, including a resolver-picked value or no selected model." },"sources": {"type": ["object", "null"],- "description": "This backend's source order — the ordered SUBSET of sources it spends, plus the policy that governs the order (spec §4.2). Replaces the removed global priority contract. Optional in this schema only because the frozen legacy examples predate it; it is REQUIRED at the API boundary. null while mode=direct.",- "required": ["policy", "order"],+ "description": "This backend's explicit Gateway Source order. It is stored configuration and an Add-time placement input; runtime model execution reads the exact per-model Route chain instead of deriving one from this order. There is no follow/custom or other policy discriminator. It is non-null in Gateway mode and null in Direct mode.",+ "required": ["order"],"additionalProperties": false,"properties": {- "policy": {- "enum": ["follow", "custom"],- "description": "follow = 跟随推荐 (default): the server computes `order` from the recommendation rule and newly added eligible sources join automatically. THE RULE IS NOT RESTATED HERE. It lives in spec §4.2 under 'document verbatim, implement verbatim', with three ordered clauses plus the channel nuance (a native_cli and a consented hub-held subscription of the same own vendor share the first slot, native_cli first), the exhaustive-over-eligible-sources claim that makes auto-join safe, and the absent-`created_at` half-rule in source.schema.json. Round 2 tried to summarise it in one parenthesis and produced something both incomplete and misleading — it read as if only a native_cli subscription could hold the first slot, quietly excluding the hub-held case the spec explicitly admits. A determinism rule that two files describe differently is not deterministic, so this field points at the one home instead of keeping a second copy that can drift. custom = 自定义: a user-owned frozen subset; new sources do NOT join and the UI hints 「有新来源未启用」. Any manual edit while in follow forks the record to custom; 「恢复推荐顺序」 returns it to follow. The server never reorders a custom list (spec §2 promise 4)."- },"order": {"type": "array",- "description": "Enabled source ids, position 0 = spend first. A SUBSET, not a permutation: sources this backend is ineligible for, or that the user removed, are absent. Authoritative — the server always re-echoes the full canonical order after any mutation; clients never compute partial reorders.",+ "description": "Configured Source ids, position 0 first. A subset, not a permutation: configuration-ineligible Sources or Sources the user removed are absent. The server re-echoes the full canonical order after mutation; clients never compute a partial reorder. Add-time placement is owned only by model-hub.md §4.2 and never reruns during a request.","items": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },"uniqueItems": true},"eligibility": {"type": ["array", "null"],- "description": "v2: server-authoritative per-source inventory, one entry per existing source (spec §4.4). Eligibility makes the UI chokepoint isSourceEligible (ui/src/components/settings/models/menus/identifiers.ts, self-documented as ESCALATED) a pure projection instead of a second hand-written copy of the compatibility matrix. The channel class pass adds two request-grain signals to the SAME complete inventory: `in_current_model_chain` says whether this source supplies the selected route's current model, and `process_availability_reason` carries the serving process's native CLI readiness blocker. Keeping non-members with `in_current_model_chain: false` is load-bearing: embedding only AgentChain would omit an in-order source that does not supply the current model, taking the drawer's availability fact with it. REQUIRED AND NON-NULL whenever `sources` is an object (07-29, review round 5) — see the conditional at the bottom of this file. Mechanical API guards enforce one row per EXISTING source, every id in `order` present with `eligible: true`, and both new signal fields present on every row once the serializer lands them.",+ "description": "Server-authoritative configuration eligibility, one row per existing Source. It makes UI eligibility a projection rather than a second compatibility matrix. `in_current_model_chain` reports whether the selected model's stored Route references the Source; `process_availability_reason` reports native CLI readiness independently of Source health. Required and non-null whenever sources is an object.","items": {"type": "object","required": ["source_id", "eligible"],"additionalProperties": false,"allOf": [{- "$comment": "v2 (07-29, review round 4): `eligible: false` ⇒ a non-null key, and `eligible: true` ⇒ null, both as conditionals. This projection exists so the UI's isSourceEligible chokepoint stops being a second hand-written copy of the compatibility matrix — but an entry that says 不适用 without saying why hands the drawer a dead row: no explanation, and no way to pick between 「换个客户端」, 「OpenCode 只支持 API Key」 and 「需要先同意实验项」, which are three different remedies. The converse matters as much: a key on an eligible source would render an unavailability reason next to a source that is available.",+ "$comment": "Final v5: `eligible: false` implies the sole non-null reason key and `eligible: true` implies null. The only configuration-ineligible case is a native subscription outside its sanctioned backend. The converse prevents an unavailable label on an eligible Source.","if": {"properties": { "eligible": { "const": false } },"required": ["eligible"]@@ -59,9 +55,7 @@"properties": {"reason_key": {"enum": [- "models.eligibility.subscription_wrong_client",- "models.eligibility.opencode_api_key_only",- "models.eligibility.consent_required"+ "models.eligibility.subscription_wrong_client"]}}@@ -85,15 +79,13 @@"reason_key": {"enum": ["models.eligibility.subscription_wrong_client",- "models.eligibility.opencode_api_key_only",- "models.eligibility.consent_required",null],- "description": "Closed i18n-key vocabulary explaining an ineligible source. REQUIRED and non-null when `eligible` is false, null when it is true. A new eligibility cause therefore requires an explicit contract and locale change."+ "description": "Closed i18n-key vocabulary explaining native subscription use outside its sanctioned backend. Required and non-null when `eligible` is false, null when it is true. Hub-held Sources are cross-backend eligible. A new cause requires the authority registry, contract, and locale consumers to change together."},"in_current_model_chain": {"type": ["boolean", "null"],- "description": "Membership in the CAPABILITY chain for this AgentSupply record's `selected_model_id`, at the same routed-Agent grain. true includes blocked members because availability does not change capability; false is the explicit not-supplying-selected-model flag that keeps a source visible to the drawer; null exactly when `selected_model_id` is null. OPTIONAL here and REQUIRED at the API boundary with the serializer, so frozen v1 examples remain byte-faithful."+ "description": "Whether the selected model's stored Route references this Source. true includes blocked hops because availability does not rewrite configuration; false keeps non-members visible; null exactly when selected_model_id is null."},"process_availability_reason": {"enum": ["native_cli_unavailable", null],@@ -108,23 +100,9 @@"supply_status": {"type": ["string", "null"],"enum": ["ok", "degraded", "waiting", "interrupted", null],- "$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.",+ "$comment": "This rollup is process-aware, not health-only. A process-unavailable native hop makes a no-runnable chain interrupted rather than waiting.","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",- "description": "fixed-menu backends only; per-agent scope (spec §4.3 step 1). Absent entry = 跟随原生 (identity). A mapping chooses a MODEL, never a source.",- "items": {- "type": "object",- "required": ["builtin_id", "target_model_id", "enabled"],- "additionalProperties": false,- "properties": {- "builtin_id": { "type": "string", "description": "real built-in model id, e.g. claude-opus-4-6" },- "target_model_id": { "type": "string" },- "enabled": { "type": "boolean" }- }- }- },"menu": {"type": ["object", "null"],"description": "open-menu backends only (frame V4 05r).",@@ -142,7 +120,7 @@},"model_supply": {"type": ["array", "null"],- "description": "v2: cheap per-menu-item chain summary so the 模型菜单 drawer can flag 「无来源可供」 without one chain query per row (spec §4.6). Read-only projection; the authoritative chain is GET /api/models/agents/<backend>/chain.",+ "description": "Per-menu-item configured Route summary so the model menu can flag an empty chain without one chain query per row. Read-only projection; the authoritative chain is GET /api/models/agents/<backend>/chain.","items": {"type": "object","required": ["model_id", "chain_length"],@@ -155,8 +133,8 @@"chain_length": {"type": "integer","minimum": 0,- "$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`."+ "$comment": "Configuration visibility is not candidate availability. Every stored hop remains counted regardless of live runnability.",+ "description": "Length of the exact configured Route chain, including cooling and process-unavailable native CLI hops. It is not a count of currently runnable candidates. Zero marks a structurally empty Route; live blockers appear through supply_status."}}}@@ -172,7 +150,7 @@"name": { "type": "string", "minLength": 1 },"effective_model_id": {"type": ["string", "null"],- "description": "The Agent's explicit model in the caller-facing menu identifier namespace. null is retained only for compatibility with isolated callers that do not project the Agent catalog."+ "description": "The Agent's explicit model in the caller-facing menu identifier namespace. null means the Agent has no explicit model."},"supply_status": {"enum": ["ok", "degraded", "waiting", "interrupted", null],@@ -198,7 +176,7 @@},"allOf": [{- "$comment": "v2 (07-29, review round 4; completed in round 5): SWEEP of the fields that direct mode does not have, so the drawer can never render hub state for a backend writing its own settings.json. Round 4 swept the SENTENCE 'null when mode=direct' and caught five fields; round 5 found the sixth, `model_supply`, which states its hub-onlyness a different way ('per-menu-item CHAIN summary') and therefore escaped a grep-shaped sweep — the exact failure the round-4 note warned about one line later ('naming three of them would leave the fourth writable'). Lesson recorded rather than just patched: sweep by what a field MEANS, not by the phrasing it happens to use. `model_supply` is not merely redundant in direct mode, it is actively wrong: `chain_length` counts sources in this backend's `order`, and direct mode has no order, so every row would carry `chain_length: 0` and the menu would flag 「无来源可供」 on every model the native CLI supplies perfectly well. FOUR fields are deliberately NOT pinned by mode, recorded so the next reviewer can tell judgement from oversight: `mappings`, `menu`, `builtin_models` and `standard_vendors` are the user's MENU configuration, not hub runtime state. They survive a mode switch on purpose — a direct-mode Claude still has built-in models and still has whatever mapping table the user set up, which becomes active again the moment they migrate to hub. Zeroing them on `mode` would delete user configuration on a switch, contradicting the non-destructive copy-only migration promise (spec §5).",+ "$comment": "Direct mode has no Gateway execution projection. Menu metadata remains available so switching modes is reversible, while Source order, supply state, and chain summaries are null.","if": { "properties": { "mode": { "const": "direct" } }, "required": ["mode"] },"then": {"properties": {@@ -217,7 +195,7 @@}},{- "$comment": "v4 Hub-mode half. `sources`, `model_supply`, and `named_agents` are non-null when present. Presence is deliberately enforced at the API boundary rather than here so the frozen legacy examples remain valid. The selection fields are deliberately NOT constrained non-null because isolated service callers may not project the Vibe Agent catalog.",+ "$comment": "Gateway mode exposes non-null Source, model-supply, and named-Agent projections. Selection fields may remain null when no routed Agent is projected.","if": { "properties": { "mode": { "const": "hub" } }, "required": ["mode"] },"then": {"properties": {@@ -290,7 +268,7 @@}},{- "$comment": "v2 (07-29, review round 4): menu shape ⇒ which menu fields exist. `menu` is open-menu only, `mappings` and `builtin_models` are fixed-menu only, `standard_vendors` is opencode only — four prose-only scopings, all four writable until now. These are the fields the UI branches on to decide whether to render a checkbox list or a mapping table, so a record carrying both leaves that choice to whichever field the component happens to read first.",+ "$comment": "Fixed-menu backends expose their built-in model catalog; open-menu state and provider metadata are null.","if": { "properties": { "menu_kind": { "const": "fixed" } }, "required": ["menu_kind"] },"then": {"properties": {@@ -303,8 +281,7 @@"if": { "properties": { "menu_kind": { "const": "open" } }, "required": ["menu_kind"] },"then": {"properties": {- "builtin_models": { "type": "null" },- "mappings": { "maxItems": 0 }+ "builtin_models": { "type": "null" }}}},@@ -318,7 +295,7 @@"then": { "properties": { "menu_kind": { "const": "fixed" } } }},{- "$comment": "v2 (07-29, review round 5): a `sources` object ⇒ a real `eligibility` array. `eligibility` sat optional AND nullable inside a container that only a v2 serializer can emit, which made the field's own reason for existing waivable: it exists so the UI chokepoint `isSourceEligible` becomes a pure projection instead of a second hand-written copy of the compatibility matrix, and a null there sends the drawer straight back to computing the matrix itself — the duplicate this contract was written to delete, restored by omission. Nothing blocks the server from computing it: `sources` being non-null already means hub mode with a resolved order, and eligibility is a pure function of the source set and this backend (spec §4.4). Note the nesting is what makes this safe — the top-level `sources` stays optional for the byte-faithful v1 round-trip, so this fires only on records that already carry v2 shape. INVARIANT NOT EXPRESSIBLE HERE, and named rather than dropped: every id in `order` MUST appear in `eligibility` with `eligible: true` — you cannot spend a source this backend is not eligible for, and 'one entry per existing source' makes the coverage half a definition, not a preference. Draft-07 cannot compare one array's items against another's without `$data`, so the guard is mechanical instead of schematic (api.md → Serializer completeness). Stating it here so the next reviewer reads a known limit rather than an oversight.",+ "$comment": "A non-null sources object always carries a real eligibility array. The API guard enforces one row per existing Source and requires every id in order to have eligible=true; draft-07 cannot compare the two arrays directly.","if": { "properties": { "sources": { "type": "object" } }, "required": ["sources"] },"then": {"properties": {@@ -337,7 +314,6 @@"backend": "claude","mode": "hub","menu_kind": "fixed",- "mappings": [ { "builtin_id": "claude-opus-4-6", "target_model_id": "glm-5.2", "enabled": false } ],"menu": null,"builtin_models": ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],"standard_vendors": null@@ -346,7 +322,6 @@"backend": "opencode","mode": "hub","menu_kind": "open",- "mappings": [],"menu": { "view": "featured", "checked": ["anthropic/claude-opus-4-6", "openai/gpt-5.6", "zhipuai/glm-5.2", "zhipuai/glm-5.2-air"] },"builtin_models": null,"standard_vendors": ["anthropic", "deepseek", "github-copilot", "google", "groq", "kimi", "minimax", "mistral", "moonshot", "openai", "openrouter", "together", "xai", "zhipuai"]diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex ddaa71b4d..824fc4056 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1,52 +1,52 @@# Model Hub — REST API contract-Status: **FROZEN v4 (targeted)**. All endpoints live under `/api/models/`.+Status: **FINAL v5 (2026-08-09)**. All endpoints live under `/api/models/`.-Success envelope: `{ok: true, contract_version: 3, ...}`.+Success envelope: `{ok: true, contract_version: 5, ...}`.Failure envelope:-`{ok: false, contract_version: 3, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 5, error: <machine_code>, detail?: <i18n_key>}`.`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. Targeted v4 amendments version their changed nested-schema objects independently; the channel class pass also tightens the service-side-OAuth seam and adds derived fields to the existing AgentSupply/source-creation-responses without changing the envelope version.+The shared envelope and every versioned nested contract use terminal version 5. Model+Hub has not shipped, so there is no internal contract migration or compatibility path.## Route table| Method and path | Request → response | Normative notes || --- | --- | --- || GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Array order is never a spend order. |-| POST `/api/models/sources` | `SourceCreate` → `{source: Source, adopted_by: AdoptedBy[], skipped_by: SkippedBy[]}` | The server assigns `id` and immutable `created_at`; plaintext keys are transient. |-| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?}` → `{source: Source}` | Metadata only. |-| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → `{source, recovered, interrupted_pairs}` | API-key replacement. The optional `force` is a JSON body field, never a query parameter. |+| POST `/api/models/sources` | `SourceCreate` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. |+| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. |+| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → guarded Source-mutation envelope | API-key replacement. `force` is a JSON body field, never a query parameter. || POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | A `native_cli` source requires the acknowledgement before OAuth starts. See repair rules. |-| DELETE `/api/models/sources/<id>?force=<bool>` | → `{ok}` or `source_last_supplier` + `would_interrupt` | Guard evaluates the post-delete enabled orders. |-| POST `/api/models/sources/<id>/refresh` | → `{source: Source, discovered: integer}` | Explicit source re-discovery, including blocked-source recovery. The returned source contains the replacement model list and successful `last_discovered_at`. |+| DELETE `/api/models/sources/<id>?force=<bool>` | → guarded `409` or `{removed_hops, interrupted}` | A confirmed delete removes the Source from every backend Source order and Route chain in one transaction. |+| POST `/api/models/sources/<id>/refresh` | `{force?: boolean}` → guarded Source-mutation envelope | The sole saved connectivity/discovery/recovery mutation. |+| POST `/api/models/sources/<source_id>/models` | `{model_id, display_name?, reasoning_efforts}` → `{source: Source}` | Creates one user-authored model entry. The Source identity comes only from the path. |+| PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list on either model origin without changing identity, origin, or Routes. |+| DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean}` → API-boundary refusal, guarded `409`, or Source-mutation success | Deletes only a user-authored entry. A discovered entry returns `source_model_managed_upstream`. || GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include `named_agents`, the enabled named-Agent live projection. || GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |-| PUT `/api/models/agents/<backend>/sources` | source-order request → `{agent: AgentSupply}` | Full canonical order is re-echoed. |+| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. |-| PUT `/api/models/agents/<backend>/mappings` | `{mappings}` → `{agent: AgentSupply}` | Fixed-menu backends only. || PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. || GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |+| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; it is the `mutation.route_replace` row of the authoritative mutation matrix. || POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |-| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `{source: Source}` | Adds manual provenance. |-| DELETE `/api/models/custom-models` | `{source_id, model_id}` → `{source: Source}` | Removes only the named manual model. || GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. || POST `/api/models/oauth/start` | `{vendor, channel}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. || GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. || POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. || POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels and forgets the flow. || POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |-| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources}` | Imported sources auto-join eligible follow orders; custom orders stay frozen. |+| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. || GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object is contract v4; `not_started` is installed lazy-start idleness, not an alarm. |+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object is contract v5; `not_started` is installed lazy-start idleness, not an alarm. || POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |-The removed global route `PUT /api/models/priority` has no v3 replacement.-Ordering is backend-owned through the sources routes.+The removed global route `PUT /api/models/priority` has no replacement. Backend Source+order is explicit configuration through the sources route; exact per-model order is+explicit configuration through the chain route.## Identifier rules@@ -57,22 +57,15 @@ Ordering is backend-owned through the sources routes.- Claude and Codex requests use fixed-menu built-in ids.- OpenCode requests use a prefixed `vendor/model` menu id. The prefix chooses theprovider; the resolver sends the bare model id upstream.-- A mapping rewrites a menu id to an upstream model id. A mapping never chooses a- source.-- Without an explicit mapping, a vendor-native fixed menu may resolve a stable menu- alias per source. Claude version aliases select the latest dated id for that exact- version; `opus`, `sonnet`, `haiku`, `opus[1m]`, and `sonnet[1m]` select the latest- discovered id in their family. A dated request remains exact. Alias candidates come- only from that source's discovered inventory; manual models, foreign-vendor sources,- and undiscovered passthrough ids do not qualify. A native CLI source preserves an- exact CLI alias instead of replacing it with a bundled-catalog model. Explicit- mappings take precedence.+- Add-time matching may suggest a sanctioned alias or mapping, but it materializes the+ accepted result as an exact `{source_id, model_id}` hop before commit. Runtime neither+ resolves aliases nor substitutes a model.- Source event references are checked when emitted. Retained feed entries remainvalid after a later legal source deletion.## AgentSupply read projection-Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:+Each backend entry on `GET /api/models/agents` carries the v5 API-boundary keys:```json{@@ -82,7 +75,6 @@ Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:"selected_model_id": "claude-opus-4-6","selected_model_explicit": true,"sources": {- "policy": "follow","order": ["src_claudepro1", "src_anthkey01"],"eligibility": [{@@ -181,81 +173,65 @@ its process availability but carries `in_current_model_chain: null`.## Per-backend source order-Request shapes are total:+The request is total:```json-{"policy": "follow"}+{"order": ["src_anthkey01", "src_relay9c1x"]}```-```json-{"policy": "custom", "order": ["src_anthkey01", "src_relay9c1x"]}-```--- `follow` accepts no `order`; the server recomputes the live recommended order.-- `custom` requires the complete desired ordered subset. The empty subset is legal.-- Any manual order mutation changes policy to `custom`.-- Restoring `follow` is the explicit restore-to-recommendation operation.+- `order` is the complete desired ordered subset. The empty subset is legal.- Every id is unique, exists, and is eligible for the backend. Otherwise the routereturns `invalid_source_order`.-- New eligible sources auto-join `follow` at their recommended position.-- A `custom` order never changes because a source was created or imported.+- Add Source and native import invoke `placement-v1` once and persist its chosen+ position. Refresh, restart, health changes, and turns never recompute this order.Eligibility is server-authoritative. An ineligible row carries exactly one closed`reason_key` from `agent-supply.schema.json`; an eligible row carries null.-### Mapping and menu enrollment--A mapping or open-menu target is accepted only when its selected source is enrolled-in the backend's post-mutation effective order. Under `follow`, the effective order-is `ModelHubConfig.effective_source_order`'s recommendation and is exhaustive over-eligible sources, so an eligible-but-non-enrolled target is representable only under-`custom`. Acceptance auto-appends that source to the custom order, and the confirm-step must surface the append. Acceptance never converts policy: a selection that-does not change the order is not an order edit. An ineligible source is never-auto-enrolled and the request fails with `mapping_target_unavailable`. Evidence at-master `05f72ae5`:-`service.py:1955-1985` validates targets against eligible inventory but does not-yet require or edit effective-order enrollment; the follow-up consumer lane owns-that acceptance change.+### Exact Route-chain configuration++Every menu model stores one `hops` array. Each hop is an exact+`{source_id, model_id}` pair; a differing upstream id is the mapping itself, not a+separate mapping object. A write validates only newly introduced or changed pairs.+The whole-array PUT uses `force` in the JSON body and the same guarded refusal/reporting+family as Source mutations. A successful write returns `{chain, removed_hops,+interrupted}`; a non-forced write that would empty protected supply returns the shared+`409 {error, would_remove_hops, would_interrupt}` envelope.+An unchanged stale pair may be retained or reordered so a user can add a working+fallback without discarding a temporarily unavailable configured hop. Runtime walks+the stored array verbatim and annotates only live runnability.## Source creation outcome-`AdoptedBy` is:+`AddedTo` is:```json-{"backend": "claude", "policy": "follow", "position": 2}+{"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_anthkey01", "model_id": "claude-opus-4-6", "position": 2}```-`position` is one-based in the effective order after commit. The array contains only-eligible `follow` backends that actually adopted the source and is frozen with the-source response. `custom` backends are absent and retain their prior order.--`SkippedBy` is:+`position` is one-based in the persisted Route chain after commit. `AdoptedBy` is the+stable Source-card projection of persisted references:```json-{"backend": "codex", "reason": "custom_order"}+{"backend": "claude", "menu_model": "claude-opus-4-6"}```-Its closed backend vocabulary is `claude | codex | opencode`; its reason vocabulary-has one v2 member, `custom_order`. The array contains every eligible custom backend-that did not adopt the new source. Ineligible backends appear in neither array, so a-consumer can distinguish “eligible but deliberately skipped” from “cannot use this-source” without reimplementing the compatibility matrix. Evidence at master-`05f72ae5`: `service.py:767-783` emits only follow-policy adoption, collapsing-eligible custom skips into the same absence as ineligibility.+Neither array carries a policy field. A Source with no accepted automatic match returns+empty arrays and remains available for explicit Route editing; there is no skipped-order+reason or “not enabled” state.The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 3,+ "contract_version": 5,"source": {"id": "src_anthkey01", "kind": "api_key"},- "adopted_by": [- {"backend": "claude", "policy": "follow", "position": 2}+ "added_to": [+ {"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_anthkey01", "model_id": "claude-opus-4-6", "position": 2}],- "skipped_by": [- {"backend": "codex", "reason": "custom_order"}+ "adopted_by": [+ {"backend": "claude", "menu_model": "claude-opus-4-6"}]}```@@ -282,20 +258,21 @@ The protected model set for a backend is the union of:1. explicit models of enabled named Vibe Agents;2. checked open-menu models;-3. the menu-side `builtin_id` of mappings whose `enabled` is true.+3. every menu model with a persisted Route row, including an empty `hops` array.The guard evaluates each protected `(backend, model)` against the post-mutation-state. It counts only runnable suppliers in that backend's enabled effective order,-never eligible inventory outside the order. A pair with no runnable supplier appears-once in `would_interrupt` or `interrupted_pairs`.+state. It counts only runnable exact hops in that model's stored Route chain, never+eligible inventory or the backend Source order by itself. A pair with no runnable hop+appears once in `would_interrupt` or `interrupted`.-DELETE and elective replacement of a healthy API key refuse with:+Every guarded Source/inventory mutation uses the §4.5 envelope matrix. A refusal is:```json{"ok": false,- "contract_version": 3,+ "contract_version": 5,"error": "source_last_supplier",+ "would_remove_hops": [],"would_interrupt": [{"backend": "claude",@@ -306,10 +283,8 @@ DELETE and elective replacement of a healthy API key refuse with:}```-DELETE uses the query `force=true`. API-key replacement uses the JSON body-`force: true`. A blocked-source repair proceeds and reports the remaining gaps in-`interrupted_pairs`; refusing it would prevent recovery from the state the route-exists to repair.+DELETE uses the query `force=true`; the other guarded mutations use the JSON body+`force: true`. Success returns the exact envelope selected by the authoritative matrix.## Credential replacement and reauth@@ -353,7 +328,7 @@ differently only if all invariants remain true:durable record names it. Successful reconciliation removes the record.8. **Channel-aware OAuth retained-material partition.** A failed Hub flow reportsone total `retained_material_disposition` from the adapter seam. `none` preserves- the prior source strictly. `flow_source_ref` is the irreversible v4b case:+ the prior source strictly. `flow_source_ref` is the irreversible retained-material case:persist `state.status: needs_action` with`state.detail_key: models.source.needs_action.oauth_expired`, clear discoveredsupply, and never route silently. `orphan_ref` preserves the prior source and@@ -387,7 +362,7 @@ API-key success:```json{"ok": true,- "contract_version": 3,+ "contract_version": 5,"source": {"id": "src_relay9c1x", "kind": "api_key"},"recovered": true,"interrupted_pairs": []@@ -413,7 +388,7 @@ operation; there is no parallel “test” or “recover” endpoint.`OAuthFlow.intent` makes the terminal shape a function of the flow:- non-terminal, failed, or canceled → `{flow}`;-- terminal `intent: "create"` → `{flow, source, adopted_by, skipped_by}`;+- terminal `intent: "create"` → `{flow, source, added_to, adopted_by}`;- terminal `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}`.Status and submit return the same terminal shape:@@ -421,7 +396,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 3,+ "contract_version": 5,"flow": {"flow_id": "oaf_claude01","intent": "create",@@ -429,22 +404,24 @@ Status and submit return the same terminal shape:"source_id": "src_claudepro1"},"source": {"id": "src_claudepro1", "kind": "subscription"},- "adopted_by": [- {"backend": "claude", "policy": "follow", "position": 1}+ "added_to": [+ {"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "position": 1}],- "skipped_by": []+ "adopted_by": [+ {"backend": "claude", "menu_model": "claude-opus-4-6"}+ ]}```-`adopted_by` is absent for reauth because the existing source order did not change.+`added_to` and `adopted_by` are absent for reauth because no new Source or Route+reference is created.## Chain and probe-In Hub mode, `AgentChain.chain` is the effective source order filtered by backend-eligibility and the server's per-source effective-model derivation. That derivation-applies an explicit mapping first, otherwise applies the vendor-native alias rule above,-then verifies the resulting id against source inventory. Cooling, source-blocked and-process-unavailable native CLI members stay in the chain at their original positions.+In Hub mode, `AgentChain.chain` is the exact stored per-model Route chain in the same+order. Runtime does not filter or rebuild it: cooling, missing, model-unsupported,+source-blocked, and process-unavailable native CLI hops stay at their configured+positions with live annotations.Each item carries `channel`, source-global `health`, process-aware `runnable`, andnullable `reason`. The complete axiom is:@@ -460,9 +437,9 @@ remains a valid `interrupted` chain.```json{"ok": true,- "contract_version": 3,+ "contract_version": 5,"chain": {- "contract_version": 4,+ "contract_version": 5,"backend": "codex","model_id": "gpt-5.6","chain": [@@ -487,7 +464,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 3,+ "contract_version": 5,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -501,9 +478,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 3,+ "contract_version": 5,"probe": {- "contract_version": 4,+ "contract_version": 5,"backend": "claude","channel": "hub","reachable": false,@@ -518,7 +495,7 @@ 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+candidate keeps v5'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 returnnot-ready. `reachable` is READINESS, not completion evidence: no upstream call is@@ -527,7 +504,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "native_cli","reachable": true,@@ -541,7 +518,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "native_cli","reachable": false,@@ -558,7 +535,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 3,+ "contract_version": 5,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -576,7 +553,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 3,+ "contract_version": 5,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -585,7 +562,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 3,+ "contract_version": 5,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}@@ -608,14 +585,20 @@ when emitted.## Error codes-Minimum v3 set:+Minimum v5 set:`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,-`invalid_source_order`, `source_last_supplier`, `mapping_target_unavailable`,-`mode_switch_blocked`, `engine_down`, `consent_required`,-`reauth_confirmation_required`, `migration_item_conflict`, `turn_not_found`,+`invalid_source_order`, `source_last_supplier`, `source_in_route_chain`,+`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,+`reauth_confirmation_required`, `source_model_managed_upstream`,+`migration_item_conflict`, `turn_not_found`,`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.+Boundary-only action-refusal values cover operations the UI already does not offer but+a script or regression can call directly. `reauth_confirmation_required` and+`source_model_managed_upstream` are API/test-only truth: they have no product copy key+or rendering slot.+Removed: `invalid_priority_order`.## Mechanical guards@@ -623,20 +606,26 @@ Removed: `invalid_priority_order`.JSON Schema draft-07 cannot express cross-document or live-state relations. Thecontract harness and API-boundary tests enforce:+<!-- authority-consumer: credential.refresh_once credential.refresh_failed credential.refresh_rejected credential.static_unauthorized credential.account_classified credential.request_nonfallback -->+<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.blocked turn.canceled -->+<!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace -->+<!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled -->+<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->+| Guard | Boundary || --- | --- || every example validates and JSON round-trips | contract 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 |+| authority registry and mirror relations are generated from live files in the same test run; every registered closed branch has a consumer and every registered consumer resolves to one authority | `mirror-registry.json` harness |+| every non-null `then` constraint has matching `required` | contract harness || every `sources.order` id exists, is unique, and is eligible | config loader + source-order route || eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler || every AgentSupply eligibility row carries `in_current_model_chain` and `process_availability_reason`; membership nullability follows `selected_model_id`, and only a native source may carry `native_cli_unavailable` | AgentSupply assembler |-| `AgentChain.chain` source ids are unique and preserve effective order, including process-unavailable native CLI items | chain assembler |+| `AgentChain.chain` re-echoes the stored exact hops in the same order, including missing, model-unsupported, and 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 || `channel_switch.from_source == channel_switch.to_source` | event emitter |-| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, `sources`, `supply_status`, `model_supply`, and `named_agents`; every Source includes persisted `last_discovered_at`; source creation returns both `adopted_by` and `skipped_by`; source refresh returns the updated Source plus count | API payload test |+| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply`, and `named_agents`; every Source includes persisted `last_discovered_at`; source creation returns `added_to` and `adopted_by`; saved refresh uses the guarded Source envelope | API payload test || every OAuthFlow response includes `intent` | API payload test || contract and in-repo adapter interface copies are byte-identical; the five retained-material enum members and ref-pairing predicates are mutation-tested | contract harness |diff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.jsonindex 657995ab5..eb041974e 100644--- a/docs/plans/model-hub-contracts/migration-scan.schema.json+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json@@ -20,7 +20,7 @@"masked_detail": { "type": "string", "description": "e.g. 'sk-…dd3c + 自定义 Base URL'; never full secrets" },"proposed_action": {"enum": ["import", "controlled_import", "keep_native", "reauth"],- "description": "Option 1: Claude oauth_native → keep_native (sanctioned as-is; NOT re-authed into the hub). Subscription OAuth (Claude AND Codex) → keep_native always: file-import of OAuth tokens is DEFERRED (2026-07-23, L6 review — adapter v1.2 forbids OAuth material in provision_credential; api_key storage cannot preserve refresh semantics). With subscription_hub_experimental on, hub-held subscriptions are established via the engine's own OAuth connect flow (start_oauth), never by file import. controlled_import remains in the enum only for a future engine-owned OAuth-import capability. Keys/base URLs → import."+ "description": "Claude and Codex native OAuth logins remain in the sanctioned CLI store via keep_native; subscription OAuth tokens are never copied by this file-import surface. Hub-held subscriptions are established only by the explicit OAuth add flow. controlled_import remains reserved for a future engine-owned import capability. API keys and Base URLs use import."},"selected": { "type": "boolean" },"notes_key": { "type": ["string", "null"], "description": "i18n key for the row's secondary line" }diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex 9930c61a7..59703e682 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -1,5 +1,83 @@{- "contract_version": 4,+ "contract_version": 5,+ "input_generation": {+ "mode": "same_run_live_files",+ "external_snapshot": "content_fingerprint_required"+ },+ "authority_table_discovery": {+ "files": ["docs/plans/model-hub.md"]+ },+ "absence_checks": [+ {+ "id": "A1",+ "source_file": "docs/plans/model-hub-implementation.md",+ "pattern": "no `([A-Za-z][A-Za-z0-9_]+)` alias exists",+ "scope_files": [+ "docs/plans/model-hub-contracts/README.md",+ "docs/plans/model-hub-contracts/adapter-interface.py",+ "docs/plans/model-hub-contracts/source.schema.json",+ "docs/plans/model-hub-contracts/api.md",+ "docs/plans/model-hub-contracts/opencode-overlay.md"+ ]+ },+ {+ "id": "A2",+ "source_file": "docs/plans/model-hub-implementation.md",+ "pattern": "`([A-Za-z][A-Za-z0-9_]+)` is derived [^\\n]+ and is never persisted",+ "scope_files": [+ "docs/plans/model-hub-contracts/turn-provenance.schema.json",+ "docs/plans/model-hub-contracts/api.md"+ ]+ }+ ],+ "schema_absence_checks": [+ {+ "id": "A3",+ "source_file": "docs/plans/model-hub-implementation.md",+ "start_marker": "The final set contains no",+ "scope_globs": [+ "docs/plans/model-hub-contracts/*.schema.json"+ ]+ }+ ],+ "field_contracts": [+ {+ "id": "P1",+ "schema_file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",+ "file": "docs/plans/model-hub-implementation.md",+ "row_id": "FC-08",+ "negated_pattern": "`([a-z][a-z0-9_]+)` is derived [^|]+ and is never persisted"+ }+ ],+ "api_boundary_only_errors": [+ {+ "value": "source_model_managed_upstream",+ "contract_file": "docs/plans/model-hub-contracts/api.md",+ "negative_test_file": "tests/test_model_hub_api.py",+ "negative_test": "test_discovered_source_model_delete_is_rejected_as_upstream_managed",+ "forbidden_ui_globs": [+ "ui/src/components/settings/models/**/*.ts",+ "ui/src/components/settings/models/**/*.tsx",+ "ui/src/i18n/*.json",+ "vibe/i18n/*.json"+ ]+ }+ ],+ "repo_absence_checks": [+ {+ "id": "A4",+ "term_parts": ["custom", "models"],+ "scope_globs": ["**/*.md", "**/*.py", "**/*.json", "**/*.ts", "**/*.tsx"]+ }+ ],+ "route_body_absence_checks": [+ {+ "id": "A5",+ "contract_file": "docs/plans/model-hub-contracts/api.md",+ "path_fragment": "/api/models/sources/<source_id>/models",+ "forbidden_field": "source_id"+ }+ ],"entries": [{"id": "M1",@@ -57,8 +135,7 @@},"exclusions": ["recovery",- "manual",- "mapping"+ "manual"],"exclusion_sets": [{@@ -169,7 +246,8 @@"/properties/served/properties/channel","/properties/terminal_error/properties/channel","/properties/canceled_attempt/properties/channel"- ]+ ],+ "exclude": [null]},{"schema": "probe-result.schema.json",@@ -202,16 +280,172 @@}}]+ }+ ],+ "decision_tables": [+ {+ "id": "D1",+ "domain": "credential failure handling",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Credential-failure decision matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "credential."+ }+ ]},{- "id": "N1",- "vocabulary": "source recommendation rule",- "rule": "none",- "home": {+ "id": "D2",+ "domain": "turn outcome and copy",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Turn-outcome copy matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "turn."+ }+ ]+ },+ {+ "id": "D3",+ "domain": "Source mutation envelopes",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Source-mutation envelope matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "mutation."+ }+ ],+ "authority_fields": {+ "kind": "markdown_field_names",+ "file": "docs/plans/model-hub.md",+ "heading": "Source-mutation envelope matrix",+ "column": "Guarded `409`"+ },+ "authority_fields_scope": [+ "docs/plans/model-hub-contracts/api.md"+ ]+ },+ {+ "id": "D4",+ "domain": "native configuration import actions",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Native-config import action matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "import."+ }+ ]+ },+ {+ "id": "D5",+ "domain": "Source protocols",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "source.schema.json",+ "paths": ["/properties/protocol"]+ },+ "consumers": [+ {+ "kind": "python_literal_annotation",+ "file": "config/v2_config.py",+ "class": "ModelHubSourceConfig",+ "field": "protocol"+ },+ {+ "kind": "python_string_assignment",+ "file": "vibe/model_hub_runtime/state.py",+ "name": "_PROTOCOLS"+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/adapter-interface.py",+ "marker": "authority-consumer: protocol "+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/opencode-overlay.md",+ "marker": "authority-consumer: protocol "+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: protocol "+ }+ ]+ },+ {+ "id": "D6",+ "domain": "configuration eligibility reasons",+ "authority": {+ "kind": "schema_vocabulary","schema": "agent-supply.schema.json",- "path": "/properties/sources/properties/policy"+ "paths": [+ "/properties/sources/properties/eligibility/items/properties/reason_key"+ ],+ "exclude": [null]},- "reason": "The deterministic ordering predicate has one normative home in model-hub.md section 4.2 and is not a shared vocabulary."+ "consumers": [+ {+ "kind": "schema_vocabulary",+ "schema": "agent-supply.schema.json",+ "paths": [+ "/properties/sources/properties/eligibility/items/allOf/0/then/properties/reason_key"+ ]+ },+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/en.json",+ "path": "/models/eligibility",+ "prefix": "models.eligibility."+ },+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/zh.json",+ "path": "/models/eligibility",+ "prefix": "models.eligibility."+ }+ ]+ }+ ],+ "ownership_checks": [+ {+ "id": "O1",+ "kind": "python_importers_have_exactly_one_lane",+ "module": "core.handlers.model_hub.resolver",+ "exclude_globs": ["core/handlers/model_hub/**"],+ "lane_table_file": "docs/plans/model-hub-implementation.md",+ "lane_table_heading": "v3 current lanes (binding)"+ }+ ],+ "file_mirrors": [+ {+ "id": "F1",+ "left": "docs/plans/model-hub-contracts/adapter-interface.py",+ "right": "core/handlers/model_hub/adapter.py"}]}diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.jsonindex 99a2f12de..7b4f41239 100644--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json@@ -5,17 +5,17 @@"description": "Subscription-connect flow state. RUNTIME-DECLARED presentation (S1 gap ③): the server declares what to show and what it expects back; the UI renders declaratively and never keys off a vendor→form table. UI shell semantics mirror the existing BackendOAuthPanel (2s poll, 15-min timeout, cancel). Forms A/B/C from spec §5 frame 09 are presentation patterns the declaration composes: A = auth_url + expects paste_code; B = auth_url + device_code + expects none; C = auth_url + expects paste_callback_url. Under Option 1, native_cli subscription connect drives the CLI's own login through this same shape.","$comment": "Owner-approved channel class audit: this is the user-facing presentation wire, not the service-side OAuthFlowState seam. `credential_ref`, `retained_material_disposition`, and `retained_credential_ref` are deliberately excluded because only the service repair consumer acts on them; no UI or wire consumer does. Both channel branches still expose `channel`, and source-bound create/reauth flows carry `source_id`. Evidence at master 05f72ae5: core/handlers/model_hub/native_oauth.py:252-289 produces native success with no engine credential ref, while the HTTP projection publishes presentation fields rather than adapter refs.","type": "object",- "required": ["flow_id", "vendor", "channel", "state", "presentation"],+ "required": ["flow_id", "intent", "source_id", "vendor", "channel", "state", "presentation", "error_key", "expires_at"],"additionalProperties": false,"properties": {"flow_id": { "type": "string" },"intent": {"enum": ["create", "reauth"],- "description": "v2 (07-29, review round 6), extended by the channel class pass: what this flow is FOR, and therefore what its terminal success response carries — `create` → `{flow, source, adopted_by, skipped_by}`, `reauth` → `{flow, source, recovered, interrupted_pairs}` (api.md → OAuth completion responses). Round 5 defined neither, which left the two creation paths inconsistent: `POST /sources` closed the 「so what now?」 loop with an adoption result while the OAuth door — the default way a subscription is added — returned only flow state. Declared as a field rather than inferred, for two reasons. `source_id` cannot discriminate: both channel branches and both intents bind a pending or existing source. And the alternative — the client remembering which button it pressed — makes the response shape a function of client state instead of of the payload, which is exactly how a poll that arrives after a page reload ends up parsed as the wrong shape. OPTIONAL here, REQUIRED at the API boundary from v2 on (README → required-vs-optional): the shipped flow payloads are validated against this file by tests/test_model_hub_api.py and predate the field, so a `required` would fail the contract gate instead of tightening it."+ "description": "The flow intent determines its terminal response: create returns `{flow, source, added_to, adopted_by}`; reauth returns `{flow, source, recovered, interrupted_pairs}`. It is explicit because source_id cannot distinguish create from reauth and clients must not infer response shape from remembered UI state."},- "source_id": { "type": ["string", "null"], "description": "v1.1: pending Source this flow binds to (deterministic association). Both hub and native_cli Model Hub create/reauth flows set it; null remains legal only for legacy presentation payloads." },+ "source_id": { "type": ["string", "null"], "description": "Pending or existing Source this flow binds to. Both hub and native_cli create/reauth flows set it; null is reserved for presentation-only flows outside Model Hub." },"vendor": { "type": "string" },- "channel": { "enum": ["native_cli", "hub"], "description": "where the resulting credential will live; hub-held subscriptions only behind the consent-gated experimental flag (S2)" },+ "channel": { "enum": ["native_cli", "hub"], "description": "Where the resulting credential lives. Claude recommends native_cli; ChatGPT recommends hub; both explicit alternatives remain legal. Hub-held subscriptions require no feature flag or consent record." },"state": { "enum": ["starting", "awaiting_action", "verifying", "success", "failed", "cancelled"] },"presentation": {"type": "object",@@ -34,6 +34,8 @@"examples": [{"flow_id": "oaf_claude01",+ "intent": "create",+ "source_id": "src_claudepro1","vendor": "anthropic","channel": "native_cli","state": "awaiting_action",diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.mdindex f3c1fd705..db01903ce 100644--- a/docs/plans/model-hub-contracts/opencode-overlay.md+++ b/docs/plans/model-hub-contracts/opencode-overlay.md@@ -1,42 +1,46 @@# OpenCode overlay contract+<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->+How Avibe generates the OpenCode runtime config overlay (`OPENCODE_CONFIG`) in-hub mode. Owner-locked identifier rules (spec §4.4) restated as testable+Gateway mode. Owner-locked identifier rules (spec §4.8) restated as testablerequirements.## Provider entries-- One provider entry per **standard vendor id** present in any hub-channel- source's model list: `anthropic`, `openai`, `zhipuai`, … Models whose vendor- cannot be identified go under a single `custom` provider.+- One provider entry per normalized **provider id** referenced by OpenCode's stored+ menu Route chains: `anthropic`, `openai`, `zhipuai`, … Models whose provider+ cannot be identified use the single `custom` provider id. Provider normalization+ occurs at Add/edit time and the stored result is authoritative.- No `avibe-` namespace anywhere (owner 07-23). Identifiers read exactly likenative OpenCode: `anthropic/claude-opus-4-6`, `zhipuai/glm-5.2`,`custom/<model-id>`.-- Each generated entry redirects transport to the local hub (base URL+- Each generated entry redirects transport to the local Gateway (base URL`127.0.0.1:<port>` + per-protocol path) and injects the **local gateway- token** (never upstream credentials). Protocol/SDK per entry follows the- vendor's protocol as recorded on the supplying source(s).-- Subscription-backed vendors: under Option 1, subscription sources are- `native_cli` channel and therefore **never** materialize as OpenCode- providers. `anthropic/…` in OpenCode is eligible only when a hub-channel- (api_key) source supplies those models. This enforces S2 scenario (b)- (Claude sub → non-Claude-Code clients: prohibited) structurally, in- addition to the code-level `allowed_origins` guard.+ token** (never upstream credentials). Protocol is read from the exact configured+ Source and is one of `anthropic | openai_responses | openai_chat`. A custom+ `base_url`, not a fourth protocol, represents a relay or self-hosted upstream.+- Any Hub-held subscription may supply OpenCode through an exact configured hop.+ A `native_cli` Source remains bound to its sanctioned backend and therefore cannot+ materialize as an OpenCode provider.## Menu projection-- The generated provider entries enumerate exactly the models `checked` in- `agent-supply.menu` (plus display names). `featured|full` is a UI view- state; the overlay always reflects `checked`.-- Custom model entries (manual provenance) appear under their source's vendor+- The generated provider entries enumerate exactly the checked menu models with a+ stored nonempty Route chain (plus display names). `featured|full` is a UI view+ state; it cannot add a model to the overlay.+- Custom model entries (`origin: manual`) appear under their Source's normalized providerprefix, or `custom/` when the vendor is unidentifiable.+- The invocation selects the exact stored `(source_id, model_id)` hop. Runtime never+ normalizes a provider, matches inventory, or substitutes a model.## Stability invariant (test requirement, L7)For a fixed set of checked models, the generated identifier strings are-byte-identical across: hub⇄direct mode switches, source add/remove/reorder,-source cooldown/failover, and engine restarts. A scenario test asserts this by-diffing generated overlays under each perturbation.+byte-identical across: Gateway⇄Direct mode switches, Source-order edits, Source+cooldown/failover, and engine restarts. Adding/removing a Source without changing the+stored OpenCode Route chains also leaves identifiers byte-identical. A scenario test+asserts this by diffing generated overlays under each perturbation.## Long-lived `opencode serve`diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex f0e66e1f2..8ba5c553a 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -2,12 +2,12 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/probe-result.schema.json","title": "ProbeResult",- "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`.",+ "description": "v5 (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", "channel", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],"additionalProperties": false,"properties": {- "contract_version": { "const": 4 },+ "contract_version": { "const": 5 },"backend": { "enum": ["claude", "codex", "opencode"] },"channel": {"enum": ["hub", "native_cli"],@@ -137,7 +137,7 @@"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.",+ "$comment": "v5 (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" },@@ -153,7 +153,7 @@}},{- "$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.",+ "$comment": "native_cli reachable=false uses the same process-availability concept as AgentChain reason=native_cli_unavailable, spelled as a closed i18n key here. It is a readiness failure rather than a completed CLI call, so latency is null.","if": {"properties": {"channel": { "const": "native_cli" },@@ -170,7 +170,7 @@}},{- "$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.",+ "$comment": "The native CLI readiness key cannot appear on a hub probe or a reachable result. Together with the channel branches, this closes channel, reachability, latency, and error in both directions.","if": {"properties": {"error": { "const": "models.probe.native_cli_unavailable" }@@ -189,7 +189,7 @@],"examples": [{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "hub","reachable": true,@@ -200,7 +200,7 @@"via_mapping": false},{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","channel": "hub","reachable": false,@@ -211,7 +211,7 @@"via_mapping": true},{- "contract_version": 4,+ "contract_version": 5,"backend": "claude","channel": "hub","reachable": false,@@ -222,7 +222,7 @@"via_mapping": true},{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "native_cli","reachable": true,@@ -233,7 +233,7 @@"via_mapping": false},{- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "native_cli","reachable": false,diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.jsonindex f1184b123..6580e4aea 100644--- a/docs/plans/model-hub-contracts/resolution-event.schema.json+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json@@ -2,9 +2,9 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/resolution-event.schema.json","title": "ResolutionEvent",- "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.",+ "description": "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"],+ "required": ["id", "ts", "agent", "kind", "model_id", "reason", "severity", "human_zh", "human_en"],"additionalProperties": false,"properties": {"id": { "type": "string" },@@ -19,7 +19,6 @@"cooldown","recover","skip",- "mapping_applied","channel_switch","needs_action","supply_interrupted"@@ -47,7 +46,6 @@"network","recovery","manual",- "mapping","credential_expired","credential_revoked","balance_exhausted",@@ -59,7 +57,7 @@"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. 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."+ "$comment": "permission_denied preserves a request-scoped denial while redacting arbitrary upstream bodies; it does not claim Source-global credential state."},"billing_note": {"enum": [null, "entered_metered", "left_metered"]@@ -116,7 +114,7 @@}},{- "$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.",+ "$comment": "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"]@@ -151,7 +149,7 @@}},{- "$comment": "Presence of severity remains optional only for byte-faithful legacy examples. The API boundary requires it.",+ "$comment": "Every event carries its presentation severity; informational and action-required branches are closed below.","if": {"properties": {"kind": {@@ -160,7 +158,6 @@"cooldown","recover","skip",- "mapping_applied","channel_switch"]}@@ -244,19 +241,6 @@}}},- {- "if": {- "properties": { "kind": { "const": "mapping_applied" } },- "required": ["kind"]- },- "then": {- "required": ["agent", "model_id"],- "properties": {- "agent": { "enum": ["claude", "codex", "opencode"] },- "model_id": { "type": "string" }- }- }- },{"$comment": "v3 AC-11: null model_id is allowed only for a source-scoped system event. The converse is deliberately open because a system test of one explicit model may honestly name that model.","if": {@@ -312,6 +296,7 @@"to_source": "src_anthkey01","reason": "quota_exhausted","billing_note": "entered_metered",+ "severity": "info","human_zh": "Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)","human_en": "Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)"},diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex ad92140a5..4003e704a 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -2,12 +2,12 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/runtime-dependency.schema.json","title": "RuntimeDependency",- "description": "v4 (2026-07-31 targeted amendment): managed engine dependency manifest + status. The installed lazy-start state is not a failure: not_started means no start has been demanded in this service lifetime; down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.",+ "description": "v5 (2026-07-31 targeted amendment): managed engine dependency manifest + status. The installed lazy-start state is not a failure: not_started means no start has been demanded in this service lifetime; down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.","type": "object","required": ["contract_version", "manifest", "status"],"additionalProperties": false,"properties": {- "contract_version": { "const": 4 },+ "contract_version": { "const": 5 },"manifest": {"type": "object","required": ["name", "version", "source_sha", "assets"],@@ -58,7 +58,7 @@},"examples": [{- "contract_version": 4,+ "contract_version": 5,"manifest": {"name": "cliproxyapi","version": "v7.2.95",diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 67377589e..d7a0df0ff 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -29,7 +29,7 @@"null"],"format": "date-time",- "description": "v2 (2026-07-29): when the source was added. IMMUTABLE once written — edits, re-auth, re-discovery and cooldown cycles never touch it. This is not decoration: `follow` policy recommends api_key sources 'by creation time ascending' (spec §4.2), so without a persisted creation stamp that rule is not reproducible — the sources array is explicitly unordered (api.md) and insertion order in config is not a contract. Two sources imported in one batch can legitimately share a stamp, so `id` ascending is the tie-breaker. NULL PLACEMENT (07-29, review round 2) — a tie-breaker does not define how null compares to a real timestamp, and leaving that open would let two correct implementations publish different canonical orders: **a null stamp sorts BEFORE every non-null one**, ties among nulls by `id` ascending. That is not an arbitrary sentinel choice, it is the truth about the record — it predates this field, so it is older than anything that carries a stamp, and 跟随推荐 sorts oldest first. The serializer PR MUST backfill pre-existing sources with the constant `1970-01-01T00:00:00Z` rather than the upgrade timestamp, so the backfill preserves exactly the order the null rule already produced instead of silently reshuffling the user's chain on upgrade (spec §4.2 promises the product never reorders behind the user's back). With both halves stated the sort is total over every mix of stamped, unstamped and same-stamped sources. OPTIONAL here / required at the API boundary once the serializer emits it (README → required-vs-optional discipline)."+ "description": "When the Source was added, retained as ordinary audit/display metadata. Add-time placement and runtime routing do not read this field. Optional in the schema and nullable when the creation time is unknown."},"last_discovered_at": {"type": [@@ -37,7 +37,7 @@"null"],"format": "date-time",- "description": "Targeted v4 (2026-07-31): the completion time of this source's latest successful full model discovery. The server updates it for every successful automatic or explicit discovery that replaces the discovered inventory, including source creation, credential/base-URL changes, re-auth, migration, and POST /sources/<id>/refresh. A failed attempt does not advance it, so the UI never presents failure time as freshness. null means the source predates this field or has no known successful discovery; no backfill invents a fetch time. This source-level fact cannot be derived from models[].discovered_at because a valid refresh may return no discovered rows while preserving manual rows. REQUIRED and nullable at the API boundary because the serializer always answers the question.",+ "description": "Completion time of the latest successful full model discovery. Every successful automatic or explicit discovery that replaces discovered inventory updates it, including Source creation, credential/Base-URL changes, re-auth, native-config import, and POST /sources/<id>/refresh. Failure does not advance it. null means no successful discovery time is known. This Source-level fact cannot be derived from models[].discovered_at because a valid refresh may return no discovered rows while preserving manual rows.","$comment": "Evidence-pinned targeted amendment: core/handlers/model_hub/service.py::_apply_discovered_models stamps the source from the same instant used for discovered rows; core/handlers/model_hub/migration.py::_new_source reuses its existing discovery stamp; config/v2_config.py::ModelHubSourceConfig persists and emits the nullable field."},"kind": {@@ -58,8 +58,7 @@"enum": ["anthropic","openai_responses",- "openai_chat",- "openai_compatible"+ "openai_chat"]},"base_url": {@@ -74,15 +73,7 @@"native_cli","hub"],- "description": "Resolved 2026-07-23 (README): subscription→native_cli by default (sanctioned CLI-held OAuth, per-turn dispatch), api_key→hub. Any hub-held subscription (Claude AND ChatGPT) requires the subscription_hub_experimental flag + recorded per-source consent; UI marks such sources 实验."- },- "experimental_consent_at": {- "type": [- "string",- "null"- ],- "format": "date-time",- "description": "Set iff this is a hub-held subscription the user explicitly consented to (subscription_hub_experimental); null otherwise. Both halves of that 'iff' are conditionals below (07-29, review round 4), not emitter discipline: a hub-held subscription with no stamp is the exact configuration the S2 ruling forbids without recorded consent, and a stamp anywhere else would imply a consent decision the user was never asked for."+ "description": "Serving channel. API keys use hub. Claude subscriptions recommend native_cli; ChatGPT subscriptions recommend hub; both explicit alternatives remain legal. Hub-held subscriptions require no feature flag, consent stamp, or per-route warning."},"billing": {"enum": [@@ -174,7 +165,7 @@],"properties": {"detail_key": {- "$comment": "Targeted v4b (finding 3675168031), completed by the owner-approved channel class pass: `models.source.needs_action.oauth_expired` is also the closed, existing classification for a hub-OAuth same-ref re-auth that wrote new grant material and then failed before the source-state commit, and for retained-material disposition `unknown`, where material may have been rewritten but no ref can be named safely. The truthful user-facing fact is that OAuth authentication must be re-established; this use does not claim a wall-clock token expiry. Evidence: vibe/model_hub_runtime/state.py:135-166 binds OAuth identity to a stable credential_ref and returns the existing ref on a match; state.py:330-341 raises on duplicate auth metadata; neither case permits restoration by guessing a ref. Deliberate non-goal: a two-ref transactional OAuth swap is REJECTED for v2 — the window is rare, the user is already mid-re-auth, one more re-auth is the convergent remedy. Revisit only on field evidence.",+ "$comment": "oauth_expired is the convergent classification when a hub OAuth re-auth may have rewritten grant material but cannot commit a safely identified replacement. It truthfully requires re-authentication without claiming a wall-clock expiry.","enum": ["models.source.needs_action.oauth_expired","models.source.needs_action.balance_exhausted",@@ -224,8 +215,8 @@"needs_action","error"],- "$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)."+ "$comment": "Source-global health never implies process-local native CLI availability. Live process availability is resolved separately and takes precedence when deciding hop runnability.",+ "description": "Source-global recovery state. cooldown is self-healing with retry_at; needs_action and error require user action; active and standby are healthy. Process availability is a distinct live fact carried by Route-hop annotations, so a globally healthy Source may still have a native_cli_unavailable hop. Quota and upstream reachability share one Source-global state across backends."},"retry_at": {"type": [@@ -233,15 +224,15 @@"null"],"format": "date-time",- "$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."+ "$comment": "retry_at belongs only to Source-global cooldown; a health timestamp never proves process availability.",+ "description": "When Source-global cooldown becomes retry-ready. Non-null only for cooldown and null for every other status. It permits another health attempt but does not promise that native CLI is available in this process."},"detail_key": {"type": ["string","null"],- "description": "i18n key, never raw upstream error text — and as of round 5 that is ENFORCED for every status rather than asserted for some (07-29). Each status closes its own vocabulary, so the union below is the complete set of values this field can ever hold and 'never raw text' is a property of the schema instead of a promise about emitters. For needs_action it names the cause or convergent remedy so the row can offer one tap to fix it, and the four keys are required: models.source.needs_action.oauth_expired (re-auth; also the v4b stable-ref rewrite failure whose only honest recovery is re-auth), .balance_exhausted (top up), .credential_revoked (replace key), .account_banned (contact vendor). For cooldown it stays OPTIONAL — a cooling source is already fully described by its `retry_at`, so a cause is useful detail rather than a required one — but the five keys it may carry are now a closed enum, not a `models.source.cooldown.*` prefix: `.network`, `.timeout`, `.rate_limited`, `.quota_exhausted`, `.server_error`. Round 4 wrote that constraint as a prefix pattern with `.+`, which accepted `models.source.cooldown.network: <raw upstream body>` — a naming convention, not a redaction boundary. Null for the two healthy statuses. For `error` — the unclassified failure — the single generic key `models.source.error.unclassified` is REQUIRED: round 4 left this status unconstrained on the grounds that the cause is by definition unknown, which is exactly backwards, since the one status an adapter reaches when it cannot classify a failure is where a raw diagnostic is most likely to land. Not knowing the cause is not permission to widen the channel; the raw text belongs in scrubbed logs. That key is ALSO an event cause as of round 6 (`resolution-event.schema.json` → `reason: unclassified_error`), because a status that never lapses on a timer is a state the user has to be told about; the five non-self-healing keys and the five non-self-healing reasons are a bijection, checked mechanically (api.md → Mechanical guards). VOCABULARY HOME: this field owns these keys — all TEN of them, the five cooldown plus the four needs_action plus this one `error` key — and probe-result.schema.json → `error` mirrors them, because draft-07 gives a bare validator no cross-file `$ref`; the lists are compared mechanically ACROSS files (README.md → vocabulary mirror table, api.md → Serializer completeness). The `examples` list below is part of that comparison and not decoration: round 6 added the `error` key to the three enforcing branches and left `examples` at nine, so the field advertised a nine-key vocabulary while enforcing ten, and round 7 found it. Two things made that survivable and are now closed: this key is pinned as a `const` rather than a one-value `enum`, so a checker that collects only `enum` lists could not see it and its 'examples equal the enforced union' guard passed vacuously; and the comparison ran inside each file rather than between them. `const` now counts as an enum of cardinality one (07-29, review round 7).",+ "description": "Closed i18n key, never raw upstream error text. Healthy states require null. Cooldown may carry a self-healing cause; needs_action requires the cause/remedy key selected by its schema branch; error requires the generic unclassified key. The mirror registry checks this vocabulary against probe and resolution-event consumers.","examples": ["models.source.cooldown.network","models.source.cooldown.timeout",@@ -299,7 +290,8 @@"type": "object","required": ["id",- "provenance"+ "origin",+ "reasoning_efforts"],"additionalProperties": false,"allOf": [@@ -307,12 +299,12 @@"$comment": "v2 (07-29, review round 4): a `manual` entry is one the user typed (spec §5 frame 08), so there is no discovery moment to stamp — a non-null `discovered_at` there would let the drawer claim the vendor advertised a model the vendor never mentioned. `discovered` is deliberately NOT required to carry a stamp: entries persisted before this field existed are legitimately unstamped, and back-dating them would invent a fact.","if": {"properties": {- "provenance": {+ "origin": {"const": "manual"}},"required": [- "provenance"+ "origin"]},"then": {@@ -335,13 +327,19 @@"null"]},- "provenance": {+ "origin": {"enum": ["discovered","manual"],"description": "manual = custom model entry (spec §5 frame 08)"},+ "reasoning_efforts": {+ "type": "array",+ "description": "Declared reasoning-effort capability values for this exact upstream model. Editable for discovered and manual entries; may be empty and has no selected or default item.",+ "items": { "type": "string", "minLength": 1 },+ "uniqueItems": true+ },"discovered_at": {"type": ["string",@@ -357,14 +355,14 @@"string","null"],- "description": "Opaque handle into the ENGINE-OWNED credential store. Secret material NEVER appears in any payload (README invariant 1). Null for native_cli sources and non-null for hub sources — both directions pinned by the conditionals below (07-29, review round 4), because a native source's credential lives in the CLI's own store and there is nothing here to point at, while a hub source with a null handle cannot be called at all. Re-authenticating a native source therefore refreshes that CLI store and leaves this null (api.md → POST /sources/<id>/reauth); only a consented hub-held subscription swaps a handle here. TOP-LEVEL REQUIRED as of round 5 (07-29): round 4 wrote the hub direction as `then: {credential_ref: {type: string, minLength: 1}}` and believed that enforced it, but draft-07 `properties` only validates fields that are PRESENT, so a hub source that simply omitted the key satisfied the branch and the stated invariant was decorative — the review is right that it was unenforced. Presence is lifted to the type level rather than pinned inside each branch because this field is TOTAL: every source has a `supply_channel`, and each channel determines an answer (null or a handle), so there is no source for which the question is open. That is also strictly stronger than two per-branch `required` lists and needs no upkeep — a future channel value inherits the presence obligation automatically, and 'absent' can never again read as 'not applicable'. Same move probe-result made for `source_id`/`model_id` in round 4, for the same reason."+ "description": "Opaque handle into the engine-owned credential store; secret material never appears in a payload. Null for native_cli Sources because their credential stays in the sanctioned CLI store, and non-null for hub Sources. Re-authenticating native_cli refreshes that CLI store and leaves this null; re-authenticating a hub Source replaces the engine-held grant behind its handle."},"account_label": {"type": ["string","null"],- "description": "v1.1 (07-23 12:10, L4 finding): human display identity for subscription sources (e.g. '[email protected]'), for the row's mono sub-line (frame 01r). Populated from the sanctioned CLI auth surface for native_cli sources; MAY stay null for hub-held experimental sources until a later adapter rev. Never secret material."+ "description": "Human display identity for subscription Sources (for example, an account label). Populated from the sanctioned CLI auth surface for native_cli Sources and from the adapter when available for hub-held Sources. It may be null and is never secret material."},"masked_credential": {"type": [@@ -465,55 +463,6 @@}}}- },- {- "$comment": "v2 (07-29, review round 4): the consent gate, as shape rather than as a flag check somewhere in the call path. A hub-held subscription is the ONE configuration the S2 ruling admits only behind `subscription_hub_experimental` plus recorded per-source consent, so a hub-held subscription carrying no consent stamp must not be a representable source — that payload is precisely the ToS exposure the ruling exists to bound, and 'we forgot to write the stamp' and 'the user never consented' are indistinguishable after the fact. The converse pins the stamp's meaning: it is set IFF this is that configuration, so it can never appear on an api_key or on a sanctioned native subscription and imply a consent decision the user was never asked for.",- "if": {- "properties": {- "kind": {- "const": "subscription"- },- "supply_channel": {- "const": "hub"- }- },- "required": [- "kind",- "supply_channel"- ]- },- "then": {- "required": [- "experimental_consent_at"- ],- "properties": {- "experimental_consent_at": {- "type": "string"- }- }- }- },- {- "if": {- "properties": {- "experimental_consent_at": {- "type": "string"- }- },- "required": [- "experimental_consent_at"- ]- },- "then": {- "properties": {- "kind": {- "const": "subscription"- },- "supply_channel": {- "const": "hub"- }- }- }}],"examples": [@@ -541,7 +490,8 @@{"id": "claude-opus-4-6","display_name": "Opus 4.6",- "provenance": "discovered",+ "origin": "discovered",+ "reasoning_efforts": [],"discovered_at": "2026-07-23T03:00:00Z"}],@@ -555,7 +505,7 @@"kind": "api_key","vendor": "custom","display_name": "relay.example",- "protocol": "openai_compatible",+ "protocol": "openai_chat","base_url": "https://relay.example/v1","supply_channel": "hub","billing": "metered",@@ -573,7 +523,8 @@{"id": "glm-5.2-air","display_name": "GLM 5.2 Air",- "provenance": "manual",+ "origin": "manual",+ "reasoning_efforts": [],"discovered_at": null}],diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex caa3728a2..8ff9a8eae 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": "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.",+ "description": "v5 debug record for one exactly attributed Gateway turn. It records exact configured Source/model attempts in stored order and one terminal outcome. No route-policy or runtime-mapping discriminator exists; ambiguous attempts produce no record.","type": "object","required": ["contract_version",@@ -15,11 +15,12 @@"served","terminal_error","canceled_attempt",- "model_supply_state"+ "model_supply_state",+ "blockers"],"additionalProperties": false,"properties": {- "contract_version": { "const": 4 },+ "contract_version": { "const": 5 },"turn_id": {"type": "string","description": "Opaque id in the existing turn/session id space."@@ -35,7 +36,7 @@},"requested_model_id": {"type": "string",- "description": "Caller-facing menu identifier before mapping."+ "description": "Caller-facing menu identifier from the turn request."},"outcome": {"enum": [@@ -54,9 +55,8 @@"type": "object","required": ["source_id",- "resolved_model_id",+ "configured_model_id","channel",- "via_mapping","reason"],"additionalProperties": false,@@ -65,9 +65,8 @@"type": "string","pattern": "^src_[a-z0-9]{8,}$"},- "resolved_model_id": { "type": "string" },+ "configured_model_id": { "type": "string" },"channel": { "enum": ["native_cli", "hub"] },- "via_mapping": { "type": "boolean" },"reason": {"enum": ["quota_exhausted",@@ -82,7 +81,7 @@"unclassified_error"],"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."+ "$comment": "permission_denied is request-scoped and distinct from Source-global credential_revoked. The failed attempt remains useful turn evidence even though no Source state is mutated."}}}@@ -90,16 +89,15 @@"served": {"type": ["object", "null"],"description": "The attempt that completed the turn; non-null only for outcome served.",- "required": ["source_id", "resolved_model_id", "channel", "via_mapping"],+ "required": ["source_id", "configured_model_id", "channel"],"additionalProperties": false,"properties": {"source_id": {"type": "string","pattern": "^src_[a-z0-9]{8,}$"},- "resolved_model_id": { "type": "string" },- "channel": { "enum": ["native_cli", "hub"] },- "via_mapping": { "type": "boolean" }+ "configured_model_id": { "type": "string" },+ "channel": { "enum": ["native_cli", "hub"] }}},"terminal_error": {@@ -107,27 +105,28 @@"description": "The attempt that stopped the turn with a non-fallback failure.","required": ["source_id",- "resolved_model_id",+ "configured_model_id","channel",- "via_mapping","reason","stream_started"],"additionalProperties": false,"properties": {"source_id": {- "type": "string",- "pattern": "^src_[a-z0-9]{8,}$"+ "anyOf": [+ { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ { "type": "null" }+ ]},- "resolved_model_id": { "type": "string" },- "channel": { "enum": ["native_cli", "hub"] },- "via_mapping": { "type": "boolean" },+ "configured_model_id": { "type": ["string", "null"] },+ "channel": { "enum": ["native_cli", "hub", null] },"reason": {"enum": ["invalid_parameter","protocol_error","tool_incompatible",- "stream_interrupted"+ "stream_interrupted",+ "engine_down"]},"stream_started": { "type": "boolean" }@@ -142,28 +141,73 @@"required": ["stream_started"],"properties": { "stream_started": { "const": true } }}+ },+ {+ "if": {+ "properties": { "reason": { "const": "engine_down" } },+ "required": ["reason"]+ },+ "then": {+ "properties": {+ "source_id": { "type": "null" },+ "configured_model_id": { "type": "null" },+ "channel": { "type": "null" }+ }+ },+ "else": {+ "properties": {+ "source_id": { "type": "string" },+ "configured_model_id": { "type": "string" },+ "channel": { "enum": ["native_cli", "hub"] }+ }+ }}]},"canceled_attempt": {"type": ["object", "null"],"description": "The in-flight attempt interrupted by explicit Stop/cancel. It carries identity but no failure reason because the source did not fail. null is honest when cancellation settled before any source attempt started.",- "required": ["source_id", "resolved_model_id", "channel", "via_mapping"],+ "required": ["source_id", "configured_model_id", "channel"],"additionalProperties": false,"properties": {"source_id": {"type": "string","pattern": "^src_[a-z0-9]{8,}$"},- "resolved_model_id": { "type": "string" },- "channel": { "enum": ["native_cli", "hub"] },- "via_mapping": { "type": "boolean" }+ "configured_model_id": { "type": "string" },+ "channel": { "enum": ["native_cli", "hub"] }}},"model_supply_state": {"type": ["string", "null"],"enum": ["waiting", "interrupted", null],- "description": "Model-scoped cause for no_candidate. null for every other outcome."+ "description": "Model-scoped state for no_candidate. null for every other outcome."+ },+ "blockers": {+ "type": "array",+ "description": "Exact-hop blockers used to render a blocked no_candidate outcome. Empty for an unconfigured route and for outcomes other than no_candidate.",+ "items": {+ "type": "object",+ "required": ["source_id", "model_id", "reason"],+ "additionalProperties": false,+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string" },+ "reason": {+ "enum": [+ "source_missing",+ "model_unsupported",+ "native_cli_unavailable",+ "cooldown",+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "unclassified_error"+ ]+ }+ }+ }}},"allOf": [@@ -274,7 +318,7 @@],"examples": [{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -283,24 +327,23 @@"failed_attempts": [{"source_id": "src_claudepro1",- "resolved_model_id": "claude-opus-4-6",+ "configured_model_id": "claude-opus-4-6","channel": "native_cli",- "via_mapping": false,"reason": "quota_exhausted"}],"served": {"source_id": "src_anthkey01",- "resolved_model_id": "claude-opus-4-6",- "channel": "hub",- "via_mapping": false+ "configured_model_id": "claude-opus-4-6",+ "channel": "hub"},"terminal_error": null,"canceled_attempt": null,- "model_supply_state": null+ "model_supply_state": null,+ "blockers": []},{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -309,19 +352,19 @@"failed_attempts": [{"source_id": "src_relay9c1x",- "resolved_model_id": "glm-5.2",+ "configured_model_id": "glm-5.2","channel": "hub",- "via_mapping": false,"reason": "balance_exhausted"}],"served": null,"terminal_error": null,"canceled_attempt": null,- "model_supply_state": null+ "model_supply_state": null,+ "blockers": []},{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -331,10 +374,17 @@"served": null,"terminal_error": null,"canceled_attempt": null,- "model_supply_state": "waiting"+ "model_supply_state": "waiting",+ "blockers": [+ {+ "source_id": "src_codexplus1",+ "model_id": "gpt-5.3-codex",+ "reason": "cooldown"+ }+ ]},{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -344,17 +394,17 @@"served": null,"terminal_error": {"source_id": "src_anthkey01",- "resolved_model_id": "claude-opus-4-6",+ "configured_model_id": "claude-opus-4-6","channel": "hub",- "via_mapping": false,"reason": "stream_interrupted","stream_started": true},"canceled_attempt": null,- "model_supply_state": null+ "model_supply_state": null,+ "blockers": []},{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",@@ -365,14 +415,14 @@"terminal_error": null,"canceled_attempt": {"source_id": "src_codexplus1",- "resolved_model_id": "gpt-5.3-codex",- "channel": "native_cli",- "via_mapping": false+ "configured_model_id": "gpt-5.3-codex",+ "channel": "native_cli"},- "model_supply_state": null+ "model_supply_state": null,+ "blockers": []},{- "contract_version": 4,+ "contract_version": 5,"turn_id": "turn_01k9x6db","ts": "2026-07-30T05:55:00Z","agent": "claude",@@ -381,21 +431,20 @@"failed_attempts": [{"source_id": "src_primary01",- "resolved_model_id": "claude-opus-4-6",+ "configured_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+ "configured_model_id": "claude-opus-4-6",+ "channel": "hub"},"terminal_error": null,"canceled_attempt": null,- "model_supply_state": null+ "model_supply_state": null,+ "blockers": []}]}diff --git a/docs/plans/model-hub-f4-ui-completeness.md b/docs/plans/model-hub-f4-ui-completeness.mdindex 142e3a79a..9a36c855b 100644--- a/docs/plans/model-hub-f4-ui-completeness.md+++ b/docs/plans/model-hub-f4-ui-completeness.md@@ -25,7 +25,7 @@ already implemented on master (`cf1b4314`).sources only — `native_cli` test is rejected server-side), delete(`DELETE`, with the only-supplier guard: a `mode_switch_blocked` responseescalates the confirm to a `?force=1` delete). Custom-model delete lives in- the OpenCode drawer's edit dialog (`DELETE /custom-models`).+ the OpenCode drawer's edit dialog (`DELETE /sources/<source_id>/models/<model_id>`).3. **P1-03 / R30 — Migration triggers.** New self-contained `MigrationBanner`(scans on mount, shows a dismissible strip when importable native configsdiff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex 7433d464d..f2d12d187 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -1,28 +1,32 @@# Model Hub — Implementation Plan-Status: draft v1 · 2026-07-23 · follows the signed product spec-Spec (signed 2026-07-23): `docs/plans/model-hub.md`-Design source: `../avibe-docs/design.pen` frames `产品改造 V4 01r – 09`-Lane workflow standard: `~/vibe-remote-project/.agents/skills/pr-delivery-loop/SKILL.md`--> **Superseded for ordering (2026-07-29).** This document plans the **v1** build,-> which shipped dormant. Spec v2 moved the spend order from one global list to a-> per-backend ordered subset (`model-hub.md` §0, §4.2; contracts at-> `contract_version: 3`, with v2 retained as the historical ordering decision).-> Anything below that assumes a global priority list is-> historical. This document is not being rewritten in place, only annotated where-> it would otherwise contradict the frozen contracts. **§3 and §8 are the-> exceptions: both are v2-current and binding** — §3 now carries the v2 lane plan-> (approved 2026-07-29), which replaces the v1 lane split, and §8 the acceptance-> criteria the spec-v2 review loop handed to implementation instead of answering-> them with more spec.+Status: **v3.0 implementation addendum** · 2026-08-09 · supersedes v2 lane authority;+follows product spec v3.0+Spec: `docs/plans/model-hub.md`+Design source: `../avibe-docs/design.pen`; the v3 interaction draft is owner-approved+as I4's implementation baseline, while I4 still owes production-complete desktop/mobile+states+Lane workflow standard: `.agents/skills/pr-delivery-loop/SKILL.md`++> **Authority banner (2026-08-07, amended 2026-08-09).** The original v1 milestones and most narrative+> below are historical records of the dormant build. **§3 and §8 are the binding+> exceptions.** In §3, only 「v3 current lanes」 is the active lane plan; the retained+> L0–L6 material is explicitly historical. In §8, AC-1 through AC-21 remain in their+> original order, AC-19 is amended in place by the final vocabulary, and AC-22 onward+> append the v3 requirements.+> contract files in this consolidation. K1 owns the final contract shape and its mechanical closure+> on this tested PR head; I1 owns the remaining prelaunch consumers+> and evidence under §3's exclusive file split.---## 0. Ground rules for this effort-- Contracts freeze **before** parallel lanes open (§2). Deviations route through- the orchestrator, never lane-to-lane.+- The 13-file terminal-version/protocol-enum closure in §8 must coexist on one tested PR+ head. Commit boundaries are not a CI gate. The remaining final-shape consumers and+ evidence may land in later PRs, but the complete handoff is a release prerequisite.+ After I1 lands the contract set, it is read-only to downstream lanes; deviations route+ through the orchestrator, never lane-to-lane.- Every lane: own worktree (`.worktrees/avibe/<branch>/`), one branch one PR,non-draft, Codex-bot review loop owned by the lane, zero unresolved threadson head before hand-back. Orchestrator does final review + merge.@@ -80,7 +84,8 @@ orchestrator only.C_callback_replay), state machine states, url?, device_code?, error?;mirrors existing `BackendOAuthPanel` semantics.6. `migration-scan.schema.json` — per backend: detected items(kind, masked- detail, action(import|reauth|controlled_import), selected).+ detail, action from `model-hub.md` §6's authoritative import-action matrix,+ selected).7. `api.md` — REST endpoint list (paths, verbs, request/response schema refs,error envelope): sources CRUD + test/discovery, per-backend source order(v2: `PUT /api/models/agents/<backend>/sources`, replacing the v1 global@@ -96,11 +101,75 @@ orchestrator only.`turn-provenance.schema.json` (per-turn model@source record). All three areread-only surfaces with no v1 implementation, so every field is required.-## 3. Lanes (v2 plan, approved 2026-07-29)+## 3. Lanes (v3 current plan, approved 2026-08-07; revised 2026-08-09)++### v3 current lanes (binding)++The v3 batch separates product truth and fidelity evidence from implementation+lanes with exclusive file ownership. K1 and K2 may run in parallel. K1 owns this+orchestrator-authorized S-1 contract consolidation and the generated authority guard;+after this head, those contract files transfer to I1 and then freeze for downstream+lanes. The I1–I6 split is **tentative pending the UI lane's design-to-spec reconciliation table**;+that reconciliation may change content but is not expected to change file ownership.++| Lane | Executor preference | Exclusive scope | Depends on |+| --- | --- | --- | --- |+| **K1 spec v3 sync** | codex | This PR's planning documents plus the owner-authorized final S-1/protocol edits under `docs/plans/model-hub-contracts/`, their byte-mirror/version consumers, and the live-input authority guard. It does not implement the remaining Gateway runtime | — |+| **K2 conversion fidelity** | codex | Preserve the recorded M0 measurements and go/no-go rows; record the 2026-08-08 owner waiver of an official-API attribution re-test and the accepted relay-attributed reasoning degradation without rewriting the evidence or adding product/UI scope | — |+| **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; `tests/test_model_hub_resolution.py`; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through the same-tested-head contract transition. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks: I1 repairs breakage caused by removed resolver symbols but does not refactor them. Owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while I1 is active | K1. **Merges first** |+| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/{config,client,state,adapter}.py`; `tests/test_model_hub_runtime.py`; after I1 merges, `tests/test_model_hub_l3.py` transfers wholly to I2 for runtime behavior | I1 |+| **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree | I1 |+| **I4 Sources / Gateway UI** *(tentative)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive | I1's API envelopes + the UI-spec PR |+| **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 |+| **I6 release-gate removal** *(tentative)* | codex | After I5 merges, exclusive ownership transfers from I1 for `is_model_hub_enabled()` and every call site, `_init_model_hub()`, `core/controller.py`, and `tests/test_controller_model_hub_gate.py`. Delete the gate function rather than leaving a constant-true shell; invert the gate test so the final default state always constructs the v3 aggregate | I5 merged and all Model Hub scenarios green |++**Executor ruling (owner, 2026-08-09).** Every new I1–I6 implementation lane uses+`codex`, including frontend work. Visual-fidelity risk is closed by process rather than+by changing executor: `design.pen` is the pixel-level authority, and a separate Codex+acceptance thread compares the built UI against its design frames. Already-dispatched+Claude lanes complete their current specification work; subsequent implementation uses+the table above.++**Merge order:** K1 first for product authority; K2 remains independent evidence. I1+must merge before I2–I5. I2 and I3 may then proceed in parallel under the exclusive+file split; I4 additionally waits for the UI-spec PR; I5 closes integration after+I1–I4; I6 removes the release gate only after that evidence is merged. Every lane+follows `pr-delivery-loop`; no lane merges itself.++**Exclusive-file circuit breakers.** `service.py` and+`tests/test_model_hub_config.py` are I1-only. Both adapter copies move together under+I1. `modules/agents/model_hub.py`, `tests/test_model_hub_injection.py`,+`core/controller.py`, and `tests/test_controller_model_hub_gate.py` are I1-only until+the explicit I6 transfer for the release-gate pair. `tests/test_model_hub_l3.py` has one serial ownership transfer: I1 alone updates its+versioned contract/provenance fixtures on the first tested head; only after I1 merges+does I2 own the whole file. I2–I5 stop and report to the orchestrator if their work+requires any other I1 file. `ui/src/i18n/*.json` is I4-only: I3 or I5 requests any new+migration-scenario note key through the orchestrator and never edits UI i18n locally.+The authority guard discovers every Python file outside the resolver package that+imports `core.handlers.model_hub.resolver` and requires each discovered file to occur+in exactly one binding lane scope; the importer list is never copied into the guard.++**Final-contract anti-drift rule.** I1 owns every final-shape edit under+`model-hub-contracts/` and the exact mechanical closure in §8. After I1 merges, those+files are read-only to I2–I5. All remaining handoff rows still must land before release;+an implementation-proven mismatch+escalates for an orchestrator-owned targeted revision; it is never patched by the+discovering lane.++**ChatGPT pre-default vendor gate.** Immediately before I1 encodes ChatGPT Hub custody+as the product default, I1 re-verifies the current OpenAI terms and product language+identified in `model-hub-tos-review.md` §2.1 and §3.1 under §11's timing gate, records dated evidence in its PR,+and asks the owner to adjudicate any material change. A failed or inconclusive check+blocks only that default; it does not silently substitute another recommendation or+block API-key implementation. K2 fidelity work and I5 post-implementation evidence do+not own this precondition.++### Historical v2 lane plan (non-binding; retained for traceability)The v1 lane split (L1–L7, built for the global priority list) is **superseded** andlives in git history at `251f8e7b`. The lane IDs below are the v2 ones, and every-lane reference in §8 means one of these.+lane reference inside AC-1 through AC-21 means one of these historical implementers.+Nothing in this subsection overrides K1/K2/I1–I5 above.Dispatch preference (owner 2026-07-13): balance claude/codex; rigor-critical andcryptography-adjacent backend → codex; product-voice / design-fidelity UI → claude.@@ -379,21 +448,13 @@ merge order already separates the lanes that would otherwise collide:statement rather than a negotiation — but L3's brief names them explicitly, because alane that discovers it needs a file outside its declared scope is a lane that hasalready collided with someone.-- **v3 is frozen ONCE, and L1 authors all of it** (orchestrator ruling, 07-29, review- round 4 — this **supersedes** the round-1 declination of a full v3 pre-freeze, which- answered 「who branches first」 without answering 「what happens when L2's and L3's own- ACs edit frozen files after v3 has published」). Round 4 named the consequence: a bump- at L1 followed by later contract edits inside downstream lanes would make- `contract_version: 3` denote several mutually incompatible contract states, which is- precisely what `model-hub-contracts/README.md`'s freeze protocol forbids. So **L1's- coordinated v3 commit expands to carry every contract shape change any AC in §8- requires** — L2's and L3's surfaces included, plus AC-11's nullable model for- source-scoped system events and AC-9's per-Agent read projection. **After L1 merges,- contracts are READ-ONLY for every remaining lane.** A shape mismatch a lane can prove- *from its implementation* escalates to the orchestrator for a targeted **v4** with that- evidence attached; it is never an in-lane edit, and never a silent reinterpretation of- v3. The merge order is unchanged (L0 → L1 → {L2 ‖ L3 ‖ L4} → L5 → L6); what changed is- how much L1 carries.+- **One contract shape lands atomically with all of its consumers** (orchestrator+ ruling, 07-29, review round 4). The discovering lane may not publish a contract edit+ and leave downstream code or tests on another meaning of the same version. The first+ contract-owning implementation lane therefore carries every affected shape,+ consumer, and checker in one commit. After it merges, contracts are **read-only** for+ every remaining lane. A mismatch proven by implementation escalates to the+ orchestrator with evidence; it is never an in-lane edit or silent reinterpretation.- L4 and L5 split `ui/src/components/settings/models/**` by subdirectory, and **thatsplit is the whole of their UI scope again** (owner ruling 07-29 14:03). Review round 7had widened L5 into `ui/src/components/workbench/` to make AC-1's conversation-surface@@ -419,36 +480,31 @@ The contracts README's wording stays as written: it is still true, and still GA-## 4. Product gates-- **Resolved (owner 2026-07-23 10:33, after S2):** default = hybrid supply —- subscription sources are `native_cli` channel (per-turn channel dispatch,- CLI-sanctioned OAuth); hub-held subscription login (incl. Claude-in-engine)- ships ONLY behind `subscription_hub_experimental` with explicit ban-risk- consent (copy from S2 §9) and per-source opt-in. API-key paths ungated.- L3 owns channel dispatch; L2 owns the flag + consent recording; L4 owns- the consent dialog + 实验 marking.-- Cross-vendor auto-fallback remains default-off experimental (spec §9);- no lane builds UI for it beyond the advanced placeholder row.-- Mode default: existing users stay in Direct until they migrate (no silent- flips); fresh installs default to Hub. Wizard/banner triggers per spec §6.+- **Subscription custody (owner 2026-08-07, amended 2026-08-08):** Claude recommends+ native custody and ChatGPT recommends Hub custody; both explicit alternatives remain+ supported. Only Claude Hub shows the factual risk sentence. Hub-held subscriptions+ may enter cross-vendor configured chains with no experimental or consent gate. I1's+ ChatGPT default remains subject to the current-vendor re-verification in §3.+- Cross-vendor supply is a normal explicit configured-chain capability, not an experimental+ placeholder or warning surface.+- Mode onboarding: existing installations with no Model Hub state start in Direct and+ switch only by user action; fresh installations start in Gateway. The product is+ available when the global enable environment variable is absent.## 5. Verification layers-- **Unit**: resolution projection, serializer completeness, overlay generation- (identifier stability invariant), migration parsers, and — added 07-29, review- round 11 — **both migration order policies**, which the rewrite in §3 makes- user-visible and nothing else here catches: an imported source **auto-joins every- `follow`-policy order it is eligible for**, and it **stays outside every `custom`- order** while- producing the new-source hint. Parsers plus non-destructiveness pass unchanged if- the migration still inserts into a custom order or fails to adopt into a follow- one, which is exactly the append that L1 is deleting.+- **Unit**: configured-chain execution, serializer completeness, overlay generation+ (identifier stability invariant), and native-config import parsers. Add/import tests+ prove that every one-time match is written at the deterministic position chosen by+ §4.2's sole placement policy, remains visible and adjustable, and never creates a+ persisted policy discriminator or “not enabled” state.- **Contract**: REST API against `model-hub-contracts` schemas (bothdirections), engine adapter against pinned engine version.- **Scenario**: `tests/scenarios/model_hub/catalog.yaml` — at minimum:- quota-exhausted failover & recovery switchback, a per-backend source reorder- takes effect next turn (v2; v1 read "priority reorder"), mapping applies to- CC only, OpenCode identifier stability- across mode switch, migration non-destructiveness, OAuth forms A/B/C happy+ quota-exhausted failover & recovery switchback, a configured per-model reorder+ takes effect next turn, a model mapping applies only to its named backend/menu model,+ OpenCode identifier stability+ across mode switch, native-config import non-destructiveness, OAuth forms A/B/C happypath + timeout/cancel. Scenario IDs appear in PR descriptions.- **Behavioral (Incus)**: real backend turns in both modes; 最近切换 logreflects induced quota errors; UI pixel pass vs the exported design frames@@ -465,7 +521,18 @@ The contracts README's wording stays as written: it is still true, and still GA-canvas. For the v2 lanes that means **V6 01–04 and M01/M02** (§3); the framesthis item originally named were V4's.-## 8. Implementation acceptance criteria (review rounds 8-12, 2026-07-29)+## 8. Implementation acceptance criteria (AC-1–AC-34; v3 addenda through 2026-08-09)++**Current authority.** AC-1 through AC-21 retain their existing order and historical+record; AC-19's final acceptance is amended in place below. S-1 supersedes every+historical acceptance phrase in AC-1 through AC-21 that names a `follow | custom`+policy, enrollment, a separate mapping phase, or runtime Source/model+matching; the original quotations remain evidence of what the earlier review found, not+executable final-shape instructions. AC-22 onward are the binding v3 additions. K1 owns+the owner-authorized S-1/protocol contract freeze and §8's live-input closure on this+tested head; after that freeze, I1 owns the remaining prelaunch consumers and any+orchestrator-approved contract correction, while I2–I6 own the remaining consumers and+evidence under §3.Review round 8 of the spec-v2 PR (#1081) returned six findings, five P1 and one P2.Rounds 6 and 7 had each answered a review by adding a spec section, and each new@@ -544,7 +611,7 @@ it, so no criterion below asks for a notification:that shape. Hub-channel api_key replacement stays transactional, unconfirmed.- **AC-6** reduces to **event-record accuracy** — which, after the downgrade recordedunder AC-6 itself, means exactly ONE unattributed record carrying **no backend list**,- the affected backends being derived from current orders and chains (corrected 07-29,+ the affected backends being derived from current configured chains (corrected 07-29,review round 9: 「which backends the record names」 was the delivery-era framing andcontradicted AC-6's own acceptance) —**AC-11** to the **event-shape half**, and **AC-9** to **which Agents a supply gap@@ -613,7 +680,7 @@ text and AC-8's contract text as one criterion even though only one of them is f| --- | --- | --- | --- | --- | --- || **AC-1** | P1 | Define provenance for Direct-mode turns | `turn-provenance.schema.json` | **L1 v3** (contract) + L3 (record + route), with L6 scenario. **No UI lane** | **settled 07-29 14:03 — record + API truth only; no chat surface, Web or IM** || **AC-2** | P1 | Reconcile irreversible native re-auth before returning failure | `api.md` | **L1 v3** (re-auth flow contract, **including a server-enforced acknowledgement** — see below) + L2 (orchestration) + L5 (confirm copy) | **settled 07-29 10:44 — confirm before the irreversible login** |-| **AC-3** | P1 | Allow blocked sources to be re-tested after user action | `model-hub.md` + `api.md` (extend the existing `POST /api/models/sources/<id>/test`) | **L1 v3** (the blocked-source semantics on the existing test route) + L2 (route + state clearing) + **L5 (the Models-page action that invokes it)** with L6 scenario | **settled 07-29 — the scenario drives the page action, not the route**; **route settled 07-29 17:09 — extend the existing test route, no second recovery path** |+| **AC-3** | P1 | Allow blocked sources to be re-tested after user action | `model-hub.md` + final `api.md` (`POST /api/models/sources/<id>/refresh`) | **I1** (one saved refresh/recovery route, state clearing, and shape) + I4 (Models-page action) + I5 (scenario) | **consolidated 08-09 — final authority is `/refresh`; no parallel `/test` recovery route** || **AC-4** | P2 | Represent canceled turns in provenance | `turn-provenance.schema.json` | **L1 v3** (contract) + L3 (emission, via the turn-lifecycle seam) with L6 scenario | **settled 07-29 — cancellation is FSM truth, never transport inference** || **AC-5** | P1 | Protect the menu-side model in deletion guards | `model-hub.md` | L2 (guard) with L6 scenario — **stays on v2** | no || **AC-6** | P1 | Record a source event once; derive per-backend impact | `model-hub.md` | L3 (event record) with L6 scenario — **stays on v2** | **settled 07-29 — reduced to the record half at 10:54, then downgraded to a single unattributed record (orchestrator ruling, owner-vetoable)** |@@ -629,19 +696,28 @@ text and AC-8's contract text as one criterion even though only one of them is f| **AC-16** | P2 | Remove the nonexistent Agent from AC-5's assertion | `model-hub-implementation.md` | L0 (applied), enforced by L2's test build | no || **AC-17** | P2 | Make notification counts independent of the open recipient policy | `model-hub-implementation.md` | L0 (superseded — recipient policy cut) | **settled 07-29 10:54 — by removal of the policy** || **AC-18** | P2 | Constrain resolution-event source references | `resolution-event.schema.json` | **L1 v3** (contract) + L3 (API-boundary guard) + **L4 (the deleted-source feed state and its UI test — 07-29 15:07 ruling, same razor)** | no |-| **AC-19** | P2 | Close the eligibility reason-key vocabulary | `agent-supply.schema.json` | **L1 v3** (contract) + **L4 (`ui/src/i18n/{en,zh}.json` for the eligibility-reason keys — 07-29 15:07 ruling: the reasons render in L4's source rows and drawer gray-outs, and L1's scope holds no `ui/` file)** | no |+| **AC-19** | P2 | Close the final eligibility reason-key vocabulary | `agent-supply.schema.json` | **I1** (final contract) + **I4** (`ui/src/i18n/{en,zh}.json` mirrors) | **settled 08-09 — retired consent/OpenCode reasons removed; closed-vocabulary invariant retained** || **AC-20** | P2 | Enforce the hub-mode half of the mode invariant | `agent-supply.schema.json` | **L1 v3** (contract) | no || **AC-21** | P2 | Make the mirror registry encode its promised checks | `model-hub-contracts/README.md` | **L1 v3** (registry + checker) | no |+| **AC-22** | P1 | Make one persisted ordered per-model chain the only Gateway routing configuration and execute it verbatim | `model-hub.md` + final `agent-supply.schema.json`, `agent-chain.schema.json`, `api.md`, and provenance/event mirrors | **I1** (final contracts, add-time match, §4.3 executor, shared tests) + I2 (runtime consumer) + I4 (Gateway UI) + I5 (scenario) | **amended 08-09 S-1 — configuration chooses; runtime only walks and classifies** |+| **AC-23** | P1 | Make subscription custody vendor-specific, enforce one native Source per backend, and distinguish a Native Gateway hop from Direct mode | `model-hub.md` + final source/OAuth/supply/API/adapter contracts | **I1** (contracts/defaults/shared guard) + I2 (dispatch) + I3 (OAuth/native import) + I4 (product states) + I5 (scenario) | **amended 08-09 — Claude native, ChatGPT Hub; Direct and Native are distinct product terms** |+| **AC-24** | P1 | Show the sole subscription-routing warning when, and only when, Claude is added as a Hub-held Source | `model-hub.md` + Models UI/i18n + scenario evidence | I4 (flow and copy) + I5 (scenario); I1 owns any contract term if implementation proves one necessary | **settled 08-07 — informational warning, not consent** |+| **AC-25** | P1 | Split subscription recommendations by vendor and disable duplicate native creation | `model-hub.md` + final source/OAuth/API contracts + add-flow UI evidence | **I1** (defaults + shared singleton guard) + I3 (OAuth) + I4 (guidance) + I5 (scenario) | **amended 08-08 — vendor defaults retained; 08-07 takeover notice withdrawn** |+| **AC-26** | P1 | Complete Source add/detail operations: add-only connectivity test/discovery, one guarded saved refresh, manual model add/remove, and editable per-model reasoning-efforts lists with no defaults | `model-hub.md` + final `source.schema.json`, probe/API/adapter contracts | **I1** (shape + routes + service) + I2 (runtime effort use) + I4 (flows) + I5 (scenario) | **amended 08-09 — one saved mutation; no latency or last-check presentation** |+| **AC-27** | P1 | Make every stored protocol response-observed before Save and immutable afterward | `model-hub.md` + final source/probe/API/adapter contracts | **I1** (shape + API) + I2 (runtime transport) + I3 (OAuth/import observation) + I4 (failure-only manual probe-order hint) + I5 (scenario) | **amended 08-09 — manual input orders probes but does not create persistent provenance or bypass observation** |+| **AC-28** | P1 | Converge protocol identity on exactly Anthropic, OpenAI Responses, and OpenAI Chat Completions | `model-hub.md` + final source/API/adapter/overlay mirrors | **I1** (13-file closure + shared tests) + I2 (transport) + I4 (failure copy only) + I5 (scenario) | **settled 08-09 — retain Chat Completions; no `openai_compatible` alias** |+| **AC-29** | P1 | Validate every persisted Source through the canonical final-shape validator | `model-hub-implementation.md` + final Source/config validation and native-import scenario evidence | **I1** (canonical validation boundary) + I3 (import writer + migration scenario) | **settled 08-09 — owner-routed investigation finding** |+| **AC-30** | P1 | Derive takeover from the resolved chain without a new field or false exhausted state | `model-hub.md` + final chain/API/mirror/locale projections | **I1** (projection + mechanical mirrors) + I2 (live current-hop input) + I4 (pull-surface rendering) + I5 (scenario) | **settled 08-09 — takeover is a projection, not stored state** |+| **AC-31** | P1 | Make existing-install Direct onboarding visible and reversible | `model-hub.md` + final mode API/UI/scenario evidence | **I1** (mode envelope/onboarding default) + I4 (Direct/Gateway groups and actions) + I5 (scenario) | **settled 08-09 — Direct remains a supported per-backend mode** |**Read the 「Owed by」 column as contract-then-implementation** (07-29, review round 5).-Where a cell begins **L1 v3**, the frozen-file edit that criterion needs is authored by-L1 inside the single coordinated bump, and the lanes named after it implement and test-against the result — they do not edit `model-hub-contracts/**` themselves. Only AC-5 and-AC-6 carry no L1 term, because their surface is the spec and neither changes a contract-shape. This is the §3 single-freeze ruling applied row by row, and it is what makes-「zero contract edits after L1 merges」 checkable rather than aspirational: any later-lane's PR that touches a file under `model-hub-contracts/` contradicts a cell in this-table and escalates for a targeted v4 instead.+For historical AC-1–AC-21, a cell beginning **L1 v3** records the lane that authored the+contract surface before its consumers. For AC-22 onward, I1 lands the final contracts+and the 13-file closure on one tested head; I2–I5 complete their exclusive consumers+and evidence before release under the rule above.+Only AC-5 and AC-6 carry no contract-owner term because their surface is the spec. In+both plans, any downstream lane touching `model-hub-contracts/**` escalates to the+orchestrator rather than publishing an in-lane reinterpretation.The last column takes exactly two values, and round 11's mechanical check reads it thatway: `no` means the criterion never turned on an owner decision, and a **settled** cell@@ -690,13 +766,387 @@ set and its membership — so whoever fixes one should re-read the other's test.to AC-17** are not implementation work: lane L0 applied them to the blocks they repair,and they are listed so the repairs are traceable to the findings that caused them.-### v3 handoff notes — delivery language the push cut stranded in frozen files+The counts and completion statements above apply to the historical AC-1–AC-21+inventory. The current ledger has **thirty-three** criteria. AC-22 onward are+owner-settled; only the explicitly owner-vetoable final-shape and vocabulary choices in+the v3 spec remain open to veto, not to lane-level invention.++### Final contract shape handoff — owner rulings 2026-08-09++K1 freezes the S-1 routing and protocol vocabulary in the contract files on this PR.+I1 owns the remaining implementation closure and any contract field not changed by this+freeze. The mechanical gate is a **same tested PR head**, not a commit boundary: the+registered version and protocol consumers must coexist on that head before I1 merges.++- The terminal `contract_version` is owner-fixed at **5** in every registered version consumer:+ `docs/plans/model-hub-contracts/mirror-registry.json`,+ `docs/plans/model-hub-contracts/agent-chain.schema.json`,+ `docs/plans/model-hub-contracts/probe-result.schema.json`,+ `docs/plans/model-hub-contracts/runtime-dependency.schema.json`,+ `docs/plans/model-hub-contracts/turn-provenance.schema.json`,+ `core/handlers/model_hub/service.py`, `core/handlers/model_hub/provenance.py`,+ `tests/test_model_hub_config.py`, `tests/test_model_hub_api.py`, and+ `tests/test_model_hub_l3.py`.+- Removing `openai_compatible` adds its schema and adapter consumers to that same tested-head closure:+ `docs/plans/model-hub-contracts/source.schema.json`,+ `docs/plans/model-hub-contracts/adapter-interface.py`, and its byte-identical+ runtime copy `core/handlers/model_hub/adapter.py`.++The version closure contains independently testable Registry, Agent+chain, Probe result, Runtime dependency, and Turn provenance. CI evaluates the complete+PR head and does not require one commit. **“CI does not prevent splitting” does not mean+an intermediate revision conforms to the final protocol.** Landing points outside the+generated closure may ship in later independent implementation PRs. Model Hub remains+unshipped and gated, so those intermediate PRs may be incomplete, but every row in this+handoff must land before the feature can be released or enabled. The contract entries+below are the exhaustive final-shape handoff:++#### Authority-table registry++`mirror-registry.json` registers every closed decision domain below. The registry stores+only authority and consumer extraction locations plus relation rules; it never stores a+copied result set or expected member count. An unregistered table is descriptive, not+authoritative. Contract rows, implementation prose, and tests may mirror or reference a+registered authority but cannot create an unlisted branch.++| Registry ID | Decision domain | Sole authority | Registered consumer class |+| --- | --- | --- | --- |+| `M1` | Source state detail keys | `source.schema.json` state branches | probe schema and locale detail objects |+| `M2` | Source state to chain health | `source.schema.json` status | chain health schema |+| `M3` | Attempt-failure causes | `resolution-event.schema.json` reason | provenance failed-attempt schema and classification code |+| `M4` | Non-self-healing cause to remedy key | resolution-event reason plus registered pair relation | Source detail schema and both locale trees |+| `M5` | Backend `supply_status` | §4.5 supply-status table | AgentSupply, AgentChain, provenance, and locale projections |+| `M6` | Backend identifiers | AgentSupply backend | chain, probe, provenance, and event schemas |+| `M7` | Supply channel | Source channel | chain, provenance, probe, OAuth, and adapter consumers |+| `M8` | Native process availability | AgentChain blocker | AgentSupply, probe, and locale consumers |+| `D1` | Credential-failure branches | §4.3 credential matrix `Decision` column | API/implementation decision markers and resolver tests |+| `D2` | Turn outcome plus copy discriminator | §4.5 turn-outcome matrix `Decision` column | provenance/API markers and locale copy |+| `D3` | Source mutation envelopes | §4.5 total mutation matrix `Decision` column | API route/envelope markers and API tests |+| `D4` | Native import actions | §6 import matrix `Decision` column | migration schema, code, locale, and scenario consumers |+| `D5` | Source protocols | `source.schema.json` protocol enum | adapter, config/runtime type, and spec consumers |+| `D6` | Configuration eligibility reasons | `agent-supply.schema.json` reason enum | §4.4, service projection, and both UI locale objects |++`M5` and `D6` are the newly exposed authorities from the circuit-breaker audit: the+earlier four-table sweep omitted supply-health and eligibility even though both were+closed decision domains. AC-33's generated test reads the listed live inputs in one+invocation and rejects orphan rows, orphan branches, stale snapshots, and unowned+external resolver importers.++| ID | Contract file | Final required shape |+| --- | --- | --- |+| **FC-01** | `README.md` | Names §4.3 as the sole configured-chain execution authority and §4.2 as the sole Add-time Source placement authority; documents the same-tested-head 13-file closure, the prelaunch full-handoff gate, and downstream read-only ownership; indexes all fourteen files and terminal `contract_version: 5`; describes Sources, exact configured routes, add-time matching, channel custody, configuration eligibility, inventory, adoption, and pull-only supply visibility without reproducing either authority. |+| **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable`), credential refresh-capability branches, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **5**. |+| **FC-03** | `source.schema.json` | `Source` requires canonical id, kind, vendor, `protocol: anthropic | openai_responses | openai_chat`, credential reference/custody, channel, ordinary `created_at` audit metadata, state/usage, and an unordered model inventory whose ids are unique within that Source. Every model is `{id, origin: "discovered" | "manual", reasoning_efforts: string[], display_name?, discovered_at?}`; the list is required, may be empty, and is editable for either origin. Hub-held subscriptions require no flag, consent field, or acknowledgement record. |+| **FC-04** | `oauth-flow.schema.json` | Subscription flows carry explicit vendor and `supply_channel`; an omitted channel resolves Claude to `native_cli` and ChatGPT to `hub`, while both opposite explicit choices remain legal. The native option exposes `native_source_already_exists` plus `existing_source_id` before login when the backend singleton is occupied. Claude Hub carries one informational risk-copy key; no other path carries warning or consent state. |+| **FC-05** | `agent-supply.schema.json` | Each backend stores `mode: hub | direct`, one explicit `sources.order`, and exactly one `{hops: [{source_id, model_id}, ...]}` row per menu model. `hops` is always present and may be empty; neither order has a policy discriminator. It enforces at most one native Source per backend and exposes `adopted_by: [{backend, menu_model}]` from persisted references; Source-card attribution reuses that projection. `supply_status` is the sole backend-health projection. Fresh-install construction uses Gateway; the onboarding service supplies Direct for an existing installation with no Model Hub state. No separate mapping, matching, enrollment, or takeover field exists. |+| **FC-06** | `agent-chain.schema.json` | Returns the stored exact Source/model hops in the same order with only `current`, `runnable`, closed blocker reasons (`source_missing`, `model_unsupported`, `native_cli_unavailable`, and Source-state reasons), and retry metadata added. It has no route-policy or capability-matching discriminator. Takeover derives from stored first hop plus live current position and adds no field. |+| **FC-07** | `probe-result.schema.json` | Covers saved-Source recovery tests, unsaved Add Source connectivity/protocol observation, route probes, and their distinct mutation guarantees. Add-flow results report classified reachability/authentication plus an observed protocol only after a real upstream response, never a credential ref. A failed observation may request a manual three-value probe-order hint but cannot save a protocol without response proof. |+| **FC-08** | `turn-provenance.schema.json` | Gateway turn records contain no route-policy discriminator; they record exact requested/configured model ids, exact Source attribution, ordered attempts, and the closed outcome set owned by §4.5's authoritative Turn-outcome copy matrix. `requested_model_changed` is derived from those exact ids and is never persisted. The schema mirrors the outcome set without reproducing its branches. A canceled in-flight attempt carries no fabricated Source failure. No separate mapping field, compatibility discriminator, or internal-version conversion state exists. |+| **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. |+| **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. |+| **FC-11** | `opencode-overlay.md` | Keeps stable normalized provider ids for menu identity and add-time match suggestions, supports the three protocols, and pins the exact configured Source/model hop per invocation. Runtime performs no provider matching, and no vendor metadata chooses a saved protocol. |+| **FC-12** | `api.md` | Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, and user-authored deletion, the explicit backend Source-order PUT, exact route GET/PUT, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes and forced Source/model deletion that preserves survivor order. A discovered-model delete returns the API-only `source_model_managed_upstream`; no UI action or copy consumes it. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, route policy, separate mapping, takeover, experimental-consent, or vendor-guessed protocol surface exists. |+| **FC-13** | `migration-scan.schema.json` | Describes only the user-facing copy-only import of existing Claude, Codex, and OpenCode local configuration. Its action enum and one contract example/fixture per value mirror §6's authoritative Native-config import action matrix, including the `keep_native` default and the rejected/deferred `reauth` and `controlled_import` cases. Successful `keep_native` and `import` items run Add Source's one-time match and sole §4.2 placement policy, then report the same visible `added_to` positions. Originals are never modified or deleted, duplicate native selection fails before OAuth or partial commit, and it contains no Model Hub internal contract/data conversion. |+| **FC-14** | `runtime-dependency.schema.json` | Defines the single local engine asset, immutable version/SHA, loopback binding, lifecycle/health, management and Gateway tokens, and fail-closed behavior. Engine availability is local Gateway health and never mutates an upstream Source cooldown. This entry does not widen the GA asset-mirror or platform-matrix research scope. |++The final set contains no `subscription_hub_experimental`, `experimental_consent_at`,+per-source consent record, `consent_required`, `opencode_api_key_only`,+`openai_compatible`, scalar model-entry `reasoning_effort`, `follow | custom`,+route `policy`, `order_enrolled_by`, separate `mappings` field, `mapping_applied` event,+`mapping` event reason, compatibility+discriminator, or internal contract-conversion transaction. I1 verifies the contract,+core, and shared-test absences; I2–I5 verify their owned runtime, UI, fixture, scenario,+and locale surfaces before release.++**Implementation and test landing checklist (complete before release).** The I1–I5 PRs+collectively touch every applicable row and leave no downstream compatibility task:++| Landing point | Required result |+| --- | --- |+| `config/v2_config.py` | Final Source/model/protocol/configured-route types, one canonical validation boundary shared by every persisted-Source writer and subsequent load, singleton and exact-pair uniqueness validation, one explicit Source order per backend and one explicit hops array per menu model, serializer completeness, fresh-install Gateway construction, and existing-install-with-no-Hub-state Direct onboarding. No policy state exists. |+| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 stored-chain executor and one Add Source implementation of §4.2's placement policy; the latter chooses and persists each matched hop position before returning `added_to`. Also owns the complete credential-failure matrix keyed by refresh capability, closed error classes, `adopted_by`, Source-global health, local-engine distinction, and all route/inventory guards. Runtime never matches, places, or substitutes. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. |+| `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py` | Vendor-specific OAuth defaults, duplicate-native rejection before adapter work, all-exit transient credential cleanup, durable revoke reconciliation, and the complete four-row native-config action matrix with original files untouched. Every imported Source passes I1's canonical final-shape validator before commit; no import writer bypasses it with direct dataclass construction. |+| `core/handlers/model_hub/{rpc,request,provenance,events}.py`, `vibe/ui_server.py`, `vibe/model_hub_client.py`, `core/controller.py` | Final API envelopes/routes mirror the guarded-mutation matrix, including forced Source-delete and whole-Route replacement in the shared `{removed_hops, interrupted}` reporting family; provenance/events mirror the complete turn-outcome matrix including `canceled`; Direct-mode responses remain explicit. During I1–I5, absence of `VIBE_MODEL_HUB_ENABLED` keeps the controller/routes/UI disabled; explicit enablement must construct the v3 aggregate. This is a release-control gate, not a compatibility layer. I6 removes it only after I5 evidence is green. |+| `core/handlers/model_hub/adapter.py` | Exact byte mirror of `model-hub-contracts/adapter-interface.py`, including three protocols and observation/cleanup signatures. |+| `core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/{config,client,state,adapter}.py` | Exact stored-hop execution, three-protocol transport, credential refresh capability, pre-stream fallthrough, post-stream no replay with classified health, and local Gateway failures at any request phase excluded from Source state and fallback. Turn copy is selected from the authoritative outcome matrix after state persistence and live annotation of the same stored chain. |+| `ui/src/components/settings/models/**` | Final Source/Gateway types and calls; protocol selector only after failed observation as a probe-order hint; Source cards reuse `adopted_by`; Add Source renders the stored backend Source order plus returned `added_to` positions without inferring newness from order; every model row edits the exact stored hops and mappings runtime executes; backend groups consume `supply_status`; takeover derives from the chain; saved Source details exposes only guarded Refresh models; Direct groups expose reversible mode actions. No bottom-only “new” section, policy control, “not enabled” hint, latency/last-check copy, consent/experimental surface, separate mapping object, takeover field, supplying-backends field, or vendor default protocol exists. Any new-item marker is transient presentation state, not a route field. `vendorMeta.ts` may order probes but cannot choose a saved protocol. Narrowing `SourceProtocol` must be checked against production and test files, not only the production-only `tsconfig.app.json` program. |+| `ui/src/i18n/{en,zh}.json`, `vibe/i18n/{en,zh}.json` | Exact mirrored final reason/detail and `supply_status` keys, including `native_cli_unavailable` and `route_unconfigured`; every Turn-outcome copy-matrix key; the derived takeover label; distinct Direct/Native terms; the sole Claude Hub warning; compact protocol-observation failure copy; and no retired policy, consent, experimental, or mechanism-copy keys. A registry-generated guard compares closed outcome/discriminator, blocker/remedy, and credential-remedy relations with both locale sets. |+| `tests/test_model_hub_config.py` | The adapter parity gate at current line 159 remains exact; the mirror-registry version gate at current line 236 and provenance version gate at current line 314 use terminal value **5**; round-trip/completeness fixtures use only final Source and route shapes. |+| `tests/test_model_hub_api.py` | The current line-1204 `experimental_consent_at` assertion becomes an absence assertion; API fixtures cover unique final model entries, edited-effort preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, deterministic policy-chosen Add Source placement with the returned persisted position, every guarded-mutation row including Source deletion from all backend Source orders and routes with survivor order preserved, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. |+| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | Sole §4.3 stored-chain consumption, no runtime matching or substitution branch, exact effort membership, every credential-capability row, configured-order fallthrough, every turn-outcome/copy row, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, canceled provenance, vendor OAuth defaults, and exact diagnostic shapes. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **5** on its same tested head; after I1 merges, I2 owns that whole file's runtime-behavior updates. |+| `ui/src/components/settings/models/**/*.test.*` | No protocol control on the normal add flow, honest manual probe-order fallback, final inventory editing, visible and adjustable backend Source order plus policy-chosen Add Source placement, no position-based newness or bottom-only new section, exact configured-chain editing, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no policy/not-enabled/latency/consent surface. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |+| `tests/scenarios/model_hub/**`, `tests/scenario_harness/model_hub_native_oauth.py` | End-to-end final-shape setup, all four native-import action rows, reversible Direct/Gateway onboarding, subscription custody, protocol observation, one-time add matching plus deterministic persisted placement, exact configured route execution and mapping, guarded saved refresh and Source-delete envelopes, silent successful takeover, truthful blocked/native/engine terminal copy, and exhaustion failure without takeover semantics. The I3-owned migration scenario validates each imported Source, serializes the full result, and reloads it through the same canonical validator. |++#### Sealed current-consumer findings — reviewed head `5cffd3fff7`++The exact-head review on 2026-08-09 found one premise superseded by the owner's+zero-migration ruling and eight implementation consumers that still expose the pre-S-1+shape. This is the review-loop circuit breaker's scope decision: K1 does not grow into+the I1/I2/I4 implementation batch. The eight live defects below are binding release+work under their existing ACs and landing rows; the default-off release gate remains in+place until those lanes and I5 evidence merge. The review text is retained verbatim so+the implementing lane receives the evidence rather than a paraphrase.++| Review thread | AC / disposition | Landing point | Responsible lane |+| --- | --- | --- | --- |+| `3742846987` | Owner ruling 2026-08-09: no internal v4-to-v5 data migration; the finding's upgraded-install premise is superseded and no compatibility loader is permitted | Final-contract handoff and `config/v2_config.py` absence proof | K1 ruling only; no implementation lane |+| `3742846989` | AC-22; valid prelaunch consumer gap | Agent projection/write flow in `service.py` and Models route editor | I1 + I4 |+| `3742846991` | AC-26; valid prelaunch consumer gap | Source serializer plus all Models `SuppliedModel` consumers and mocks | I1 + I4 |+| `3742846992` | AC-30; valid prelaunch consumer gap | No-candidate provenance producer, runtime blocker propagation, and pull-surface rendering | I1 + I2 + I4 |+| `3742846996` | AC-33 / terminal-version handoff; valid prelaunch consumer gap | Outer Model Hub REST envelope and its contract/API tests | I1 |+| `3742846998` | AC-22; valid prelaunch consumer gap | Source-order PUT/read projection and Models Source-order editor | I1 + I4 |+| `3742847000` | AC-26; valid prelaunch consumer gap | Model-delete refusal/force/success envelope and confirmation consumer | I1 + I4 |+| `3742847001` | AC-26; valid prelaunch consumer gap | Per-model reasoning-efforts inventory editor and UI evidence | I4 |+| `3742847002` | AC-26; valid prelaunch consumer gap | Refresh merge implementation and API test | I1 |++> **Preserve v4 model provenance when loading config**+>+> On any upgraded installation with saved Model Hub models, the existing JSON contains+> `provenance` because the parent serializer wrote that key, but this loader now reads+> only `origin`; every non-empty legacy model inventory therefore raises+> `Config 'model_hub.sources.models.origin' is invalid` during `V2Config.load()`. Accept+> and migrate the legacy key before requiring the v5 spelling so persisted Sources+> remain usable after upgrade.++> **Keep persisted mappings in the live UI projection**+>+> When Claude or Codex already has custom model mappings, removing them from every Agent+> response makes `AgentCard` display those routes as Global because it reads+> `agent.mappings`; more seriously, the next route edit in+> `SettingsModelsPage.setModelRoute` reconstructs the total mapping write from that+> now-empty projection and can overwrite all previously stored mappings with only the+> newly edited one. Do not strip this field until the current Web UI is migrated to an+> equivalent authoritative route read/write flow.++> **Align the Source model discriminator with the current UI**+>+> For every Source returned by the live API, this serializer now emits `origin`, while+> `ui/src/components/settings/models/types.ts::SuppliedModel`, `OpenCodeMenuDrawer`, and+> the custom-model helpers still read `provenance`. Consequently manual models loaded+> from the server are no longer recognized as editable/custom models, even though the+> mock API continues using the old property and masks the regression. Update the Web UI+> consumers in the same transition or retain a compatible projection.++> **Populate blockers for blocked no-candidate turns**+>+> When a non-empty route has no runnable hop because Sources need re-auth, key+> replacement, top-up, or native CLI repair, the v5 provenance record still writes+> `blockers: []`, making it indistinguishable from an unconfigured route and preventing+> consumers from rendering the required remedy. Fresh implementation evidence beyond+> the earlier documentation thread is that both `mark_no_candidate` paths retain only+> `supply_state`, and this new producer hardcodes the blocker array; carry the exact+> blocked-hop identities and reasons into this record.++> **Bump the outer REST envelope to contract version 5**+>+> Every Model Hub endpoint still builds its success and failure envelope from+> `CONTRACT_VERSION`, which remains 3, even though this change declares the final REST+> contract to be v5 and bumps the nested chain, probe, and runtime payloads to 5. Any+> client that validates the advertised v5 envelope will therefore reject every response+> before it can inspect the nested object; advance the outer constant with the rest of+> the atomic contract transition.++> **Complete the policy-free source-order transition**+>+> When a v5 caller follows the new API contract and sends+> `PUT /agents/<backend>/sources` with `{order: [...]}`, `set_agent_sources` still+> rejects it because the implementation accepts only the retired `policy` bodies; at+> the same time this read projection now omits `policy`, causing the current+> `SourceOrderDrawer` to default every persisted Custom order to Follow. Migrate the+> write handler and Web UI together instead of removing only the read discriminator.++> **Return the guarded cascade envelope for model deletion**+>+> When a manual model is referenced by configured routes, the non-forced delete returns+> only the generic `mode_switch_blocked` error, so the UI receives neither+> `would_remove_hops` nor `would_interrupt` and has no information with which to present+> the required force confirmation. A forced delete then returns only the Source despite+> pruning references, omitting the corresponding `removed_hops` and `interrupted`+> result; implement the shared guarded-mutation envelope so the deletion can be+> confirmed and reported without silently losing route information.++> **Expose reasoning-effort editing in the Models UI**+>+> For every model created through the current Models page, this dialog hardcodes+> `reasoning_efforts: []`, and repo-wide UI search finds no React caller of the newly+> added `updateModelReasoningEfforts` API. Users therefore cannot declare any supported+> reasoning effort for either discovered or manual inventory entries, despite the new+> capability being persisted and exposed by the server; add the specified inventory+> editor rather than shipping an unreachable PATCH method.++> **Preserve per-model discovery timestamps on refresh**+>+> When refresh returns a model ID that was already in the discovered slice, the code+> correctly preserves its edited display name and reasoning capabilities but always+> replaces `discovered_at` with the refresh time. That destroys the model's original+> discovery timestamp on every successful unchanged refresh and contradicts the+> separate `last_discovered_at` field that records inventory freshness; copy+> `existing.discovered_at` for retained IDs and stamp only newly discovered entries.++#### Sealed current-consumer findings — reviewed head `f57f6f2b1f`++This is the second reviewed head on the same prelaunch-consumer root-cause class, so the+review-loop circuit breaker remains open: K1 records the complete inventory and does not+patch I1/I2/I3/I4 implementation. Every finding is valid implementation evidence against+the final contract and remains release-blocking under the default-off gate.++| Review thread | AC / disposition | Landing point | Responsible lane |+| --- | --- | --- | --- |+| `3742889356` | AC-19; valid prelaunch producer/consumer vocabulary gap | `_source_eligibility`, final TypeScript union, and both locale objects | I1 + I4 |+| `3742889357` | AC-26; valid prelaunch inventory-edit gap | Existing-model display-name edit payload and Models API/UI test | I4 |+| `3742889359` | AC-22 / FC-13; valid prelaunch import-result gap | `migration_apply`, RPC/result type, and native-import UI flow | I1 + I3 + I4 |+| `3742889361` | AC-26; valid prelaunch invocation gap | Exact-model effort membership in the shared service/runtime invocation path | I1 + I2 |++> **Keep emitted eligibility keys in the UI vocabulary**+>+> When a Claude or Codex subscription Source is projected for the OpenCode agent,+> `_source_eligibility` still emits `models.eligibility.opencode_api_key_only`+> (`core/handlers/model_hub/service.py:1903-1904`), even though this change removes that+> value from the TypeScript union and both locale files. The resulting `/agents` payload+> violates the newly closed vocabulary and the UI can display an untranslated key.+> Fresh implementation evidence beyond the earlier documentation finding is that the+> live service producer was not migrated; map this case to the retained reason or update+> the producer together with the vocabulary.++> **Preserve reasoning capabilities during display-name edits**+>+> When an existing manual model has a non-empty `reasoning_efforts` list, opening its+> current edit dialog submits `reasoning_efforts: []`; `add_custom_model` treats that+> existing entry as an update and assigns the submitted list at+> `core/handlers/model_hub/service.py:2321-2325`. Thus changing only the display name+> silently erases the persisted capabilities. Fresh evidence beyond the earlier+> unreachable-editor comment is this destructive existing-entry upsert path; submit the+> current list or use a mutation that does not replace capabilities.++> **Return the contracted migration placement results**+>+> When native-config import succeeds, this v5 route now promises `added_to`, but+> `ModelHubService.migration_apply` still returns only `{applied, sources}`+> (`core/handlers/model_hub/service.py:3166-3176`), and the frontend+> `MigrationApplyResult` likewise has no placement field. A client following the final+> contract therefore cannot receive or display the exact Route positions created by the+> import. Update the service, RPC/UI type, and import flow together, or remove this field+> from the authoritative response contract.++> **Enforce per-model reasoning capabilities before invocation**+>+> When a turn requests a reasoning effort that is absent from this newly persisted list,+> the value is never consulted: the only later engine call forwards the original request+> unchanged at `core/handlers/model_hub/service.py:3271-3282`. Consequently an+> unsupported effort reaches the upstream instead of being replaced with `null`,+> producing the terminal parameter failures the v5 execution contract is intended to+> prevent. Apply the exact-model capability check in the shared invocation path so+> Claude, Codex, and OpenCode inherit the same behavior.++#### Sealed current-consumer findings — reviewed head `8572a542ab`++This is the third reviewed head on the same prelaunch-consumer root-cause class. The+review-loop circuit breaker therefore remains open and the sealed implementation-ledger+ruling continues to apply: K1 records these release-blocking consumers without patching+I1/I2/I3/I4 implementation while the default-off release gate remains in force.++| Review thread | AC / disposition | Landing point | Responsible lane |+| --- | --- | --- | --- |+| `3742927535` | AC-33; valid prelaunch contract-mirror gap | Nested chain/probe version constants, mock responses, and frontend contract fixtures | I1 + I4 |+| `3742927537` | AC-26 + AC-29; valid prelaunch canonical-validation gap | Final Source/model payload and persisted-config validator plus omission fixtures | I1 |+| `3742927538` | AC-26 / FC-12; valid prelaunch guarded-mutation result gap | Source-delete service, RPC, HTTP/client envelope, and confirmation/reconciliation consumer | I1 + I4 |++> **Bump the frontend nested contract mirrors with the backend**+>+> When the Models UI or its mock client consumes a chain or probe, the backend and+> schemas now advertise nested contract version 5, but+> `ui/src/components/settings/models/types.ts:15-17` still defines both versions as 4+> and `modelsApi.ts:781,811` builds mock responses from those stale constants. The live+> client blindly casts responses to these v4 types, while mock-mode tests continue+> exercising v4 payloads, so the frontend no longer provides contract-version coverage+> for the v5 transition; update the TypeScript constants and affected fixtures in the+> same atomic bump.++> **Reject final model entries that omit reasoning efforts**+>+> When a v5 persisted model or Source-create payload omits `reasoning_efforts`, this+> default silently accepts it and serializes the entry back with `[]`, even though+> `source.schema.json` requires the field and the final contract defines an empty array+> as an explicit declaration that the model supports no reasoning effort. This lets+> malformed final-shape data bypass the canonical config boundary and changes omission+> into a capability decision; require the key to be present rather than defaulting it.++> **Return cascade details from Source deletion**+>+> When a forced Source deletion removes configured route hops,+> `ModelHubService.delete_source` returns nothing and both+> `core/handlers/model_hub/rpc.py:31-33` and `vibe/ui_server.py:3124-3125` discard all+> mutation detail. This new v5 route contract promises `removed_hops` and `interrupted`,+> so the client cannot reconcile or report which routes were pruned after a successful+> cascade; return the contracted guarded-mutation envelope through the service, RPC,+> and HTTP layers.++#### Sealed contract-and-consumer findings — reviewed head `8287d41da3`++This fourth reviewed head remains behind the same default-off release gate. Two findings+identify final-contract closure still owed by I1 and two identify canonical consumer+validation still owed by I1; none identifies two contradictory normative sentences.+Under the sealed-ledger ruling, K1 records all four without changing contract or+implementation files.++| Review thread | AC / disposition | Landing point | Responsible lane |+| --- | --- | --- | --- |+| `3742980271` | AC-26 + AC-29; valid prelaunch identity-validation gap | Per-Source model-id uniqueness at config, Source-create, and discovery boundaries plus mutation fixtures | I1 |+| `3742980274` | AC-22 + AC-33; valid prelaunch final-contract persistence gap | Final `agent-supply.schema.json` Route rows and V2 config serialize/reload boundary | I1 |+| `3742980278` | AC-23 + AC-33; valid prelaunch final-contract rejection gap | Final OAuth/API failure envelope, pre-adapter singleton guard, and add-flow consumer | I1 + I3 + I4 |+| `3742980279` | AC-26 + AC-29; valid prelaunch credential-boundary gap | Canonical reasoning-effort validator and create/persist/PATCH negative fixtures | I1 |++> **Enforce unique model IDs within each Source**+>+> When a Source-create payload or discovery response contains the same model ID twice+> with different metadata, this new uniqueness invariant is not enforced:+> `ModelHubConfig.from_payload` checks duplicate Source IDs only, and+> `_apply_discovered_models` appends one entry per discovery result. The persisted+> inventory can therefore contain ambiguous identities;+> `update_model_reasoning_efforts` updates only the first match while+> `delete_custom_model` removes every match. Reject duplicate per-Source model IDs at+> the V2 config boundary and deduplicate or reject discovery results.++> **Add persisted routes to AgentSupply**+>+> When Add Source or the route PUT writes `B.routes[M].hops`, the claimed persistence+> shape has nowhere to store it: `agent-supply.schema.json` has+> `additionalProperties: false` but no `routes` property, and+> `ModelHubAgentSupplyConfig` still persists the retired `mappings` list instead.+> Consequently the exact chains required by §4.3 cannot survive serialization/reload,+> and implementations cannot satisfy FC-05 without changing this supposedly final+> schema. Add the per-menu Route rows to both the schema and the V2 config boundary.++> **Contract duplicate-native OAuth rejection**+>+> When a backend already has its singleton `native_cli` Source, AC-23 requires OAuth+> start to return `native_source_already_exists` with `existing_source_id` before+> invoking the adapter, but neither `oauth-flow.schema.json` nor `api.md` defines that+> error or response field; repo-wide occurrences are limited to this prose. A server+> and client can therefore invent incompatible rejection envelopes—or begin the+> irreversible login despite following every frozen contract. Define the exact failure+> envelope in the authoritative API/schema and cover the pre-adapter rejection.++> **Reject credentials in reasoning-effort values**+>+> When a Source-create body, persisted config, or reasoning-effort PATCH contains a+> credential-looking value such as an API key, this validator accepts it as an ordinary+> non-empty effort string and `to_payload` writes it back verbatim. The surrounding+> create path explicitly rejects credential material in model IDs and display names,+> but neither that scan nor `_validated_reasoning_efforts` checks the new list, so+> plaintext credentials can enter config and API responses despite the contract's+> no-plaintext-credentials invariant. Apply the same credential-material rejection to+> every reasoning-effort entry at the canonical config boundary.++After I1 lands, `model-hub-contracts/**` is read-only to I2–I5. An implementation-proven+mismatch is reported to the orchestrator for a targeted decision; the discovering lane+does not edit or reinterpret the contract locally.++### Final-language sweep — push delivery wording-Lane L0 could not fix these: editing a frozen file **is** the version event (above), so-a docs-only spec-sync PR that touched them would have published `contract_version: 3`-by accident. They are listed here for **L1** to sweep inside its coordinated bump. None-of them changes a shape — each is description or prose text asserting a delivery layer-that no longer exists, and the fix is to restate it as feed/UI semantics (spec §4.5).+These existing contract descriptions assert a delivery layer that is absent from the+final product. They are listed for **I1** to sweep in its contract PR. Each final+description states feed/UI pull semantics from spec §4.5.| File | Where | What it still asserts || --- | --- | --- |@@ -710,7 +1160,7 @@ that no longer exists, and the fix is to restate it as feed/UI semantics (spec| `README.md` | the round-7 note (`:178`, `:228`) | 「§4.5's recipient rule now expands in two hops, backend → enabled Agents → scopes」 and 「expands to no Agent and therefore to no recipient」 — the two-hop recipient resolution the 10:54 cut superseded || `api.md` | events feed row (`:43`) | 「the IM push layer keys off `severity == "action_required"`」, 「recipients are resolved at push time … against the live routing table」 || `api.md` | mechanical-guard table (`:755`) | 「a push whose 「去处理」 lands on a row that renders nothing」 |-| `api.md` | `POST /sources/<id>/test` recover rule (`:559`) | 「severity promotion can push it to the user as news」 — the stated *reason* the unconditional `recover` emit is wrong, so L1 must restate the reason (a 「已恢复」 line in a feed with nothing to recover from) rather than delete the sentence and lose the rule |+| `api.md` | `POST /sources/<id>/refresh` recover rule (`:559`) | 「severity promotion can push it to the user as news」 — the stated *reason* the unconditional `recover` emit is wrong, so I1 must restate the reason (a 「已恢复」 line in a feed with nothing to recover from) rather than delete the sentence and lose the rule || `api.md` | `supply_interrupted` worked payload (`:685-693`) | 「always ELIGIBLE for a proactive push and never feed-only」, `agent: "codex"` as 「the addressing input」, 「the push layer resolves it to the scopes whose routing currently selects a Codex Vibe Agent」, and 「resolving at delivery rather than at emit」 as the kind's rationale |**The table above is a seed list, not a census — corrected twice, and that is the point@@ -723,8 +1173,8 @@ sit outside the twelve — `resolution-event.schema.json` `:49`, `:83`, `:94` an`README.md` `:98`, `:109`, `:145-146`.A hand-counted list of a moving target has now generated a finding in three consecutive-rounds, so **L1 must not treat this table as the sweep.** The sweep is mechanical and its-result, not this table, is the completion condition of the v3 bump. Run both from+rounds, so **I1 must not treat this table as the sweep.** The sweep is mechanical and its+result, not this table, is the completion condition of the final contract commit. Run both from`docs/plans/model-hub-contracts/`:```@@ -733,7 +1183,7 @@ grep -rniE 'push|IM 推送|notif|alert|interrupt the user|proactive' .grep -rnE 'IM surfaces?|IM 平台|conversation surface' .```-The first must return **zero** hits when v3 is frozen — the heading no longer exists. The+The first must return **zero** hits in the final contract set — the heading no longer exists. The**third was added in review round 7**, because the second misses a whole class: it greps`IM 推送`, not bare `IM`, so `README.md:258` — which still lists `turn-provenance.schema.json`as consumed by 「IM surfaces (per-turn detail)」 — survives it untouched, and would have@@ -742,22 +1192,22 @@ batch owes. That is a **surface-ownership** promise rather than delivery semantiis why the delivery-semantics pattern never saw it. Its two current hits are both seeds:that README row, and `turn-provenance.schema.json:5`'s 「the conversation surface reveals ondemand」. **Both are now outright wrong rather than merely loose** (owner ruling 07-29 14:03):-provenance has no chat surface at all, so v3 must delete the consumer promise and the+provenance has no chat surface at all, so the final contract must omit the consumer promise and therendering phrasing rather than narrow either to Web. The second grep returns a supersetthat still needs judgement: `interrupted`/`supply_interrupted`are state names the design keeps, and 「never pushes」 phrasing may legitimately survive asa statement of the cut. What must not survive is any passage a later lane could read aslicence to build proactive delivery, or any pointer into a deleted heading. The rows above-are the seeds — the ones already read and characterised — and they save L1 the reading,+are the seeds — the ones already read and characterised — and they save I1 the reading,not the sweeping.-**L1's v3 mandate includes purging ALL delivery-semantics text the sweep returns**, not+**I1's final-contract mandate includes purging ALL delivery-semantics text the sweep returns**, notjust the rows that also change a shape. The distinction matters because these files are-the normative contract: a frozen description that still says 「always ELIGIBLE for a+the normative contract: a description that still says 「always ELIGIBLE for aproactive push」 will be read by L2/L3 as licence to build the push the owner cut, and adangling §4.5 reference sends the reader to a heading that no longer exists — atranscription defect either way. None of them changes a *shape*; the fix is to restate-each as feed/UI semantics (spec §4.5), inside the same coordinated bump.+each as feed/UI semantics (spec §4.5), inside I1's contract PR.One entry changes meaning rather than just wording, per AC-6's downgrade — and with itthe **root the expansion starts from** (07-29, review round 2). The@@ -819,9 +1269,17 @@ Review round 8, P1, on `docs/plans/model-hub.md`, [thread](https://github.com/av>> A `balance_exhausted` source remains `needs_action` until a request observes the top-up, but this sentence's promised “next probe or turn” cannot perform that observation: the turn pipeline excludes every `needs_action` source as non-runnable, and the probe returns `probe_no_candidate` when the chain has no runnable member. If it is the only supplier, the source is therefore never called again and can never recover after the user tops up. Add a source-specific recovery probe that may test a blocked source after explicit user action, or otherwise define how the state is cleared safely.-**Spec action at round 8.** `model-hub.md` §4.5 retracts the claim that a topped-up balance is 「re-checked on the next probe or turn」 and states why both paths exclude the source; the recovery route is deliberately not frozen.+**Final route ruling (2026-08-09).** `model-hub.md` §4.5 retracts the claim that a+topped-up balance is re-checked on a normal turn. The one explicit saved-Source path is+`POST /api/models/sources/<id>/refresh`.-**Acceptance.** A source that is the ONLY supplier of a model, sitting in `balance_exhausted`, returns to service after the user tops up and takes the documented action — without deleting and re-adding the source, and without a credential change. Scenario `model_hub_blocked_source_recovery` (new) covers exactly that sequence and fails on the round-8 behaviour, where the state can never clear. **The scenario drives the Models-page action, not the route** (07-29 ruling): calling the recovery endpoint directly would pass while the button that reaches it does not exist, which is the exact gap this criterion was reopened to close — 「the user tops up and takes the documented action」 is only true if the action is reachable from the page. **The action reaches the existing route, and a second one is not added** (07-29 17:09 ruling, which replaced round 8's 「the recovery route is deliberately not frozen」 with a decision): `api.md:33` already contracts `POST /api/models/sources/<id>/test` as re-discovery, `ModelHubService.test_source` already re-discovers that one source and clears its state to `standby`, and **AC-11's acceptance already names that endpoint as THE non-turn re-discovery path** — so a second recovery route beside it is the duplicated-mechanism class this batch deletes on sight, and it would let the Models-page action be wired to a path AC-11 does not test. What L1's v3 owes is therefore the **blocked-source semantics on that route**, not a new term: the page affordance and AC-11's path are the same endpoint by construction and cannot diverge. One fewer v3 term.+**Acceptance.** A Source that is the only supplier of a model, sitting in+`balance_exhausted`, returns to service after the user tops up and invokes the+Source-details action — without deletion, recreation, or a credential change. Scenario+`model_hub_blocked_source_recovery` drives that visible action and asserts it calls the+sole saved refresh/recovery mutation. The same route may test `needs_action` and+`error`, and AC-11 drives its non-turn event fixture through it.+There is no parallel `/test` or `/recover` Source mutation.### AC-4 — Represent canceled turns in provenance@@ -831,7 +1289,9 @@ Review round 8, P2, on `docs/plans/model-hub-contracts/turn-provenance.schema.js>> Avibe has explicit Stop/cancel paths that settle an in-flight turn as canceled, including `SessionTurnManager.cancel`, but none of these four outcomes can represent that terminal state. It is not `served`, fallback exhaustion, a non-fallback adapter error, or a no-candidate turn; labeling it `failed_terminal` would also require inventing one of the four error reasons and possibly a source attempt. Since this contract says provenance always exists when a turn resolves, add a canceled outcome and define how any attempt that was interrupted is recorded.-**Spec action at round 8.** `model-hub.md` §4.5 names this as AC-4 alongside AC-1; `turn-provenance.schema.json` keeps its four outcomes at round 8.+**Final-shape action (2026-08-09).** Round 8 left the contract with four outcomes;+FC-08 now requires `canceled` as the fifth terminal outcome in I1's final contract and+same-tested-head closure.**Acceptance.** A turn settled by Stop/cancel produces a provenance record that is not `served`, not `exhausted`, not `failed_terminal` and not `no_candidate` — i.e. the vocabulary grew — and an attempt that was in flight when the cancel landed is recorded without inventing a failure reason for it. Cancelling mid-stream must not produce a record that claims a source failed. **The classification comes from the turn FSM's terminal state** (07-29 ruling, §3): a test drives a real Stop through `SessionTurnManager` and asserts the canceled outcome, and a second drives a dropped connection on an otherwise identical turn and asserts it is *not* recorded as canceled. Both legs are required, because an implementation that infers cancellation from the transport passes the first and fails the second — and it is the second that decides whether this record can be trusted. **Both legs presuppose that the in-flight attempt can be tied to the turn at all** — which is what the **process-scoped** gateway credential plus the FSM's active-turn lookup delivers (07-29 round-7 ruling as amended 14:04, replaced 14:39, and **settled 15:07**, §3). Without it, a concurrent same-backend turn's attempt can be recorded against the canceled turn and the second leg passes for the wrong reason — so **both legs run on the unambiguous fixture**, one active turn for that scope, where the attribution is exact. A **third leg** covers the case that fixture excludes, restated 07-29 15:42 so that it asserts only against what the frozen contracts already carry — **ambiguous-leg-absent plus control-leg-present**: two turns deliberately concurrent in the same cwd, one canceled, and **neither turn's provenance contains the interrupted attempt**; then **the same fixture run sequentially**, without concurrency, **must** produce the provenance record. It fails an implementation that resolves the ambiguity by picking — which would let a cancellation record blame an attempt that belonged to the turn still running — and equally one that drops silently, since the control leg would come up empty. The 15:07 wording's second half (「the resolution-event log does contain its source-level outcome」) is deleted: events trace transitions, healthy attempts are silent by design, and an unattributable attempt legitimately leaves no trace — the control leg carries the anti-dropping burden without contracting a new kind or reason. The earlier 14:39 wording (「recorded at the coarse grain, marked as such」) is superseded: `turn-provenance.schema.json` requires `turn_id`, so no such record could be written. The classification itself is unchanged: still FSM terminal state, never transport.@@ -855,18 +1315,25 @@ Review round 8, P1, on `docs/plans/model-hub.md`, [thread](https://github.com/av>> When a hub API-key source appears in multiple backends' `sources.order`, a failure discovered on Claude changes the source-global health for Codex as well. Expanding only the event's single backend therefore omits Codex-routed scopes from the required push, contradicting the preceding rule that source-scoped events affect every Agent whose order contains the source. Resolve source-scoped events from `from_source` across all backend orders (or emit one event per affected backend), while retaining backend-only expansion for `supply_interrupted`.-**Spec action at round 8, narrowed at round 9, reduced at 10:54, DOWNGRADED 07-29 (orchestrator ruling — owner-vetoable).** The finding's remedy — expand the record across every affected backend — was built for a push that no longer exists, and carrying it into the record layer created a criterion no conforming record could satisfy: `resolution-event.schema.json` has no field for a backend SET (`agent` is a single enum), so closing it would have required a frozen-schema edit and moved this criterion into the v3 set. **The ruling is that the record layer stays single-grained.** A source-scoped event is recorded ONCE, unattributed: `agent` keeps its current semantics — the discovering context, or `system` — and the record makes no claim about which backends are affected. Per-backend impact is **derived live by the consumers** from current per-agent orders, using the (backend, model) chain test the supply guard already computes: the feed renders source events as unattributed lines, and the agent status pills evaluate the question at render time. Derivation is not a downgrade of the round-8/9 reasoning but its correct home — a set frozen into the record goes stale the first time a user reorders a backend, while the derived answer cannot. **No schema change, and this criterion stays on v2.**+**Spec action at round 8, narrowed at round 9, reduced at 10:54, DOWNGRADED 07-29 (orchestrator ruling — owner-vetoable).** The finding's remedy — expand the record across every affected backend — was built for a push that no longer exists, and carrying it into the record layer created a criterion no conforming record could satisfy: `resolution-event.schema.json` has no field for a backend set (`agent` is a single enum). The record therefore stays single-grained. A source-scoped event is recorded once, unattributed: `agent` keeps its current semantics — the discovering context, or `system` — and the record makes no claim about which backends are affected. Under S-1, per-backend impact is **derived live by consumers from persisted per-model chains**: status surfaces read the Source's current blocking state only for exact hops that reference it. The record never stores fan-out, and runtime never constructs another chain.-**Acceptance** (rewritten 07-29 to the downgrade; the round-8 and round-9 wording it replaces is the delivery-era text). One hub API-key source that sits in both Claude's and Codex's `sources.order` **and supplies a protected model on each** fails once, and **exactly one source-state failure record is written** — no per-backend fan-out, no backend list on the record, `agent` naming only the discovering context. The count is over the failure record, not over the event stream (07-29, review round 2): when a fallback covers the failure, `resolution-event.schema.json:104` requires the pair 「one `switch`, info + one `needs_action`, action_required」, each true about its own subject, so the companion `switch` is conforming traffic that does not count toward this assertion — a test written as 「exactly one event total」 would reject the contract's own behaviour and pressure the implementation into suppressing the feed's switch line. Both backends' status surfaces nevertheless report the failure — **computed from the source's CURRENT blocking state against each backend's current order and chains, never from the retained record** (corrected 07-29, review round 8: the earlier 「computed from that single record against their current orders」 wording put the normative sentence in direct conflict with the derivation-input paragraph below, and an implementer following this line alone could pass the failure leg while leaving both backends stuck at 需处理 until the record aged out) — and the negative case still holds through the derivation rather than through the record: the same source in Codex's order but in no Codex chain (a GLM-only key while Codex runs `gpt-5.6`) leaves Codex's surface unaffected. An implementation that emits one `needs_action` per affected backend fails the count assertion; one that renders only the discovering backend fails the derivation assertion.+**Acceptance** (final S-1 reading). One Hub API-key Source referenced by an exact Claude+route hop and an exact Codex route hop fails once, and exactly one source-state failure+record is written — no per-backend fan-out or backend list, with `agent` naming only the+discovering context. Both backends' status surfaces derive the effect from the Source's+current blocker against their persisted chains, never from the retained record. A Source+with no Codex hop leaves Codex unaffected. Emitting one `needs_action` per affected+backend fails the record count; rendering only the discovering backend fails the live+chain projection.**The derivation input is live state, never the retained record (07-29, review round 6).**-The paragraph above says the surfaces are 「computed from that single record against their-current orders」, which read literally licenses exactly the sticky status §4.5 forbids: a+The historical paragraph above said the surfaces were 「computed from that single record+against their current orders」, which read literally licenses exactly the sticky status §4.5 forbids: asource that recovers on its own — a cooldown lapsing, a quota window resetting — wouldstay marked 需处理 on both surfaces until the record aged out, because the record is whatwas queried. It is the wrong input. A record answers 「what happened」 and belongs to the最近切换 feed; a status answers 「what is true now」 and reads the source's **current**-blocking state against each backend's **current** order and chains (spec §4.5, and+blocking state against each backend's **current persisted chains** (spec §4.5, and`model-hub.md`'s 「source and agent status read live state, not events」). The record iswhat makes the failure *visible in the feed*; it is not what makes the status *true*.@@ -891,6 +1358,12 @@ Review round 9, P1, on `docs/plans/model-hub-contracts/api.md`, [thread](https:/### AC-8 — Exclude disabled mapping rows from the protected set+**Current v3 disposition (2026-08-09).** The live-mapping acceptance block retained+below is historical and non-executable. AC-22's final-shape acceptance supersedes it+with configured-route fixtures that exercise protected-model and disabled-configuration+behavior without creating a mapping field or resolver branch.+The guard invariant survives; the historical fixture shape does not.+Review round 10, P2, on `docs/plans/model-hub-contracts/api.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099008). Verbatim:> **Ignore disabled mappings when building the protected set**@@ -963,11 +1436,18 @@ Review round 10, P1, on `docs/plans/model-hub-contracts/resolution-event.schema.**Spec action at round 10, reduced 07-29 10:54.** RECORDED, not fixed, and this was the one round-10 finding where the two texts were flatly opposed. The schema says `system` 「expands to no Agent and therefore to no recipient」; §4.5 said 「a Web UI mutation and a mid-turn failure resolve their recipients identically」 and derives a source-scoped kind's affected backends from the failed source. §4.5 is the normative side: `agent` was never the addressing key (round 7 made it a backend identifier consumers must expand), and the zero-recipient sentence is right only for the case it was written for — an event with no affected source, such as a manual recovery that changed nothing about supply. **With push cut, 「recipient」 drops out of both texts and what is left is the event shape**: the schema's `system` sentence still tells a consumer that such an event affects nothing, which is false for a settings-page revocation and would leave that failure out of the feed and out of the 「模型」 page's 需处理 state. The two remedies the finding asks for are unchanged and are both shape rules: reserve the zero-expansion reading for events with no affected source, and disallow `system` on backend-scoped `supply_interrupted`. Note the grain this now works at, per AC-6's downgrade: 「affects something」 means the record carries a `from_source` the consumers can derive impact from — not that the record itself names backends, which it never does.-**Acceptance** (delivery half deleted 07-29 10:54; the event-shape half is the whole criterion). Drive it from a declared non-turn path: `POST …/sources/<id>/test` re-discovers a source that is the last supplier of a protected model and finds it dead, producing a `needs_action` event with `agent: "system"` and `from_source` set to that source (corrected 07-29, review round 11: round 10 drove it from a Web-UI revocation, which `api.md` documents as an agent-scoped `supply_interrupted` with `from_source: null` and `reason: "no_enabled_source"` — a trigger that never emits the event under test, and `system` appears nowhere in that file). The record this path writes is **equal in kind, `reason`, `from_source` and `severity`** to the one the identical failure writes when discovered mid-turn — record equality between the two paths is the assertion, replacing round 10's recipient equality — so the consumers derive the same state either way and the feed and the 「模型」 page agree regardless of who noticed. Equality is asserted on the record's own fields, not on a backend set, per AC-6's downgrade. A `supply_interrupted` event carrying `agent: "system"` is rejected by the schema. An implementation that reads the current description literally records the re-discovery as affecting nothing and fails.+**Acceptance** (delivery half deleted 07-29 10:54; route consolidated 2026-08-09).+Drive the non-turn path through `POST …/sources/<id>/refresh`: it re-discovers a Source+that is the last supplier of a protected model and finds it dead, producing a+`needs_action` event with `agent: "system"` and `from_source` set to that Source. The+record is equal in kind, `reason`, `from_source`, and `severity` to the identical+mid-turn failure, so feed and Models-page consumers derive the same state regardless of+who noticed. A `supply_interrupted` event carrying `agent: "system"` is rejected. AC-3+and this criterion name the same saved refresh/recovery route; no `/test` alias exists.**Remedy surface, added 07-29 review round 5 — L1's coordinated v3.** The fixture above isunbuildable against the frozen shape, and this is the defect rather than the fixture: `POST-…/sources/<id>/test` takes **no model input** — it re-probes a source — while+…/sources/<id>/refresh` takes **no model input** — it re-probes a source — while`resolution-event.schema.json` lists `model_id` in `required` as a bare `{"type":"string"}`. A source that supplies several models therefore leaves the implementation threebad options: fabricate one model, emit one event per model (which breaks AC-6's 「recorded@@ -1004,7 +1484,7 @@ Review round 10, P1, on `docs/plans/model-hub-contracts/api.md`, [thread](https:**The two halves take different confirmations** (orchestrator ruling, 07-29 — review round 1 of the L0 PR): the re-auth confirmation is **unconditional**, and the computed `would_interrupt` guard belongs **only to the `api_key`/Hub path**. The reason is that the guard is not computable on the native path: which models a narrower account can reach is knowable only *after* the login, and the login is the irreversible act. Requiring a computed guard before it would make the confirmation depend on a fact that does not exist yet — so what the owner ruled was a flat irreversibility warning, shown every time, not a supply prediction. The Hub path has the opposite shape: discovery precedes commit, so there the guard is real and the refusal is computed from it.-**Acceptance** (re-auth half settled 07-29 10:44 by AC-2's ruling; guard scope fixed 07-29 by the ruling above). An elective `PUT …/credential` onto a narrower key is refused with `source_last_supplier` + `would_interrupt`, and the identical request carrying the documented override commits and reports `interrupted_pairs` — with the override travelling through a declared request field, not a query string the contract never mentions. For re-auth, the assertion is the **unconditional** one: every `native_cli` re-auth presents AC-2's irreversibility confirmation before the login starts and can be aborted there, **regardless of what the new account will turn out to supply**, and no path reaches a completed OAuth flow that then needs a second round trip to confirm. A UI that must re-run the OAuth flow to confirm fails this test; so does one that lets the login complete and only then discovers it cannot commit; and so does one that tries to gate the confirmation on a pre-login supply computation, which cannot be performed.+**Acceptance** (re-auth half settled 07-29 10:44 by AC-2's ruling; guard scope fixed 07-29 by the ruling above). An elective `PUT …/credential` onto a narrower key is refused with `source_last_supplier` and the exact guarded response from §4.5's authoritative Source-mutation envelope matrix; the identical request carrying that row's override commits with that row's success envelope. For re-auth, the assertion is the **unconditional** one: every `native_cli` re-auth presents AC-2's irreversibility confirmation before the login starts and can be aborted there, **regardless of what the new account will turn out to supply**, and no path reaches a completed OAuth flow that then needs a second round trip to confirm. A UI that must re-run the OAuth flow to confirm fails this test; so does one that lets the login complete and only then discovers it cannot commit; and so does one that tries to gate the confirmation on a pre-login supply computation, which cannot be performed.### AC-14 — Split AC-8's guard mutations across fresh fixtures@@ -1064,7 +1544,7 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/resolution-event.schema.**Disposition.** New criterion, and AC-10's defect in a second file — the same canonical id left unconstrained, found by the same reasoning. `^src_[a-z0-9]{8,}$` goes on the string branch of both `from_source` and `to_source`, with `null` retained on both (legitimately null for `supply_interrupted`); referential existence goes to the API boundary as in AC-10, because it sits outside draft-07 on the boundary this PR already declared. The existing examples (`src_claudepro1`, `src_anthkey01`) already satisfy the pattern, so no example is rewritten. **The push cut does not touch this** — the event is still recorded, and the feed's one-tap re-auth is exactly the consumer that needs `from_source` to name a real row. Frozen surface: joins the `contract_version: 3` set.-**Acceptance.** Contract layer, owed by **L1's v3** (the pattern constraint on both fields), with **L3** owning the API-boundary guard and the emission — corrected 07-29, review round 6, to match the AC table and §3's single-freeze rule; the earlier 「owed by L3」 wording predated that rule and would have had L3 editing `resolution-event.schema.json` after the freeze. `{"from_source": "direct", …}` and `{"to_source": "cli-anthropic", …}` are both rejected by `resolution-event.schema.json`; `null` on either field still validates for `supply_interrupted`; every example in the file validates after the v3 bump; and **every non-null endpoint must name an existing `Source` row at emission time** — the server-side guard rejects a `switch` whose `from_source` is well-formed but unknown *and* one whose `to_source` is (07-29, review round 2: checking only the origin lets a `switch` pass with a destination the feed cannot resolve or open, which is the same defect one field over) — with the mechanical checker asserting both are declared in `api.md`'s guard table. **The guard is on emission, not on retention** (07-29, review round 3): sources are deletable, `force=true` deletes one the guard would otherwise refuse, and the events feed is bounded by count rather than by source lifetime, so a retained row can legitimately reference a source that no longer exists — re-validating retained rows would make a legal DELETE retroactively invalidate the record of what happened before it, or push the implementation into rewriting history to keep the feed valid. Neither the record nor the schema changes when a source is deleted; what changes is the **rendering**. **Where the remembered name comes from was left unstated until 07-29, review round 9** — the event carries ids, not a display-name snapshot, so 「the remembered display name」 named nothing the feed could reach. It is the **recorded human strings**: `human_zh` / `human_en` are **required on every event** (`resolution-event.schema.json:7`) and are composed at *record* time with the source display name already embedded — the file's own example, `「Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)」` (:168), names both endpoints inside the sentence. **The recorded strings ARE the snapshot; no schema field is added** (orchestrator ruling, 07-29 15:07, verified against the schema before transcription). So: **the feed renders the recorded human string verbatim**, and the 「(已删除)」 marker is **derived at render time** from the id failing to resolve against live sources, with the one-tap re-auth affordance withdrawn because there is nothing left to re-auth. The corollary binds the emission side, **scoped to the kinds that have a source subject** (corrected 07-29, review round 10): every kind whose endpoints name a source — `switch`, `channel_switch`, `recover`, `cooldown`, `needs_action`, `skip` — must name that source in its string template, and a template that does not is a defect in the template, fixed in this spec, never by adding a field. It cannot bind the two kinds that have no source subject, and read over them the round-9 wording asked the emitter to fabricate one: `supply_interrupted` pins **both** endpoints to `null` by conditional — the chain emptied, nothing switched — and `mapping_applied` is decided at §4.3 step 1 before any candidate exists, so its line names models rather than sources (「claude-opus-4-6 → glm-5.2(经映射)」, the schema's own note). Excluding them costs the snapshot nothing: neither references a source, so neither can outlive one's deletion. Acceptance covers both halves — emission of an unknown id is rejected, and a feed rendered after its referenced source is deleted still loads, still shows the line, and offers no dead action. Fails today: both fields accept any string.+**Acceptance.** Contract layer, owed by **L1's v3** (the pattern constraint on both fields), with **L3** owning the API-boundary guard and the emission — corrected 07-29, review round 6, to match the AC table and §3's single-freeze rule; the earlier 「owed by L3」 wording predated that rule and would have had L3 editing `resolution-event.schema.json` after the freeze. `{"from_source": "direct", …}` and `{"to_source": "cli-anthropic", …}` are both rejected by `resolution-event.schema.json`; `null` on either field still validates for `supply_interrupted`; every example in the file validates after the v3 bump; and **every non-null endpoint must name an existing `Source` row at emission time** — the server-side guard rejects a `switch` whose `from_source` is well-formed but unknown *and* one whose `to_source` is (07-29, review round 2: checking only the origin lets a `switch` pass with a destination the feed cannot resolve or open, which is the same defect one field over) — with the mechanical checker asserting both are declared in `api.md`'s guard table. **The guard is on emission, not on retention** (07-29, review round 3): sources are deletable, `force=true` deletes one the guard would otherwise refuse, and the events feed is bounded by count rather than by source lifetime, so a retained row can legitimately reference a source that no longer exists — re-validating retained rows would make a legal DELETE retroactively invalidate the record of what happened before it, or push the implementation into rewriting history to keep the feed valid. Neither the record nor the schema changes when a source is deleted; what changes is the **rendering**. **Where the remembered name comes from was left unstated until 07-29, review round 9** — the event carries ids, not a display-name snapshot, so 「the remembered display name」 named nothing the feed could reach. It is the **recorded human strings**: `human_zh` / `human_en` are **required on every event** (`resolution-event.schema.json:7`) and are composed at *record* time with the source display name already embedded — the file's own example, `「Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)」` (:168), names both endpoints inside the sentence. **The recorded strings ARE the snapshot; no schema field is added** (orchestrator ruling, 07-29 15:07, verified against the schema before transcription). So: **the feed renders the recorded human string verbatim**, and the 「(已删除)」 marker is **derived at render time** from the id failing to resolve against live sources, with the one-tap re-auth affordance withdrawn because there is nothing left to re-auth. The corollary binds the emission side, **scoped to the kinds that have a source subject** (corrected 07-29, review round 10): every kind whose endpoints name a source — `switch`, `channel_switch`, `recover`, `cooldown`, `needs_action`, `skip` — must name that source in its string template, and a template that does not is a defect in the template, fixed in this spec, never by adding a field. It cannot bind the two kinds that have no source subject, and read over them the round-9 wording asked the emitter to fabricate one: `supply_interrupted` pins **both** endpoints to `null` by conditional — the chain emptied, nothing switched — and legacy v4 `mapping_applied` was decided by the pre-candidate mapping step, so its line names models rather than sources (「claude-opus-4-6 → glm-5.2(经映射)」, the schema's own note). Excluding them costs the snapshot nothing: neither references a source, so neither can outlive one's deletion. Acceptance covers both halves — emission of an unknown id is rejected, and a feed rendered after its referenced source is deleted still loads, still shows the line, and offers no dead action. Fails today: both fields accept any string.### AC-19 — Close the eligibility reason-key vocabulary@@ -1074,9 +1554,17 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/agent-supply.schema.json>> When `eligible` is false, this branch accepts any nonempty `reason_key`, although the contract names three distinct remedies and the UI must resolve the value through its locale files. A typo or invented value therefore validates but leaves the ineligible row without translatable copy or an actionable remedy. Constrain this branch to the declared `subscription_wrong_client`, `opencode_api_key_only`, and `consent_required` keys, extending the enum alongside locale support when a new eligibility cause is introduced.-**Disposition.** New criterion. `enum: ["models.eligibility.subscription_wrong_client", "models.eligibility.opencode_api_key_only", "models.eligibility.consent_required"]` on the ineligible branch — **fully qualified**, because that is what the frozen contract actually emits (`agent-supply.schema.json:94`, `api.md:214`); the finding's bare short names are the causes, not the wire values, and an enum written from them would reject every conforming payload. With the extension rule — a new cause ships its enum member and its locale copy in the same change — stated where the enum lives. **Missed instance of a class this PR swept in round 3** (closed vocabularies), which is why it carries the extension rule rather than just the enum: an enum with no stated extension path is the reason the sweep left instances behind. Frozen surface: joins the v3 set.+**Final disposition (owner 2026-08-09).** The closed-vocabulary invariant survives,+but the historical three-member set quoted above does not. The final enum is exactly+`["models.eligibility.subscription_wrong_client"]`; `consent_required` retired with+per-Source consent, and `opencode_api_key_only` retired when Hub-held subscriptions+became valid OpenCode inputs. This paragraph explicitly supersedes the quoted enum and+every earlier acceptance sentence that required either retired member.-**Acceptance, split across two lanes** (corrected 07-29, review round 11 — it read as wholly owed by L1, which the 15:07 i18n ruling had already made impossible: L1 has no UI locale scope and L4 depends on L1, so L1 could not have satisfied its own v3 gate without crossing the no-touch boundary or waiting on its dependent). **The contract half is L1's**, which also carries the v3 bump: `{"eligible": false, "reason_key": "models.eligibility.subscription_wrong_clint"}` is rejected; so is the unqualified `"subscription_wrong_client"`; each of the three declared fully-qualified keys validates. **The locale half is L4's**, whose surfaces render those reasons and whose lane row already owns the keys: `ui/src/i18n/{en,zh}.json` contain a key for **every member of the frozen enum**, checked mechanically against the schema so the two cannot drift. The extension rule spans both — a new cause ships its enum member (L1's file) and its locale copy (L4's) in the same change — and the mechanical check is what makes that rule enforceable rather than advisory. Fails today: any nonempty string validates, so the typo above passes the contract and renders as a raw key.+**Acceptance.** I1 rejects a typo, an unqualified key, either retired key, and every+unlisted value; the one fully qualified final key validates. I4 carries the matching+entry in both UI locale files. A generated guard compares schema enum and both locale+sets in both directions. A future cause ships its enum member and locale copy together.### AC-20 — Enforce the hub-mode half of the mode invariant@@ -1086,9 +1574,20 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/agent-supply.schema.json>> The schema pins all Hub-only projections to null in Direct mode but never enforces the converse, so a response with `mode: "hub"` and present-but-null `selected_model_id`, `sources`, `supply_status`, and `model_supply` still validates even after the API-boundary presence checks land. Such a payload leaves the Hub drawer without an order or selected model and makes the chain/probe defaults unusable while claiming Hub mode. Add a Hub branch that constrains these fields to their non-null shapes; it can remain non-required here so the frozen v1 examples that omit the fields still validate.-**Disposition.** New criterion. A `hub` branch constraining **the four projections the finding names** — `selected_model_id`, `sources`, `supply_status`, `model_supply` — to their non-null shapes, **not required**, so the frozen v1 examples that omit them still validate. Exactly those four, and no more: `selected_by_agent` and `current` are declared `["string","null"]` / `["object","null"]` and are legitimately null in Hub mode (no Agent has selected, nothing is current), so pinning them non-null would reject conforming payloads — the invariant is about Hub projections that must exist for the drawer to function, not about every nullable field in the file. The four deliberately mode-independent fields (`mappings`, `menu`, `builtin_models`, `standard_vendors`) stay out of both branches. **Missed instance of the partial-predicate class**, also swept in round 3 — and it is the exact shape that sweep named: a `then` whose `properties` never bite because nothing requires the field. Note the interaction with the `required` guard in `api.md`'s mechanical-guard table: this branch is a **declared exception** to it, deliberately non-required, so the checker must recognise it as such rather than flag it. Frozen surface: joins the v3 set.--**Acceptance.** Contract layer, owed by **L1**. Every fixture below is built from an **otherwise-valid** Hub payload, varying only the projections under test (07-29, review round 2): `backend`, `mode` and `menu_kind` are the file's top-level `required` set, so a fixture that omits them is rejected today for a reason this branch has nothing to do with, and a test copied from it would pass vacuously while all four null projections stayed accepted. `{"backend": "claude", "mode": "hub", "menu_kind": "fixed", "selected_model_id": null, "sources": null, "supply_status": null, "model_supply": null}` is rejected, and rejected *by the Hub branch* — the same payload with the four projections carrying their non-null shapes validates, which is what proves the rejection came from the branch and not from a missing required field; the frozen v1 examples that omit those fields still validate; a Hub payload with `selected_by_agent: null` and `current: null` still validates, since those are not part of the branch; the four mode-independent fields validate identically under both modes; and the mechanical checker records this branch as a declared non-required exception instead of reporting it as a partial predicate. Fails today: that payload validates, and the Hub drawer receives it with no order and no selected model.+**Final disposition (S-1, 2026-08-09).** The hub-mode completeness invariant survives,+but the final five projections are `selected_model_id`, `sources`, `routes`,+`supply_status`, and `model_supply`. `mappings` is not a final field. `selected_by_agent` and+`current` remain legitimately nullable, and `menu`, `builtin_models`, and+`standard_vendors` remain mode-independent.++**Acceptance.** I1 builds every fixture from an otherwise-valid payload. A Hub payload+with any of the five final projections explicitly null is rejected by the Hub branch;+the same payload with one explicit route row per menu model, including empty `hops`,+validates. `sources` contains an explicit `order` and no policy. `selected_by_agent: null`+and `current: null` still validate. Direct mode has+its documented representation. The mechanical checker records the branch as a declared+non-required exception for historical examples while rejecting `mappings` or a policy+discriminator in the final shape.### AC-21 — Make the mirror registry encode its promised checks@@ -1102,6 +1601,417 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/README.md`, [thread](htt**Acceptance.** Contract layer, owed by **L1**. A harness generated purely from the registry rows — with no hand-written supplements — runs both relations: the reason ↔ `detail_key` bijection in both directions, and `resolution-event.agent` ⊆ home set ∪ `{system}`. Three mutations are caught by that generated harness: deleting one `detail_key` from either side; **swapping two `detail_key`s between reasons in one file while leaving M4's `pairs` list alone** (07-29, review round 3 — the case a set-only bijection cannot see, and the one that ships wrong copy to a real user); and adding an undeclared value to `resolution-event.agent`, whose enum already holds four, `claude`/`codex`/`opencode`/`system`, so the test adds a fifth. Fails today: M4 reads `none` and M6 omits the field, so a faithful generator emits neither check and still reports the registry fully covered.+### AC-22 — Make one ordered per-model route chain the only Gateway routing model++**Owner rulings 2026-08-07 and 2026-08-09 S-1.** Per-model ordering remains in scope,+but `follow | custom` does not. Every `(backend, menu model)` stores one ordered `hops`+array of exact `(source_id, model_id)` pairs. Add Source matches once and writes those+pairs; the Gateway UI edits the same configuration; runtime walks it verbatim.++**Acceptance.** Config, schema, API, and UI contain one persisted backend Source order+and no placement-policy or route-policy discriminator, missing-row default, separate+mapping object, or runtime Source/model matching branch. Every menu model owns an explicit+`hops` array, including an empty array for an unconfigured route. For every accepted+Add/import match, fixtures assert that §4.2's sole placement policy chooses one+deterministic position, the transaction persists and returns that position, the Gateway+shows it, and the user can adjust it.+They do not assert the current policy's concrete position. Existing Source-order entries+and hops preserve their relative order, no “not enabled” state is emitted, and+refresh/catalog/runtime paths never rerun placement. Explicit edits preserve submitted+order and model ids and cannot change another menu model.++A table-driven runtime suite executes the normative §4.3 pseudocode against the stored+array. It fails any implementation that normalizes a provider, walks inventory to pick a+model, prepends Native, or otherwise constructs a second chain. Every hop is rechecked+only for live runnability immediately before its turn. Exact configured reasoning-effort+membership is honored. Credential fixtures execute every authoritative matrix row;+fallthrough follows stored order, and a static-key `401` makes no duplicate request.++Turn fixtures execute every §4.5 outcome row: a nonempty all-blocked chain produces+`no_candidate` with its actual blockers; an empty chain produces `route_unconfigured`;+`native_cli_unavailable` is `interrupted`; local engine loss before the request,+mid-request, and after streamed output is terminal `engine_down` with no Source mutation,+replay, or next-hop walk; streamed Source failures persist attributable state without+replay; retry copy appears only when the next turn's same stored chain has a different+current hop.++Source-card attribution consumes `adopted_by: [{backend, menu_model}]`. The backend+subtitle and Usage page consume the exact four-value `supply_status`; no independent+walk or parallel prose status exists. Takeover derives from the stored first hop and+live current position without a field.++Mutation fixtures cover non-forced exact-hop refusal, confirmed cascade with survivor+order intact, background stale-hop retention, and the forced Source-delete success+envelope. Deletion removes the Source id from every backend Source order and Route chain+in the same transaction and the result passes canonical serialization/reload validation. No path+substitutes another model or claims invalidated supply survived.++Fresh installs write `mode: "hub"`; existing installations with no Model Hub state+start in `direct`. Until I5's evidence is merged, absence of `VIBE_MODEL_HUB_ENABLED`+keeps the controller, API, and Models UI disabled; I1 proves the v3 aggregate only under+explicit enablement, and I6 later deletes the gate in one ownership transfer. A newly introduced menu model gets an explicit empty route and is+not retroactively matched. Historical AC-5/AC-8 mapping fixtures are non-executable;+I1 replaces their guard intent with configured-route fixtures. The final no-parallel-+mapping shape remains owner-vetoable; a veto blocks I1 rather than reviving two route+authorities.++### AC-23 — Make subscription custody vendor-specific with a native singleton++**Owner ruling 2026-08-07, amended that afternoon.** Claude subscriptions recommend+and default to `native_cli`; Claude Hub custody is optional. ChatGPT subscriptions+recommend and default to `hub`; native Codex login remains supported but receives no+default guidance. Vendor custody recommendation is an input only to §4.2's Add-time+placement policy; the stored output is authoritative. Any Hub-held subscription may+participate in any backend's configured chain; its stored position and model mapping are+authoritative.+The 2026-08-08 orchestrator ruling, owner-vetoable, permits at most one `native_cli`+Source per backend; extra accounts use Gateway custody. Native account selection is+deferred until an official CLI supports stable profiles.++**Acceptance.** An omitted OAuth channel resolves by vendor, Claude → `native_cli` and+ChatGPT → `hub`, while both explicit alternatives remain accepted. With a native row+present, another native creation is disabled in the UI and rejected at the OAuth-start+API boundary with `native_source_already_exists` plus `existing_source_id` **before the+adapter is called**; a spy proves the adapter received no request. §4.3 executor tests+are the sole acceptance authority for configured precedence, channel dispatch,+per-hop live revalidation, pre-stream fallthrough, post-stream+no-replay, and recovery.++Mode and hop labels are mechanically distinct in UI and locale fixtures: **Direct**+appears only for backend `mode: direct`, while a `native_cli` hop inside Gateway mode is+**Native**. Product copy contains no “not through Gateway” explanation, and no Native+hop is allowed to imply or mutate Direct mode.++Before ChatGPT Hub becomes default-on, I1's PR includes a dated re-verification of+`model-hub-tos-review.md` §2.1 and §3.1 under §11's timing gate. A material or inconclusive vendor change blocks+that default and is escalated to the owner; passing by omission, relying on K2 fidelity,+or deferring the check to I5 fails this criterion.++Every successful native-to-Hub handoff is silent (owner ruling 2026-08-08, superseding+the 2026-08-07 afternoon notice). No session message, setting, outbox row, or push path+is created. The takeover badge, connector state, recent-switch record, and usage remain+available on the Model Gateway and Usage pull surfaces. Negative fixtures also prove+that this silence does not suppress the existing truthful failure when no hop is+runnable. Streamed terminal rendering follows §4.5's authoritative matrix: retry copy is+allowed only after a persisted Source blocker makes a different hop current, while a+non-fallback request error truthfully says that switching Sources will not help.++The eligibility matrix has two independently tested axes: native subscription origins+remain restricted to their own backend client, while Hub-held Claude and ChatGPT+subscriptions are eligible for Claude, Codex, and OpenCode chains. Explicit Hub add+works with neither `subscription_hub_experimental` nor a consent timestamp. The reason+vocabulary has neither `consent_required` nor `opencode_api_key_only`: Hub-held+subscriptions are eligible for OpenCode, while a native subscription in any+non-sanctioned client uses the channel-specific `subscription_wrong_client` reason.+This supersedes AC-19's historical three-member enum, not AC-19's closed-vocabulary+invariant; the final mirror registry checks every remaining member against both locale files. Native+wrong-client use remains rejected; this is channel binding, not a cross-vendor ban on+Hub Sources.++### AC-24 — Warn only when Claude is added as a Hub-held Source++**Owner ruling 2026-08-07.** The sole subscription-routing warning belongs to the+explicit opt-in path that adds a Claude subscription to the Gateway. It states that+Anthropic explicitly prohibits this use, enforces server-side blocks, real account+bans have occurred, and the path may fail intermittently. It is informational, not a+consent gate or persisted acknowledgement.++**Acceptance.** The warning appears exactly once before the Claude Hub-held OAuth+flow begins. It does not appear for Claude native login, ChatGPT native login,+ChatGPT Hub-held login, adding a Hub-held subscription to a cross-vendor configured chain, native+quota takeover, or automatic return to native. No server flag, Source consent stamp,+or repeat prompt is required. UI copy and scenario evidence cover every row of that+matrix. AC-2 and AC-13's irreversibility confirmations remain intact: those guard a+credential-repair operation and are not subscription-routing warnings.++### AC-25 — Split subscription guidance by vendor and disable duplicate native creation++**Owner ruling 2026-08-07 afternoon, retained by the 2026-08-08 amendment.** The add+flow recommends Claude native custody+for compliance and ChatGPT Hub custody for product utility. A native path remains+available for ChatGPT, but the UI does not present it as the default.++**Acceptance.** Add Claude defaults to `native_cli`; Add ChatGPT defaults to `hub`.+Both explicit alternatives persist and resolve correctly. Add-flow custody defaults and+labels are tested for both vendors without asserting a concrete route position. When the backend already has+its singleton native Source, the native choice is visibly unavailable and cannot+submit a second row.++### AC-26 — Complete Source add and detail operations++**Owner rulings 2026-08-07 afternoon and 2026-08-08 design acceptance.** Source setup+must include manual connectivity testing, compatible model discovery, manual model+add/remove, and an editable per-model reasoning-efforts capability list with no default+item, selected state, or prefill. The existing probe, refresh, and discovery mechanisms+are reused. The list is editable on every inventory entry, including discovered entries+(owner-vetoable orchestrator scope ruling, 2026-08-08), because discovery commonly+returns ids without effort metadata; editing it never changes the entry's `origin`.++**Acceptance.** Add Source exposes one non-persisting submission that combines+connectivity classification with response-backed protocol observation. Source details+instead exposes exactly one mutating action, “Refresh models” / 「重新拉取」, backed by+`POST /api/models/sources/<id>/refresh`: it uses the stored adapter, refreshes inventory+and health, and clears `needs_action`/`error` only on current recovery evidence. Source+details has no “Test connectivity” button and no separate saved discovery route. Its+request, guarded refusal, and success mirror the refresh row of §4.5's authoritative+Source-mutation envelope matrix. An inventory shrink runs the same exact-hop and+protected-route supply-gap guards as Source/model deletion.+The UI and API never label the saved and unsaved operations as each other. The unsaved variant+returns classified reachability, authentication, and a protocol only when a real+upstream response proves it, without persisting a Source, changing route configuration, or+running an Agent turn. For an API-key test, success, authentication failure, adapter+error, timeout, and cancellation each revoke the transient provisioned+ref before the operation settles. A fault-injected revoke failure writes the existing+durable pending-revocation record, and a reconstructed service reconciles it; no response+contains the ref and no final state leaves live material unreferenced and untracked.+Unsaved Add Source model discovery has the same independently provisioned transient-ref+cleanup on success, failure, adapter error, timeout, and cancellation, plus the same+fault-injected reconciliation proof. Third-party Anthropic-compatible and+OpenAI-compatible Sources can fetch models in Add Source; after Save, refresh is the+single path to the same discovery result. The result distinguishes added, removed,+unchanged, and failed discovery while preserving manual entries. A successful full+replacement advances `last_discovered_at`; failure leaves it unchanged. Source detail+may render only “Model list updated at …” / 「型号列表更新于…」 from that value. No+latency or “last checked” field, copy, fixture, or route heuristic is introduced.++`source.models` no longer relies on bare strings. Every item carries exact `id`,+`origin: "discovered" | "manual"`, and required `reasoning_efforts: string[]`. The list+may be empty and declares supported values; it never declares a selected or default+value, and ids are unique within a Source. Discovery creates `origin: "discovered"`;+user-added entries create `origin: "manual"`. Rediscovering the same id preserves the+user-edited `reasoning_efforts` list plus existing `display_name` and `discovered_at`;+an upstream result cannot reset them to empty/default values.+`PATCH /api/models/sources/<source_id>/models/<model_id>` accepts+`{reasoning_efforts}` for an existing discovered or manual+entry, atomically validates the complete list through the selected adapter, returns+`{"source": Source}`, preserves `origin`, and leaves every route chain unchanged.+An invocation-level spy covers exact configured hops and asserts §4.3:+the turn-requested effort is passed through the unchanged single-value invocation+parameter only when it exactly matches that exact model entry's list; a missing+or non-member value passes `null`, with no approximate mapping or downgrade. This makes+a persistence/UI-only implementation fail.+Base URL replacement, credential replacement, explicit refresh/recovery, and+user-authored model deletion stage inventory and run AC-22's exact-hop **and** protected-route supply-gap+guards before committing. Their JSON bodies and canonical guarded/success responses+mirror their rows in FC-12; force-cascade fixtures cover each mutation. Native CLI+and Hub OAuth re-auth instead+use AC-2's pre-login acknowledgement and retain newly invalid hops as visible,+non-runnable entries with exactly `reason: "model_unsupported"` and `retry_at: null`+after the irreversible exchange.+UI evidence covers loading, reachable, authentication failure, discovery failure,+empty result, merge result, manual add, all-inventory reasoning-efforts list editing+with an empty/no-default state, guarded removal, and mobile treatment. The control form+follows `design.pen`; this spec does not prescribe it. Explanatory copy lives behind+compact info affordances rather than permanent instruction blocks.++### AC-27 — Observe protocol before Save and keep it immutable afterward++**Owner ruling 2026-08-09, clarified by the owner-routed UI handoff the same day.**+This supersedes the 2026-08-07 afternoon manual-choice ruling. The normal Add Source+form has no protocol selector. A stored value must be traceable to a real response from+that upstream; vendor, Base URL, and a user's manual hint may order probes but cannot+produce a saved conclusion.++**Acceptance.** The Add action reuses its connectivity interaction to observe protocol+before the Source commits. A proven result is stored atomically with the Source. An+ambiguous or failed result persists nothing and displays the only manual protocol entry+point in the product: a one-time three-value probe-order hint whose selected adapter must+itself receive a verifying upstream response before Save. Tests fail any vendor-table,+Base-URL, manual-hint, timeout, or catch-all path that writes a protocol without that+evidence.++After Save, connectivity retest, discovery, refresh, credential/Base-URL replacement,+and restart all preserve the stored value byte-for-byte and invoke only that adapter.+Changing protocol requires a new Source. The stored shape has no manual/automatic+provenance marker and no protocol-level unverified value. “Add anyway” is available only+after the protocol was proved and a different result, such as model inventory, remains+unavailable; that uncertainty is a health fact. UI evidence shows no normal selector,+an honest failed-add state, and the compact verified-hint fallback without inventing a+default. Invariant: every saved Source has one response-proven protocol; every path+without that proof produces no Source.++### AC-28 — Converge the protocol vocabulary on three transports++**Owner ruling 2026-08-09.** The final enum is exactly+`anthropic | openai_responses | openai_chat`. `openai_chat` is the Chat+Completions-compatible transport; no `openai_compatible` alias exists. Chat Completions+stays because the platform API remains supported and many third-party/open-source+upstreams expose no Responses API.++**Acceptance.** Schemas, examples, adapter/runtime branches, OpenCode overlay, API+payloads, UI types, locale keys, mirror registry, fixtures, and scenario data expose+exactly the three values. `vibe/model_hub_runtime/config.py` and `client.py` contain one+Chat path, and no save path or vendor metadata table synthesizes a protocol. Mechanical+tests reject a fourth enum member and catch any `openai_compatible` occurrence outside+the explicit absence assertion in this handoff.++### AC-29 — Validate every persisted Source through the canonical validator++**Owner-routed investigation finding 2026-08-09.** Every path that writes Model Hub+configuration produces a Source accepted by the same canonical validator used on the+next configuration load. Creation, OAuth, and native-config import may differ in how+they obtain data; they do not differ in what constitutes a valid persisted Source.++**Acceptance.** I1 exposes one canonical final-shape validation boundary and I3 routes+every native-import result through it before commit rather than constructing an+unchecked persisted dataclass. The migration scenario imports each supported native+item, validates the resulting Source through that boundary, serializes it, and reloads+the complete configuration successfully. A protocol or model shape rejected on reload+must be rejected before the import reports success.++### AC-30 — Derive takeover without storing a second state++**Owner design-reconciliation ruling 2026-08-09, retained by S-1.** Takeover is true+exactly when the configured chain's current hop is not its first stored hop and that+first hop is unavailable for a self-healing quota/cooldown reason. It is a projection+of visible configuration plus live runnability, not a stored sibling state.++**Acceptance.** Resolver/UI fixtures cover four transitions: a recoverably blocked+first hop with a later current hop renders takeover; recovery of the first hop clears+it; a configured chain whose first hop is healthy and intentionally not native does+not fabricate takeover; and a chain with no runnable hop resolves to the exact+`no_candidate | exhausted` result selected by §4.3, without any takeover badge,+connector color, or other takeover visual semantics. No+schema, API envelope, serializer, or UI type adds a stored takeover boolean or sibling+routing field. The Model Gateway and Usage pages derive the view from the same chain+projection, and mirror-registry tests require the takeover label plus all four+`supply_status` labels to exist in both locale sets. Successful fallback remains silent.++### AC-31 — Make Direct onboarding visible and reversible++**Owner design-reconciliation ruling 2026-08-09.** Direct is a supported backend-wide+mode and the first Models-page state for an existing installation with no Model Hub+state; Native names a `native_cli` hop inside Gateway mode and never names a mode.++**Acceptance.** For every existing-install backend in Direct, the Models page renders a+Direct-labelled backend group, its current self-managed configuration summary, no+Gateway chain, and one explicit Switch to Gateway action in that group. Gateway mode+offers Switch to Direct. A round-trip scenario switches one backend Direct → Gateway →+Direct while another backend remains unchanged, preserves saved Sources and route+configuration, and leaves native config byte-identical. UI and locale guards reserve+Direct for `mode: direct`, reserve Native for `native_cli` hops, and reject “not through+Gateway” mechanism copy.++### AC-32 — Keep route selection stable while live runnability changes++**Owner S-1 transfer, 2026-08-09.** Add-time matching and placement write visible+configuration. Runtime may inspect whether an exact stored hop can execute now, but it+may not choose different route membership or order from hidden live inputs.++**Acceptance.** Given byte-identical persisted Model Hub configuration and an identical+turn request, the ordered `(source_id, model_id)` Route selected for execution is+byte-identical even when wall-clock time, Source quota, Source health, or native-process+availability differs. Those live inputs may change only each stored hop's+`runnable/reason/retry_at` annotation and the current execution position; they may+neither add, remove, reorder, remap, nor substitute a hop. A behavior-level test runs+the same configuration/request against changed live inputs and compares membership and+order before inspecting the permitted annotations.++### AC-33 — Generate the authority closure from live inputs++**Circuit-breaker ruling, 2026-08-09.** `mirror-registry.json` is the sole registry for+closed decision domains. A table or enum absent from that registry is not authoritative;+prose may reference a registered authority but may not add a branch. A section-level+vocabulary change updates its referenced AC in the same head.++**Acceptance.** One test invocation reads the current Markdown tables, every registered+schema path under `docs/plans/model-hub-contracts/`, registered Python/type consumers,+and registered locale objects directly from the worktree. It computes authority and+consumer member sets in that invocation and fails in both directions: a consumer value+without an authority row is an orphan branch, and an authority row without a consumer+is an orphan row. The checker contains no copied decision member, member count, or+expected registry-id list. A future external snapshot is accepted only with a content+fingerprint recomputed from its producing artifacts in the same invocation; missing or+stale input fails rather than skips.++The same invocation discovers Python files outside the resolver package that import+`core.handlers.model_hub.resolver` and requires every discovered path to appear in+exactly one binding lane scope. Zero owners and multiple owners both fail. This makes+consumer ownership part of the generated closure instead of another hand-maintained+file list. Contract, code, and locale consumers are included through the registry's+live extraction relations; a hand-written consumer inventory is not accepted as evidence.++**Generated closure findings for this head (owner ruling 2026-08-09).** These five+findings were the seed set for AC-33's live closure run. They are recorded with their+original wording and resolved in the registered authority tables; no consumer may add+a parallel branch outside those tables.++| Finding / root cause | AC | Registered authority / landing point | Lane |+| --- | --- | --- | --- |+| **Define failures of the credential refresh operation.** When a refresh-capable credential receives its first 401 but the refresh operation itself times out, is rejected, or returns an invalid response, neither the existing refresh row nor the retry-after-401 row applies. | AC-22 + AC-33 | §4.3 Credential-failure decision matrix: `credential.refresh_failed`; `api.md` marker and resolver/adapter tests | I1 + I2 |+| **Assign the model-hub injection suite to a lane.** The suite imports final-shape config/resolver symbols and exercises the shared backend launch boundary, but no active lane owned it. | AC-22 + AC-33 | v3 current lanes, I1 scope; dynamic resolver-import ownership check | I1 |+| **Add permission denial to the terminal-copy matrix.** A request-scoped `permission_denied` failure was not named by the exhaustive request-failure row. | AC-22 + AC-33 | §4.5 Turn-outcome copy matrix: `turn.request_nonfallback`; no new discriminator | I1 + I2 |+| **Contract the guard on direct route edits.** Whole-array route replacement lacked the guarded refusal, force confirmation, and success envelope defined for other inventory mutations. | AC-22 + AC-33 | §4.5 Source-mutation envelope matrix: `mutation.route_replace`; `api.md` route PUT | I1 + I5 |+| **Remove the redundant mapping discriminator.** `requested_model_changed` duplicated the fact derivable from exact requested/configured model ids while the contract prohibited a separate mapping discriminator. | AC-22 + AC-33 | FC-08 and exact-hop/provenance shapes; derive from ids | I1 + I2 |++### AC-34 — Make Source-model ownership and routes one total resource contract++**Owner ruling, 2026-08-09.** Source inventory is a subresource of one Source. A+`discovered` entry's existence is upstream-owned; a user may edit its declared+`reasoning_efforts`, but only user-authored entries can be created or deleted.++**Acceptance.** Model creation, capability-list replacement, and user-authored deletion+use only the three `/api/models/sources/<source_id>/models` family routes registered in+§4.5's total Source-mutation matrix. Source identity is carried only by the path, never+by those request bodies. POST and PATCH cannot change an existing `id`, `origin`, or+Route, so their matrix rows are explicitly unguarded; DELETE reuses the registered+guarded Source envelope. Rediscovery of the same id continues to preserve the edited+`reasoning_efforts`, `display_name`, and `discovered_at` as one total merge rule.++A direct DELETE of `origin: "discovered"` returns+`source_model_managed_upstream`. The registry names the contract error and+`test_discovered_source_model_delete_is_rejected_as_upstream_managed` as its negative+route consumer and rejects the value from Model Hub UI/i18n files. No UI entry may exist+whose only possible result is this refusal. The generated same-run closure also proves+the retired parallel route literal is absent repo-wide and that no Source-model request+body repeats `source_id`; these are derived checks, not copied occurrence counts.++### Post-consolidation review ledger — sealed 2026-08-08++The orchestrator-authorized consolidation commit closes the constructive prose loop.+The 2026-08-09 owner rulings explicitly reopen the no-migration final shape,+response-observed protocol, enumerated 18-thread closeout, and the two narrowed UI-lane+AC handoffs routed by the owner; they do not repeal the seal for review-generated scope.+After that head, a review finding permits a normative-text edit only when it identifies+two specific normative sentences that contradict each other. Every other actionable+finding is copied verbatim into this ledger with its AC, implementation landing point,+and responsible lane; the review reply cites this ruling and the thread is resolved.+No new explanatory prose is added elsewhere in the planning documents.++The four findings that caused the consolidation — OpenCode provider normalization,+native Source identity, per-hop live runnability, and enrollment versus adoption — are+resolved by the final-shape handoff above. S-1 removes enrollment entirely; `adopted_by`+now projects persisted route references, while §4.3 owns only live execution. They+predate the seal and are not deferred ledger items.++**S-1 architecture disposition (owner 2026-08-09).** The next exact-head review did+trigger the forward stop. S-1 supplies the required design action rather than another+lane patch: §4.3 is now machine-checkable pseudocode over one persisted chain, with no+runtime matching. Its bounded rewrite closes the five reviewed contradictions in their+authoritative homes: blocked `no_candidate` copy and all-phase `engine_down` in the+Turn-outcome matrix; the final one-member eligibility enum in AC-19; Source deletion+from every persisted route in the mutation/postcondition contract; and+`native_cli_unavailable` in the blocker/supply-status relation. These findings are+architecture inputs to S-1, not sealed-ledger deferrals.++| Finding (verbatim) | AC | Implementation landing point | Responsible lane |+| --- | --- | --- | --- |+| **Guard the saved Fetch models mutation**<br><br>When a user runs the newly specified “Fetch models” action from saved Source details and upstream discovery removes a referenced model, lines 185–191 say that operation replaces the discovered slice, but this exhaustive guard list covers refresh/recovery and manual deletion without covering saved discovery. Fresh evidence beyond the earlier inventory-shrink thread is that Fetch models is now a separate saved-Source mutation; unless it is explicitly defined as an alias of guarded refresh or given the same exact-hop and supply-gap handling, it can invalidate a Custom hop or the last Follow supplier without refusal, cascade confirmation, or stale-hop retention. | AC-26 | `core/handlers/model_hub/service.py`; final `api.md`; `tests/test_model_hub_api.py`; saved Source-details Fetch-models UI test | I1 (shape/guard) + I4 (action) + I5 (scenario) |+| **Include the required auth-setup scenarios**<br><br>When K3/K4 change the multi-step OAuth flows—vendor-specific defaults, duplicate-native rejection before adapter work, re-auth acknowledgement, polling, cancellation, and retry—the final landing checklist names only `tests/scenarios/model_hub/**` and the lower-level native OAuth harness. That can leave the repository's auth/setup catalog and its closed-loop user journey on the old flow even while all listed Model Hub tests pass; add or update the mandated `tests/scenarios/auth_setup/catalog.yaml` entry and `test_auth_setup_scenarios.py` case in this handoff.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/7984aabf4e1d9d541084c7078dba093f2832045d/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I1 (final auth envelopes) + I3 (catalog/test) + I5 (integration gate) |+| **Define protocol observation for OAuth-created Sources**<br><br>When a Claude/Codex native login or a Hub-held subscription OAuth flow completes, the resulting Source still requires a `protocol`, but the specified observation workflow covers only the API-key Add form and never defines how OAuth credentials are probed before commit. The current OAuth creation path uses `core/handlers/model_hub/service.py::_default_protocol(binding.vendor)`, which this rule explicitly forbids; removing that default leaves OAuth creation without a contract-valid value, while retaining it violates AC-27. Define response-backed observation and failure/credential-cleanup behavior for OAuth Sources, or make `protocol` conditional where native dispatch does not use it. | AC-23 + AC-27 | final `source.schema.json`, `oauth-flow.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{service,oauth,native_oauth,revocations}.py`; OAuth/API/scenario tests | I1 (final shape/API) + I3 (OAuth observation/cleanup) + I5 (scenario) |+| **Define discovery collisions with manual model IDs**<br><br>When a user manually adds model id `foo` and a later Fetch models result also contains `foo`, the preceding discovery rule says to preserve the manual entry while these lines require unique ids and say discovery creates a discovered entry. Without collision precedence, an implementation must either emit duplicate ids, fail the refresh, or overwrite the user's manual origin and edited capability metadata. Define a deterministic coalescing rule for manual/discovered collisions and cover it in the discovery fixtures. | AC-26 | final `source.schema.json`, `api.md`, and adapter interface; `core/handlers/model_hub/service.py`; API, adapter, Source-details UI, and scenario fixtures | I1 (shape/consumer) + I4 (result rendering) + I5 (scenario) |+| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. K3 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) |+| **Assign the actual auth-setup scenario file**<br><br>Fresh evidence after the recorded auth-scenario thread is the repository layout: repo-wide search finds the harness at `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`, while this lane assigns the nonexistent `tests/test_auth_setup_scenarios.py`. Because I5 owns only the Model Hub scenario tree, the real closed-loop OAuth/setup test remains outside every active lane and can stay stale while the listed work completes; correct the path and ownership here and in the landing ledger.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I3 |+| **Assign the shared backend launch seam to an active lane**<br><br>When I1 replaces resolver/config shapes and I2 changes exact-hop transport, `modules/agents/model_hub.py` must change as well: it is the shared launch boundary for Claude, Codex, and OpenCode and currently imports and executes the runtime-matching resolver through `resolve_model_hub_turn`, `matching_sources`, and eligibility walks. None of the active I1–I5 scopes or landing rows owns this file; its only assignment is in the explicitly non-binding historical L3 table, so every active lane can complete while backend launches still use the retired routing model. Assign this shared seam and its backend call-site coverage to I1 or I2.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 | `modules/agents/model_hub.py`; shared Claude/Codex/OpenCode launch call-site tests | I2 |+| **Specify the add-time model matching algorithm**<br><br>When upstream IDs do not literally equal menu IDs—for example Claude's dated aliases or normalized OpenCode identifiers—this new architecture deletes runtime matching and makes the Add Source result permanently authoritative, but it defines only Source ordering and never defines which upstream model is matched to each menu model or how ties are resolved. The current resolver has concrete logic such as `_native_claude_alias`, which I1 is instructed to remove from runtime; without an add-time replacement, implementations can persist different mappings or leave supported routes empty while satisfying the stated ordering tests. Freeze the sanctioned alias/normalization rules and deterministic tie-breaks, with fixtures for each backend, before making the one-time write authoritative. | AC-22 | final `agent-chain.schema.json`, `opencode-overlay.md`, and `api.md`; `core/handlers/model_hub/{service,resolver}.py`; `tests/test_model_hub_{api,resolution}.py` | I1 |+| **Assign the controller gate removal to I1**<br><br>Fresh evidence beyond the resolved default-off thread is that this landing row promises an available Models controller but assigns only handler files and `vibe/ui_server.py`; neither the active lane scopes nor the complete checklist includes `core/controller.py` or `tests/test_controller_model_hub_gate.py`. The current controller returns early when `VIBE_MODEL_HUB_ENABLED` is absent, and that test explicitly expects `model_hub_runtime is None`, so I1 can satisfy every named file/test while fresh installations still have no runtime. Add the controller and its gate test to I1's owned transition.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L145-L147) | AC-22 + AC-31 | `core/controller.py`; `tests/test_controller_model_hub_gate.py` | I1 |++**Forward stop.** After the S-1 head, if a review reports at least three findings in the same+runtime/fallthrough, Source identity/inventory, or route-data-semantics classes, freeze+this lane without editing. Return the complete inventory to the owner for the separate+design action of expressing the algorithm in a machine-checkable form such as+pseudocode or a decision table.+## 7. Kickoff checklist (orchestrator)**This is the v1 kickoff and it is spent.** It ran: its surveys are on diskdiff --git a/docs/plans/model-hub-tos-review.md b/docs/plans/model-hub-tos-review.mdindex 405ee7545..599f1837a 100644--- a/docs/plans/model-hub-tos-review.md+++ b/docs/plans/model-hub-tos-review.md@@ -331,3 +331,113 @@ cross-vendor, cn-sub)Re-verify §2.1/§3.1 language and the §7 architectural conclusion **immediately before**enabling any subscription flow default-on. This memo gates *defaults*, per impl plan §4; thebuild may proceed on API-key paths in parallel.++---++## 12. Owner addendum — 2026-08-07++This dated product ruling supersedes the parts of §8 recommendations **#1** and **#5**+that would make API-key-only supply or native-client binding a blanket restriction on+Hub-held subscriptions. The preceding research, evidence, and original recommendations+remain intact as the historical risk record; they are not product gates where this+addendum differs.++The recommended and default subscription path is native: Claude stays in Claude Code's+local login and ChatGPT stays in Codex's local login. Native supply leads that backend's+recommended Follow resolution. A Custom chain remains authoritative and may put a Hub+hop first with no hidden native pre-pass. When the leading native hop reports quota+exhaustion or cooldown before any output starts, the same turn automatically continues+to the next runnable hop in that chain. A later native hop remains native; selecting Hub+is the Gateway takeover. If native output has already streamed, the interrupted turn+ends without retry and the next turn selects the next runnable candidate while native+remains cooling. After native supply recovers, subsequent Follow turns return to it+automatically.++Users may explicitly add either a Claude or ChatGPT subscription as a Hub-held Source.+Once added, that Source may supply any configured backend and may appear in a+cross-vendor per-model route chain. Native subscription origins remain bound to their+own client; this restriction does not apply to Hub-held Sources. The+`subscription_hub_experimental` flag and per-Source consent mechanism are retired.++The only subscription-routing warning appears when a user explicitly adds a Claude+subscription as a Hub-held Source. It must state that Anthropic explicitly prohibits+this use, enforces server-side blocks, real account bans have occurred, and the path may+fail intermittently. It is informational, not a consent gate. No warning appears for+Claude native login, any ChatGPT path, automatic Gateway takeover, automatic return to+native, or cross-vendor routing.++## 13. Owner addendum — 2026-08-07 afternoon (amendment #2)++This later ruling supersedes §12 where they differ and, for product behavior, all+conflicting portions of §8 recommendations **#1 through #5**. The original memo,+evidence, risk matrix, and recommendation text remain unchanged as historical research;+they do not override this addendum. Recommendation #1's API-key support remains valid,+but it is not an API-key-only product gate. Recommendations #2–#5 no longer make+Claude Direct-only, gate ChatGPT behind consent, require an experimental flag, or bind+Hub-held subscription credentials to their native client.++Subscription custody is vendor-specific:++- Claude subscriptions recommend and default to Claude Code's native local login.+ Adding Claude as a Hub-held Source is optional and shows the sole factual warning:+ Anthropic explicitly prohibits this use, enforces server-side blocks, real account+ bans have occurred, and the path may fail intermittently.+- ChatGPT subscriptions recommend and default to a Hub-held Source. Native Codex login+ remains supported but is not recommended and is not the default add-flow guidance.+ The owner bases this product recommendation on Codex OAuth supporting login from+ third-party applications. No warning or consent prompt appears for either ChatGPT+ path.+- Any Hub-held subscription may serve any configured backend and may join a+ cross-vendor Custom chain. Native credentials remain usable only by their sanctioned+ client. Neither `subscription_hub_experimental` nor per-Source consent survives.++When a native subscription leads the effective chain, pre-stream quota exhaustion or+cooldown advances to the next runnable chain hop regardless of channel; after streamed+output begins, the turn is not replayed. A later native hop remains native, while the+first selected Hub hop is the Gateway takeover. The first such native-to-Gateway+takeover in a conversation may emit one lightweight informational notice when the default-on+`native_takeover_notice_enabled` setting is enabled. This is active-conversation copy,+not a warning, risk prompt, resolution-event delivery, or proactive push system; the+2026-07-29 proactive-push cut remains in force.++## 14. Owner addendum — 2026-08-08 (amendment #3)++This ruling supersedes §13's successful-takeover notice and setting, while retaining+its vendor-specific subscription custody recommendation and every other routing rule.+No automatic native-to-Gateway takeover emits a conversation message, and+`native_takeover_notice_enabled` does not enter the v5 contract.++The rationale matches the 2026-07-29 proactive-push cut and the ruling that provenance+is a debug affordance: model supply should feel like tap water or air. A user stays+focused on the current task rather than supplier identity, switching, or remaining+balance. The Model Gateway and Usage pages are the pull surfaces for experts who choose+to inspect the takeover badge, connector state, recent-switch record, and usage.++This silence applies only to a successful handoff. If every candidate is unavailable,+the turn still reports the existing truthful failure; if streamed output prevents a+transparent retry, the existing retry copy remains. Page state and recorded switching+evidence also remain. This amendment removes a message and setting, not routing,+failure reporting, or observability.++## 15. Owner addendum — 2026-08-09 (configured-chain architecture)++This ruling supersedes only the routing-policy language in §§12–14 that describes+`Follow`, `Custom`, an effective chain, or a runtime-selected candidate. Their risk+evidence, vendor-specific custody recommendation, single Claude Hub warning, silent+successful fallback, truthful terminal failure, and pull-only observability remain in+force.++Every `(backend, menu model)` has one visible persisted chain of exact Source/model+hops. Add Source performs matching once and writes the resulting hops; the user then+adds, removes, reorders, or remaps those same entries. Runtime walks the stored order,+checks whether each exact hop can run now, and applies the classified fallthrough rule.+It does not derive another provider list, insert native supply, or choose a substitute+model. A user-configured cross-vendor or cross-model mapping is authoritative and needs+no warning beyond the existing Claude Hub add warning.++Vendor custody recommendations affect only Add Source placement. The sole policy in+`model-hub.md` §4.2 chooses a deterministic position during Add Source, persists it in+the visible configured chain, and never runs at runtime. Takeover remains a derived+execution fact: a later stored hop is current while the first stored hop is unavailable+for a recoverable quota or cooldown reason. It is not a routing policy or persisted+state.diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 7c22b6cc7..7849b99d3 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -1,90 +1,79 @@# Model Hub — Product Spec-Status: **v2.0** (2026-07-29) · supersedes v1.1 (2026-07-23) outright-Owner decisions incorporated through: 2026-07-29 (+08:00)-Design source: `../avibe-docs/design.pen`, frames `产品改造 V6 01 – V6 04` (desktop)-and `产品改造 V6 M01 – V6 M02` (mobile). The V4 frames document the shipped v1 and-are kept as history; V5A/V5B/V5C are rejected explorations.-Contracts: `model-hub-contracts/` at `contract_version: 3` (single batch freeze).-Discussion record: Show Page of session `sesb7r2qwb4z4` (v1 rounds 1–10) plus the-V6 redesign round (2026-07-28/29).--## 0. Revision note — why v2 replaces v1--Owner ruling (2026-07-28/29): **a single global source priority list is a product-model error.** Ordering is a *consumption* property, not a *supply* property. A-source is an asset the user owns; how eagerly to spend it is a decision each-agent backend makes for itself. Claude Code and Codex legitimately want different-orders over the same set of sources, and one global list cannot express that-without lying to at least one of them.--v2 therefore moves ordering off the source and onto the per-backend supply-strategy: each agent backend owns **an ordered subset of the sources it is-eligible for**, plus a policy stating whether that order follows the product's-recommendation or is frozen by the user.--**No back-compat, no migration shims.** The feature has not GA'd:-`VIBE_MODEL_HUB_ENABLED` is dormant by default and every backend defaults to-`direct` (PR #1019). v2 replaces the v1 structures outright — the global-`priority_order` config key and `PUT /api/models/priority` are removed, and old-keys are dropped on load rather than translated. Nothing user-visible regresses,-because nothing user-visible shipped.--This is distinct from the product's **native-config import** feature (migration-scan/apply, §6): that is an onboarding capability for users arriving with existing-CLI configuration, and this ruling does not touch it.--Changed since v1.1: §2 promises 3–4, §3 vocabulary, §4 (restructured around the-supply/consumption split, plus server-authoritative eligibility, the state-taxonomy, and the per-(agent, model) chain), §5 frames, §9 non-goals, §10 open-items.--**Addendum — cross-vendor models are first-class (owner ruling 2026-07-29 02:22).**-GPT models must be usable in Claude Code, and Claude models in Codex, as a-**built-in** hub capability — never a user-visible "plugin" concept. Two-consequences, both folded into this revision:--- v2 now says plainly that this already works: an `api_key` source of the other- vendor plus an explicit per-agent mapping (§4.3), riding eligibility rules that- admit any vendor's key for any backend (§4.4) and engine-core protocol- translation. §9's non-goal is sharpened accordingly — what is default-off is- *automatic* substitution, not cross-vendor supply the user asked for.-- §10.4 carries the v2.1 candidate that makes it a first-class menu entry. That item- **evolves the fixed-menu decision locked 2026-07-22** — built-in ids only — into- built-in core plus user-added upstream models. Recorded here because a locked- decision is being changed, on the ruling above, and gated on a fidelity spike- rather than adopted outright.--**Addendum — proactive push is cut (owner ruling 2026-07-29 10:54).** No resolution-event is delivered to any conversation. Supply problems surface in the turn that hits-them and on the 「模型」 page; events stay recorded for the 最近切换 feed, while source-and agent **status reads live blocking state rather than the event log** (07-29, review-round 4 — §4.5 carries the reasoning), and `severity` becomes feed/UI metadata rather-than a delivery trigger. 「Surface in the turn」 means the turn that supply **broke**: a-turn a fallback carried says nothing, because it succeeded. §4.5 is-rewritten accordingly, and with it two decisions this spec had carried as settled or-open are **superseded**: the round-5/7 recipient resolution (two-hop expansion from-backend to named Agents to scopes) and the standing open decision on a 「home」-scope-fallback plus recency filtering. Both answered "who gets the message"; there is no-message. The 07-29 10:44 ruling that `SupplyGap.agents` includes the Agents inheriting-a backend default **stands** — it was never about delivery, and it is the payload of-the delete guard and the confirm dialogs.--A third decision follows from the same cut but needed its own ruling, because it was-about the record rather than the delivery: round 8's 「a source event names every-backend it affects」 is **superseded** (orchestrator ruling, 07-29 — owner-vetoable).-Source **state** events are recorded **once, unattributed** — the traffic kinds (`switch`,-`channel_switch`, fallback-return `recover`) stay backend-attributed, because there the-backend is the event's own subject rather than an impact claim (§4.5, and AC-18's frozen-example opens 「Claude Code:」 on exactly that ground; scoped 07-29, review round 15).-Per-backend impact is derived live-by the consumers from current per-agent orders, which is both what the shipped feed-frames already render and the only answer that stays true after an order changes.-No schema field is added, and no contract version moves for it; §4.5 carries the-reasoning.--Subscriptions are untouched by all of this: they stay bound to their own vendor's-backend in both channels (S2/ToS, §4.4).+Status: **v3.0** (2026-08-09) · supersedes v2.0 (2026-07-29) outright+Owner decisions incorporated through: 2026-08-09 (+08:00)+Design source: `../avibe-docs/design.pen`. The V6 frames remain the visual baseline;+the v3 interaction draft for the two-module information architecture is owner-approved+as the implementation baseline (2026-08-07 afternoon). The design lane still owes+production-complete desktop/mobile states.+Contracts: `model-hub-contracts/` remain unchanged by this docs-only revision.+`model-hub-implementation.md` records the exhaustive final-shape handoff. Its mechanical+closure must coexist on one tested PR head; all remaining consumers and evidence must+land before release.++## 0. Revision note — why v3 replaces v2++Owner ruling (2026-08-07): **Model Hub is Avibe's default local model gateway.**+Its end-to-end product model is:++1. upstream sources — vendor subscriptions, API keys, and third-party relays represented+ as API keys with custom Base URLs;+2. the local Gateway — protocol adaptation, model pairing, ordered routing, failover,+ retry, and recovery;+3. downstream Agents — consumers of the Gateway, not owners of upstream credentials.++Every `(backend, menu model)` owns one persisted ordered route chain, and every hop+names the exact `(source_id, model_id)` to call. This formally supersedes v2 §9's “No+per-model ordering” non-goal on 2026-08-07.++**Configured-chain ruling (owner 2026-08-09, S-1).** Matching happens when a Source is+added and writes the resulting exact hops. From then on the Gateway screen is the+configuration and the configuration is what executes: users add, remove, reorder, or+edit a hop's explicit model mapping, while runtime only walks those hops and classifies+live availability and fallthrough. There is no `follow | custom` state, no runtime+Source/model matching, and no second projection from a backend order. §4.3 is the only+normative execution algorithm for this stored chain.++The final product has no separate fixed-menu `mappings` structure beside route chains.+A same-model choice is simply a hop whose `model_id` equals the menu model; a mapped+choice is a hop whose explicit `model_id` differs. Both are ordinary configured hops.+The final shape and its rationale are in §4.6 and are **owner-vetoable (2026-08-07,+amended by S-1 on 2026-08-09)**. Model Hub has not shipped, so no compatibility layer,+data conversion, policy transition, or second routing authority is part of the+implementation.++**Subscription ruling (owner 2026-08-07, amended later the same day).** Recommended+custody is vendor-specific. Claude subscriptions stay in Claude Code's local login by+default for compliance; adding one as a Gateway upstream remains an explicit optional+path. ChatGPT subscriptions are recommended and defaulted to a Gateway-held Source;+native Codex login remains supported but is neither recommended nor the default+add-flow guidance. Each backend has at most one `native_cli` Source because its official+CLI exposes one current local login; additional accounts are added as Gateway-held+Sources. This singleton ruling is **owner-vetoable (2026-08-08)**. The channel handoff+remains a first-class product story, not an escape hatch or hidden pre-pass; §4.3 alone+defines its exact runtime behavior.++A user may explicitly add either subscription as a Gateway-held upstream, and a+Gateway-held subscription may participate in a cross-vendor configured chain. The only+warning is one factual sentence shown when the user chooses the Claude-as-Gateway+path: Anthropic explicitly prohibits it, enforces server-side blocks, real account+bans have occurred, and the path may fail intermittently. Native Claude, ChatGPT in+either channel, and cross-vendor routing show no warning. No experimental flag or+per-source consent record exists in the final specification.++**Surface ruling (owner 2026-08-07).** The Models page has two product modules:+Sources and **Gateway**. Sources answer what upstream access the user owns. Gateway is+the main work surface for exact pairing, model mapping, and per-model chain order.+The line between them visualizes current state; it is not a configurable object. A+third “Configure Agents” module — adding models, reasoning effort, and related Agent+settings to Agent definitions — is explicitly deferred; v3 records the intent and+does not design it.++**GA direction (owner 2026-08-07).** Three directions are accepted, without expanding+the GA scope in this revision: conversion-fidelity evidence, a release gate covering+Avibe-owned engine asset mirroring plus the supported-platform matrix, and the+vocabulary recut in §3. §10 records only the remaining research questions and evidence+owed before those gates can be specified mechanically.---@@ -102,293 +91,388 @@ endpoints). They want subscription quota consumed first, automatic fallbackwhen it runs out, automatic switch-back on recovery — without understandingbase URLs, protocol conversion, account pools or routers.-## 2. Product promise (user-facing, locked)--1. Connect a source once — every Agent that can use it, can use it.-2. Subscriptions are consumed first (already paid); when quota runs out- Avibe switches to the next source automatically and switches back on- recovery. Work never stalls. (Mechanism: per-turn channel dispatch —- subscriptions burn via the CLI's sanctioned native channel; the hub- arbitrates the api-key tier. See §4.3.)-3. **Spending order is per-Agent and user-owned.** Each Agent has its own- ordered list of sources; that list order **is** its spending order. By- default the order follows the product's recommendation; the moment the user- touches it, the order becomes theirs and Avibe stops changing it.-4. **The product never reorders behind the user's back.** Predictability- outranks cleverness: no health scores, no learned ordering, no silent- promotion of a "better" source. Every order change is either an explicit user- edit or the documented recommendation rule admitting a newly added source at a- stated position.+## 2. Product promise (user-facing, locked 2026-08-07)++1. **Connect upstream access once.** A vendor subscription, API key, or API key+ with a custom Base URL becomes a Source that every eligible Gateway route can+ use.+2. **Subscription custody is vendor-specific, and native takeover stays seamless.**+ Claude recommends its compliant native login; ChatGPT recommends a Gateway-held+ Source. Each backend has at most one native Source. §4.3 defines the complete+ native-to-Gateway handoff, recovery, and no-replay behavior without placing a hidden+ native attempt ahead of a user-owned configured chain.+3. **Every route is visible configuration.** Each `(backend, menu model)` stores one+ exact ordered chain of `(source_id, model_id)` hops. Adding a Source proposes and+ persists its matches once; afterward the user edits that same chain directly.+4. **The user owns every configured order and mapping.** No health score, learned+ ranking, vendor label, or runtime inventory walk silently rewrites the chain. Avibe+ may skip an unrunnable hop for the current turn; it never mutates configured order+ or model ids as a side effect.+5. **Adaptation stays local and invisible.** The Gateway performs protocol+ conversion, retry, failover, and recovery. Agents consume a stable model menu;+ users never configure an engine plugin or account pool.Core persona: individual users who already pay for Claude Pro/Max or ChatGPTPlus/Pro ("spend what I bought first"). Secondary: API-key-only users.Explicit non-persona: relay-station operators ("站长") — Avibe ships nooperations console.-## 3. Vocabulary (locked; UI copy uses ONLY these nouns)+## 3. Vocabulary (v3 recut; UI copy uses only these nouns)| Concept | zh | en | Notes || --- | --- | --- | --- || The settings surface | 模型 | Models | Single nav entry between 通讯平台 and 后端 |-| Where tokens come from | 来源 | Source | Two kinds only: 订阅账号 (subscription account, OAuth) and API Key (key + editable base URL). A source carries **no order** |-| Per-Agent spend order | 来源顺序 | Source order | Per agent backend: an ordered subset of that backend's eligible sources. Replaces v1's global 优先级 |-| Order policy | 跟随推荐 / 自定义 | Follow / Custom | 跟随推荐 = server-computed, new sources auto-join; 自定义 = frozen by the user |-| Supply mode per backend | 中枢模式 / 直连模式 | Hub / Direct | Hub = default & recommended; Direct = legacy native-config mode, kept but not recommended |-| Per-Agent health rollup | 供给状态 | Supply status | 正常 / 降级 / 无可用来源 (§4.5) |--Banned from UI copy: 网关/gateway, 路由/router, 逻辑模型, Provider(作为界面-名词), 账号池, 中转站(as a **category**; the word may appear only inside-helper copy as an example use-case for a custom base URL), plus — new in v2 —-**优先级** as a standalone global noun. An order always belongs to somebody: name-the Agent. "Relay station" is NOT a source type — it is an API Key with a custom-base URL (owner decision 07-23; avoids the unanswerable official/unofficial-classification for OpenAI/Anthropic-compatible vendor endpoints).--## 4. Architecture: supply, consumption, resolution--The v2 split, stated once: **sources supply; agents consume; ordering lives on-the consumer.**+| Upstream module | 来源 | Sources | Inventory of access the user owns; never an ordering surface |+| Local adaptation and routing module | 网关 | Gateway | First-class product noun, owner-locked 2026-08-07; pairing, allocation, ordering, retry, failover, recovery |+| Where tokens come from | 来源 | Source | Two kinds only: 订阅账号 (OAuth) and API Key (key + editable Base URL); a relay is the latter, not a third kind |+| Per-model route | 路由链 | Route chain | Ordered hops for one `(backend, menu model)`; every hop is an exact Source + upstream model pair |+| Explicit model mapping | 型号映射 | Model mapping | A configured hop whose upstream `model_id` differs from its menu model; the system never invents one at runtime |+| Per-backend path | 网关 / 直连 | Gateway / Direct | Wire values are `hub | direct`; Gateway is the default product path, Direct is the diagnostic/self-managed path |+| Gateway hop using the official CLI login | 原生 | Native | Required for a `native_cli` hop inside Gateway mode; it is not Direct mode |+| Per-backend health rollup | 供给状态 | Supply status | 正常 / 降级 / 暂时全部在冷却 / 无可用来源 (§4.5) |+| Recoverable fallback state | 接管 | Takeover | Derived by §4.3 when a later hop is current because the first hop is recoverably unavailable; never persisted |++The remaining vocabulary rulings below are **owner-vetoable (2026-08-07)**; they+apply to UI nouns, not precise technical prose in this specification.++| Formerly banned term | v3 ruling | Reason |+| --- | --- | --- |+| 网关 / Gateway | **Required product noun** | The owner named the main module Gateway; banning it now hides the product model |+| 路由 / route | **Allowed only as 路由链 / route chain or as a verb**; standalone 路由器 / router remains banned | Gateway is the component; route chain is the user-owned configuration |+| 逻辑模型 / logical model | **Banned** | Menu model and upstream model id already name the two real identities |+| Provider (as a UI noun) | **Banned** | The UI manages concrete Sources; vendor may appear as metadata, and “upstream provider” remains valid architecture prose |+| 账号池 / account pool | **Banned** | It implies operator tooling and multi-tenant pooling that Avibe does not ship |+| 中转站 / relay station as a category | **Banned** | It is an API Key Source with a custom Base URL; helper copy may use it as an example |+| 优先级 / priority as a standalone global noun | **Banned** | Name the owning model Route chain; ordinal copy such as “first upstream” is allowed |++**Copy-density rule (owner-approved interaction baseline, 2026-08-07 afternoon).**+Use the glossary nouns in controls and status. Put explanations behind a compact info+icon or contextual affordance; do not turn Sources or Gateway into permanent help-text+panels. This is the vocabulary recut applied to interaction copy, not a third module or+an excuse to hide action-required state.++## 4. Architecture: upstream → Gateway → Agents++The v3 split, stated once: **Sources represent upstream access; Gateway owns local+adaptation and routing; Agents consume the result.** Ordering is never a property of+a Source.### 4.1 Supply — Sources (global assets, no ordering)Each source carries: kind (subscription | api_key), vendor, credential-reference, protocol (anthropic | openai | openai_compatible …), an editable base+reference, protocol (`anthropic | openai_responses | openai_chat`), an editable baseURL (api_key kind; prefilled for known vendors), a **model list** it can supply(auto-discovered where possible, e.g. `/models`; manually extendable via custommodel entries), billing type (包月 | 按量 ¥), state (§4.5), and usage-(subscription cycle % / monthly spend).--A source carries **no position, rank, or priority field anywhere** — not in-config, not in the API, not in the UI. The 来源 list is an asset inventory sorted-for reading convenience, never a spend order.+(subscription cycle % / monthly spend). Existing `last_discovered_at` records the last+successful full inventory replacement; it is not a connectivity-check timestamp.++The Source workflow is complete at both entry points:++- **Connectivity and protocol observation.** The normal Add Source form asks only for+ optional name, Base URL, and API key. Its user-triggered Add action reuses one+ connectivity interaction to classify reachability/authentication and observe the+ protocol before Save can commit; it adds no separate step and presents no protocol+ selector. This unsaved operation does not save a Source, consume routing order, or+ run an Agent turn. For an API key it may provision an engine credential only+ transiently:+ every success, failure, timeout, and cancellation path revokes that ref before the+ operation settles. A revoke failure enters the existing durable pending-revocation+ reconciliation rather than leaving an unreferenced credential untracked. No test+ response exposes the ref. A reachability or authentication failure is reported+ independently from protocol observation: Save may proceed only when that interaction+ still produced response evidence for the protocol, and it provisions the committed+ Source independently.+- **Saved Source refresh and recovery.** Source details exposes the distinct+ `POST /api/models/sources/<id>/refresh` operation. It is intentionally mutating: it+ tests the stored protocol, rediscovers inventory, updates Source health, and clears a+ `needs_action` or `error` blocker only when current evidence proves recovery. Before+ committing a smaller inventory it runs §4.5's configured-hop and supply-gap guards.+ This is the **only saved-Source test/discovery mutation and the only corresponding+ Source-details button**, labelled “Refresh models” / 「重新拉取」. Its request,+ guarded refusal, and success are exactly the refresh row of §4.5's authoritative+ Source-mutation matrix. The UI displays the resulting inventory and state and never+ presents a second “Test connectivity” action.+- **Model discovery.** Third-party Anthropic-compatible and OpenAI-compatible Sources+ expose an explicit “Fetch models” action while they are still in Add Source. A saved+ Source gets the same discovery behavior only through the refresh operation above;+ there is no parallel saved discovery route. Discovery uses the observed protocol+ adapter, replaces only the discovered slice, preserves manual entries, and renders+ added, removed, unchanged, and failed results. Rediscovering an unchanged model id preserves its edited+ `reasoning_efforts`, `display_name`, and `discovered_at`; only an id absent from the+ new upstream list leaves the discovered slice. Unsaved Add Source discovery applies+ the same transient credential rule as connectivity observation: success, failure,+ timeout, and cancellation all revoke the provisioned ref, and a revoke failure enters+ durable pending-revocation reconciliation before the operation settles.+ The saved Source surface may render freshness only as “Model list updated at …” /+ 「型号列表更新于…」 from `last_discovered_at`. It carries no latency or “last checked”+ field or copy.+- **Model inventory and manual entries.** A `discovered` entry's existence is an+ upstream fact, not a user decision; creating and deleting inventory entries therefore+ applies only to entries the user wrote. Model `id` is unique within a Source. Every+ model-list item has+ `{id, origin: "discovered" | "manual", reasoning_efforts: string[]}`; discovery+ creates `origin: "discovered"`, while a user-created entry uses `origin: "manual"`.+ `reasoning_efforts` is required and may be empty. It declares the exact reasoning+ effort values that the upstream model supports; it does not select one value. An+ empty list declares none, and no entry receives a default, selected value, or+ prefilled value. Existing optional `display_name` and `discovered_at` metadata remain+ part of the entry and survive refresh. This capability list belongs to+ Source model inventory, not the deferred Configure Agents module: it describes which+ invocation values that exact upstream model accepts, not which model or effort an+ Agent selects.+ Editing the list on either a discovered or manual entry uses the atomic+ `PATCH /api/models/sources/<source_id>/models/<model_id>` mutation with+ `{reasoning_efforts}`; the adapter validates the submitted list+ and re-echoes the canonical stored value as `{source: Source}`. Editing the list never+ changes `id`, `origin`, or a route chain. Model creation and deletion use the same+ Source-model subresource; deleting a discovered entry is rejected at the API boundary+ with `source_model_managed_upstream`. This all-inventory editing scope is an+ owner-vetoable orchestrator+ ruling dated 2026-08-08: discovery endpoints commonly return only ids, so a+ discovered-only immutable list would leave the capability permanently undeclarable.++**Protocol observation (owner ruling 2026-08-09, superseding AC-27's 2026-08-07+manual-choice ruling).** Every stored `protocol` is traceable to a real response from+that upstream before Save. Avibe never infers the value from vendor name or Base URL;+known-vendor metadata may order the three probes but cannot produce a conclusion or a+save-time default. When observation cannot distinguish a protocol, the failure state+honestly asks the user for a one-time manual hint among the same three values. The hint+changes probe order only: its selected adapter must still receive a successful upstream+response before Save. A failed observation therefore stores nothing rather than guessing.++Once saved, `protocol` is immutable for that Source. Connectivity retest, model+discovery, refresh, credential replacement, Base URL replacement, and restart all use+the stored adapter and never rewrite it. Changing protocol means creating a new Source,+so a later operation cannot silently reinterpret existing inventory or configured hops.+The stored shape carries no manual/automatic provenance marker and no unverified+protocol state: manual and automatic probe ordering become indistinguishable after the+same response-backed conclusion. “Add anyway” is available only after protocol has been+proved and some other information, such as model inventory, remains unavailable; that+uncertainty belongs to Source health, not protocol identity. Every saved Source therefore+has a response-proven protocol, and any path without that proof produces no Source.++`openai_chat` is the one Chat Completions-compatible transport; there is no separate+`openai_compatible` value because both names drove the same engine section and endpoint.+Chat Completions remains supported: OpenAI has not retired the platform API, and many+third-party and open-source upstreams expose it as their only compatible surface.++A source carries **no position, rank, or priority field of its own**. The Sources+module is an asset inventory sorted for reading convenience. Gateway configuration+owns one explicit Source order per backend and one exact Route chain per menu model;+neither order is stored on a Source.**Supply channel.** Each source has a `supply_channel`:-- `native_cli` — the credential lives in the CLI's own sanctioned store and- quota is consumed by launching the CLI in its native form. Default for- subscription sources (mandatory-default for Claude subscriptions:- Anthropic prohibits and server-enforces credential use outside Claude- Code; see `model-hub-tos-review.md`).-- `hub` — the engine holds the credential and re-originates requests.- Default for api_key sources. For subscription sources this channel is- available ONLY behind the consent-gated experimental flag- (`subscription_hub_experimental`): explicit ban-risk consent copy (S2 §9),- per-source opt-in, visible "experimental" marking in the source row.- This applies to Claude and ChatGPT subscriptions alike; the flag ships,- but nothing enables it silently.--The same model may be supplied by multiple sources; that is exactly what each-agent's source order arbitrates.--### 4.2 Consumption — per-Agent supply strategy (每 Agent 供给策略)--One record per agent backend. It owns:--- `mode` — 中枢 hub | 直连 direct.-- `menu_kind` plus the menu itself: `menu` (open-menu backends, i.e. OpenCode) or- `mappings` (fixed-menu backends, i.e. Claude Code and Codex). Unchanged from- v1: a mapping chooses a *model*, never a source.-- **the agent's source order** — an ordered subset of the sources eligible for- this backend (§4.4), plus a policy:--| Policy | zh | Behavior |-| --- | --- | --- |-| `follow` (default) | 跟随推荐 | Order is server-computed by the recommendation rule below. A newly added eligible source **joins automatically** at its recommended position. |-| `custom` | 自定义 | A user-owned, frozen ordered subset. A newly added eligible source does **not** join; the UI hints 「有新来源未启用」 and offers one-tap enable. |--State machine: `follow` --any manual edit--> `custom` --「恢复推荐顺序」--> `follow`.-Forking to `custom` is implicit and immediate: reordering, enabling, or removing a-source while in `follow` freezes the current order as the user's own. Returning to-`follow` discards the frozen subset and recomputes.--**Recommendation rule (deterministic; document verbatim, implement verbatim).**-For a given backend, the recommended order is:--1. the backend's **own-vendor subscription**, if present and eligible — Anthropic- subscription for Claude Code, OpenAI subscription for Codex — *regardless of- supply channel*: a `native_cli` subscription and a consented hub-held one- (`subscription_hub_experimental`) occupy the same first slot, because both are- the same thing to the user, their own subscription, and the channel is a- delivery detail. If both exist for one vendor, `native_cli` precedes the- hub-held one — the sanctioned path is the safer default;-2. then all eligible `api_key` sources, **by `created_at` ascending**;-3. tie-break anywhere above by **source `id` ascending**.--The rule is *exhaustive over eligible sources*: nothing eligible can fall outside-it, which is what makes 跟随推荐 safe to auto-join. (A cross-vendor subscription-is never eligible for a foreign backend in the first place — §4.4 — so it is not-an omission here.)--Nothing else participates: no health score, no latency, no cost heuristic, no-usage-based reordering. This rule is the *entire* content of 跟随推荐, and it is-stable — the same set of sources always yields the same order.--Two obligations follow, and both are contract, not implementation detail:--- **Creation order must be persisted**, as immutable `created_at` on the source- (`source.schema.json`). Insertion order in the config file is not a contract and- the sources array is explicitly unordered (`api.md`), so without a stored stamp- rule 2 is not reproducible.-- **Rule 3 is not decoration**, and it needs one companion rule to finish the job.- Two sources imported in one migration batch can legitimately share a timestamp, and- the id tie-break settles those. It does *not* settle how a record predating- `created_at` compares to a stamped one — a tie-break orders equals, and null is not- equal to a timestamp. The missing half is therefore stated normatively in- `source.schema.json`: **an absent stamp sorts before every present one** (the record- is older than the field itself), ties by id, and the serializer backfills such- records with a constant epoch stamp rather than the upgrade time, so the backfill- reproduces the order the user was already shown instead of reshuffling it. With both- halves the sort is total over every mix of stamped, unstamped and same-stamped- sources, so 跟随推荐 is neither ambiguous nor liable to drift on upgrade.--**Ordering is per-agent; health is global.** Cooldown and health state stay-**source-global**, shared across all agents. From first principles: quota-exhaustion and network reachability are properties of the *account*, not of the-agent that happened to touch it — if Claude Pro's cycle quota is gone, it is gone-for every consumer. The current implementation already works this way (the-cooldown pool keyed on the shared source row, `_cooldown` in-`core/handlers/model_hub/service.py`); v2 keeps it deliberately.--### 4.3 Resolution pipeline (step 0 + three steps)--0. **Channel dispatch** — per turn, before launch: if the first eligible,- retry-ready source in *this agent's* order is `native_cli` (e.g. a healthy- Claude subscription for Claude Code), launch the CLI natively with zero- injection — sanctioned form, hub untouched. If that source is- quota-exhausted/cooling (inferred from prior native-turn errors plus recovery- timers), launch with hub injection so steps 1–3 arbitrate the hub-channel- tier. Recovery flips the next turn back. This is possible because Avibe- launches backends per request; switching never happens mid-process.- `native_cli` sources are eligible only for their sanctioned client (Claude sub- → Claude Code); enforced in code via `allowed_origins`-style binding.-1. **Mapping** — requested model ID → explicit target, when one exists.- Only fixed-menu agents (Claude Code / Codex) can override, per-agent- (e.g. Claude Code's `claude-opus-4-6` → `glm-5.2`). Mapping is an explicit,- deterministic user choice and always takes precedence. No mapping means the- caller-facing menu ID stays intact for the next, per-source derivation; it does- not promise blind identity passthrough to an upstream.-2. **Candidates (v2)** — start from **this agent's ordered subset** (§4.2), in- its order, then filter in two stages:- - **capability** (structural, stable): a. derive this source's **effective- upstream model id**, then require the source to supply it; b. the source is- eligible for this backend and channel (§4.4); c. for open menus, the source's- vendor matches the **provider segment** of the- requested identifier. Predicate c does not fold into a: sources advertise bare- model ids, so `zhipuai/glm-5.2` and `custom/glm-5.2` present the *same* bare id,- and without the vendor predicate the agent's source order alone would decide- which upstream answers — quietly serving a zhipuai request from a relay that- happens to sit higher. The shipped resolver already enforces it- (`opencode_provider_id(source.vendor) == provider`,- `core/handlers/model_hub/resolver.py`); v2 keeps it, and keeps it in the- *capability* stage, because a vendor is structural and not momentary.- The effective-id derivation has one precedence order. An explicit mapping- requires its target id exactly. Without one, a `native_cli` source first- preserves an exact CLI alias such as `opus` or `sonnet[1m]`; the installed CLI- owns that alias's compatibility. For every other fixed-menu source on its- backend-native vendor, built-in aliases resolve against **that source's- discovered inventory only**: a Claude version alias chooses the latest dated id- for that exact version; `opus`, `sonnet`, `haiku`, `opus[1m]`, and- `sonnet[1m]` choose the latest version/date in the same family; a dated request- remains exact. If no automatic native alias applies, exact identity is accepted- when the source advertises the menu id.- Manual inventory, a foreign vendor, and an undiscovered id never satisfy this- automatic branch. Therefore two Hub sources may derive different dated ids for- one menu id. The caller-facing menu id- remains the stable chain, probe, gateway, and event correlation key; only the- upstream attempt carries the per-source effective id.- What survives is the *capability chain* for this (agent, model) pair — what- §4.6 defines and what the UI displays, cooling members included.- - **runnability** (momentary, per turn): d. the source is retry-ready —- `healthy`, or `cooldown` whose `retry_at` has already passed, since the- resolver retries a recovered source rather than waiting for a state flip.- Never `needs_action` (cannot recover unattended) and never `error` (already- known broken); today's resolver skips both, and admitting either would spend- the turn on a known failure. What survives is the *runnable candidate list*- this turn walks.-- The two are one definition with one extra filter, deliberately: a cooling- source must stay **visible and dimmed** in the chain (frame V6 04) while being- skipped by the turn. Dropping it from the displayed chain would tell the user- they own less than they do; keeping it in the runnable list would burn a turn- on a known-exhausted account. There is no global list at any point, and no- per-model ordering: a model never carries an order, it only filters the- agent's one order.-3. **Supply** — use candidate #1; on quota-exhausted/429, transient 5xx or- network failure enter cooldown and take the next **within the same turn**;- switch back on recovery. Convert protocol when needed. Every switch is- appended to the human-readable 最近切换 log.--Error taxonomy (no blind fallback): parameter/protocol/tool-compat errors-surface to the caller; 401 → refresh once, then retry; 429 / explicit quota-exhaustion / transient 5xx / network → cooldown + next candidate, with cooldown-duration classified per cause (network / rate-limit / quota). Once streaming has-started, no transparent retry — see §4.5 for the copy this obliges.--**Mapping ≠ automatic cross-vendor fallback.** The latter ("Claude quota-gone → serve GPT") stays an experimental, default-off advanced flag with-visible per-event marking, pending capability/ToS verification. Architecture-reserves `allowed_origins` to restrict which clients a subscription-credential may serve.--**Cross-vendor supply IS a supported v2 capability** (owner ruling 2026-07-29-02:22). Running a GPT model inside Claude Code, or a Claude model inside Codex, is-something v2 supports today: add an `api_key` source of the other vendor, then map-that backend's built-in model id to the model you want. This is a designed-capability, not an accident of the plumbing, and it is **built in** — there is no-user-visible "plugin" concept anywhere in it. The user configures 来源 + 模型; the-hub owns everything under that.--Two existing mechanisms carry it, which is why it needs no new machinery:--- **Eligibility already admits it.** §4.4 row 1: `api_key` sources of *any* vendor- are eligible for *every* backend. The gate is kind + vendor, never protocol — an- OpenAI key is a legitimate source for Claude Code by construction, not by- exception.-- **Protocol translation is engine-core.** The source declares its upstream wire- protocol (`anthropic | openai_responses | openai_chat | openai_compatible`,- `model-hub-contracts/adapter-interface.py`); the calling backend fixes the- client-side protocol; the engine's built-in translator registry connects the- pair, in both directions, streaming and non-streaming (S1 survey §3 conversion- matrix). No plugin participates in the anthropic↔openai pairs.--§4.6's 「经映射」 marking is the v2 UX for it: the user sees which link in the chain-is reached through a mapping, so cross-vendor supply is *visible* rather than a-silent substitution — which is exactly what separates it from the default-off-automatic case above.--**What v2 does not yet promise is fidelity.** S1 §3 settled that *syntax*-conversion is implemented and heavily tested, and equally that thinking,-prompt-cache, tool, image/audio and service-tier semantics are **not**-capability-equivalence guarantees. So the visible mapping warning stays, and "how-well does a GPT model actually behave as Claude Code's model" is a measurement-question, not a design one — §10.4 makes it a spike with a go/no-go per conversion-pair.--### 4.4 Eligibility is server-authoritative (v2)--Which sources an agent backend may consume at all — independent of the user's-order — follows the compatibility matrix (unchanged from v1, keyed on-kind + vendor, because the engine performs protocol translation):+- `native_cli` — the credential remains in the official CLI's local store. This is+ the recommended and default channel for Claude subscriptions (Claude → Claude+ Code). ChatGPT native login (ChatGPT → Codex) remains supported, but is a+ secondary, non-recommended path and is never the default add-flow guidance.+- `hub` — the managed engine holds the credential and re-originates requests. This+ is the default for API keys and the recommended add-flow path for ChatGPT+ subscriptions. It is an explicit opt-in for Claude subscriptions. A hub-held+ subscription is a normal Gateway upstream and may appear in a cross-vendor+ configured chain (§4.4).++**Native Source singleton (orchestrator ruling, owner-vetoable 2026-08-08).** Each+backend may own at most one `native_cli` Source. The official CLI exposes one current+local login and no selectable credential slot, so a second row would not identify a+second runnable account. When that row exists, Add Source disables another “Use+native” choice for the backend and the API rejects duplicate creation with the+existing Source id. Additional accounts belong in Gateway custody as `hub` Sources.+§4.3 alone defines how the singleton participates in resolution.++The ChatGPT recommendation is an owner product ruling based on Codex OAuth supporting+login from third-party applications. It supersedes the earlier memo's experimental+default; it does not weaken the single Claude warning below.++There is no feature flag, consent stamp, experimental row state, or per-route warning+for hub-held subscriptions. The single exception is informational copy shown while+adding **Claude as a hub-held Source**:++> Anthropic explicitly prohibits routing Claude subscriptions through third-party+> gateways, enforces server-side blocks, and real account bans have occurred; this+> path may stop working intermittently.++That sentence does not appear for native Claude, ChatGPT in either channel, or when+the user later places an already-added Source in a cross-vendor chain.++The same model may be supplied by multiple Sources; §4.3 alone executes the exact+stored route for that model.++### 4.2 Gateway strategy — add-time defaults, then explicit configuration++One record per Agent backend owns `mode`, its menu, one stored Source order, and one+stored Route chain for each menu model. The Source order is a visible Gateway default+for Add-time placement, not a runtime capability filter. There is no backend+Source-order policy discriminator and no per-model route policy. The only order runtime+can execute is the exact hop order stored for that model.++Matching is an **Add Source write-time operation**. After connectivity, protocol, and+inventory have been observed, the add transaction proposes exact Source/model matches,+writes the accepted hops, and returns their visible positions. A later refresh,+restart, health change, catalog change, or turn never repeats matching. Users maintain+the persisted chains directly: add or remove a hop, move it, or edit its explicit+upstream `model_id` mapping.++**Add-time Source placement policy (sole authority; owner 2026-08-09 S-1).** The Add+Source service owns one write-time rule that chooses deterministic positions for the+new Source and every accepted exact match. The same transaction writes those positions,+returns each hop through `added_to.position`, and exposes the canonical backend Source+order; the Gateway renders the stored results and the user may adjust them immediately.+No adapter, UI consumer, refresh path, or runtime resolver may implement or rerun+placement. This named policy is one implementation rule, not a plugin point, registry,+user setting, or persisted policy discriminator.++**Current policy value (`placement-v1`).** Append a newly added Source to each+configuration-eligible backend Source order, and append every accepted exact match to+that menu model's current Route-chain tail. This is only the current policy value, not+an API, UI, or acceptance invariant. A later version may choose a better visible+position from model fit or a fixed Source-reliability priority, but it must still run+only during Add Source, persist the chosen position, and leave runtime to execute that+configuration verbatim. There is no “new Source not enabled” state or prompt, and the+UI never uses position to distinguish new from old.++No health score, latency, cost, usage, vendor label, creation timestamp, or later+inventory result reorders existing configuration. `created_at` remains ordinary Source+metadata for audit/display; routing and placement never read or mutate it.++**Routing configuration is per backend and per model; health is Source-global.** Quota+and reachability belong to the Source, not the Agent that touched it. §4.3 reads the+stored chain and annotates its live execution state; it does not construct another+chain.++### 4.3 The only normative configured-chain execution algorithm++For backend `B` and menu model `M`, let `C` be the exact persisted hop array at+`B.routes[M].hops`. Every hop is `{source_id, model_id}` and its `model_id` is the exact+upstream value to invoke. Configuration writes validate Source existence, channel+binding, and that the Source can call the submitted model; any alias resolution or+suggested mapping is completed before the hop is stored. Runtime never matches by+vendor or inventory, inserts a Source, substitutes a model, or reorders `C`.++The following pseudocode is normative and exhaustive:++```text+if B.mode == "direct":+ return DIRECT++attempted = false+for hop in C, in stored order:+ live = inspect_exact_hop(hop)+ annotate hop with live.runnable, live.reason, and live.retry_at+ if not live.runnable:+ continue++ attempted = true+ result = invoke_exact(hop.source_id, hop.model_id, exact_reasoning_effort(hop))+ if result == served: return SERVED(hop)+ if result == canceled: return CANCELED+ if result is terminal_request_error: return FAILED_TERMINAL(result)+ if result is engine_down_at_any_request_phase: return FAILED_TERMINAL(engine_down)++ persist_attributable_source_state(result)+ if result.output_started: return FAILED_TERMINAL(result)+ if result is fallback_class: continue+ return FAILED_TERMINAL(result)++return NO_CANDIDATE(classify_blockers(C)) if not attempted+else EXHAUSTED(classify_blockers(C))+```++`inspect_exact_hop` checks only whether that configured hop can run now. `healthy` and+an elapsed cooldown are runnable. An unelapsed cooldown, `needs_action`, `error`, a+missing/deleted Source, a configured model no longer callable by that Source, or an+unavailable native CLI process is not runnable; the hop stays at its configured+position. The canonical reasons are respectively the existing classified Source reason,+`source_missing`, `model_unsupported`, and `native_cli_unavailable`. A normal turn never+repairs or rewrites configuration.++`invoke_exact` preserves chain order. A `native_cli` hop uses the sanctioned backend's+singleton local login; a `hub` hop uses the local Gateway and may be cross-vendor. The+system never prepends native supply or chooses a model. If the requested reasoning+effort exactly appears in the configured hop model's `reasoning_efforts`, pass that one+value; otherwise pass `null`, with no approximation or downgrade.++Parameter, protocol, and tool-compatibility failures are terminal without fallthrough.+A local Gateway start, listener, or process loss at **any** request phase is terminal+`engine_down`: it mutates no Source, does not replay output, and does not walk another+hop. Credential failures follow the authoritative matrix below. Before output starts,+explicit quota exhaustion, 429, transient 5xx, or attributable upstream network failure+persists its classified Source-global blocker and continues to the next configured hop.+After output starts, no failure is replayed; attributable Source state is still+persisted for the next turn.++The read projection is `C` with live annotations plus `current`, never a reconstructed+provider list. Takeover remains derived: the current hop is not `C[0]` and `C[0]` is+unavailable for a recoverable quota/cooldown reason. Recovery changes current execution+position on the next turn without changing `C`. Every switch is recorded for pull+surfaces; a successful handoff emits no conversation notice or setting.++**Credential-failure decision matrix (authoritative and exhaustive; owner ruling+2026-08-09).** The refresh branch is selected by the credential's actual refresh+capability, not by vendor, Source kind label, or HTTP status alone. Surrounding prose+and every contract consumer may reference this matrix but cannot introduce another+credential-failure branch.++| Decision | Observed result | Credential capability | Retry / classification | Persisted state and remedy | Route effect |+| --- | --- | --- | --- | --- | --- |+| `credential.refresh_once` | first `401` | exposes a refresh operation | refresh once, then retry the same hop exactly once | none before the retry resolves | stay on this hop for the bounded retry |+| `credential.refresh_failed` | the refresh operation times out, is rejected, or returns an invalid response | exposes a refresh operation | no retry; use the existing `credential_expired` or `credential_revoked` classification the adapter can prove | the matching existing `needs_action` detail and refresh-capability-specific remedy | before output, continue to the next runnable hop |+| `credential.refresh_rejected` | retry after refresh is still `401` | exposes a refresh operation | no second refresh; `credential_expired` | `needs_action` + `models.source.needs_action.oauth_expired`; `POST /sources/<id>/reauth` | before output, continue to the next runnable hop |+| `credential.static_unauthorized` | first `401` | no refresh operation, including a static API key | no retry; `credential_revoked` | `needs_action` + `models.source.needs_action.credential_revoked`; `PUT /sources/<id>/credential` | before output, continue to the next runnable hop |+| `credential.account_classified` | classified `402/403` account result | any | no credential refresh; retain the adapter's existing source-global credential classification | `needs_action`; choose the remedy from both classification and credential capability: refresh-capable auth re-authorizes, a static key is replaced, balance is topped up, and a banned account goes to the vendor | before output, continue to the next runnable hop |+| `credential.request_nonfallback` | a non-fallback request-level failure | any | no credential refresh and no Source-global credential classification | no Source-health mutation; surface the request failure | terminal without fallback |++The final mirror registry checks the closed (classification, credential capability) →+`detail_key` → remedy relation in both directions. The resolver suite executes every+row and fails any extra retry or unlisted remedy.++Because health is source-global, a cooldown created through one backend affects every+route using that Source. Because every turn runs the algorithm again, an elapsed+cooldown naturally restores the configured leading hop without mutating order.+The Model Gateway and Usage pages remain the pull surfaces for takeover state,+connector color, recent switches, and usage; provenance remains a debug affordance.++**Takeover projection.** A configured route is in **takeover** exactly when its current+hop is not the first stored hop and that first hop is unavailable for a+self-healing quota/cooldown reason. This is computed from the resolved chain's current+hop and live runnability; it is never a stored boolean or a second routing field. A+chain with no runnable hop is not takeover: it reaches §4.5's truthful `exhausted`+terminal outcome and must not reuse takeover's visual semantics.++**Cross-vendor and conversion fidelity ruling (owner 2026-08-08).** Cross-vendor or+converted supply is functionally usable while its reasoning chain may degrade; that is+expected behavior, not a defect. A relay may itself fall back across models or vendors,+some upstreams omit reasoning, and Claude verifies official reasoning signatures, so a+relay may discard non-official reasoning content. The M0 survey measurements and their+go/no-go rows remain unchanged as recorded evidence. An official-API attribution+re-test is **owner-waived**, not still unverified. Compatibility copy is compact,+info-level, and never a conspicuous per-hop warning. Tool calls, streaming, and system+semantics remain the functional floor; the observed Messages-direction system/tuple+distortion stays recorded as relay behavior, does not block the product direction, and+creates no new acceptance criterion.++### 4.4 Configuration eligibility is server-authoritative (v3)++Which Sources may be written into a backend's configured chain follows the+channel-aware matrix:| Source | claude | codex | opencode || --- | --- | --- | --- || `api_key` (any vendor) | ✅ | ✅ | ✅ || `subscription`, vendor `anthropic`, channel `native_cli` | ✅ | ✗ | ✗ || `subscription`, vendor `openai`, channel `native_cli` | ✗ | ✅ | ✗ |-| `subscription`, vendor `anthropic`, channel `hub` | requires `subscription_hub_experimental` | ✗ | ✗ |-| `subscription`, vendor `openai`, channel `hub` | ✗ | requires `subscription_hub_experimental` | ✗ |-| `subscription`, any other vendor | ✗ | ✗ | ✗ |--**The vendor→client binding is absolute; the flag only unlocks the channel.**-Read the last four rows together: a hub-held subscription is keyed on vendor-exactly like a native one, so `subscription_hub_experimental` can never make an-Anthropic subscription eligible for Codex. Getting this wrong would breach the-frozen security invariant (`model-hub-contracts/README.md` #3, from spike S2):-subscription credentials are never offered to agents outside their sanctioned-client. Subscriptions are never eligible for OpenCode in any channel — it has no-sanctioned subscription relationship with either vendor.--**What changes in v2:** the rules stay, the *authority* moves. The agents payload+| `subscription`, any vendor, channel `hub` | ✅ | ✅ | ✅ |++`allowed_origins` enforces **configuration-time channel semantics**, not a product-risk gate. For+`native_cli`, it contains only the sanctioned backend because the credential remains+inside that CLI. For `hub`, it may contain any supported backend selected by Gateway+configuration, including a cross-vendor consumer. No flag or consent record changes+either result. Runtime does not re-run this matrix to choose or reject a provider; a+validated stored hop is its authority.++The agents payloadnow carries a per-source eligibility signal (`eligible` + `reason_key`) computedonce on the server. The UI stops deciding: the chokepoint `isSourceEligible`(`ui/src/components/settings/models/menus/identifiers.ts`), which self-documents@@ -396,19 +480,23 @@ as ESCALATED precisely because it hand-mirrors backend logic, becomes a pureprojection of server truth. This pays down a debt the v1 lanes escalated and neverclosed — two independent implementations of one rule, free to drift silently.-`reason_key` is an i18n key, so the drawer can say *why* a source is greyed out-(「ChatGPT 订阅不适用于 Claude Code」) instead of merely hiding it.--**Server-validated invariants** (07-29, review round 6). Eligibility is not the only-rule the server owns rather than the schema. These hold on every agents payload and-each is enforced by the route that writes it, because JSON Schema draft-07 cannot-state them at all — the full list with the reason per item is in `api.md` →-「Mechanical guards the schemas cannot carry」, and the boundary itself is-`model-hub-contracts/README.md` → required-vs-optional:--- **`sources.order`** — every id exists, is eligible for this backend, appears once,- and the whole list is a subset of the eligible set (omitting one is how the user- says 未启用). Rejected as `invalid_source_order`, naming the first offending id.+`reason_key` is an i18n key, so the drawer can explain structural ineligibility.+The final vocabulary contains neither `consent_required` nor `opencode_api_key_only`;+Hub-held subscriptions are eligible for OpenCode, and risk copy is not eligibility. Native+wrong-client use retains `subscription_wrong_client`.++**Server-validated invariants** (07-29, review round 6; replaced for configured chains+by S-1 on 2026-08-09). These hold on every agents payload and each route that writes+configuration:++- **`routes`** — exactly one row per menu model; every row owns one ordered `hops`+ array. Exact `(source_id, model_id)` pairs are unique within a route, while one Source+ may intentionally appear again with another model. Every new/edited hop names an+ existing Source allowed by the matrix above and an exact callable model validated at+ write time. Runtime may annotate a later-invalid hop but cannot remove or replace it.+- **Source deletion** — the transaction removes every hop naming the deleted Source+ from every backend route, preserves survivor order, reports the resulting gaps, and+ leaves a configuration that passes the same canonical validator used on reload.- **`model_supply`** — exactly **one row per menu model**: `model_id` values areunique, and the set covers that backend's whole menu. Duplicates are the dangerousdirection: two rows for one model let `chain_length: 0` sit beside `chain_length: 2`@@ -417,9 +505,9 @@ state them at all — the full list with the reason per item is in `api.md` →drawer unable to say anything about a model the menu offers. Neither half isexpressible — `uniqueItems` compares whole items, so rows differing only in`chain_length` pass, and coverage is a relation to a different document.-- **`AgentChain.chain`** — `source_id` values are unique (a duplicate inflates- `chain_length` into counting one credential as two fallbacks) and appear in the- relative order of `sources.order`.+- **`AgentChain.chain`** — preserves the exact stored hop order and model ids. Its only+ additional fields are live annotations and current execution position; no consumer+ performs another Source/model walk.### 4.5 State taxonomy — classified by "does it heal itself"@@ -430,12 +518,12 @@ Three classes, because the action owed by the user differs in each.| Status | zh (UI) | Heals itself | Meaning || --- | --- | --- | --- || `active` | 使用中 | — | currently serving |-| `standby` | 备用 | — | healthy, not at the head of some order |+| `standby` | 备用 | — | healthy, but not currently serving any configured route || `cooldown` | 暂不可用 (gold) | **yes** | quota/rate/network; `retry_at` known; recovers unattended || `needs_action` | 需处理 (rose) | **no** | OAuth expired, balance exhausted, key revoked/banned — dead until the user acts || `error` | 异常 | **no** | unclassified failure — no `retry_at`, so nothing clears it unattended |-`needs_action` is new in v2 and carries a `detail_key` naming the cause, so the+`needs_action`, introduced in v2 and retained by v3, carries a `detail_key` naming the cause, so therow can offer **one tap to fix it** (re-auth, top up, replace key) instead of adead-end error string.@@ -460,31 +548,23 @@ one source it needs to open. The five non-self-healing source keys and the fivenon-self-healing event causes are a bijection, checked mechanically rather thanpromised (`api.md` → 「Mechanical guards the schemas cannot carry」).-Two of those three taps need a route that v1 never had, so v2 freezes them:+Two of those three taps use routes frozen by the current contract:`PUT /api/models/sources/<id>/credential` replaces an api_key in place and`POST /api/models/sources/<id>/reauth` re-runs OAuth bound to the existing source(`api.md`; the adapter already exposes `start_oauth(source_id)`). Both are-**replacement, not re-creation** — deliberately, because "add a new source and-delete the old one" is not the same operation from the user's side: it loses the-source's `created_at` and its slot in every backend's order, so 跟随推荐 quietly-reshuffles as a side effect of fixing a key, and any `custom` order that named the-old id silently shortens. Recovery must not be a reorder. (Top-up is the third tap+**replacement, not re-creation** — deliberately, because the existing Source identity is+referenced by configured hops and must remain stable during credential repair. `created_at` is+ordinary audit/display metadata and is not a routing guard. Recovery must preserve the Source+and every stored route position. (Top-up is the third tapand needs no *replacement* route of ours — no credential of ours changes; it is alink out to the vendor.)-**What re-checks a topped-up balance is NOT 「the next probe or turn」** (07-29, review-round 8; the earlier wording claimed it was). `balance_exhausted` is a `needs_action`-state, `needs_action` is never `runnable`, and the probe answers `probe_no_candidate`-when the chain has no runnable member — so for a source that is the only supplier of a-model, both paths exclude the very source whose recovery they would have to observe,-and the state can never clear on its own. The same trap is generic to `needs_action`:-a re-keyed source recovers because `PUT …/credential` re-discovers through the new-credential, but a source whose blocker was cleared *at the vendor* has no such route.-Defining the path that may test a blocked source after an explicit user action — its-surface, and what it is allowed to spend — is an implementation requirement, recorded-as **AC-3** in `model-hub-implementation.md`. This spec does not invent that route at-round 8: it is a new tap on a frozen contract, and freezing it as a side effect of a-review round is how the last two rounds generated findings.+**A normal turn never probes a blocked Source in hope that it recovered.** The explicit+Source-details recovery path is `POST /api/models/sources/<id>/refresh`, the same saved+mutation defined in §4.1. It may test `needs_action` or `error` after a+user acts; a successful current observation clears the blocker without recreating or+reordering the Source. AC-3 and AC-11 use this one route and no parallel `/test` recovery+route.**Agent-level derived `supply_status`** (computed, never stored):@@ -496,20 +576,29 @@ splits — on whether the user owes an action:| `ok` | 正常 | — | serving from the intended head of the chain || `degraded` | 降级 | — | serving via a fallback, and/or some sources in the chain are down || `waiting` | 暂时全部在冷却 | **yes** | nothing runnable right now, but every blocker is a cooldown — recovers unattended at the earliest `retry_at` |-| `interrupted` | 无可用来源 | **no** | nothing runnable and at least one blocker needs the user, or the capability chain is structurally empty |+| `interrupted` | 无可用来源 | **no** | nothing runnable and the stored chain is empty or at least one hop has a non-self-healing blocker: `needs_action`, `error`, `source_missing`, `model_unsupported`, or `native_cli_unavailable` |++These four values are the **only backend-level supply-health wording**. The Gateway+backend-group subtitle and the Usage page render this projection directly; neither+surface invents a parallel prose status. `takeover` is a separate display term for+§4.3's derived recoverable-fallback projection, not a fifth `supply_status` value or a+persisted field. A mechanical mirror/locale guard keeps the four status labels and the+takeover label synchronized across both locale sets.`interrupted` is the honest name for the state v1 could not express: the source-list looks populated, yet *this* agent has nothing left to call. The UI shows+list or configured chain can look populated, yet *this* Agent has nothing left to call. The UI shows「当前无可用来源」 with a cause breakdown and exactly two exits — fix the-`needs_action` items, or add a source.+classified items, or edit the route. `native_cli_unavailable` uses its own mirrored+detail/remedy copy for restoring the sanctioned local CLI; it is never presented as an+upstream Source cooldown.`waiting` exists to keep the surfacing rule below consistent. An agent whosesources are *all* mid-cooldown has nothing runnable, but nothing is owed either —it heals itself in minutes. Collapsing that into `interrupted` would tell the user togo fix a problem that resolves before they finish reading the sentence, which is-exactly what the self-healing tier is supposed to prevent. Its copy states the-recovery time, not a fault; `current` is null in both states, so neither ever renders-a stale 使用中.+exactly what the self-healing tier is supposed to prevent. The Turn-outcome copy matrix+renders its recovery time rather than a fault; `current` is null in both states, so+neither ever renders a stale 使用中.**Two grains, one taxonomy.** `supply_status` above is the **agent** rollup, and itanswers for that backend's *currently selected* model. The same three classes are@@ -537,21 +626,24 @@ the revoked key behind the fact that something else in the chain is merely cooli| Class | Where the user meets it || --- | --- |-| self-healing (`cooldown`, `waiting`, recovery, in-turn switch) | 最近切换 feed and the row's status pill — **and nothing in the turn when the turn survived** (07-29, review round 4 ruling): a fallback that worked is not news, and announcing it inside a turn that succeeded is exactly the interruption the push cut exists to prevent. In-turn copy appears only when the turn did **not** proceed transparently: the retry form when §4.3 forbids the transparent retry, the `waiting` form when nothing is runnable but every blocker is timed |-| `needs_action`, `error`, `interrupted` | the in-turn copy of the turn that hit it — the **interrupted** form's cause breakdown plus a pointer to 「模型」 — and 需处理 state on the 「模型」 page until cleared. A blocker left behind by a turn that **succeeded** is page-and-feed only, by the row above |+| self-healing (`cooldown`, `waiting`, recovery, in-turn switch) | 最近切换 feed, connector state, and the row's status pill on the Model Gateway and Usage pull surfaces. In-turn rendering is exclusively the Turn-outcome copy matrix below; this row adds no message branch |+| `needs_action`, `error`, `interrupted` | in-turn rendering comes exclusively from the Turn-outcome copy matrix; 需处理 remains on the Model Gateway and Usage pages until cleared. A blocker left behind by a turn that **succeeded** is page-and-feed only, by the row above |`error` is named in the second row explicitly (07-29, review round 6). It wasimplicitly there all along — it is a blocker, and blockers are what the row is about —but leaving it unnamed while the status table called it 「unknown」 is how a reviewerends up asking, correctly, which tier an unclassified failure belongs to.-**No proactive delivery** (owner ruling 2026-07-29 10:54; supersedes the recipient-machinery this section carried through review rounds 5, 7, 8 and 9). **No resolution-event is pushed anywhere.** Avibe does not open a conversation to report supply state:-an interruption is surfaced **in the turn that hit it**, and otherwise waits on the-「模型」 page for the user to come looking. That is the colleague test read strictly — a-colleague who cannot do the work says so when you ask them to do it; they do not-message every channel they belong to the moment their key expires. It also dissolves+**No proactive or successful-takeover delivery** (owner rulings 2026-07-29 10:54 and+2026-08-08; the latter supersedes the 2026-08-07 afternoon notice and setting while+retaining the earlier push cut). **No resolution event is pushed anywhere, and a+successful switch produces no turn copy.** Avibe does not open or annotate a+conversation merely to report supply state. An interruption is surfaced **in the turn+that hit it**, and otherwise waits on the Model Gateway and Usage pages for a user who+chooses to inspect it. The rationale is deliberate invisibility: tokens should feel+like tap water or air, not a mechanism that competes with the user's current work. This+also aligns with the 2026-07-29 ruling that provenance is a debug affordance rather than+a conversation feature. It dissolvesthe recipient problem the earlier rounds kept narrowing without closing (which scopes,which grain of 「Agent」, what a zero-scope result means): with nothing delivered, thereis nobody to address.@@ -579,7 +671,7 @@ What survives the cut, so the removed text is not read back in:`system` when nothing discovered it — and nothing in the record claims a set ofaffected backends. Source health is a property of the source, so the fan-out wasnever information the record held; it is a **live derivation** the consumers already- have to do anyway, because per-agent orders change after the event is written and a+ have to do anyway, because configured per-model chains change after the event is written and afrozen set would go stale the moment one does. The feed renders those state linesunattributed (「relay.example 连续超时 → 暂停使用 1 小时」, as the V4/V6 frames alreadyshow them). **The TRAFFIC kinds are outside this rule and must not be swept into it**@@ -593,7 +685,7 @@ What survives the cut, so the removed text is not read back in:renders source events as unattributed lines」 was too wide: read over the trafficfamily it contradicted a frozen example this PR does not touch.The status surfaces answer 「what is affected」 by asking the current question- against current orders — **at two grains, which must not be collapsed** (corrected+ against current configured chains — **at two grains, which must not be collapsed** (corrected07-29, review round 9). The SOURCE grain: **a backend has affected supply when asource that is blocking *now* appears in the capability chain of at least one of itsprotected models** — the (backend, model) test `api.md`'s supply guard already@@ -607,7 +699,7 @@ What survives the cut, so the removed text is not read back in:round 12 — the round-10 wording claimed not to restate the predicate and then restatedit, as 「nothing runnable and at least one blocker needs the user」, which silentlydropped the OR-branch's other half: a **structurally empty** chain has no blocker at- all, so a forced deletion or an emptied order would have fallen out of `interrupted`+ all, so a forced deletion or an emptied chain would have fallen out of `interrupted`and lost the 需处理 state and the in-turn explanation the user is owed. The table and`agent-chain.schema.json` both carry the empty-chain case; a restatement that has to bekept in sync with two of them is the defect, not the wording). **Read the class off the@@ -621,13 +713,13 @@ What survives the cut, so the removed text is not read back in:which is exactly the case AC-9's Case A forbids (`model-hub-implementation.md`, AC-9). Both halves arecurrent-state reads, and both are load-bearing(07-29, review round 3): chain membership alone folds a *historical* event against a- *current* chain, and since a recovered source normally stays in the same orders and- chains, and the failure event stays in the bounded feed, that predicate would pin the+ *current* chain, and since a recovered source normally stays in the same configured+ chains while the failure event stays in the bounded feed, that predicate would pin thepill to 「affected」 for as long as the event is retained — a recovery could neverclear it. The event is what the **feed** renders; it is not what the **pill** reads.The pill reads the source's live blocking state — the same **contracted** facts the- resolver consults when it picks a candidate: `state.status` and, for a cooling-down- source, `state.retry_at` (`source.schema.json`), surfaced per chain entry as+ configured-chain executor checks before invoking each stored hop: `state.status` and,+ for a cooling-down source, `state.retry_at` (`source.schema.json`), surfaced per chain entry as`runnable` (`agent-chain.schema.json`). **No `blocked_until` field exists anywhere inthe contracts** (corrected 07-29, review round 9: the earlier`blocked_until` / disabled / credential-invalid wording named a field the frozen@@ -640,12 +732,11 @@ What survives the cut, so the removed text is not read back in:stops contributing to any pill on the next render, with no event written to say so andnone needed. That test is theconsumer's, evaluated at render time; it is not a field.- Note that the chain grain is what makes it right: a `follow` order holds every- eligible source — an API-key source is eligible for every backend — so a GLM-only key- sits in Codex's order while appearing in no chain Codex can run, and treating order- membership as impact would mark a backend degraded over supply it could never have- used. A **backend-scoped** kind (`supply_interrupted`, whose cause is that backend's- own order or selection) still names exactly the one backend it is about, because+ Note that the configured-chain grain is what makes it right: Source inventory alone+ does not mean a backend uses that Source. Only an exact stored hop creates impact, so+ an unrelated Source failure cannot mark a backend degraded. A **backend-scoped** kind+ (`supply_interrupted`, whose cause is that backend's configured route) still names+ exactly the one backend it is about, becausethere the backend *is* the subject of the event rather than a consequence of it.If some later consumer genuinely needs a recorded affected-set, it gets a field then,with the evidence that derivation was insufficient — not speculatively now.@@ -662,102 +753,113 @@ The event carries no recipient, channel, platform, or audience field — it neveand after this ruling nothing would want one. The feed is a record of what happened tosupply; it is not an outbox.-**In-turn error copy is the normative surfacing mechanism, and silence is its first-case** (07-29, orchestrator ruling on review round 4 — this **supersedes** round 2's-action tail and the 「已自动换线」 in-turn line). A turn supply affected either says-nothing at all, or says exactly one of three **classes** — never a fourth story, and never-a tail appended to one of them. The `interrupted` class carries **two copy variants**-(below), so three classes are four message forms; what is forbidden is a fourth *story*,-not a fourth string (clarified 07-29, review round 15 — the count read 「three things」-after the 16:35 split created the second variant, and read literally it would have forced-one required form to be merged away):--- **survived transparently → silent.** A fallback that carried the turn produces **no- in-turn copy whatsoever**. The turn worked; the user asked for work and got it, and- interrupting a successful answer to narrate the plumbing is the same restraint failure- the push cut removed one layer up — it is a push, merely delivered in-band. The switch- is recorded and surfaces where a record belongs: the 最近切换 feed and the row's- 已切换 state. **This includes the case where the switch left a real problem behind** —- a revoked key a second source covered is filed as its usual two records- (「one `switch`, info + one `needs_action`, action_required」), and the `needs_action`- half surfaces as 需处理 on the 「模型」 page, not as a line on a turn that succeeded.- Round 2 reached the opposite conclusion by asking 「where else would the user hear- about it」 and answering 「nowhere」; the page is that somewhere, and it is the surface- the cut deliberately kept for exactly this class. Note the implementation consequence,- which is why the ruling went this way: a successful turn returns through the normal- result path and never reaches the failure emitter, so **every form below is on the- failure path** and the copy has one home rather than two.-- **self-healing** — supply moved and the turn could **not** proceed transparently:- 「下一回合已自动换线,直接重试即可」 when §4.3 forbids the transparent retry. It names- no fault and asks for nothing, because the user's next action is one retry. This is- the whole of the form now: the surviving-turn line above moved to silence.- **Confirmed by the orchestrator, 07-29**: the tail is dropped from *this* case too, not- just from the silent one — the retry moment's action is the retry itself, and- residual-blocker guidance lives in the interrupted copy and the 「模型」 page. Keeping a- tail here would leave one exception whose only argument — 「the user is already being- interrupted, so one more line is free」 — is the argument the whole section rejects.-- **waiting** — nothing runnable *right now*, but every blocker clears on a timer with- no user action: the copy states **what it is waiting on and when it recovers**- (「全部来源冷却中,约 12 分钟后恢复」), and asks for nothing. It is a distinct form- rather than a variant of the other two, because the self-healing copy would be a lie- (the turn did not survive) and the interrupted copy would be worse than one (it would- send the user to 「模型」 to fix something that fixes itself). A turn whose blockers- are mixed — some timed, some needing action — is `interrupted`, not `waiting`: the- AND/OR taxonomy above decides that, and the presence of one user-actionable blocker- is what makes the third form the wrong one.-- **interrupted** — this class has **two entries, and they need different copy**, because- the taxonomy's OR-branch admits a case with nothing to break down.- - *blocked* — nothing runnable and at least one blocker needs the user: a **cause- breakdown** at the grain that actually failed (which model, which sources, and which- blocker each of them is in), then a pointer to 「模型」, where the one-tap fixes live.- This is the only place the user is told to act, so it carries the whole story rather- than a truncated headline that forces a second question.- - *structurally empty* — the chain has no candidate at all, so there is no source and no- blocker to name. **The copy is owned by the lane that emits it** (L3, §3), and the- exact strings land in that lane's design pass, which carries **its own owner approval- step** — they are not written here (07-29 16:35 ruling). What this spec fixes is its- **semantics**, and all three are already contracted: it **names the model** the turn- asked for, it states the cause using the **event layer's own reason**- (`no_enabled_source | no_eligible_source | model_unsupported`, below) **rendered- through `vibe/i18n/` like every other backend-emitted string**, and it **points at- 「模型」** like the blocked form. A generic error, or silence, satisfies- none of the three.--One asymmetry has to be named, because it is easy to implement wrong: an agent can-enter `interrupted` with **no source changing state at all** — its last enabled-source is dropped from its order, or its selected model stops being supplied by-anything left in that order. Every other entry in the feed is keyed on a source, so-that transition gets its own agent-scoped event kind (`supply_interrupted`, with-`reason: no_enabled_source | no_eligible_source | model_unsupported` naming which-one-tap fix applies) instead of borrowing a credential or quota reason that would-misstate the cause. It fires once, on the transition — never once per starved turn.-Its counterpart guard is on delete: refusing to remove a source that is the last-enabled supplier of some **selected model** for some backend (`api.md`) is-what keeps this event rare rather than routine. Note the grain — per (backend,-model), not per backend. A backend with four enabled sources is not safe by-inspection: if only one of them supplies `claude-haiku-4-5`, deleting it starves-that model while the backend still looks well supplied, and the user learns about it-from a failed turn. Backend-level emptiness is just the case where every selected-model hits zero at once. **"Selected" is deliberately wider than 「已勾选/已映射」**-(07-29, review round 5): it is the union of an open menu's checked entries-(`menu.checked` — 07-29, review round 9: round 5 wrote 「checked fixed-menu models」,-which names state a fixed menu does not persist; `api.md` carries the scoping), **the-menu-side `builtin_id` of every mapping row that is `enabled`** (07-29, review round 4:-a disabled row is one the resolver treats as identity, so protecting it refuses a delete-no live selection would break — the same over-protection this paragraph rejects two-sentences on; `api.md` carries the matching narrowing as AC-8, and the two normative-homes have to say the same thing), `agents.<backend>.default_model`, and-each enabled Vibe Agent's own `model`. Menu-side, not the mapping's target (07-29,-review round 8): for `claude-opus-4-6 → glm-5.2` the protected identifier is-`claude-opus-4-6`, because that is what an Agent can be running and what `api.md`'s-single definition of the guard tests — one namespace, the menu one. Testing `glm-5.2`-would compare a resolved id against menu identifiers, match nothing, and let the-delete proceed without `force` while the selected built-in loses its last supplier.-The earlier phrasing tested the menu instead of the runtime, so the model an Agent is-actually running could go unprotected — unchecked in a drawer the user never opened,-and resolving by identity with no mapping row to find. `api.md` → DELETE carries the-full set and the confirm copy names the affected **Agents**, since 「删除后 pm 将没有-可用来源」 is actionable where a bare (backend, model) pair is not.+**Turn-outcome copy matrix (authoritative and exhaustive; owner ruling 2026-08-09).**+In-turn copy is a+projection of the recorded terminal outcome plus only the discriminator named in this+table. Prose, emitters, and UI code may reference the selected row but cannot assert a+switch, remedy, or message branch absent from it.++| Decision | Terminal outcome | Exhaustive discriminator | Route/source fact | In-turn rendering |+| --- | --- | --- | --- | --- |+| `turn.served` | `served` | any, including a transparent fallback | the turn completed; any switch is only a pull-surface record | silent: no Error, warning, info notice, or appended action tail |+| `turn.exhausted` | `exhausted` | final model `supply_state` from the §4.5 taxonomy | fallback walked to the end; no attempt completed | `waiting` renders `models.launch.waiting`; `interrupted` renders `models.launch.interrupted` with the classified blockers |+| `turn.request_nonfallback` | `failed_terminal` | any non-fallback request-level failure | the attempted Source remains runnable and no switch occurred | `models.launch.request_incompatible`: this request is incompatible; switching Sources will not help |+| `turn.engine_down` | `failed_terminal` | local `engine_down` at any request phase, including after an upstream attempt or streamed output | no Source is blamed or mutated; no replay or next-hop walk occurs | `models.errors.engine_down`; after output began it also states that this turn's output may be incomplete |+| `turn.streamed_fallback` | `failed_terminal` | streamed fallback-class Source failure; its cooldown or `needs_action` was persisted | replay is forbidden; render `models.launch.retry` only when live inspection of the same stored chain makes a different hop current for the next turn; otherwise no switch exists | different current hop: “The next turn has switched Sources; retry.” No runnable hop: use the same `waiting`/`interrupted` rendering selected for `exhausted` |+| `turn.no_candidate.unconfigured` | `no_candidate` | configured chain is empty | no Source was attempted because no hop is configured | `models.launch.route_unconfigured`, naming the requested model and pointing to Models |+| `turn.no_candidate.blocked` | `no_candidate` | configured chain is nonempty and model `supply_state` is `waiting` or `interrupted` | no Source was attempted because every exact hop is currently blocked | derive copy from the exact blocker set and reuse `_launch_failure` remedies: reauthorize, replace the key, or top up; `waiting` uses `models.launch.waiting`, while `interrupted` uses `models.launch.interrupted` |+| `turn.canceled` | `canceled` | the turn FSM, never a transport inference, settled Stop/cancel | no Source failure or route switch is fabricated | no Model Hub supply copy; the existing turn-canceled surface owns the message |++The matrix supersedes the earlier unconditional 「下一回合已自动换线」 sentence. Its+outcome/discriminator → copy-key relation is closed in the final mirror registry and+checked mechanically against both `vibe/i18n` locale files. A new outcome, discriminator,+or supply message ships as one new matrix row plus its enum/key/mirror fixtures; none may+land as standalone prose.++One asymmetry has to be named, because it is easy to implement wrong: an Agent can enter+`interrupted` with **no Source changing state at all** — its route is unconfigured, a+configured Source was deleted, its exact model stopped being callable, or its native+CLI process is unavailable. Every other entry in the feed is keyed on a Source, so that+transition gets its own Agent-scoped event kind (`supply_interrupted`) with the exact+`route_unconfigured | source_missing | model_unsupported | native_cli_unavailable`+reason instead of borrowing a credential or quota reason. It fires once on the+transition, never once per starved turn. Its counterpart guard is on every explicit+route mutation: the response reports every selected model whose configured chain would+be emptied. Note the grain — per `(backend, model)`, not per backend. **"Selected" is+deliberately wider than 「已勾选」**: it is the union of an open menu's checked entries,+every menu model with a configured route, `agents.<backend>.default_model`, and each+enabled Vibe Agent's own `model`.+The protected identifier is always the **menu model**, never a hop's upstream+`model_id`, because the menu model is what an Agent can run and what the chain query+addresses. A configured chain that no Agent currently selects still represents deliberate+configuration and remains protected from a silent Source deletion; its+`SupplyGap.agents` list may correctly be empty. `api.md` → DELETE carries the full set+and the confirm copy names affected Agents when any exist.++Exact-hop referential integrity is a separate guard from the supply-gap calculation.+A non-forced Source DELETE refuses whenever any configured chain names that Source, even+when a later hop still supplies the menu model, and returns `source_in_route_chain`+plus ordered `would_remove_hops` entries naming each `(backend, menu_model,+source_id, model_id)` reference. `force=true` is an explicit cascade confirmation:+the same transaction deletes the Source and every exact hop that names it across every+backend route, while the identity and relative order of all surviving hops remain+unchanged. An emptied route remains an explicit empty configuration.+Any resulting protected-model gap is reported through the existing+`would_interrupt` projection alongside `would_remove_hops`. This explicit cascade is+not the silent side effect prohibited by §2; without the confirmation, neither the+Source nor any chain changes.++The same invariant applies to **every Source-inventory mutation**, not only Source+deletion. Reversible or transactional changes — API-key Base URL replacement, API-key+credential replacement, explicit refresh/recovery, and manual-model deletion — first+stage the resulting inventory and run **both** guards: compare it with every exact+configured hop and recompute `would_interrupt` for every protected menu model. If an+exact configured model would cease to be callable, the non-forced mutation is refused+with `source_model_in_route_chain` and ordered `would_remove_hops`; another Source+supplying the same menu model does not make that exact reference disposable. If no+exact hop is lost but a protected route loses its last supplier, it is refused with+`source_last_supplier`. When both apply, the exact-hop error leads and the response+still carries both complete arrays. A confirmed `force=true` applies the inventory+change and removes only those invalidated hops in one transaction, preserving the+identity and relative order of all survivors and keeping an empty route configured.+It also reports every resulting supply gap; force is confirmation, not a claim that+the mutation is interruption-free.++**Source-mutation envelope matrix (authoritative and exhaustive; owner rulings+2026-08-09).** These are all Source/inventory mutations, including writes that cannot+remove supply. Prose may describe their guard rationale but cannot define a request or+success envelope outside this table. Omitted `force` is false; every reported array is+present even when empty.++| Decision | Mutation | Request | Guarded `409` | Success |+| --- | --- | --- | --- | --- |+| `mutation.source_metadata` | change Source metadata/Base URL | `PATCH /api/models/sources/<id>` with `{display_name?, base_url?, force?: boolean}`; `force` matters only when `base_url` changes | `{error, would_remove_hops: RouteHopRef[], would_interrupt: SupplyGap[]}` | `{source: Source, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` |+| `mutation.credential_replace` | replace API key | `PUT /api/models/sources/<id>/credential` with `{key, force?: boolean}` | same guarded `409` | same Source success envelope |+| `mutation.source_refresh` | refresh/recover saved Source | `POST /api/models/sources/<id>/refresh` with `{force?: boolean}` | same guarded `409` | same Source success envelope |+| `mutation.model_create` | create a user-authored model entry | `POST /api/models/sources/<source_id>/models` with `{model_id, display_name?, reasoning_efforts}` | not guarded: it creates one new exact `id` with `origin: "manual"` and changes no existing `id`, `origin`, or Route | `{source: Source}` |+| `mutation.model_efforts` | replace one model entry's capability list | `PATCH /api/models/sources/<source_id>/models/<model_id>` with `{reasoning_efforts}` | not guarded: it changes no `id`, `origin`, or Route | `{source: Source}` |+| `mutation.model_delete` | delete a user-authored model entry | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean}` | deleting `origin: "discovered"` returns `source_model_managed_upstream`; otherwise the same guarded `409` | same Source success envelope |+| `mutation.source_delete` | delete Source | `DELETE /api/models/sources/<id>?force=<bool>` | same guarded `409` | `{removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` after atomically pruning the Source from every backend Source order and every Route chain while preserving each survivor order; the deleted Source is not returned and legacy `{ok}` is invalid |+| `mutation.route_replace` | replace one model's complete Route chain | `PUT /api/models/agents/<backend>/chain?model=<id>` with `{hops: RouteHop[], force?: boolean}` | same guarded `409` | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; the reporting fields are the same guarded-mutation family as Source success |++The request carrier shown in each row is the only one. The final `api.md`, server/client+envelopes, confirmation UI, and route tests mirror this matrix row-for-row.+Automatic background discovery never performs this cascade: when neither literal+inventory nor sanctioned-alias evidence remains, it records the model as+`model_unsupported`, keeps the configured hop visible and non-runnable, and waits for+an explicit user refresh/edit to repair or confirm removal.++Native CLI re-authentication and Hub OAuth re-authentication are the irreversible+exception. Each presents AC-2's server-enforced acknowledgement **before** login starts;+the user can abort there, but the product promises no rollback or post-login refusal+once the OAuth exchange has begun. After authentication, the engine commits the+resulting credential and any inventory it can establish. Exact hops whose source/model+pair is no longer present remain visible but non-runnable with exactly+`reason: "model_unsupported"` and `retry_at: null`, and the response reports the+resulting gaps and `needs_action` work for a later explicit edit or force cascade. It never silently+replaces the configured model or claims that the old supply is intact. Thus no+credential lifecycle event or inventory drift silently calls a model the Source no+longer advertises or rewrites the user's chain.**Turn provenance.** Each turn whose attribution is **exact** records the model@sourcethat served it — the write rule below is what 「exact」 means, and it is the promise's@@ -767,13 +869,12 @@ ruling 2026-07-29 14:03, superseding the earlier 「per-turn detail in the convesurface」 phrasing): users should be unaware of supply machinery, so provenanceinspection is a **debug affordance, not a user feature**, and it appears neither inthe Web transcript nor on any IM platform. If it is ever surfaced, the place is the-请求日志 / 诊断 entry in the 「模型」 page's 高级 area — a v2.1 candidate, not v2. Mid-stream failure, where no transparent-retry is permitted (§4.3), must say exactly 「下一回合已自动换线,直接重试即可」 and-nothing further: the user's next action is one retry, so the copy states that instead-of describing the fault. A source the switch left needing repair surfaces as 需处理 on-the 「模型」 page, per §4.5 — not as a second line here.+请求日志 / 诊断 entry in the 「模型」 page's 高级 area — a post-v3 candidate, not v3.+Mid-stream failure rendering comes only from §4.5's Turn-outcome copy matrix; this+provenance section does not infer or announce a switch. A Source left needing repair+still surfaces as 需处理 on the Models page, not as an appended turn message.-This promise needs an interface, not just a paragraph, so v2 freezes one:+This promise needs an interface, not just a paragraph, so the frozen contract carries one:`turn-provenance.schema.json` + `GET /api/models/turns/<turn_id>/provenance`.It defines *what* is recorded and *how it is read*; where it is stored is theimplementing lane's call, with one constraint — provenance is written when the turn@@ -797,50 +898,40 @@ lookup — is designed and owned by L3** (07-29 16:20 ruling): see L3's design nbounded by the invariants in `model-hub-implementation.md` §3. This spec fixes what mustbe true of the record, not how the attempt is tied to the turn.-**The same rule bounds which turns v2 records at all: no FSM truth → no record**+**The same rule bounds which turns v3 records at all: no FSM truth → no record**(07-29 15:42 ruling). Exactness is resolved through the turn FSM, so a turn the FSM-does not track cannot be recorded exactly — and v2 does not record it approximately.-**IM and CLI turns write no provenance in v2**, and this spec states that limitation+does not track cannot be recorded exactly — and v3 does not record it approximately.+**IM and CLI turns write no provenance in v3**, and this spec states that limitationrather than implying a coverage it does not have. The loss is debug-marginal becausethe *other* half of the trace is channel-independent: the source-grainedresolution-event feed covers every channel, so an IM turn's failures and switches still-appear in the feed even though its per-turn attempt list does not exist. **v2.1+appear in the feed even though its per-turn attempt list does not exist. **Post-v3candidate**: extend FSM registration to the IM and CLI dispatch paths — provenance thenfollows for free, because the write rule above is path-agnostic and needs no change whencoverage widens.-**That interface covers Hub-mode turns** (07-29, review round 8): a `served` record+**That interface covers Gateway-mode turns** (07-29, review round 8): a `served` recordrequires a `source_id` matching `^src_`, and a Direct-mode turn runs from nativeconfiguration with no `Source` row to name — so 「每个回合都有记录」 is satisfiable-inside Hub and unsatisfiable outside it without fabricating a source. Existing users-stay in Direct until they migrate (§6), which makes this the common case rather than-an edge one, so it is named here instead of left to the implementer to discover.+inside Gateway mode and unsatisfiable outside it without fabricating a source. Existing+installations with no Model Hub state start in Direct until the user explicitly switches+that backend (§6), which makes this a first-class onboarding case rather than an edge+case left to the implementer to discover.Whether a Direct turn gets a no-source provenance representation or the route answers-「此回合无中枢记录」 is an implementation requirement recorded as **AC-1** — a question+「此回合无网关记录」 is an implementation requirement recorded as **AC-1** — a questionabout the record and the route only, since 14:03 left no affordance to render it.**Neither branch licenses silence** (07-29, review round 8): the every-turn promise above-is scoped to Hub-mode turns by the paragraph that opens this one, and a Direct turn must+is scoped to Gateway-mode turns by the paragraph that opens this one, and a Direct turn muststill answer the contracted route with a documented payload or a documented error — whatit may not do is come back indistinguishable from a turn whose provenance was never-written. **Which of the two branches v2 ships is L1's v3 contract call** (§8, AC-1), not a-choice each implementer resolves for itself. Two further terminal states the four outcomes below-cannot express — a user cancel, and an attempt interrupted by one — are **AC-4**.--Four outcomes are recorded, not one: `served`; `exhausted` (fallback walked to the-end, every attempt failed for a fallback cause); `failed_terminal` — an attempt hit-one of §4.3's **non-fallback** errors and the turn stopped there, param/protocol/-tool-compat, or anything after the first streamed token, where no transparent retry-is permitted; and `no_candidate` — the turn that never touched a source, because this-(agent, model) chain had nothing runnable. `failed_terminal` is the fourth because-§4.3's error taxonomy deliberately routes those errors to the caller instead of the-next candidate, and a record with only three outcomes had no honest slot for the-result: not served, not exhausted (the chain was never exhausted), not-`no_candidate` (something was tried). Filing it as `exhausted` would additionally-force a fallback reason like `server_error` onto it and blame the user's account for-a malformed request. `no_candidate` is precisely the turn a user needs explained, so-the record has to hold an **empty** attempt list rather than force the emitter to-fabricate a phantom attempt or write nothing at all; it carries the model-scoped-`waiting`/`interrupted` state instead, which is the thing that actually explains it.+written. The current contract chooses and tests the representation; v3 does not reopen+it. Cancellation remains FSM truth rather than transport inference.++The five recorded outcomes and their exhaustive discriminators are defined only by+§4.5's Turn-outcome copy matrix. Provenance mirrors that closed outcome set rather than+reclassifying it. `no_candidate` carries an empty attempt list; `canceled` may retain an+unambiguously attributed interrupted-at-cancel attempt but never fabricates a Source+failure. Attribution-ambiguous attempts remain absent under AC-4's control fixture.The terminating attempt is recorded in exactly one place — failedattempts in an ordered list, the served attempt in its own field, the terminal errorin a third, at most one of the latter two ever populated, the full sequence@@ -848,299 +939,356 @@ reconstructible by appending. That is a shape decision rather than a validationit makes 「两个成功者」, 「成功者不在最后」 and 「摘要指向列表里没有的来源」 impossible towrite down, instead of invariants prose asks every implementer to respect.-### 4.6 The chain per (agent, model) — capability vs runnable--The chain that actually executes is **per (agent, model)**: the agent's order,-filtered by "can this source supply this model" (§4.3 step 2, capability stage).-This closes v1's honesty gap — v1 displayed one order per agent while N different-chains ran underneath it, one per model.--What the UI shows is the **capability** chain: every source that *could* serve this-model, in the agent's order, with cooling and `needs_action` members present but-dimmed and labelled. Runnability is a per-item flag (`runnable`, plus `retry_at`),-not a filter — so one payload answers both "what do I own for this model" and "what-would run right now", and the two can never disagree on screen.--Surfaced as:--- Tapping the model box on an agent row reveals that model's chain, reusing the- order-chip visual from the agent row. Supply reached through a mapping is marked- 「经映射」 — the v2 surface for cross-vendor supply (§4.3), so a GPT model serving- Claude Code is legible in the chain instead of hiding behind a built-in id.-- Each item in the 模型菜单 drawer can reveal its own chain the same way.-- A menu model whose **capability** chain is empty is flagged 「无来源可供」 in the- drawer — a checkbox that would silently fail is a bug, not a choice. Note the- distinction this rests on: 「无来源可供」 is structural and stable, so it must not- appear merely because every source is mid-cooldown. That case is- `supply_status: waiting`, and the row stays checkable.--Contract: a chain query (`GET /api/models/agents/<backend>/chain?model=<id>` →-ordered `[{source_id, via_mapping, resolved_model_id, health, runnable,-retry_at}]`), plus cheap per-menu-item capability-chain counts on the agents-payload so the drawer can flag empties without N round-trips. `health` carries the-source-global health only; per-agent role is positional (the first `runnable` item-serves the next turn), never a stored per-agent 使用中/备用 flag — a source can lead-one agent's order and trail another's.+### 4.6 Configured-chain storage and mutation++This section defines §4.3's persisted input and mutation boundary. Every known+`(backend, menu model)` has one row:++```json+{"hops": [{"source_id": "src_...", "model_id": "upstream-model-id"}]}+```++Each backend also persists one `sources.order: string[]`. It is a visible Gateway+configuration and Add-time placement input, contains only existing configuration-+eligible Source ids, and has no `follow | custom` or other policy discriminator. A+Source deletion removes its id from every backend order in the same transaction and+preserves the relative order of survivors. Serialization/reload rejects a dangling id.++`hops` may be empty and is always present. A newly introduced menu model starts with an+empty route; catalog expansion and inventory refresh do not retroactively match it.+Only Add Source's one-time match or an explicit user edit changes the array. Hop order,+Source identity, and model mapping are user-visible configuration.++A write validates every newly introduced or changed exact pair before commit. An exact+pair already present in the persisted array may be retained or reordered even when a+later inventory or process change currently annotates it non-runnable; retaining or+moving that unchanged pair does not reclassify it as a new mapping. Its live reason+remains visible until the Source recovers, the user removes or changes the pair, or a+guarded cascade removes it. Source deletion follows §4.5's transaction: a non-forced+delete refuses while any route names the Source; a confirmed delete removes all such+hops across all backends and preserves survivor order.++There is no separate `mappings` field, policy discriminator, matching resolver, or+mapping diagnostic. `model_id == menu_model` is an identity mapping;+another explicit `model_id` is a user-configured substitution and must be invoked as+written. **The system never invents a substitution; user-configured mappings are legal+and authoritative.** This final-shape decision is **owner-vetoable (2026-08-07,+amended by S-1 on 2026-08-09)**.++The chain resource is `GET /api/models/agents/<backend>/chain?model=<id>`, with a+matching `PUT` carrying `{hops: [{source_id, model_id}, ...]}`. The read projection+returns the same stored array, in the same order, with only §4.3 live annotations and+current execution position added.### 4.7 Downstream — Agents| Agent | Menu | Notes || --- | --- | --- |-| Claude Code | fixed (built-in model IDs) | wants another vendor's model ⇒ per-agent mapping in its 模型菜单 — supported, §4.3; first-class user-added entries are the §10.4 v2.1 candidate |+| Claude Code | fixed (built-in model IDs) | each built-in menu model owns one exact configured route chain; adding new menu entries belongs to the deferred Configure Agents module || Codex | fixed | same |-| OpenCode + future in-house agents | open | follows upstream model lists; supports user-defined custom model entries |+| OpenCode + future in-house agents | open | uses exact configured route chains; supports user-defined model entries |-### 4.8 OpenCode identifier scheme (locked 07-23, unchanged in v2)+### 4.8 OpenCode identifier scheme (locked 07-23, retained in v3)OpenCode models are `provider/model-id`. Rules:- The provider segment uses the **standard vendor id** (`anthropic/`,`openai/`, `zhipuai/`, …) — identical to native OpenCode usage. No`avibe-` namespace (owner: keep it simple). Unrecognizable vendors fall- back to a single `custom/` provider.-- Hub mode merely redirects those providers' transport to the local hub in+ back to a single `custom/` provider. Add Source may use this normalized id when it+ proposes a one-time match; runtime reads only the stored exact hop.+- Gateway mode merely redirects those providers' transport to the local Gateway inthe generated runtime config overlay. Therefore **identifiers are stable- across Hub/Direct switches, across source add/remove/failover, and — new in- v2 — across any per-agent reordering**; never encode a concrete source into+ across Gateway/Direct switches, across source add/remove/failover, and — new in+ v3 — across any configured-chain edit**; never encode a concrete Source intothe provider segment.- Users never hand-assemble the string. Menu checkboxes pick models; thecustom-model form generates and previews the identifier (source + model IDin → `zhipuai/glm-5.2-air` out). A custom model entry is, in data terms, asupplement to that source's supply list.-## 5. Surfaces (design.pen V6 frames)+## 5. Surfaces — two modules, one understandable handoff-The V6 frames are the v2 UI source of truth. Structure: **L1 overview stays-minimal, the L2 drawer holds the editing surface.** The V5A/V5B/V5C explorations-all failed the same way — laying N backends' orders on one page at once renders-every source N times and starves each column.+Concrete first-run example: the user adds Claude Pro with the recommended “Use Claude+Code login” choice, then adds an Anthropic API key. The Gateway module shows one+continuous route for Claude Code: `Claude Pro (native) → Anthropic API Key (Gateway)`.+If Claude Pro cools down, the first hop dims, the second becomes current, and the+status says it will return to native automatically. The user does not have to infer+that “native” means Direct mode: this route is still **Gateway mode**, because Avibe+owns the handoff. Direct is the separate backend-wide mode and never labels one hop.-| Frame | Content contract |-| --- | --- |-| **V6 01** 总览 | 来源 card is a pure asset inventory: **no drag handle, no position number, no 使用中 column** — icon, name, mono sub-line (account label / masked key; cooldown ETA), usage column (subscription progress bar / monthly ¥), billing chip 包月/按量¥, health chip. **Agent** card, one row per backend: a name row (+ 菜单固定/菜单开放 badge, mode chip 中枢/直连) and a supply row = `[模型盒 mono]` + the order chain as chips `1→2→3` + a policy/status badge. The current source chip is mint-highlighted; a cooling source's chip carries a gold dot. Row action 「来源顺序」 opens the drawer. Below: 最近切换 (3 rows, human phrasing, view-all) and a single 高级 row (跨厂商自动顶替 default-off · 请求日志 · 诊断). |-| **V6 02** Agent 抽屉 · 自定义态 | Three sections: **启用** (drag handle + position number + 当前/暂不可用 pill + 移出 ×), **未启用** (+ 启用 button; annotated where a mapping makes the source usable, e.g. 智谱「经模型菜单改写后可供 Claude Code」), **不适用** (greyed, with the `reason_key` cause, e.g. a ChatGPT subscription under Claude Code). Header right: 「恢复推荐顺序」. Footer left: 「模型菜单与映射」 entry. |-| **V6 03** Agent 抽屉 · 跟随推荐态 | Section-header badge 「跟随推荐中 · 新来源自动加入」; no 恢复推荐顺序 link, since it is already following. Demonstrates one source set ordered differently per agent (relay at Claude #3, Codex #2) — the whole point of v2. |-| **V6 04** 故障实况总览 | Gold status capsule 「Claude Pro 额度用完 · 已自动切换,恢复后切回」; the source row shows a 100% gold bar + 暂不可用; the agent's chain shows chip 1 dimmed with a gold dot and chip 2 mint = current. |-| **V6 M01** 移动总览 (390) | Agent row stacks: L1 (tile + name + mode chip) / `[模型盒 + 策略徽标]` / chain row (10px chips) / full-width 「来源顺序」 button. OpenCode shown as 直连 + note + 接入中枢. |-| **V6 M02** 移动来源顺序 (two states) | Bottom sheet, height fits content. Mobile moves 「恢复推荐顺序」 to the footer-left button, replacing the desktop header link; the follow state drops that button and shows the 跟随推荐中 section badge instead. |--Carried forward unchanged from v1, still described by the V4 frames: 后端 ·-供给方式 card (V4 02), 迁移对话框 (V4 03), 添加来源 menu + API Key form (V4 06r/07),-连接订阅 OAuth shell with flow forms A/B/C (V4 09), 模型菜单 · Claude Code mapping-table (V4 04), 模型菜单 · OpenCode grouped menu (V4 05r), 添加自定义模型 (V4 08).--**Obsolete under v2:** the old mobile M02 row-action panel with 上移/下移, and any-sort-mode control on the 来源 list. The source library has no order, so it gets no-reorder affordance; ordering affordances exist only inside an agent's drawer.--Pending mocks (not blocking): the OpenCode drawer frame (same pattern as V6 02),-first-run empty state, Dark variants, plus a copy pass under the rule **"if UI-style can express it, don't write copy"**.--## 6. Modes & migration+The Models page has exactly two top-level product modules:-- **Hub (default)**: Avibe injects runtime-only configuration into processes+| Module | Owns | Does not own |+| --- | --- | --- |+| **Sources** | Add/edit subscription and API-key Sources; credential location; discovered/manual model inventory; usage and source-global health | Route-chain order or model mapping |+| **Gateway** | Backend mode; exact per-menu-model configured chains; Source + model pairing; runnability, current hop, retry/failover/recovery state; probe and diagnostics entry | Credential entry, Agent-definition settings |++The visual connection between a Source and Gateway answers only current facts: configured+in N routes, serving now, cooling, or needs action. It has no id, CRUD route,+drag handle, or persisted policy. Configuration lives at one of the two real owners:+the Source or the Gateway chain.++A Source card's “Supplying …” line consumes the existing+`adopted_by: [{backend, menu_model}]` projection: group its configured rows+by backend, de-duplicate backend names, and combine them with the current §4.3+runnability projection. No parallel “supplying backends” field is stored. If this+projection proves insufficient in implementation, the lane reports the exact missing+fact for a targeted expansion of `adopted_by`; it does not add a sibling field.++Required interaction rules:++- Sources remains an unordered asset inventory; there is no reorder affordance in that+ module.+- Gateway is the primary editing surface. Each model row shows the exact stored order+ and mapping that runtime will execute; blocked hops remain in place and dim.+- Add Source writes each one-time match at the deterministic position chosen by §4.2's+ placement policy. That position is visible immediately and remains user-editable.+ The UI never uses position to mean “new”: it has no bottom-only new section or other+ ordering-dependent newness. If temporary differentiation is needed, it uses a+ dismissible/transient marker derived from the add result, not a route field.+- Each Gateway backend group renders §4.5's exact `supply_status` value in its subtitle.+ This is the sole backend-health line; explanatory prose cannot compete with it.+- Adding Claude selects `native_cli` by default and presents Gateway custody as the+ optional path. Adding ChatGPT recommends and selects `hub` by default; native Codex+ login remains an available secondary choice without default guidance. Only the+ Claude + Gateway branch shows §4.1's one-sentence warning; it is informational, not+ a consent flow. When a backend already has its singleton native Source, its native+ choice is disabled rather than creating an alias for the same CLI login.+- Add Source exposes §4.1's combined connectivity/protocol observation and compatible+ model discovery without a normal protocol control. Source details exposes only the+ separately named mutating “Refresh models” / 「重新拉取」 action against the stored+ protocol; it has no “Test connectivity” button or second discovery mutation. Results+ stay in the current flow and use compact status plus an+ info affordance for explanation; the page does not grow permanent instructional+ paragraphs. Every inventory model exposes an editable per-model `reasoning_efforts`+ list beside the exact id. The list has no default item or selected state; the control+ form follows the owner-approved `design.pen` baseline and is not prescribed here. A+ protocol selector appears only inside an observation-failure state and its hint still+ requires a successful response before Save. Source freshness may say only “Model list+ updated at …” / 「型号列表更新于…」 from `last_discovered_at`; latency and “last+ checked” copy are absent.+- Compatibility detail for converted or cross-vendor supply stays behind a compact+ info affordance: functionality is supported while reasoning content may degrade.+ There is no per-hop warning or alert treatment.+- Recently switched, connector state, source/route status, and usage remain pull+ surfaces. A successful fallback adds no turn copy. If every source is unavailable,+ the existing failure path still reports the error honestly.++The existing V6 frames remain a visual baseline for row density, health states, and+mobile treatment, but their Agent-card grouping and mapping drawer are not v3 product+authority. The owner-approved v3 interaction draft is the implementation baseline for+the two modules, native → Gateway takeover → native recovery, configured model chains,+and the Claude hub-add warning. The design lane adds production-complete+desktop/mobile states without reopening the approved information+architecture.++**Deferred third module: Configure Agents.** The intent is to let users add models,+reasoning effort, and related model preferences to Agent definitions from this product+area. v3 does not define its information architecture, data contract, controls, or+delivery lane. It must not appear as a placeholder third module in the v3 UI.++## 6. Modes & onboarding++- **Gateway (wire value `hub`, default)**: every backend on a fresh installation starts+ in Gateway mode. An existing installation with no Model Hub state starts in Direct;+ each backend moves to Gateway only after the user explicitly switches it in the+ Models page. This onboarding rule prevents a silent routing change for existing+ users without introducing an internal contract-conversion path. Avibe injects+ runtime-only configuration into processesit launches (env vars for Claude Code; `-c` overrides for Codex app-server;`OPENCODE_CONFIG` overlay for OpenCode, gateway-config hash tracked forlong-lived `opencode serve`). Native user configs are never written.-- **Direct (legacy, kept, not recommended)**: current behavior preserved —+- **Availability is default-on.** Absence of `VIBE_MODEL_HUB_ENABLED` cannot disable+ the controller, `/api/models/` routes, or Models UI. I1 deletes the old default-off+ gate; an explicitly configured development/emergency override may disable the surface,+ but no fresh user depends on an environment variable to receive the product default.+- **Direct (supported diagnostic/self-managed path)**: current behavior —per-backend native config editing (auth tabs, API key + base URL, writes to- `settings.json` etc.), useful for diagnostics and self-managed setups.-- Backends can differ in mode; the Models page Agent rows surface per-backend- mode with one-click 接入中枢.-- **Native-config import** (frame V4 03) is unchanged by the v2 ruling: copy-only- and reversible, a per-item checklist grouped by backend. API keys + base URLs →- direct import; subscription OAuth → `keep_native` by default (stays in the CLI's- sanctioned store and becomes a `native_cli` source; hub-held import only via the- consent-gated experimental flag); Codex `auth.json` → `keep_native`. Footer- promise: originals never modified or deleted; Direct always available. Triggers:- first open after upgrade, setup wizard, backend-page banner.-- **Add-source closing loop (v2).** Creating a source answers "so what now?" in- the same response: `adopted_by: [{backend, policy}]` tells the UI which agents- picked it up automatically (those on 跟随推荐), so the success state can say so- and offer one-tap enable for the agents on 自定义 that did not.+ `settings.json` etc.), useful for diagnostics and self-managed setups. On an existing+ installation's first Models-page visit, each Direct backend remains visible as a+ backend group labelled **Direct**, shows its current self-managed configuration+ summary, renders no Gateway chain, and offers one explicit **Switch to Gateway**+ action in that group. Gateway mode offers the inverse **Switch to Direct** action.+ The switch is per backend and reversible: it changes mode without deleting saved+ Sources or route configuration, and never rewrites the user's native config.+- Backends can differ in mode; the Gateway module surfaces the mode per backend.+ A `native_cli` hop inside Gateway mode is labelled **Native**, not Direct: Avibe still+ owns the pre-stream same-turn fallback and recovery policy. Product copy reserves+ “Direct” for `mode: direct` and does not explain either path as “not through Gateway.”+- **Native-config import** remains copy-only and reversible, a per-item checklist+ grouped by backend. Its action comes only from the authoritative matrix below; prose,+ scan code, and contract examples cannot add another value or infer a different default.++**Native-config import action matrix (authoritative and exhaustive; owner ruling+2026-08-09).** Originals are never modified or deleted, and Direct remains available.++| Decision | Action | Eligible detected item | Default / apply behavior |+| --- | --- | --- | --- |+| `import.keep_native` | `keep_native` | Claude or Codex subscription OAuth held by the sanctioned local CLI | selected by default; retain the credential in the CLI store, create the backend's singleton `native_cli` Source, and run the same one-time route match plus §4.2 placement as Add Source; reject a duplicate native Source before OAuth or partial commit |+| `import.copy_key` | `import` | API key plus optional Base URL, including an OpenCode provider key | selected by default; copy into a validated Hub Source, run the same one-time route match plus §4.2 placement as Add Source, and leave the original file byte-identical |+| `import.reauth` | `reauth` | detected material that cannot be safely copied or retained as a usable native login | not auto-applied as import; direct the user into the explicit authentication flow |+| `import.controlled` | `controlled_import` | future engine-owned OAuth-import capability that can preserve refresh semantics | reserved and not selectable/applicable in v3; explicit OAuth add is the only hub-held subscription path |++The final mirror registry compares this exact action enum with+`models.migration.action.<value>` in both UI locale files, following AC-19's closed-enum+guard; deferred still has explanatory copy even though it is not selectable.++The `keep_native` default prevents silent credential movement and does not replace+§4.1's ChatGPT add-flow recommendation. A hub-held subscription is established only+through explicit OAuth add, not native-file import. The import entry points are first+open after upgrade, the setup wizard, and the backend-page banner.+- **Add-source closing loop (v3).** Creating a Source returns+ `added_to: [{backend, menu_model, source_id, model_id, position}]` for every exact hop+ written by the one-time match. `adopted_by: [{backend, menu_model}]` is the stable+ Source-card projection of those persisted references; transient health and process+ availability do not change it. A Source with no automatic match reports an empty+ `added_to` and remains available for an explicit route edit, without a separate “not+ enabled” state.## 7. Security boundaries- Three credential rings, never mixed: management key (Avibe→engine adminAPI), local gateway token (the only thing backends receive), upstream- credentials (API keys and — only under the consent-gated experimental- flag — subscription OAuth tokens; engine-held, local runtime dir with- restricted permissions, not `~/.cli-proxy-api`). By default the engine- never holds subscription OAuth tokens: `native_cli` subscriptions keep- their credential in the CLI's own sanctioned store (§4.1).+ credentials (API keys and explicitly hub-held subscription OAuth tokens;+ engine-held in a restricted local runtime directory, not `~/.cli-proxy-api`).+ Claude defaults to the official CLI store through `native_cli`; ChatGPT defaults+ to the engine-held Gateway path. A native credential is never copied into engine+ custody implicitly: even for ChatGPT, moving from an existing native login to the+ recommended Hub path requires an explicit OAuth add flow.- Credentials never enter Avibe Cloud, IM messages or logs. Static keys mayintegrate with Avibe Vault; no duplicate key entry across surfaces.- Gateway failure is fail-closed; Direct mode is the explicit escape hatch.-- The dry-run probe (§10.1) inherits the redaction invariant of resolution+- The contracted dry-run probe inherits the redaction invariant of resolutionevents: it reports classified outcomes, never raw upstream error bodies.## 8. Data plane-The hub's data plane is a **replaceable, Avibe-managed, versioned runtime+The Gateway data plane is a **replaceable, Avibe-managed, versioned runtimedependency** (current candidate: CLIProxyAPI ~14 MiB download / ~41 MiBbinary): pinned version + SHA256, 127.0.0.1-only listener, random managementkey and gateway token, lifecycle owned by Avibe. Its YAML/auth files/manageUI are **not** product surface.-**v2 requires no engine change.** Failover is ours, not the engine's: the engine+**v3 routing requires no new engine policy.** Failover is ours, not the engine's: the engineruns as a single global instance with its own cooling and request-retry disabled(`vibe/model_hub_runtime/config.py`), model prefixes pin the source, and Python-owns candidate walking and error classification. That boundary was chosen because+owns configured-hop walking and error classification. That boundary was chosen becausethe engine's blind switching is broader than our signed error taxonomy-(`model-hub-engine-survey.md`, P0). Moving ordering from global to per-agent sits-entirely above that line: it changes which candidate list Python walks, and-nothing about how the engine is driven.--## 9. Explicit non-goals (v2)--- **No global priority list.** Ordering only ever exists per agent backend.-- **No per-model ordering.** A model filters an agent's single order (§4.3- step 2); it never carries an order of its own.+(`model-hub-engine-survey.md`, P0). Per-model configured chains sit above that line:+Python walks exact `(source_id, model_id)` hops; the engine executes the+one pinned hop it receives.++## 9. Explicit non-goals (v3)++- **No product-global or backend-wide priority list.** Execution ordering exists only+ inside one `(backend, menu model)` Route chain.+- **Per-model ordering is explicitly in scope.** Owner ruling 2026-08-07+ supersedes v2's “No per-model ordering” non-goal. The scope is exactly §4.3 and+ §4.6's stored configured-chain input;+ there is no session-level or request-level editor.+- **No native CLI account selector or multiple native slots.** A backend has one+ `native_cli` Source because its official CLI has one current local login. Additional+ accounts are Gateway-held Sources. Selectable native profiles are deferred until an+ official CLI exposes a stable account-selection contract.- **No health-scoring or smart auto-reordering.** No latency ranking, no learnedpreference, no cost optimizer. This is the §2.4 predictability promise — aproduct decision, not a missing feature.- **No session-level source pinning.** "Run just this turn on that source" is adiagnostic need, served by Direct mode plus the dry-run probe — not by aper-session override that would make spending unpredictable.-- **No *automatic* cross-vendor substitution by default.** Sharpened 2026-07-29,- because the old one-liner was read as banning cross-vendor supply altogether.- What is off by default is the product choosing another vendor *for* the user when- their own runs dry ("Claude quota gone → silently serve GPT") — that remains an- experimental, default-off advanced flag with visible per-event marking. Explicit- cross-vendor supply is a **sanctioned path**: per-agent mapping over an `api_key`- source (v2, §4.3), and user-added cross-vendor menu entries (v2.1 candidate,- §10.4). The line is drawn at *who chose*, not at *which vendor* — and it never- moves for subscriptions, which stay bound to their own vendor's backend (§4.4).+- **No automatic model substitution.** The system never changes a configured hop's+ `model_id`. A user-configured mapping to another model or vendor is legal and is+ executed exactly; that hop may use an API key or a hub-held subscription and requires+ no additional warning.+- **No protocol guessing or post-save backfill.** A stored protocol comes from a real+ pre-save upstream response, never a vendor/Base-URL string heuristic. If observation+ fails, the product may ask once for a manual probe-order hint, but the hinted adapter+ must still return a successful response before anything is saved. No later operation+ changes the stored value.- No billing-grade accounting, multi-tenant pools, or operator consoles.- No third source category ("relay" merged into API Key).--## 10. Open items--1. **Dry-run probe** (`POST /api/models/agents/<backend>/probe`): one minimal- request through the agent's current chain → `{probe: {source_id, model_id,- latency_ms, reachable, error, via_mapping}}`. The outcome field is `reachable`- and the object is nested, so it never collides with the response envelope's- `ok` — **whether the call worked and whether the upstream completed the request- usably are different questions** (corrected 07-29, review round 9: this line still- read 「the upstream answered」, the definition `api.md` and the frozen- `probe-result.schema.json` reject — a completed 402 or 429 *answered*, and must- report `reachable: false` with the error key that says why, so the old wording- would have produced `reachable: true` alongside an error and failed the schema).- UI: 「试跑一次」 in the agent drawer footer, **offered for Hub-mode backends only**- (07-29, review round 9): a Direct backend has no source order to run the probe- through and no source id to name in the result, and what it should answer instead is- AC-7. Contract frozen in v2; **implementation lands with L3** (corrected 07-29,- review round 11 — this line read 「the L2 rebuild」, a label that predates the lane- split and now collides with it: `model-hub-implementation.md` §3 assigns the probe- route to **L3**, while L2 owns repair paths and guards, so an executor reading the- spec alone would have built it in the wrong lane).-2. **Quota projection**: nullable `projected_exhaust_at` on subscription usage- (linear projection over recent usage), driving a sub-line 「按近 7 天用量,预计- 周三用完」. Phased deliberately — the contract field is frozen in v2, the- projection itself may land later, and the UI must render the null case as- simply absent.-3. **Fallback spend attribution** 「本月替补消费 $X」 — **v2.1 candidate, not in- v2.** It needs per-source metered spend attributable to fallback turns- specifically; whether the engine's usage data can support that (with its usage- feed disabled for key-leak reasons, S1 gap ②) is unverified. Revisit once the- L3 provenance work shows what turn-level accounting we actually hold (same- round-11 correction: 「the L2 rebuild」 named no lane in the current split, and the- turn record it waits on is L3's).-4. **First-class cross-vendor menu entries for Claude Code / Codex — v2.1- candidate, spike-gated** (owner ruling 2026-07-29 02:22). v2 already *supports*- cross-vendor supply (§4.3); what it lacks is a natural way to **add** a model.- Mapping makes the user spend a built-in slot: to run GPT-5 in Claude Code they- overwrite `claude-opus-4-6` with it — expressive, but it reads as a disguise, and- it costs them a slot they may still want. The v2.1 shape:-- - **Evolve the fixed-menu rule** (locked 2026-07-22, §4.7) into **built-in core- + explicitly user-added upstream models**. The user picks 来源 + 模型 directly- and the entry stands on its own — no GPT model wearing a built-in Claude id.- This reuses the OpenCode custom-model pattern rather than inventing one- (§4.8: the form takes source + model id and previews the identifier; the entry- is a supplement to that source's supply list) — the same interaction, extended- to the two fixed-menu backends. UI nouns stay 来源 / 模型: **Provider stays- banned** as a UI noun (§3), and so does any user-facing notion of a plugin.- - **Engine translation stays invisible.** If specific conversion pairs turn out- to need CPA plugins, we bake them into the engine build/config we ship — never- surfaced as user configuration. The survey's standing ruling holds unless the- spike overturns it: dynamic-library plugins are globally disabled by default- and must not become a runtime dependency (S1 §7). If the outcome does change- the engine build or pin, that is a `runtime-dependency.schema.json` revision —- new pin + SHA256, mirrored assets published before the manifest moves — not a- config tweak.- - **The spike is the gate.** Validate CPA v7.2.95 anthropic↔openai- (Messages ↔ Responses / Chat Completions) fidelity under real **agentic**- workloads: tool calls, streaming, system prompts, thinking/reasoning- parameters. Do **not** re-litigate what S1 §3 already settled — syntax- conversion exists, is registry-driven, and covers both directions; the open- question is precisely the one S1 flagged as unguaranteed, semantic- equivalence. Deliverable: a capability matrix plus **go/no-go per conversion- pair**, stating which pairs are engine-core and which are plugin-dependent.- Extend the findings in `model-hub-engine-survey.md`; do not start a new- document.- - **Scope guard — `api_key` sources only.** Cross-vendor supply is for API-key /- provider sources. **Subscriptions stay bound to their own vendor's backend** in- both channels; the S2/ToS ruling is unchanged (`model-hub-tos-review.md`, §4.4,- contracts README security invariant 3). A ChatGPT subscription never becomes a- source for Claude Code, before or after this item ships.- - Contract impact, recorded so nobody assumes v2 covers it: this needs an- `agent-supply` revision at a contract version **above** this batch's 3 — the next- one available when it ships, not a number reserved here (a fixed-menu backend gains- user-added entries alongside `mappings`; unpinned 07-29 17:41, review round 16: v2's- coordinated freeze consumes 3, so naming 3 here would make one version describe two- incompatible shapes). v2 deliberately carries **no**- speculative fields for it.-5. Remaining mocks (§5 pending): OpenCode drawer frame, empty state, Dark, copy- pass; plus deleting the rejected V5A/V5B/V5C frames from design.pen once the- owner confirms. The §10.4 item, if it clears the spike, also needs a 模型菜单- frame showing built-in core + user-added entries for a fixed-menu backend.-6. ~~Implementation plan & lane split for v2.~~ **Closed 2026-07-29**:- `model-hub-implementation.md` §3 now carries the approved v2 lane plan (L0–L6)- and §8 the full 21-criterion acceptance ledger. The rest of that document still- describes the shipped v1 and stays superseded for anything touching ordering —- §3 and §8 are the two v2-current, binding sections, as its banner says.-7. Naming final check in the EN locale: Hub / Direct, and now Follow / Custom for- 跟随推荐/自定义, in `en.json`.-8. Deferred capability: engine-owned OAuth import (adapter rev) — prerequisite- for any future auth-file controlled_import; revisit only with a concrete need.+- No v3 Configure Agents module (§5), runtime plugin UI, or GA scope beyond the+ three directions recorded in §10. Source-inventory `reasoning_efforts` capability+ lists are in scope and do not create Agent-definition configuration.++## 10. Open items and GA research directions++These items do not enlarge the owner-approved GA scope. They turn the three accepted+directions into questions that later lanes must answer before writing mechanical gates.++1. **Conversion fidelity (parallel K2 lane).** Keep the M0 measurements and go/no-go+ rows unchanged. The owner accepts relay-attributed reasoning loss and waives an+ official-API attribution re-test; this item is evidence, not an unresolved product+ blocker. Continue to record tool calls, streaming, system prompts, reasoning, cache,+ and terminal semantics without exposing plugins or per-hop warnings. Tool,+ streaming, and system behavior remain the functional floor; the recorded+ Messages-direction system/tuple distortion is non-blocking relay behavior.+2. **Release gate: engine asset mirror.** Research the exact Avibe-owned mirror,+ provenance, manifest publication order, availability monitor, restore behavior,+ and immutable-SHA evidence required before the pinned engine is a GA dependency.+ Do not change the pin or claim the gate complete in this specification.+3. **Release gate: platform matrix.** Re-verify install, startup, upgrade, rollback,+ and smoke evidence for every platform the current runtime contract lists. Decide+ the minimum repeatable evidence and unsupported-host behavior. Do not add platforms+ or platform-specific product promises here.+4. **Configure Agents — deferred.** First-class user-added menu models, reasoning+ effort, and Agent-definition configuration belong to the deferred third module.+ Its architecture and contract are intentionally absent from v3.+5. **Later diagnostics and accounting.** Request-log UI, fallback spend attribution,+ and quota projection remain post-v3 candidates. Each needs evidence from existing+ provenance/usage data before it becomes a product promise.+6. **Remaining UI evidence.** The approved v3 interaction draft is the implementation+ baseline. The design lane still owes complete desktop/mobile frames, empty and+ failure states, Dark variants, and English copy;+ a product re-review is required only if those artifacts change the approved+ information architecture. Rejected V5 explorations remain history until separately+ deleted.+7. **Engine-owned OAuth file import.** The §6 Native-config import action matrix is the+ sole authority for `controlled_import`; this research item adds no action branch.## 11. Owner acceptance checklist (~10 min)-- [ ] §0 revision note states the ruling and its no-back-compat consequence correctly.-- [ ] §2 promises 3 and 4 (per-agent order; never reorder behind the user) match intent.-- [ ] §3 vocabulary: 来源顺序 / 跟随推荐 / 自定义 / 供给状态; 优先级 banned as a global noun.-- [ ] §4.2 recommendation rule is exactly what you want implemented verbatim.-- [ ] §4.2 cooldown staying source-global rather than per-agent is right.-- [ ] §4.4 eligibility moving to the server closes the `isSourceEligible` debt.-- [ ] §4.5 three-class state taxonomy plus the two-tier surfacing rule, including- `waiting` — an all-cooling agent stays in the feed and never asks the user to- act, because it fixes itself.-- [ ] §4.5 states your 07-29 10:54 ruling correctly: nothing is pushed, the failing- turn carries the error, and the 「模型」 page holds the state until it is fixed.-- [ ] §4.5's silent-success rule is the one you want: a turn a fallback carried says- **nothing** in-turn, even when the switch left a source needing repair — that- blocker surfaces as 需处理 on the 「模型」 page instead. Every in-turn form is- therefore on the failure path, and the round-2 action tail is gone.-- [ ] §4.5 turn provenance gets a real read contract, not just a promise — including- the turn that gave up before trying anything, which the record must be able to- hold rather than skip.-- [ ] §4.5 the two grains: agent rollup `supply_status` for the selected model,- chain `supply_state` for any (agent, model) the user asks about.-- [ ] §4.3 candidate filtering keeps both predicates today's resolver has — the- OpenCode provider/vendor match (so `zhipuai/x` is never served by `custom/x`)- and skipping `error` sources, not just cooling ones.-- [ ] §4.6 chain per (agent, model) is the honesty fix you asked for, and showing- cooling sources dimmed rather than hiding them is right.-- [ ] §5 frame contracts match the V6 mocks you reviewed (01–04, M01–M02).-- [ ] §9 non-goals: no health scoring, no session pinning, no global list — and the- sharpened cross-vendor line draws the boundary at *who chose*, not at vendor.-- [ ] §4.3 states your 07-29 ruling correctly: cross-vendor supply (GPT in Claude- Code, Claude in Codex) is a supported, built-in v2 capability — no plugin- concept ever reaches the user.-- [ ] §10.4 is the right shape for making it first-class in v2.1: built-in core +- user-added 来源/模型 entries, engine translation invisible, gated on the- agentic-fidelity spike, and API-key sources only — subscriptions stay bound- to their own vendor.-- [ ] §10.3 deferring fallback spend attribution to v2.1 is acceptable.+- [ ] §0 and §2 say “default local model Gateway,” recommend Claude native and+ ChatGPT hub-held custody, and point all channel behavior to §4.3.+- [ ] §3 makes Gateway a first-class noun and the owner-vetoable banned-term table+ matches the intended UI language.+- [ ] §4.1 defaults Claude to `native_cli` and ChatGPT to `hub`; explicit hub-held+ Claude is the only branch with a warning, no flag or consent remains, and each+ backend has at most one native Source.+- [ ] §4.1 defines manual connectivity testing, model discovery, manual model+ add/remove, and editable `reasoning_efforts` lists for every inventory entry;+ every saved protocol is response-proven before Save and immutable afterward,+ with no persistent provenance marker or protocol-level unverified value.+- [ ] §4.1 exposes exactly `anthropic | openai_responses | openai_chat`, retains Chat+ Completions, and shows protocol choices only after observation cannot decide.+- [ ] §4.2 alone owns Add Source placement: every accepted match is persisted at one+ deterministic policy-chosen position that is visible and adjustable; no later+ path reruns placement, and no UI test infers newness from position.+- [ ] §4.4 allows every hub-held subscription to serve every backend while retaining+ native CLI's sanctioned-backend binding.+- [ ] §4.3 is the document's only configured-chain execution algorithm: it reads stored+ hops verbatim, checks only live runnability and error fallthrough, and derives the+ non-persisted takeover projection; §4.6 stores the same exact pairs the UI shows.+- [ ] The owner-vetoable final route shape is acceptable: every backend has one explicit+ Source order, every menu model has one explicit `hops` array, and no+ `follow | custom`, separate mapping, or runtime matching authority exists.+- [ ] §4.5 keeps state source-global, status live-derived, and every successful+ takeover silent; `supply_status` is the sole backend-health line, and a no-runnable-+ hop exhaustion never borrows takeover semantics; terminal in-turn errors plus+ Model Gateway/Usage pull state remain available.+- [ ] §5 has exactly Sources + Gateway modules; the connector is state-only and+ Configure Agents is deferred without a placeholder design. Source-card supply+ attribution reuses `adopted_by`, and saved Source details has only guarded+ 「重新拉取」 with no latency or “last checked” copy.+- [ ] §6 reports the exact hops Add Source wrote through `added_to`, and Source-card+ `adopted_by` reflects only persisted route references.+- [ ] §6 reserves Direct for `mode: direct`, labels a `native_cli` Gateway hop Native,+ and defines a visible, reversible Direct ↔ Gateway action for every backend.+- [ ] §9 explicitly supersedes the old no-per-model-ordering non-goal and states that+ only users configure model substitution.+- [ ] §10 records the owner-waived official-API fidelity re-test, preserves M0 evidence,+ and does not expand GA scope.+- [ ] The implementation plan appends AC-22 onward and gives I1 an exhaustive final+ contract handoff with a 13-file same-tested-head closure; every remaining consumer+ and test lands before release under the I1–I5 file split.diff --git a/scripts/check_model_hub_authorities.py b/scripts/check_model_hub_authorities.pynew file mode 100644index 000000000..94f932efd--- /dev/null+++ b/scripts/check_model_hub_authorities.py@@ -0,0 +1,672 @@+#!/usr/bin/env python3+"""Validate Model Hub authority tables against live registered consumers."""++from __future__ import annotations++import argparse+import ast+import fnmatch+import hashlib+import json+import re+from pathlib import Path+from typing import Any+++ROOT = Path(__file__).resolve().parents[1]+CONTRACTS = ROOT / "docs/plans/model-hub-contracts"+REGISTRY = CONTRACTS / "mirror-registry.json"+++class AuthorityInput:+ def __init__(self, root: Path) -> None:+ self.root = root+ self.files: dict[Path, bytes] = {}++ def bytes(self, relative: str) -> bytes:+ path = self.root / relative+ payload = path.read_bytes()+ self.files[path] = payload+ return payload++ def text(self, relative: str) -> str:+ return self.bytes(relative).decode("utf-8")++ def json(self, relative: str) -> Any:+ return json.loads(self.text(relative))++ def fingerprint(self) -> str:+ digest = hashlib.sha256()+ for path, payload in sorted(self.files.items()):+ digest.update(path.relative_to(self.root).as_posix().encode())+ digest.update(b"\0")+ digest.update(hashlib.sha256(payload).digest())+ return digest.hexdigest()+++def _json_pointer(document: Any, pointer: str) -> Any:+ value = document+ for token in pointer.lstrip("/").split("/"):+ token = token.replace("~1", "/").replace("~0", "~")+ value = value[int(token)] if isinstance(value, list) else value[token]+ return value+++def _schema_vocabulary(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ schema = source.json(f"docs/plans/model-hub-contracts/{spec['schema']}")+ values: set[Any] = set()+ for pointer in spec["paths"]:+ node = _json_pointer(schema, pointer)+ values.update(node["enum"] if "enum" in node else [node["const"]])+ values -= set(spec.get("exclude", ()))+ return {value for value in values if isinstance(value, str)}+++def _schema_values(source: AuthorityInput, schema: str, paths: list[str], *, exclude=()) -> set[Any]:+ document = source.json(f"docs/plans/model-hub-contracts/{schema}")+ values: set[Any] = set()+ for pointer in paths:+ node = _json_pointer(document, pointer)+ values.update(node["enum"] if "enum" in node else [node["const"]])+ return values - set(exclude)+++def _schema_property_names(source: AuthorityInput, relative: str) -> set[str]:+ names: set[str] = set()++ def walk(node: Any) -> None:+ if isinstance(node, dict):+ properties = node.get("properties")+ if isinstance(properties, dict):+ names.update(properties)+ for value in node.values():+ walk(value)+ elif isinstance(node, list):+ for value in node:+ walk(value)++ walk(source.json(relative))+ return names+++def _schema_decision_tokens(source: AuthorityInput, relative: str) -> set[str]:+ """Collect schema-controlled field names and closed values, never prose."""++ tokens: set[str] = set()++ def walk(node: Any) -> None:+ if isinstance(node, dict):+ properties = node.get("properties")+ if isinstance(properties, dict):+ tokens.update(properties)+ required = node.get("required")+ if isinstance(required, list):+ tokens.update(value for value in required if isinstance(value, str))+ enum = node.get("enum")+ if isinstance(enum, list):+ tokens.update(value for value in enum if isinstance(value, str))+ const = node.get("const")+ if isinstance(const, str):+ tokens.add(const)+ for value in node.values():+ walk(value)+ elif isinstance(node, list):+ for value in node:+ walk(value)++ walk(source.json(relative))+ return tokens+++def _normative_absence_terms(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ text = source.text(spec["source_file"])+ start = text.index(spec["start_marker"])+ block = text[start:].split("\n\n", 1)[0]+ terms: set[str] = set()+ for token in re.findall(r"`([^`]+)`", block):+ terms.update(part.strip() for part in token.split("|") if part.strip())+ return terms+++def _markdown_row_contract(source: AuthorityInput, spec: dict[str, Any]) -> tuple[set[str], set[str]]:+ row = next(+ line+ for line in source.text(spec["file"]).splitlines()+ if line.startswith(f"| **{spec['row_id']}**")+ )+ tokens = {+ token+ for token in re.findall(r"`([^`]+)`", row)+ if re.fullmatch(r"[a-z][a-z0-9_]+", token)+ }+ negated = set(re.findall(spec["negated_pattern"], row))+ return tokens - negated, negated+++def _markdown_table(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ lines = source.text(spec["file"]).splitlines()+ try:+ heading_index = next(+ index+ for index, line in enumerate(lines)+ if line.strip().startswith(f"**{spec['heading']}")+ )+ except StopIteration as exc:+ raise ValueError(f"heading not found: {spec['heading']}") from exc++ table_index = next(+ index+ for index in range(heading_index + 1, len(lines))+ if lines[index].lstrip().startswith("|")+ )+ headers = [cell.strip() for cell in lines[table_index].strip().strip("|").split("|")]+ try:+ column = headers.index(spec["column"])+ except ValueError as exc:+ raise ValueError(+ f"column {spec['column']!r} not found under {spec['heading']!r}"+ ) from exc++ values: set[str] = set()+ for line in lines[table_index + 2 :]:+ if not line.lstrip().startswith("|"):+ break+ cells = [cell.strip() for cell in line.strip().strip("|").split("|")]+ if len(cells) != len(headers):+ raise ValueError(f"malformed authority row under {spec['heading']!r}: {line}")+ tokens = re.findall(r"`([^`]+)`", cells[column])+ if len(tokens) != 1:+ raise ValueError(+ f"authority cell must contain one backticked value: {cells[column]!r}"+ )+ values.add(tokens[0])+ return values+++def _markdown_field_names(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ lines = source.text(spec["file"]).splitlines()+ heading_index = next(+ index+ for index, line in enumerate(lines)+ if line.strip().startswith(f"**{spec['heading']}")+ )+ table_index = next(+ index+ for index in range(heading_index + 1, len(lines))+ if lines[index].lstrip().startswith("|")+ )+ headers = [cell.strip() for cell in lines[table_index].strip().strip("|").split("|")]+ column = headers.index(spec["column"])+ fields: set[str] = set()+ for line in lines[table_index + 2 :]:+ if not line.lstrip().startswith("|"):+ break+ cell = [part.strip() for part in line.strip().strip("|").split("|")][column]+ fields.update(re.findall(r"\b([a-z][a-z0-9_]*)\s*:", cell))+ return fields+++def _marker_values(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ text = source.text(spec["file"])+ prefix = re.escape(spec["prefix"])+ return set(re.findall(rf"(?<![a-z0-9_.])({prefix}[a-z0-9_.]+)", text))+++def _marker_tail_values(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ """Read a live consumer declaration without embedding its members here."""+ values: set[str] = set()+ for line in source.text(spec["file"]).splitlines():+ if spec["marker"] not in line:+ continue+ tail = line.split(spec["marker"], 1)[1].split("-->", 1)[0]+ values.update(token for token in tail.split() if token)+ return values+++def _literal_strings(node: ast.AST) -> set[str]:+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return {node.value}+ values: set[str] = set()+ for child in ast.iter_child_nodes(node):+ values |= _literal_strings(child)+ return values+++def _python_test_literals(source: AuthorityInput, relative: str, name: str) -> set[str]:+ tree = ast.parse(source.text(relative), filename=relative)+ for node in tree.body:+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:+ return _literal_strings(node)+ raise ValueError(f"test function not found: {name}")+++def _python_literal_annotation(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ tree = ast.parse(source.text(spec["file"]), filename=spec["file"])+ for node in tree.body:+ if not isinstance(node, ast.ClassDef) or node.name != spec["class"]:+ continue+ for item in node.body:+ if (+ isinstance(item, ast.AnnAssign)+ and isinstance(item.target, ast.Name)+ and item.target.id == spec["field"]+ ):+ return _literal_strings(item.annotation)+ raise ValueError(f"annotation not found: {spec['class']}.{spec['field']}")+++def _python_string_assignment(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ tree = ast.parse(source.text(spec["file"]), filename=spec["file"])+ for node in tree.body:+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):+ continue+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]+ if not any(isinstance(target, ast.Name) and target.id == spec["name"] for target in targets):+ continue+ value = node.value+ if value is None:+ break+ return _literal_strings(value)+ raise ValueError(f"assignment not found: {spec['name']}")+++def _json_object_keys(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ value = _json_pointer(source.json(spec["file"]), spec["path"])+ if not isinstance(value, dict):+ raise ValueError(f"JSON object not found: {spec['file']}#{spec['path']}")+ prefix = spec.get("prefix", "")+ return {f"{prefix}{key}" for key in value}+++def _extract(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:+ kind = spec["kind"]+ if kind == "schema_vocabulary":+ return _schema_vocabulary(source, spec)+ if kind == "markdown_table":+ return _markdown_table(source, spec)+ if kind == "markdown_field_names":+ return _markdown_field_names(source, spec)+ if kind == "marker":+ return _marker_values(source, spec)+ if kind == "marker_tail":+ return _marker_tail_values(source, spec)+ if kind == "python_literal_annotation":+ return _python_literal_annotation(source, spec)+ if kind == "python_string_assignment":+ return _python_string_assignment(source, spec)+ if kind == "json_object_keys":+ return _json_object_keys(source, spec)+ raise ValueError(f"unknown extractor: {kind}")+++def _markdown_decision_tables(source: AuthorityInput, relative: str) -> set[str]:+ lines = source.text(relative).splitlines()+ headings: set[str] = set()+ current_heading: str | None = None+ for line in lines:+ stripped = line.strip()+ if stripped.startswith("**") and "(authoritative and exhaustive" in stripped:+ current_heading = stripped[2:].split("**", 1)[0].split(" (", 1)[0]+ continue+ if not stripped.startswith("|"):+ continue+ headers = [cell.strip() for cell in stripped.strip("|").split("|")]+ if "Decision" in headers:+ if current_heading is None:+ raise ValueError(f"Decision table has no named heading in {relative}")+ headings.add(current_heading)+ return headings+++def _mirror_findings(source: AuthorityInput, entry: dict[str, Any]) -> list[dict[str, Any]]:+ findings: list[dict[str, Any]] = []++ def vocabulary(item: dict[str, Any], paths_key: str = "paths") -> set[Any]:+ paths = item.get(paths_key)+ if paths is None:+ paths = [item["path"]]+ return _schema_values(+ source,+ item["schema"],+ paths,+ exclude=item.get("exclude", ()),+ )++ def add(kind: str, **detail: Any) -> None:+ findings.append({"kind": kind, "domain": entry["id"], **detail})++ rule = entry["rule"]+ if rule == "equality":+ normalized: list[set[Any]] = []+ for item in entry["sets"]:+ actual = vocabulary(item)+ extras = set(item.get("extras", ()))+ if not extras <= actual:+ add("mirror_missing_extra", schema=item["schema"], values=sorted(extras - actual))+ normalized.append(actual - extras)+ if normalized and any(values != normalized[0] for values in normalized[1:]):+ add(+ "mirror_equality_drift",+ values=[sorted(values, key=repr) for values in normalized],+ )+ return findings++ if rule == "mapping":+ home = vocabulary(entry["home"])+ targets = entry.get("targets")+ if targets is None:+ targets = [{**entry["target"], "mapping": entry["mapping"]}]+ for item in targets:+ target = vocabulary(item)+ mapping = item["mapping"]+ if home != set(mapping):+ add("mirror_mapping_domain_drift", schema=item["schema"])+ if target != set(mapping.values()):+ add("mirror_mapping_range_drift", schema=item["schema"])+ return findings++ if rule == "partition":+ home = vocabulary(entry["home"])+ member = vocabulary(entry["member"])+ exclusions = set(entry["exclusions"])+ for item in entry["exclusion_sets"]:+ exclusions |= vocabulary(item)+ if member & exclusions:+ add("mirror_partition_overlap", values=sorted(member & exclusions))+ if home != member | exclusions:+ add("mirror_partition_drift")+ return findings++ if rule == "bijection":+ home = vocabulary(entry["home"])+ target: set[Any] = set()+ for item in entry["target_sets"]:+ target |= vocabulary(item)+ pairs = entry["pairs"]+ if not set(pairs) <= home:+ add("mirror_bijection_domain_drift")+ if len(set(pairs.values())) != len(pairs):+ add("mirror_bijection_not_injective")+ if target != set(pairs.values()):+ add("mirror_bijection_range_drift")+ return findings++ if rule == "projection":+ home = vocabulary(entry["home"])+ for item in entry["targets"]:+ target = vocabulary(item)+ if target != home - set(item["drop_from_home"]):+ add("mirror_projection_drift", schema=item["schema"])+ return findings++ add("unknown_mirror_rule", rule=rule)+ return findings+++def _binding_lane_rows(source: AuthorityInput, check: dict[str, Any]) -> list[str]:+ lines = source.text(check["lane_table_file"]).splitlines()+ heading_index = next(+ index+ for index, line in enumerate(lines)+ if check["lane_table_heading"] in line+ )+ table_index = next(+ index+ for index in range(heading_index + 1, len(lines))+ if lines[index].startswith("| Lane |")+ )+ rows: list[str] = []+ for line in lines[table_index + 2 :]:+ if not line.startswith("|"):+ break+ if re.match(r"\| \*\*I[0-9]+\b", line):+ rows.append(line)+ return rows+++def _python_importers(source: AuthorityInput, check: dict[str, Any]) -> set[str]:+ importers: set[str] = set()+ for path in sorted(source.root.rglob("*.py")):+ relative = path.relative_to(source.root).as_posix()+ if any(fnmatch.fnmatch(relative, pattern) for pattern in check.get("exclude_globs", ())):+ continue+ try:+ tree = ast.parse(source.bytes(relative), filename=relative)+ except (SyntaxError, UnicodeDecodeError):+ continue+ if any(+ isinstance(node, ast.ImportFrom) and node.module == check["module"]+ for node in ast.walk(tree)+ ):+ importers.add(relative)+ return importers+++def check(root: Path = ROOT) -> dict[str, Any]:+ source = AuthorityInput(root)+ registry = source.json("docs/plans/model-hub-contracts/mirror-registry.json")+ findings: list[dict[str, Any]] = []++ # Absence assertions are discovered from the live normative text. The checker+ # never embeds a retired member; it derives each term from the assertion and+ # checks every contract artifact in the same invocation.+ for absence in registry.get("absence_checks", ()):+ text = source.text(absence["source_file"])+ for term in re.findall(absence["pattern"], text):+ for relative in absence["scope_files"]:+ if term in source.text(relative):+ findings.append(+ {"kind": "retired_contract_value", "domain": absence["id"], "file": relative, "value": term}+ )++ for absence in registry.get("schema_absence_checks", ()):+ terms = _normative_absence_terms(source, absence)+ for pattern in absence["scope_globs"]:+ for path in sorted(root.glob(pattern)):+ relative = path.relative_to(root).as_posix()+ tokens = _schema_decision_tokens(source, relative)+ for term in sorted(terms & tokens):+ findings.append(+ {+ "kind": "retired_schema_token",+ "domain": absence["id"],+ "file": relative,+ "value": term,+ }+ )++ for contract in registry.get("field_contracts", ()):+ properties = _schema_property_names(source, contract["schema_file"])+ claimed, negated = _markdown_row_contract(source, contract)+ for field in sorted(claimed - properties):+ findings.append(+ {"kind": "orphan_prose_field", "domain": contract["id"], "value": field}+ )+ for field in sorted(negated & properties):+ findings.append(+ {"kind": "forbidden_persisted_field", "domain": contract["id"], "value": field}+ )++ for boundary in registry.get("api_boundary_only_errors", ()):+ value = boundary["value"]+ if value not in source.text(boundary["contract_file"]):+ findings.append({"kind": "missing_boundary_error_contract", "value": value})+ try:+ test_literals = _python_test_literals(+ source,+ boundary["negative_test_file"],+ boundary["negative_test"],+ )+ except (OSError, SyntaxError, ValueError) as exc:+ findings.append(+ {"kind": "input_error", "domain": "boundary_error", "detail": str(exc)}+ )+ else:+ if value not in test_literals:+ findings.append(+ {+ "kind": "boundary_error_test_does_not_assert_value",+ "value": value,+ "test": boundary["negative_test"],+ }+ )+ for pattern in boundary["forbidden_ui_globs"]:+ for path in sorted(root.glob(pattern)):+ relative = path.relative_to(root).as_posix()+ if value in source.text(relative):+ findings.append(+ {"kind": "boundary_error_has_ui_consumer", "value": value, "file": relative}+ )++ for absence in registry.get("repo_absence_checks", ()):+ term = "-".join(absence["term_parts"])+ for pattern in absence["scope_globs"]:+ for path in sorted(root.glob(pattern)):+ if not path.is_file():+ continue+ relative = path.relative_to(root).as_posix()+ if term in source.text(relative):+ findings.append(+ {+ "kind": "retired_repo_literal",+ "domain": absence["id"],+ "file": relative,+ "value": term,+ }+ )++ for route_check in registry.get("route_body_absence_checks", ()):+ matching_rows = [+ line+ for line in source.text(route_check["contract_file"]).splitlines()+ if line.startswith("|") and route_check["path_fragment"] in line+ ]+ if not matching_rows:+ findings.append({"kind": "missing_route_family", "domain": route_check["id"]})+ continue+ for row in matching_rows:+ cells = [cell.strip() for cell in row.strip().strip("|").split("|")]+ request = cells[1].split("→", 1)[0]+ if re.search(rf"\b{re.escape(route_check['forbidden_field'])}\b", request):+ findings.append(+ {+ "kind": "route_body_contains_path_identity",+ "domain": route_check["id"],+ "value": route_check["forbidden_field"],+ "row": row,+ }+ )++ registry_ids = [+ *(entry["id"] for entry in registry["entries"]),+ *(entry["id"] for entry in registry["decision_tables"]),+ *(entry["id"] for entry in registry.get("ownership_checks", ())),+ *(entry["id"] for entry in registry.get("file_mirrors", ())),+ ]+ if len(registry_ids) != len(set(registry_ids)):+ findings.append({"kind": "duplicate_registry_id", "ids": registry_ids})++ registered_tables: dict[str, set[str]] = {}+ for decision in registry["decision_tables"]:+ authority = decision["authority"]+ if authority["kind"] == "markdown_table":+ registered_tables.setdefault(authority["file"], set()).add(authority["heading"])+ for relative in registry["authority_table_discovery"]["files"]:+ try:+ discovered = _markdown_decision_tables(source, relative)+ except (OSError, ValueError) as exc:+ findings.append({"kind": "input_error", "domain": "table_discovery", "detail": str(exc)})+ continue+ registered = registered_tables.get(relative, set())+ for heading in sorted(discovered - registered):+ findings.append({"kind": "unregistered_authority_table", "file": relative, "heading": heading})+ for heading in sorted(registered - discovered):+ findings.append({"kind": "missing_authority_table", "file": relative, "heading": heading})++ for entry in registry["entries"]:+ try:+ findings.extend(_mirror_findings(source, entry))+ except (KeyError, OSError, ValueError, json.JSONDecodeError) as exc:+ findings.append({"kind": "input_error", "domain": entry["id"], "detail": str(exc)})++ for decision in registry["decision_tables"]:+ try:+ authority = _extract(source, decision["authority"])+ consumer_sets = [_extract(source, item) for item in decision["consumers"]]+ except (KeyError, OSError, ValueError, json.JSONDecodeError, SyntaxError) as exc:+ findings.append(+ {"kind": "input_error", "domain": decision["id"], "detail": str(exc)}+ )+ continue+ consumers = set().union(*consumer_sets)+ for value in sorted(consumers - authority):+ findings.append(+ {"kind": "orphan_branch", "domain": decision["id"], "value": value}+ )+ for value in sorted(authority - consumers):+ findings.append(+ {"kind": "orphan_row", "domain": decision["id"], "value": value}+ )+ if decision.get("authority_fields"):+ fields = _extract(source, decision["authority_fields"])+ contract_text = "\n".join(+ source.text(relative)+ for relative in decision["authority_fields_scope"]+ )+ for field in sorted(fields):+ if field not in contract_text:+ findings.append(+ {"kind": "orphan_authority_field", "domain": decision["id"], "value": field}+ )++ for ownership in registry.get("ownership_checks", ()):+ if ownership["kind"] != "python_importers_have_exactly_one_lane":+ findings.append(+ {"kind": "unknown_ownership_check", "domain": ownership["id"]}+ )+ continue+ rows = _binding_lane_rows(source, ownership)+ for path in sorted(_python_importers(source, ownership)):+ owners = [row for row in rows if f"`{path}`" in row]+ if len(owners) != 1:+ findings.append(+ {+ "kind": "ownership_cardinality",+ "domain": ownership["id"],+ "path": path,+ "owners": len(owners),+ }+ )++ for mirror in registry.get("file_mirrors", ()):+ left = source.bytes(mirror["left"])+ right = source.bytes(mirror["right"])+ if left != right:+ findings.append({"kind": "file_mirror_drift", "domain": mirror["id"]})++ return {+ "ok": not findings,+ "input_mode": registry["input_generation"]["mode"],+ "input_fingerprint": source.fingerprint(),+ "findings": findings,+ }+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--root", type=Path, default=ROOT)+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args()+ result = check(args.root.resolve())+ if args.json:+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))+ elif result["ok"]:+ print(f"Model Hub authority closure OK ({result['input_fingerprint']})")+ else:+ for finding in result["findings"]:+ print(json.dumps(finding, ensure_ascii=False, sort_keys=True))+ return 0 if result["ok"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())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 b8564e960..b62ea26a0 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@@ -174,46 +174,23 @@ async def _post_turn(return response.status, await response.read()-def test_mh_pri_001_order_mutations_change_the_next_turn(tmp_path: Path) -> None:- """MH-PRI-001: custom edits and follow restoration affect the next turn."""-- async def exercise() -> None:- alpha = _source("src_alpha001")- zulu = _source("src_zulu0001")- store = MemoryStore(_config(alpha, zulu))- adapter = AdapterBoundaryFake([])- 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:- initial = await router.resolve("claude", "model-live")- assert initial.source_id == alpha.id-- custom = await service.set_agent_sources(- "claude",- {"policy": "custom", "order": [zulu.id, alpha.id]},- )- assert custom["sources"]["policy"] == "custom"- reordered = await router.resolve("claude", "model-live")- assert reordered.source_id == zulu.id-- restored = await service.set_agent_sources(- "claude",- {"policy": "follow"},- )- assert restored["sources"]["policy"] == "follow"- assert restored["sources"]["order"] == [alpha.id, zulu.id]- recommended = await router.resolve("claude", "model-live")- assert recommended.source_id == alpha.id- finally:- await gateway.close()+def test_mh_pri_001_source_order_projection_has_no_policy_state(tmp_path: Path) -> None:+ """MH-PRI-001: the persisted Source order is projected without policy state."""++ alpha = _source("src_alpha001")+ zulu = _source("src_zulu0001")+ store = MemoryStore(_config(alpha, zulu))+ store.config.agents["claude"].sources.order = [zulu.id, alpha.id]+ service = _service(+ tmp_path,+ store,+ AdapterBoundaryFake([]),+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )- asyncio.run(exercise())+ projected = service.get_agent_sources("claude")["sources"]+ assert projected["order"] == [zulu.id, alpha.id]+ assert "policy" not in projecteddef test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex 76630b501..7d7a52333 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -793,7 +793,7 @@ def test_opencode_builtin_provider_is_importable_without_catalog_cache()assert item.vendor == "openrouter"- assert item.protocol == "openai_compatible"+ assert item.protocol == "openai_chat"assert item.base_url == "https://openrouter.example/v1"diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.pyindex 9b660d7f6..1441dc7ec 100644--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py@@ -157,14 +157,7 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_pf"/api/models/oauth/status/{started['flow_id']}",base_url=BASE_URL,).get_json()- assert set(completion) == {- "ok",- "contract_version",- "flow",- "source",- "adopted_by",- "skipped_by",- }+ assert {"ok", "contract_version", "flow", "source", "adopted_by"} <= set(completion)completed = completion["flow"]source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]codex = next(@@ -178,11 +171,7 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_passert source["state"]["status"] == "standby"assert source["account_label"] == "[email protected] \u00b7 plus \u00b7 Example Org"assert source["credential_ref"] is None- assert completion["adopted_by"] == []- assert completion["skipped_by"] == [- {"backend": "codex", "reason": "custom_order"}- ]- assert codex["sources"]["policy"] == "custom"+ assert "policy" not in codex["sources"]assert codex["sources"]["order"] == []assert codex["sources"]["eligibility"] == [{@@ -264,7 +253,7 @@ def test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly(monkeypatch, t).status_code == 404-def test_mh_oauth_consent_001_is_required_and_persisted(monkeypatch, tmp_path):+def test_mh_oauth_consent_001_public_source_omits_retired_consent_stamp(monkeypatch, tmp_path):"""Scenario: MH-OAUTH-CONSENT-001."""harness = HubOAuthScenarioHarness(tmp_path)@@ -304,7 +293,7 @@ def test_mh_oauth_consent_001_is_required_and_persisted(monkeypatch, tmp_path):assert completed["state"] == "success"assert source["id"] == started["source_id"]assert source["supply_channel"] == "hub"- assert source["experimental_consent_at"] == "2026-07-25T00:00:00+00:00"+ assert "experimental_consent_at" not in sourceharness.adapter.flows.clear()repeated = client.get(diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex de5b4d422..356f4a984 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -337,7 +337,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):runtime = asyncio.run(service.runtime_start())assert adapter.start_calls == 1- assert runtime["contract_version"] == 4+ assert runtime["contract_version"] == 5assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -508,7 +508,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 4, "status": {"health": "ok"}}+ return {"contract_version": 5, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -733,8 +733,9 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():("PATCH", "/api/models/agents/claude/mode"),("PUT", "/api/models/agents/claude/mappings"),("PUT", "/api/models/agents/opencode/menu"),- ("POST", "/api/models/custom-models"),- ("DELETE", "/api/models/custom-models"),+ ("POST", "/api/models/sources/src_test0001/models"),+ ("PATCH", "/api/models/sources/src_test0001/models/custom-model"),+ ("DELETE", "/api/models/sources/src_test0001/models/custom-model"),("GET", "/api/models/events?limit=invalid"),("POST", "/api/models/oauth/start"),("GET", "/api/models/oauth/status/oaf_test0001"),@@ -938,14 +939,14 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):)custom = response.get_json()_assert_envelope(custom)- assert custom["agent"]["sources"]["policy"] == "custom"+ assert "policy" not in custom["agent"]["sources"]assert custom["agent"]["sources"]["order"] == []codex_sources = client.get("/api/models/agents/codex/sources",base_url=base_url,).get_json()["agent"]["sources"]- assert codex_sources["policy"] == "follow"+ assert "policy" not in codex_sourcesassert codex_sources["order"] == [source_id]restored = client.put(@@ -954,7 +955,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):headers=headers,base_url=base_url,).get_json()- assert restored["agent"]["sources"]["policy"] == "follow"+ assert "policy" not in restored["agent"]["sources"]assert restored["agent"]["sources"]["order"] == [source_id]response = client.patch(@@ -1015,8 +1016,12 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):service.now = original_nowresponse = client.post(- "/api/models/custom-models",- json={"source_id": source_id, "model_id": "custom-model", "display_name": "Custom Model"},+ f"/api/models/sources/{source_id}/models",+ json={+ "model_id": "custom-model",+ "display_name": "Custom Model",+ "reasoning_efforts": [],+ },headers=headers,base_url=base_url,)@@ -1202,7 +1207,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):assert oauth_creation["skipped_by"] == []consented_source = oauth_creation["source"]_assert_valid("source.schema.json", consented_source)- assert consented_source["experimental_consent_at"] == "2026-07-23T03:00:00+00:00"+ assert "experimental_consent_at" not in consented_sourcecompleted_binding = service.oauth_flows.binding(hub_flow["flow_id"])assert completed_binding is not Noneassert completed_binding.completed is True@@ -1223,8 +1228,8 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):assert all("<" not in asset["url"] for asset in runtime["manifest"]["assets"])response = client.delete(- "/api/models/custom-models",- json={"source_id": source_id, "model_id": "custom-model"},+ f"/api/models/sources/{source_id}/models/custom-model",+ json={},headers=headers,base_url=base_url,)@@ -1246,8 +1251,8 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):)_assert_envelope(response.get_json())response = client.delete(- "/api/models/custom-models",- json={"source_id": source_id, "model_id": "custom-model"},+ f"/api/models/sources/{source_id}/models/custom-model",+ json={},headers=headers,base_url=base_url,)@@ -1280,6 +1285,21 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):("/api/models/agents/claude/mode", "patch", "mode_switch_blocked"),("/api/models/agents/claude/mappings", "put", "mapping_target_unavailable"),("/api/models/agents/opencode/menu", "put", "mapping_target_unavailable"),+ (+ "/api/models/sources/src_test0001/models",+ "post",+ "mapping_target_unavailable",+ ),+ (+ "/api/models/sources/src_test0001/models/custom-model",+ "patch",+ "mapping_target_unavailable",+ ),+ (+ "/api/models/sources/src_test0001/models/custom-model",+ "delete",+ "mapping_target_unavailable",+ ),],)def test_model_hub_routes_reject_non_object_json_with_error_envelope(@@ -1308,6 +1328,53 @@ def test_model_hub_routes_reject_non_object_json_with_error_envelope(assert body["error"] == error+def test_discovered_source_model_delete_is_rejected_as_upstream_managed(+ monkeypatch,+ tmp_path,+):+ service, store, _ = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_discovered01",+ kind="api_key",+ vendor="openai",+ display_name="Observed inventory",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="gpt-5", provenance="discovered")],+ credential_ref="cred_discovered01",+ )+ store.config.sources.append(source)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ updated = client.patch(+ f"/api/models/sources/{source.id}/models/gpt-5",+ json={"reasoning_efforts": ["high"]},+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert updated.status_code == 200+ updated_model = updated.get_json()["source"]["models"][0]+ assert updated_model["origin"] == "discovered"+ assert updated_model["reasoning_efforts"] == ["high"]++ refused = client.delete(+ f"/api/models/sources/{source.id}/models/gpt-5",+ json={},+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert refused.status_code == 409+ assert refused.get_json()["error"] == "source_model_managed_upstream"+ assert [model.id for model in store.config.sources[0].models] == ["gpt-5"]+ assert store.config.sources[0].models[0].reasoning_efforts == ["high"]++def test_native_reauth_route_requires_ack_before_oauth_and_returns_reauth_tail(monkeypatch,tmp_path,@@ -3303,7 +3370,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tassert accepted.status_code == 200runtime = accepted.get_json()["runtime"]assert adapter.start_calls == 1- assert runtime["contract_version"] == 4+ assert runtime["contract_version"] == 5_assert_valid("runtime-dependency.schema.json", runtime)@@ -3353,7 +3420,7 @@ def test_native_source_configuration_does_not_require_l1_engine(tmp_path):_assert_valid("source.schema.json", source)assert source["supply_channel"] == "native_cli"assert any(model["id"] == "claude-opus-4-6" for model in source["models"])- assert {model["provenance"] for model in source["models"]} == {"discovered"}+ assert {model["origin"] for model in source["models"]} == {"discovered"}assert store.config.effective_source_order("claude") == [source["id"]]resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))assert resolved.source_id == source["id"]@@ -3483,7 +3550,7 @@ def test_follow_auto_adopts_new_sources_while_custom_stays_frozen(tmp_path):}restored = asyncio.run(service.set_agent_sources("claude", {"policy": "follow"}))- assert restored["sources"]["policy"] == "follow"+ assert "policy" not in restored["sources"]assert restored["sources"]["order"] == store.config.recommended_source_order("claude")@@ -3638,7 +3705,7 @@ def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path)"vendor": "anthropic","display_name": "Safe source","key": "sk-test-transient-only",- "models": [{"id": pasted_key, "provenance": "manual"}],+ "models": [{"id": pasted_key, "origin": "manual"}],},{"kind": "api_key",@@ -3649,7 +3716,7 @@ def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path){"id": "safe-model-id","display_name": pasted_key,- "provenance": "manual",+ "origin": "manual",}],},@@ -3673,7 +3740,12 @@ def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path)))with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.add_custom_model({"source_id": source["id"], "model_id": pasted_key}))+ asyncio.run(+ service.add_custom_model(+ source["id"],+ {"model_id": pasted_key, "reasoning_efforts": []},+ )+ )assert exc_info.value.code == "mapping_target_unavailable"assert pasted_key not in json.dumps(store.config.to_payload())diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex a2687058c..f97e47940 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -24,6 +24,7 @@ from config.v2_config import (is_model_hub_enabled,)from core.services.settings import default_config+from scripts.check_model_hub_authorities import check as check_model_hub_authoritiesfrom vibe import apiCONTRACTS = Path("docs/plans/model-hub-contracts")@@ -177,6 +178,9 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():"builtin_models": example.get("builtin_models"),"standard_vendors": example.get("standard_vendors"),}+ # AgentSupply is the API projection; the dormant pre-I1 config object+ # still carries its old mapping list behind the default-off gate.+ serialized.pop("mappings", None)if "sources" not in example:serialized.pop("sources")else:@@ -203,7 +207,6 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():"selected_model_id": "claude-opus-4-5","selected_model_explicit": True,"sources": {- "policy": "follow","order": ["src_anthropic1"],"eligibility": [{@@ -216,7 +219,6 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():],},"supply_status": "ok",- "mappings": [],"menu": None,"model_supply": [{"model_id": "claude-opus-4-5", "chain_length": 1}@@ -229,27 +231,19 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():_assert_valid("agent-supply.schema.json", payload)-def test_v4_mirror_registry_is_executable_and_complete():+def test_v5_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"] == 4- assert [entry["id"] for entry in registry["entries"]] == [- "M1",- "M2",- "M3",- "M4",- "M5",- "M6",- "M7",- "M8",- "N1",- ]+ assert registry["contract_version"] == 5+ ids = [entry["id"] for entry in registry["entries"]]+ assert ids+ assert len(ids) == len(set(ids))for entry in registry["entries"]:_validate_mirror_entry(entry, schemas)-def test_v4_mirror_registry_mutation_probes_detect_every_comparable_drift():+def test_v5_mirror_registry_mutation_probes_detect_every_comparable_drift():registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))schemas = _mirror_schemas(registry)@@ -292,6 +286,13 @@ def test_v4_mirror_registry_mutation_probes_detect_every_comparable_drift():_validate_mirror_entry(entry, mutated)+def test_model_hub_authority_closure_is_generated_from_live_files():+ result = check_model_hub_authorities(Path.cwd())+ assert result["input_mode"] == "same_run_live_files"+ assert result["input_fingerprint"]+ assert result["ok"], result["findings"]++def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():event_schema = _schema("resolution-event.schema.json")event_validator = Draft7Validator(event_schema)@@ -311,7 +312,7 @@ def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():event_validator.validate(invalid_cooldown)provenance_schema = _schema("turn-provenance.schema.json")- assert provenance_schema["properties"]["contract_version"]["const"] == 4+ assert provenance_schema["properties"]["contract_version"]["const"] == 5permission_record = next(examplefor example in provenance_schema["examples"]@@ -338,7 +339,7 @@ def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():)-def test_v4_shape_amendments_reject_the_false_states_they_replace():+def test_v5_shape_amendments_reject_the_false_states_they_replace():supply_schema = _schema("agent-supply.schema.json")supply_validator = Draft7Validator(supply_schema)base_supply = {@@ -348,9 +349,8 @@ def test_v4_shape_amendments_reject_the_false_states_they_replace():"selected_by_agent": None,"selected_model_id": None,"selected_model_explicit": False,- "sources": {"policy": "follow", "order": [], "eligibility": []},+ "sources": {"order": [], "eligibility": []},"supply_status": None,- "mappings": [],"menu": None,"model_supply": [],"named_agents": [],@@ -397,7 +397,6 @@ def test_v4_shape_amendments_reject_the_false_states_they_replace():})signal_supply["sources"] = {- "policy": "custom","order": ["src_anthkey01"],"eligibility": [{@@ -543,9 +542,14 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmapi_payload = api.config_to_payload(loaded)expected_root = {field.name for field in fields(ModelHubConfig)}source_fields = {field.name for field in fields(ModelHubSourceConfig)}+ # Retired consent metadata remains an internal compatibility attribute for+ # in-memory fixtures but is intentionally absent from the final payload.+ source_fields.discard("experimental_consent_at")source_state_fields = {field.name for field in fields(ModelHubSourceStateConfig)}source_usage_fields = {field.name for field in fields(ModelHubSourceUsageConfig)}source_model_fields = {field.name for field in fields(ModelHubModelConfig)}+ source_model_fields.discard("provenance")+ source_model_fields.add("origin")agent_fields = {field.name for field in fields(ModelHubAgentSupplyConfig)}agent_sources_fields = {field.name for field in fields(ModelHubAgentSourcesConfig)}mapping_fields = {field.name for field in fields(ModelHubMappingConfig)}@@ -594,7 +598,7 @@ def test_model_hub_release_capability_defaults_and_fails_closed(value):assert is_model_hub_enabled({MODEL_HUB_ENABLED_ENV: value}) is False-def test_hub_subscription_requires_server_recorded_consent():+def test_hub_subscription_load_ignores_retired_consent_metadata():source = _schema("source.schema.json")["examples"][0]source = {**source, "supply_channel": "hub"}payload = {@@ -603,12 +607,8 @@ def test_hub_subscription_requires_server_recorded_consent():"subscription_hub_experimental": True,}- try:- ModelHubConfig.from_payload(payload)- except ValueError as exc:- assert "recorded experimental consent" in str(exc)- else:- raise AssertionError("hub-held subscription loaded without recorded consent")+ loaded = ModelHubConfig.from_payload(payload)+ assert loaded.sources[0].supply_channel == "hub"def test_legacy_global_priority_key_is_dropped_without_validation():diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 4a024807f..fc644c00b 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -1020,7 +1020,7 @@ def test_agent_chain_and_runtime_router_share_resolution_table(tmp_path: Path) -"src_hub_open_mapped",kind="api_key",vendor="custom",- protocol="openai_compatible",+ protocol="openai_chat",channel="hub",model_ids=("mapped-open",),)@@ -1037,7 +1037,7 @@ def test_agent_chain_and_runtime_router_share_resolution_table(tmp_path: Path) -"src_hub_open_ready",kind="api_key",vendor="custom",- protocol="openai_compatible",+ protocol="openai_chat",channel="hub",model_ids=("ready-model",),)@@ -1555,7 +1555,7 @@ def _opencode_config() -> ModelHubConfig:"src_hub0005",kind="api_key",vendor="relay-vendor",- protocol="openai_compatible",+ protocol="openai_chat",channel="hub",model_ids=("local-model",),)diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex c2724591f..aeeb4e4a5 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -460,9 +460,8 @@ def test_authenticated_gateway_validation_failure_is_correlated(assert record["outcome"] == "failed_terminal"assert record["terminal_error"] == {"source_id": "src_primary01",- "resolved_model_id": "shared-model",+ "configured_model_id": "shared-model","channel": "hub",- "via_mapping": False,"reason": reason,"stream_started": False,}@@ -513,9 +512,8 @@ def test_gateway_terminalizer_records_pre_observer_engine_down_before_return(assert trace.pending_attempt is Noneassert trace.terminal_error == {"source_id": "src_primary01",- "resolved_model_id": "shared-model",+ "configured_model_id": "shared-model","channel": "hub",- "via_mapping": False,"reason": "protocol_error","stream_started": False,}@@ -579,9 +577,8 @@ def test_gateway_provenance_retains_pre_mapping_model_identity(assert record["requested_model_id"] == "gpt-5"assert record["served"] == {"source_id": "src_primary01",- "resolved_model_id": "custom-gpt-5",+ "configured_model_id": "custom-gpt-5","channel": "hub",- "via_mapping": True,}_assert_valid("turn-provenance.schema.json", record)@@ -672,7 +669,7 @@ def test_gateway_preserves_native_alias_for_per_source_failover(assert record is not Noneassert record["requested_model_id"] == requested_modelassert record["served"]["source_id"] == backup.id- assert record["served"]["resolved_model_id"] == backup_model+ assert record["served"]["configured_model_id"] == backup_model_assert_valid("turn-provenance.schema.json", record)asyncio.run(exercise())@@ -741,9 +738,8 @@ def test_native_terminal_failure_is_not_recorded_as_served(assert record["failed_attempts"] == [{"source_id": "src_primary01",- "resolved_model_id": "shared-model",+ "configured_model_id": "shared-model","channel": "native_cli",- "via_mapping": False,"reason": "quota_exhausted",}]@@ -1322,7 +1318,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:"anthropic","openai_responses","openai_chat",- "openai_compatible",+ "openai_chat",)]+ [@@ -1336,7 +1332,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:"anthropic","openai_responses","openai_chat",- "openai_compatible",+ "openai_chat",)]+ [@@ -1354,7 +1350,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:"anthropic","openai_responses","openai_chat",- "openai_compatible",+ "openai_chat",)],)@@ -1410,7 +1406,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:probe = asyncio.run(service.probe_agent("codex", "shared-model"))assert probe == {- "contract_version": 4,+ "contract_version": 5,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 2e9d684e4..8a6236687 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1708,10 +1708,11 @@ def test_custom_model_preserves_slash_qualified_upstream_id(tmp_path):updated = asyncio.run(service.add_custom_model(+ source.id,{- "source_id": source.id,"model_id": "anthropic/claude-sonnet-4","display_name": "Claude Sonnet 4",+ "reasoning_efforts": [],}))@@ -1814,7 +1815,6 @@ def test_mapping_auto_enrolls_eligible_non_enrolled_source(tmp_path):))- assert agent["sources"]["policy"] == "custom"assert agent["sources"]["order"] == [*original_order, added.id]assert config.agents["claude"].mappings[0].target_model_id == "mapped-model"@@ -1852,7 +1852,6 @@ def test_opencode_menu_auto_enrolls_eligible_non_enrolled_source(tmp_path):))- assert agent["sources"]["policy"] == "custom"assert agent["sources"]["order"] == [*original_order, added.id]assert agent["menu"]["checked"] == ["openrouter/anthropic/claude-sonnet-4"@@ -1978,7 +1977,6 @@ def test_follow_order_exhaustively_enrolls_eligible_sources_and_stays_follow(if config.source_eligible_for_backend(source, backend)}assert set(config.effective_source_order(backend)) == eligible- assert agent.sources.policy == "follow"claude = asyncio.run(service.set_mappings(@@ -2001,8 +1999,6 @@ def test_follow_order_exhaustively_enrolls_eligible_sources_and_stays_follow())- assert claude["sources"]["policy"] == "follow"- assert opencode["sources"]["policy"] == "follow"@pytest.mark.parametrize("mutation", ["mapping", "menu"])diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex ffcb7c082..c7df71d18 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -95,7 +95,7 @@ def _binding(credential_ref: str, **overrides: object) -> SourceBinding:payload = {"source_id": "src_fixture123","vendor": "custom",- "protocol": "openai_compatible",+ "protocol": "openai_chat","base_url": "https://api.example.test/v1","credential_ref": credential_ref,"allowed_origins": (),@@ -745,14 +745,14 @@ def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> Non)credential_ref = await adapter.provision_credential("custom",- "openai_compatible",+ "openai_chat","probe-secret",base_url,)models = await adapter.discover_models("custom",- "openai_compatible",+ "openai_chat",f"{base_url}/",credential_ref,)@@ -762,7 +762,7 @@ def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> Nonwith pytest.raises(EngineStateError, match="does not match"):await adapter.discover_models("custom",- "openai_compatible",+ "openai_chat","https://different.example/v1",credential_ref,)@@ -1090,7 +1090,7 @@ def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> Nonadapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)credential_ref = await adapter.provision_credential("custom",- "openai_compatible",+ "openai_chat","upstream-secret","https://api.example.test/v1",)@@ -1176,7 +1176,7 @@ def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> Non@pytest.mark.parametrize(("source_protocol", "origin", "caller_protocol", "request_protocol"),[- ("openai_compatible", "claude", "openai_chat", "anthropic"),+ ("openai_chat", "claude", "openai_chat", "anthropic"),("anthropic", "codex", "anthropic", "openai_responses"),("openai_chat", "opencode", "anthropic", "anthropic"),],@@ -1443,7 +1443,7 @@ def test_adapter_stream_outcome_commits_after_first_byte(tmp_path: Path) -> Noneadapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)credential_ref = await adapter.provision_credential("custom",- "openai_compatible",+ "openai_chat","upstream-secret","https://api.example.test/v1",)diff --git a/tests/test_opencode_provider_base_url.py b/tests/test_opencode_provider_base_url.pyindex 00e5c6f5a..3ed9a3aa5 100644--- a/tests/test_opencode_provider_base_url.py+++ b/tests/test_opencode_provider_base_url.py@@ -279,7 +279,7 @@ def test_remove_provider_model_keeps_empty_model_tombstone_and_options(tmp_path:assert config["provider"]["deepseek"]["options"]["baseURL"] == "https://api.deepseek.com"-def test_upsert_custom_openai_compatible_provider_writes_opencode_shape(tmp_path: Path) -> None:+def test_upsert_custom_openai_chat_provider_writes_opencode_shape(tmp_path: Path) -> None:upsert_opencode_custom_provider("my-relay","My Relay",diff --git a/ui/src/components/settings/models/contractLocaleKeys.test.ts b/ui/src/components/settings/models/contractLocaleKeys.test.tsindex 40fb1c4db..d61bd36e4 100644--- a/ui/src/components/settings/models/contractLocaleKeys.test.ts+++ b/ui/src/components/settings/models/contractLocaleKeys.test.ts@@ -67,17 +67,13 @@ const lookup = (bundle: unknown, key: string): unknown =>describe('contract i18n key coverage (AC-19)', () => {const keys = contractKeys();- it('reads a non-trivial vocabulary out of the frozen schemas', () => {- // Guards the check itself: a broken path or a renamed contract directory- // would otherwise make every assertion below pass over an empty list.- expect(keys).toContain('models.eligibility.subscription_wrong_client');- expect(keys).toContain('models.eligibility.opencode_api_key_only');- expect(keys).toContain('models.eligibility.consent_required');- // Declared by a `const` in source.schema.json — today ALSO by probe-result's- // enum, which is why the enum-only collector still covered it. Asserting it- // here keeps the coverage from silently depending on that coincidence.- expect(keys).toContain('models.source.error.unclassified');- expect(keys.length).toBeGreaterThanOrEqual(13);+ it('keeps eligibility locale objects equal to the live contract vocabulary', () => {+ const suffixes = keys+ .filter((key) => key.startsWith('models.eligibility.'))+ .map((key) => key.slice('models.eligibility.'.length))+ .sort();+ expect(Object.keys(en.models.eligibility).sort()).toEqual(suffixes);+ expect(Object.keys(zh.models.eligibility).sort()).toEqual(suffixes);});it('collects a key a schema closes with `const`, not only with `enum`', () => {diff --git a/ui/src/components/settings/models/eligibility.test.ts b/ui/src/components/settings/models/eligibility.test.tsindex a32f82cb7..aaabb5aed 100644--- a/ui/src/components/settings/models/eligibility.test.ts+++ b/ui/src/components/settings/models/eligibility.test.ts@@ -96,7 +96,7 @@ describe('eligibleSources', () => {order: ['src_c'],eligibility: [{ source_id: 'src_a', eligible: true, reason_key: null },- { source_id: 'src_b', eligible: false, reason_key: 'models.eligibility.opencode_api_key_only' },+ { source_id: 'src_b', eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' },],});expect(eligibleSources(sources, a).map((s) => s.id)).toEqual(['src_a', 'src_c']);diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsxindex 7bf852f09..87d106812 100644--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx@@ -1,7 +1,7 @@// 添加自定义模型 (frame 08). Supplements a source's supply list with a model the// auto-discovery missed. OpenCode callers show its provider-prefixed identifier;// fixed-backend and source-list callers keep the upstream's raw model id. Persists-// via POST /custom-models; also used to edit an existing custom entry.+// through the Source-model subresource; also used to edit an existing custom entry.import * as React from 'react';import { ChevronDown, Copy, Plus, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -181,7 +181,11 @@ export const AddCustomModelDialog: React.FC<{if (!source || source.kind !== 'api_key' || !trimmedId || saving) return;setSaving(true);try {- await modelsApi.addCustomModel({ source_id: source.id, model_id: trimmedId, display_name: displayName.trim() || null });+ await modelsApi.addCustomModel(source.id, {+ model_id: trimmedId,+ display_name: displayName.trim() || null,+ reasoning_efforts: [],+ });onSaved(identifier);onClose();} catch {diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsxindex 3ceca84be..e1b71e317 100644--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx@@ -44,7 +44,7 @@ const ModelRow: React.FC<{<button type="button" onClick={onToggle} className="flex min-h-11 min-w-0 flex-1 items-center gap-2.5 text-left sm:min-h-0">{/* Never truncate the model id: frame 05r's contract is that the fullidentifier is visible by construction, and custom ids are unbounded- (add_custom_model sets no length limit). break-all wraps instead, so+ (the Source-model create route sets no length limit). break-all wraps instead, soa long id can't overflow the row without hiding its suffix. */}<span className="min-w-0 break-all font-mono text-[14px] font-medium text-foreground">{row.modelId}</span>{row.displayName && <span className="truncate text-[13px] text-muted">{row.displayName}</span>}@@ -250,7 +250,8 @@ export const OpenCodeMenuDrawer: React.FC<{// so saving unchanged can't overwrite it with another source's name.const custom = row.sources.find((s) => s.models.some((m) => m.id === row.modelId && m.provenance === 'manual'));const manual = custom?.models.find((m) => m.id === row.modelId && m.provenance === 'manual');- setEditTarget({ sourceId: (custom ?? row.sources[0]).id, modelId: row.modelId, displayName: manual?.display_name ?? null });+ if (!custom || !manual) return;+ setEditTarget({ sourceId: custom.id, modelId: row.modelId, displayName: manual.display_name ?? null });setCustomOpen(true);}}/>diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex 4bff3fd7d..ed016f92b 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -443,21 +443,14 @@ const OWN_VENDOR: Record<AgentBackend, string | null> = {opencode: null,};-/** §4.4 — server-authoritative eligibility, one row per source. api_key sources- * serve every backend; a subscription is bound to its own client, and the- * hub-held channel additionally needs the flag plus explicit consent. */+/** §4.4 — server-authoritative eligibility, one row per source. API-key Sources+ * serve every backend; a native subscription is bound to its own client. */export function mockEligibility(sources: Source[], backend: AgentBackend): SourceEligibility[] {return sources.map((s): SourceEligibility => {if (s.kind === 'api_key') return { source_id: s.id, eligible: true, reason_key: null };- if (backend === 'opencode') {- return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.opencode_api_key_only' };- }if (s.vendor !== OWN_VENDOR[backend]) {return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' };}- if (s.supply_channel === 'hub' && !(SUBSCRIPTION_HUB_EXPERIMENTAL && s.experimental_consent_at)) {- return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.consent_required' };- }return { source_id: s.id, eligible: true, reason_key: null };});}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex cbfef6b9e..c3bcab207 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -131,7 +131,8 @@ export type ModelsApi = {setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;putMappings(backend: AgentBackend, mappings: AgentMapping[]): Promise<AgentSupply>;putMenu(menu: AgentMenu): Promise<AgentSupply>;- addCustomModel(draft: CustomModelCreate): Promise<Source>;+ addCustomModel(sourceId: string, draft: CustomModelCreate): Promise<Source>;+ updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]): Promise<Source>;deleteCustomModel(sourceId: string, modelId: string): Promise<Source>;scanMigration(): Promise<MigrationScan>;applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;@@ -385,8 +386,9 @@ const liveApi: ModelsApi = {setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),putMappings: (backend, mappings) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mappings`, jsonInit('PUT', { mappings })).then((r) => (r.agent ?? r) as AgentSupply),putMenu: (menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { menu })).then((r) => (r.agent ?? r) as AgentSupply),- addCustomModel: (draft) => call<{ source?: Source } & Source>('/api/models/custom-models', jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),- deleteCustomModel: (sourceId, modelId) => call<{ source?: Source } & Source>('/api/models/custom-models', jsonInit('DELETE', { source_id: sourceId, model_id: modelId })).then((r) => (r.source ?? r) as Source),+ addCustomModel: (sourceId, draft) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models`, jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),+ updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('PATCH', { reasoning_efforts: reasoningEfforts })).then((r) => (r.source ?? r) as Source),+ deleteCustomModel: (sourceId, modelId) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('DELETE', {})).then((r) => (r.source ?? r) as Source),scanMigration: () => call<{ scan?: MigrationScan } & MigrationScan>('/api/models/migration/scan', jsonInit('POST')).then((r) => (r.scan ?? r) as MigrationScan),applyMigration: (itemIds) => call<MigrationApplyResult>('/api/models/migration/apply', jsonInit('POST', { item_ids: itemIds })),listEvents: (limit = 20, before) =>@@ -907,24 +909,35 @@ class MockStore {return delay(structuredClone(agent));}- addCustomModel(draft: CustomModelCreate) {- const source = this.sources.find((s) => s.id === draft.source_id);+ addCustomModel(sourceId: string, draft: CustomModelCreate) {+ const source = this.sources.find((s) => s.id === sourceId);if (!source) throw new ApiCallError('source_not_found');const existing = source.models.find((m) => m.id === draft.model_id);if (existing) {existing.display_name = draft.display_name ?? existing.display_name;existing.provenance = 'manual';+ existing.reasoning_efforts = [...draft.reasoning_efforts];} else {source.models.push({id: draft.model_id,display_name: draft.display_name ?? null,provenance: 'manual',+ reasoning_efforts: [...draft.reasoning_efforts],discovered_at: null,});}return delay(structuredClone(source), 400);}+ updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]) {+ const source = this.sources.find((s) => s.id === sourceId);+ if (!source) throw new ApiCallError('source_not_found');+ const model = source.models.find((item) => item.id === modelId);+ if (!model) throw new ApiCallError('mapping_target_unavailable');+ model.reasoning_efforts = [...reasoningEfforts];+ return delay(structuredClone(source));+ }+deleteCustomModel(sourceId: string, modelId: string) {const source = this.sources.find((s) => s.id === sourceId);if (!source) throw new ApiCallError('source_not_found');@@ -1227,7 +1240,8 @@ const mockApi: ModelsApi = {setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),putMappings: (backend, mappings) => mockStore.putMappings(backend, mappings),putMenu: (menu) => mockStore.putMenu(menu),- addCustomModel: (draft) => mockStore.addCustomModel(draft),+ addCustomModel: (sourceId, draft) => mockStore.addCustomModel(sourceId, draft),+ updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => mockStore.updateModelReasoningEfforts(sourceId, modelId, reasoningEfforts),deleteCustomModel: (sourceId, modelId) => mockStore.deleteCustomModel(sourceId, modelId),scanMigration: () => mockStore.scanMigration(),applyMigration: (itemIds) => mockStore.applyMigration(itemIds),diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 99f96ec91..63c0302bb 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -77,15 +77,13 @@ export type SuppliedModel = {id: string;display_name?: string | null;provenance: ModelProvenance;+ reasoning_efforts?: string[];discovered_at?: string | null;};export type Source = {id: string;- /** v3, immutable once written: the `follow` policy recommends api_key sources- * by creation time ascending, so the rule needs a persisted stamp (the- * sources array itself is explicitly unordered). May be null on rows- * persisted before the field existed; `id` ascending is the tie-breaker. */+ /** Source creation time; ordinary audit/display metadata only. */created_at?: string | null;/** Latest successful full model discovery for this source. null means the* source predates the field or has no known successful discovery. */@@ -145,9 +143,7 @@ export type SourcePolicy = 'follow' | 'custom';/** Why a source cannot serve this backend at all. A closed vocabulary — a new* cause ships its enum member and its locale copy in the same change. */export type EligibilityReasonKey =- | 'models.eligibility.subscription_wrong_client'- | 'models.eligibility.opencode_api_key_only'- | 'models.eligibility.consent_required';+ 'models.eligibility.subscription_wrong_client';/** Why a source that MAY serve this backend still cannot be launched on this* machine. Independent of eligibility and of the source's own health: the@@ -576,12 +572,12 @@ export type SourceRepaired = {interrupted_pairs: SupplyGap[];};-/** POST /api/models/custom-models — appends a manual-provenance model entry to- * a source's supply list (frame 08). */+/** POST /api/models/sources/<source_id>/models — appends a user-authored model+ * entry to a Source inventory (frame 08). */export type CustomModelCreate = {- source_id: string;model_id: string;display_name?: string | null;+ reasoning_efforts: string[];};/** POST /api/models/migration/apply response. */diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f1fa638a1..ca1e7d908 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1201,9 +1201,7 @@},"models": {"eligibility": {- "subscription_wrong_client": "{{vendor}} subscriptions only work in {{backend}}",- "opencode_api_key_only": "OpenCode can only be supplied by API-key sources",- "consent_required": "Needs your consent for experimental hub supply first"+ "subscription_wrong_client": "{{vendor}} subscriptions only work in {{backend}}"},"oauth": {"upstream_failed": "The vendor didn't complete this sign-in, please retry",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e617ff60f..632a28396 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1201,9 +1201,7 @@},"models": {"eligibility": {- "subscription_wrong_client": "{{vendor}} 订阅仅可供 {{backend}} 使用",- "opencode_api_key_only": "OpenCode 只能由 API Key 来源供给",- "consent_required": "需要先同意实验性中枢供给"+ "subscription_wrong_client": "{{vendor}} 订阅仅可供 {{backend}} 使用"},"oauth": {"upstream_failed": "厂商没有完成这次登录,请重试",diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 07bb5ae4a..54775d394 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -128,13 +128,33 @@ class ModelHubRemoteService:async def set_opencode_menu(self, menu: object) -> dict:return await _rpc("set_opencode_menu", {"menu": menu})- async def add_custom_model(self, payload: dict) -> dict:- return await _rpc("add_custom_model", {"model": payload})+ async def add_custom_model(self, source_id: object, payload: dict) -> dict:+ return await _rpc(+ "add_custom_model",+ {"source_id": source_id, "model": payload},+ )- async def delete_custom_model(self, source_id: object, model_id: object) -> dict:+ async def update_model_reasoning_efforts(+ self,+ source_id: object,+ model_id: object,+ payload: dict,+ ) -> dict:+ return await _rpc(+ "update_model_reasoning_efforts",+ {"source_id": source_id, "model_id": model_id, "model": payload},+ )++ async def delete_custom_model(+ self,+ source_id: object,+ model_id: object,+ *,+ force: bool = False,+ ) -> dict:return await _rpc("delete_custom_model",- {"source_id": source_id, "model_id": model_id},+ {"source_id": source_id, "model_id": model_id, "force": force},)def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 4addb443c..e31ebe259 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -524,7 +524,7 @@ def _endpoint_for_protocol(protocol: str) -> str:return "/v1/messages"if protocol == "openai_responses":return "/v1/responses"- if protocol in {"openai_chat", "openai_compatible"}:+ if protocol == "openai_chat":return "/v1/chat/completions"raise ValueError("unsupported source protocol")diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex b47444ab0..75fe5025c 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -90,7 +90,7 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineSentry["models"] = modelspayload.setdefault("codex-api-key", []).append(entry)return- if source.protocol in {"openai_chat", "openai_compatible"}:+ if source.protocol == "openai_chat":base_url = source.base_urlif not base_url and source.vendor == "openai":base_url = "https://api.openai.com/v1"diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 55d7adef4..77e80ca0f 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -16,7 +16,7 @@ from urllib.parse import urlparse_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")-_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "openai_compatible"}+_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat"}class EngineStateError(RuntimeError):@@ -107,7 +107,7 @@ class EngineStateStore:value: str,*,vendor: str = "custom",- protocol: str = "openai_compatible",+ protocol: str = "openai_chat",base_url: str | None = None,) -> str:if not isinstance(value, str) or not value:@@ -523,5 +523,5 @@ def _validate_source_target(vendor: str, protocol: str, base_url: str | None) ->raise EngineStateError("Anthropic-compatible source requires a base URL")if protocol == "openai_responses" and base_url is None and vendor not in {"openai", "codex"}:raise EngineStateError("Responses API source requires a base URL")- if protocol in {"openai_chat", "openai_compatible"} and base_url is None and vendor != "openai":+ if protocol == "openai_chat" and base_url is None and vendor != "openai":raise EngineStateError("OpenAI-compatible source requires a base URL")diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 777629d7b..2f5b454a6 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3263,26 +3263,52 @@ async def model_hub_opencode_menu_put():return _model_hub_error(exc)[email protected]("/api/models/custom-models", methods=["POST"])-async def model_hub_custom_models_post():[email protected]("/api/models/sources/<source_id>/models", methods=["POST"])+async def model_hub_source_models_post(source_id):from core.handlers.model_hub import ModelHubErrortry:source = await _model_hub_service().add_custom_model(- _model_hub_json_object("source_not_found", status=404)+ source_id,+ _model_hub_json_object("mapping_target_unavailable"))return _model_hub_success(source=source), 201except ModelHubError as exc:return _model_hub_error(exc)[email protected]("/api/models/custom-models", methods=["DELETE"])-async def model_hub_custom_models_delete():+ "/api/models/sources/<source_id>/models/<path:model_id>",+ methods=["PATCH"],+)+async def model_hub_source_models_patch(source_id, model_id):+ from core.handlers.model_hub import ModelHubError++ try:+ source = await _model_hub_service().update_model_reasoning_efforts(+ source_id,+ model_id,+ _model_hub_json_object("mapping_target_unavailable"),+ )+ return _model_hub_success(source=source)+ except ModelHubError as exc:+ return _model_hub_error(exc)+++ "/api/models/sources/<source_id>/models/<path:model_id>",+ methods=["DELETE"],+)+async def model_hub_source_models_delete(source_id, model_id):from core.handlers.model_hub import ModelHubErrortry:payload = _model_hub_json_object("mapping_target_unavailable")- source = await _model_hub_service().delete_custom_model(payload.get("source_id"), payload.get("model_id"))+ source = await _model_hub_service().delete_custom_model(+ source_id,+ model_id,+ force=payload.get("force") is True,+ )return _model_hub_success(source=source)except ModelHubError as exc:return _model_hub_error(exc)