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): spec v2.0 + contracts v2 — per-agent source order (#1081)
Call White251f8e7b2061
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 5119b6949..05023b21f 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,13 +1,33 @@# Model Hub — Interface Contracts-Status: **FROZEN v1** · 2026-07-23 10:45 (+08:00) · change only via orchestrator-Derived from: signed spec (`../model-hub.md`), implementation plan-(`../model-hub-implementation.md`), spike S1 engine survey-(branch `spike/model-hub-engine`, `docs/plans/model-hub-engine-survey.md`),-spike S2 ToS review (branch `spike/model-hub-tos`,-`docs/plans/model-hub-tos-review.md`).+Status: **FROZEN v2** · 2026-07-29 · change only via orchestrator+Supersedes FROZEN v1 (2026-07-23 10:45) outright — no back-compat, no migration shims.+Derived from: spec v2 (`../model-hub.md`), implementation plan+(`../model-hub-implementation.md`, v1 — a v2 lane plan is cut separately),+spike S1 engine survey (`docs/plans/model-hub-engine-survey.md`),+spike S2 ToS review (`docs/plans/model-hub-tos-review.md`).-## Resolved decision (owner, 2026-07-23 10:33)+## 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`).++## 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@@ -19,35 +39,231 @@ 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, authoritative ordered-priority, and a standalone managed-dependency manifest/status contract.+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-- After the owner decision, the orchestrator commits these files with message- `docs(model-hub): freeze interface contracts v1` 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`.+- The orchestrator commits these files with message+ `docs(model-hub): freeze interface contracts v2` 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`.- Contract tests (implementation plan §5) validate both directions againstthese schemas.+## Required-vs-optional discipline (v2)++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` /+ `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 an alert the user silently never+ gets); `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 push. 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+ a push obligation and no representable 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, 「Agent」 in routing is a named+ Vibe Agent, and the two coincide only because the default Agents are named after+ their backends — so §4.5's recipient rule now expands in two hops, backend → enabled+ Agents on it → scopes selecting those Agents.+- **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.++| # | Vocabulary | Home | Mirrors | Rule |+| --- | --- | --- | --- | --- |+| M1 | the ten `detail_key` values (5 cooldown + 4 needs_action + 1 error) | `source.schema.json` → `state`, across all three status branches — the `error` key is pinned as a `const`, which counts | `probe-result.schema.json` → `error` (minus null), and the `examples` list on the home field itself | `equality` |+| M2 | source status → chain health | `source.schema.json` → `state.status` | `agent-chain.schema.json` → `chain[].health` | `projection` |+| M3 | attempt-failure causes | `resolution-event.schema.json` → `reason` | `turn-provenance.schema.json` → `failed_attempts[].reason` | `partition` |+| M4 | non-self-healing cause ↔ blocking `detail_key` | `resolution-event.schema.json` → `reason` description | `source.schema.json` → the `needs_action` and `error` `detail_key` branches | `none` |+| M5 | the supply-state taxonomy | `agent-supply.schema.json` → `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` → `agent` | `equality` |+| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; `turn-provenance.schema.json` → `failed_attempts[].channel`, `served.channel`, `terminal_error.channel` | `equality` |+| N1 | source recommendation rule | `agent-supply.schema.json` → `sources.policy` | — | `none` |++What the rules mean, and why three of them are not equality:++- **`equality`** — the sets are identical, in both directions. M6 carries one declared+ superset: `resolution-event.agent` is the home set plus `system`, the emitter for+ events no backend produced, which expands to no Agent and therefore to no recipient.+ 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.+- **`none`** — registered as non-comparable, with the reason. M4 is a BIJECTION, not a+ set identity: a permuted pairing has identical sets, so it is checked against the+ mapping documented in the home field's own description instead. N1 is a pointer to a+ rule (spec §4.2 plus the absent-`created_at` half-rule), not a shared value set —+ there is nothing to compare. A row with neither rule nor reason is itself a failure.+## Files| File | Consumers || --- | --- |-| `source.schema.json` | L2 API, L4 UI |-| `priority.schema.json` | L2, L4 |-| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI |-| `resolution-event.schema.json` | L2 (adapter-owned), L4 UI, L1 adapter |+| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action` (+ mandatory `detail_key` there, enforced by an `if/then`), +immutable `created_at` (the sort key 跟随推荐 needs) with its **null placement now normative (07-29)** — absent sorts before every stamp, constant-epoch backfill, because a tie-break orders equals and cannot order null against a timestamp — +optional `usage.projected_exhaust_at`. No ordering field, ever. |+| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. **v2 owns the spend order:** +`sources` {policy, order, eligibility}, +`supply_status` (incl. `waiting`), +`model_supply`, +top-level `selected_model_id`. **07-29 round 3:** the selection was hoisted out of `current` (where round 2 had it as `menu_model_id`) because `current` is null in `waiting`/`interrupted` — the two states where the drawer most needs to name the model. A persisted user choice must not inherit the nullability of a momentary fact. `policy` also stopped paraphrasing the 跟随推荐 rule and now points at spec §4.2. **+`selected_by_agent`** names the GRAIN of that selection — which Vibe Agent's `model` produced it, null when it came from `agents.<backend>.default_model` — because N Agents can share one backend with different models, so `selected_model_id` on its own answers for nobody in particular. It names a grain and does NOT reverse the frozen per-Agent ordering ruling. It is required on every hub-mode response at the API boundary (`api.md`) rather than by `required` here, for the byte-faithful reason below. |+| `agent-chain.schema.json` | **New in v2.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain — cooling members included with `runnable: false` — and per-item `health` only; per-agent role is positional, never a copied `active`/`standby`. **+`supply_state` (07-29):** the three-class taxonomy at the (agent, model) grain, and the ONE field every model-scoped consumer reads (chain drill-in, the probe's `supply` sibling, turn record) so none of them consults the agent rollup for a model it does not describe. Its predicate is not restated here or there — spec §4.5 owns it, after round 3 found two files paraphrasing it into a different rule. |+| `probe-result.schema.json` | **New in v2.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. **07-29 round 3:** `reachable` now drives conditionals in both directions, so a reachable probe cannot carry null ids or an error; and `probe_no_candidate` moved its structured half out of `detail` into a typed `supply` sibling — the shipped clients declare `detail?: string`, so the object would have rendered as `[object Object]`. It reads the requested model's `supply_state`, never `supply_status`. |+| `turn-provenance.schema.json` | **New in v2.** L2 API, L3 (writes it per turn), IM surfaces (per-turn detail). Gives spec §4.5's turn-provenance promise an actual read contract. **Shape ruling 07-29:** top-level `outcome` + `failed_attempts` + one slot for the terminating attempt; the empty attempt list is legal because a turn that never touched a source is exactly the one users inspect, and the terminating attempt lives in one place so contradictory records cannot be written at all. **Round 3 added the fourth outcome:** `failed_terminal` + a `terminal_error` slot, for §4.3's non-fallback errors (param/protocol/tool-compat, and anything after the first streamed token). Without it such a turn fit no outcome, and filing it as `exhausted` would have forced a fallback reason onto it — blaming the user's account for a malformed request. |+| `priority.schema.json` | **Removed in contract v2 — v1 tombstone, do not implement.** Nothing in v2 reads it. Kept only because dormant v1 code still emits the shape and `tests/test_model_hub_api.py` still validates against it; the lane that removes `PUT /api/models/priority` and `ModelHubConfig.priority_order` deletes this file and replaces that one assertion with an inline shape check. |+| `resolution-event.schema.json` | L2 (adapter-owned), L4 UI, L1 adapter. **v2:** +`severity` (notification tier), +`kind: needs_action`, +`kind: supply_interrupted` — the only AGENT-scoped kind, for a chain that empties without any source changing state (last enabled source removed). Its shape is enforced by conditionals, not prose: `severity` is `action_required`, source endpoints are null, and its three reasons are unusable with any other kind. Worked payload in `api.md` (a schema example would need `severity`, which the shipped emitter has no field for). **Round 5 (07-29):** `severity` decides WHETHER to interrupt, never WHOM — there is deliberately no recipient, channel, platform, or audience field, and recipients resolve at push time from the event's `agent` against the live routing table (spec §4.5 → 「Who receives an action-required push」). Carrying them here would freeze a routing snapshot into an append-only feed; the feed is a record of what happened to supply, not an outbox. || `oauth-flow.schema.json` | L2, L4 UI, L1 engine adapter |-| `migration-scan.schema.json` | L6, L5 UI |-| `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). |-| `api.md` | all |-| `opencode-overlay.md` | L3, L7 (identifier-stability tests) |-| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). Dual-copy rule: both lanes copy VERBATIM to `core/handlers/model_hub/adapter.py` in their branches — byte-identical, merge is a no-op. Added 07-23 10:55 after L1 raised the ordering race; **v1.1 07-23 11:05**: +OAuth surface with deterministic source binding (`start_oauth(source_id)` → success carries `credential_ref`), +`allowed_origins`/`invoke(origin)`/`OriginNotAllowedError` (both from L1 review findings). |+| `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. **v2:** `PUT /api/models/priority` removed; +`PUT /api/models/agents/<backend>/sources`, +chain query, +probe, +`adopted_by`. **07-29 round 3:** +`PUT /api/models/sources/<id>/credential` and +`POST /api/models/sources/<id>/reauth` — spec §4.5 promised the `needs_action` card a one-tap 「换 Key / 重新登录」 and there was no route to send that tap to, only create-a-new-source, which loses the source's `created_at` and its slot in every order. Recovery must not be a reorder. Also: the `detail`-is-a-string rule made normative, and the DELETE guard re-scoped to (backend, model) — a backend with four enabled sources still starves a model supplied by only the one being deleted. |+| `opencode-overlay.md` | L3, L7 (identifier-stability tests). Identifiers stay stable across per-agent reordering — a source is never encoded into the provider segment. |+| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). Dual-copy rule: both lanes copy VERBATIM to `core/handlers/model_hub/adapter.py` in their branches — byte-identical, merge is a no-op. Added 07-23 10:55 after L1 raised the ordering race; **v1.1 07-23 11:05**: +OAuth surface with deterministic source binding (`start_oauth(source_id)` → success carries `credential_ref`), +`allowed_origins`/`invoke(origin)`/`OriginNotAllowedError` (both from L1 review findings). Unchanged by v2: candidate walking and error classification stay Python-side, so moving ordering from global to per-agent needs no adapter or engine change (spec §8). |## Security invariants (from S1/S2, non-negotiable)@@ -59,7 +275,15 @@ priority, and a standalone managed-dependency manifest/status contract.computed once at provisioning, never re-derivable) exist precisely sothe UI never needs anything stronger.2. The engine's own usage feed stays disabled; events originate from our- adapter (S1 gap ②).+ 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: subscriptionsources are never eligible for agents outside their sanctioned client- (S2; server-side enforcement exists for Claude anyway).+ (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).diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonnew file mode 100644index 000000000..2fef2a0ba--- /dev/null+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -0,0 +1,231 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/agent-chain.schema.json",+ "title": "AgentChain",+ "description": "v2 (2026-07-29): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by 'this source can supply this model, mapping applied'. For open menus the requested identifier carries a provider segment, and the vendor predicate is part of that filter: a `zhipuai/…` request is supplied only by zhipuai sources, never by whatever `custom/…` source happens to advertise the same bare model id (spec §4.3 step 2; the shipped resolver already enforces it). Deliberately NOT filtered by retry-readiness: a cooling source stays in the chain, dimmed, because the user needs to see it (frame V6 04). The RUNNABLE candidate list of spec §4.3 step 2 is this chain further filtered to `runnable: true`, evaluated per turn — so the two are one definition with one extra filter, not two independent lists. Closes v1's honesty gap: v1 showed one order per agent while N different chains ran underneath it, one per model. Read-only projection, computed per request, never persisted.",+ "type": "object",+ "required": ["contract_version", "backend", "model_id", "chain", "supply_state"],+ "additionalProperties": false,+ "properties": {+ "contract_version": { "const": 2 },+ "backend": { "enum": ["claude", "codex", "opencode"] },+ "model_id": {+ "type": "string",+ "description": "The CALLER-FACING menu identifier — the built-in id for fixed-menu backends, the prefixed vendor/model identifier for open menus (never the bare resolved upstream id; see api.md → identifier rules). Mapping is applied inside; the caller does not pre-resolve it."+ },+ "chain": {+ "type": "array",+ "description": "Ordered, position 0 = highest in this backend's order. The next turn uses the FIRST item with `runnable: true`; role is positional and is never stored per source (a source can be serving one agent while merely standing by for another, so `active`/`standby` are not per-chain facts). Rendered with the same order-chip visuals as the agent row (frame V6 01). An EMPTY array is a first-class answer, not an error: the model is in the menu but no eligible source in this backend's order can supply it at all, so the UI flags 无来源可供 (spec §4.6) rather than offering a checkbox that silently fails. A non-empty chain with no `runnable` item is a different thing — `supply_state` on this object says which, at this model's grain. TWO STRUCTURAL INVARIANTS the schema cannot state, named here so they are enforced somewhere rather than assumed everywhere (07-29, review round 5): (1) `source_id` is UNIQUE across the chain — this is a FILTER over `sources.order`, which is itself `uniqueItems`, so a repeat means the projection double-counted; the damage is not cosmetic, since `chain.length` is what `AgentSupply.model_supply.chain_length` reports and 「2 个来源可供」 over one duplicated account is a false promise of redundancy, and a duplicate at the head would also make the resolver's fill-first retry the same cooling account twice before moving on. (2) The chain PRESERVES `sources.order` — a projection that filters must not reorder, or position 0 stops meaning 'spend first' and the drill-in shows a different order than the agent row it drilled in from. Draft-07 expresses neither: `uniqueItems` compares whole items, so two entries for one source with different `health` values are 'unique' to it, and no keyword can reference the ordering of another document. Both are therefore mechanical guards on the serializer (api.md → Serializer completeness), not schema keywords.",+ "items": {+ "type": "object",+ "required": ["source_id", "via_mapping", "resolved_model_id", "health", "runnable", "retry_at"],+ "additionalProperties": false,+ "allOf": [+ {+ "$comment": "v2 (07-29, review round 4): health ⇒ runnability, as a conditional per health value. Round 3 stated the rule three times in prose — here, in spec §4.3 step 2's runnability filter, and in source.schema.json → retry_at — and enforced it nowhere, so an assembler regression could hand the resolver a `needs_action` source flagged `runnable: true` and pass contract validation. That is the one defect in this file that costs a real turn: the consumer takes the first runnable item, so a known-dead source at the head of the chain burns the turn AND suppresses the `interrupted` state that would have told the user to fix it. `needs_action` and `error` are pinned false and stampless; neither recovers unattended, so a `retry_at` on either would promise a recovery that is never coming.",+ "if": {+ "properties": { "health": { "enum": ["needs_action", "error"] } },+ "required": ["health"]+ },+ "then": {+ "properties": {+ "runnable": { "const": false },+ "retry_at": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): `healthy` is unconditionally runnable — there is no other filter left at this point in the pipeline (eligibility and capability are already applied to build the chain), so a healthy member flagged unrunnable would hide supply the user owns. Stampless for the same reason as above: nothing is being waited for.",+ "if": {+ "properties": { "health": { "const": "healthy" } },+ "required": ["health"]+ },+ "then": {+ "properties": {+ "runnable": { "const": true },+ "retry_at": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): `cooldown` is the only health value with a stamp, and it always has one — mirroring source.schema.json → state.retry_at, where `cooldown` is defined as the self-healing status whose recovery time is known. `runnable` is deliberately left free here alone: it is exactly `retry_at` already in the past (the resolver retries a recovered source rather than waiting for a state flip), and a schema cannot compare a timestamp to now.",+ "if": {+ "properties": { "health": { "const": "cooldown" } },+ "required": ["health"]+ },+ "then": {+ "required": ["retry_at"],+ "properties": {+ "retry_at": { "type": "string" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): `via_mapping: true` means a mapping REWROTE the requested id, so there is by construction a different id to report; a null here would say 'mapped to itself', which is what `via_mapping: false` already says.",+ "if": {+ "properties": { "via_mapping": { "const": true } },+ "required": ["via_mapping"]+ },+ "then": {+ "properties": {+ "resolved_model_id": { "type": "string" }+ }+ }+ }+ ],+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "via_mapping": {+ "type": "boolean",+ "description": "true when this source supplies the model only because a per-agent mapping rewrote the requested id (spec §4.3 step 1). UI marks the chip 经映射."+ },+ "resolved_model_id": {+ "type": ["string", "null"],+ "description": "The id actually sent upstream (e.g. glm-5.2 for a requested claude-opus-4-6); null only when it is byte-identical to `model_id`. For open menus that never happens — the request is prefixed and the upstream id is bare — so this is non-null for every opencode chain, pinned by the conditional at the end of this file. Also non-null whenever `via_mapping` is true, since a mapping by definition produced a different id."+ },+ "health": {+ "enum": ["healthy", "cooldown", "needs_action", "error"],+ "description": "Source-GLOBAL health, mirrored from source.schema.json → state.status so the chip can dim / gold-dot / flag without a second round trip. Global by design: quota and reachability belong to the account. Note this carries only the health half of that enum — `active`/`standby` are consumption facts and are expressed here by position + `runnable`, never copied per agent."+ },+ "runnable": {+ "type": "boolean",+ "description": "Whether this candidate is usable right now: health `healthy`, OR health `cooldown` whose `retry_at` has already passed — the shipped resolver retries such a source rather than waiting for a state flip, so a contract reading `runnable == (health == healthy)` would understate what the next turn will do. ALWAYS false for `needs_action` and for `error`: the first cannot recover unattended, the second is a source already known to be broken, and retrying either burns a turn. Still shown in the chain, dimmed, in every one of those cases. This is exactly the retry-readiness filter of spec §4.3 step 2."+ },+ "retry_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When `runnable` flips back true unattended. Non-null only for health == cooldown; null for needs_action and for error, because neither recovers without the user. A cooldown item whose `retry_at` is already in the past is `runnable: true` with `retry_at` retained — the stamp records when it became eligible again, it is not a promise about the future."+ }+ }+ }+ },+ "supply_state": {+ "enum": ["ok", "waiting", "interrupted"],+ "description": "v2 (07-29, review round 2): the MODEL-SCOPED supply state — the same three-class taxonomy as agent-supply `supply_status`, evaluated for THIS (agent, model) pair instead of the backend as a whole. The predicate is spec §4.5's, verbatim, and is stated once there: `ok` = at least one `runnable: true` item. Otherwise the chain is blocked, and the split is on whether the user owes an action — `interrupted` = the chain is empty, or AT LEAST ONE blocker needs the user (`needs_action` / `error`) — 「需处理」; `waiting` = chain non-empty and EVERY blocker is a cooldown, so it recovers unattended at the earliest `retry_at` — 「稍等即可」. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which left the mixed chain — one cooling source plus one revoked key — matching neither class, so the (agent, model) grain silently disagreed with `supply_status` (which had 'at least one' all along) and suppressed the action-required push for exactly the case that needs it most. `interrupted` is the OR-branch and `waiting` the AND-branch; in that order the two are total over every blocked chain, and a chain that needs the user is never reported as one that heals itself. Exists because the agent-level rollup answers only for the backend's CURRENT model: a user can inspect, probe, or request a model that is starved while the selected one is perfectly healthy, and consulting the rollup there reports `ok` for a chain that cannot run. Every consumer of a model-scoped answer reads this one field — the chain drill-in, `probe_no_candidate`'s typed `supply` sibling (api.md), and TurnProvenance `model_supply_state` — so 「稍等即可」 vs 「需处理」 has exactly one definition per grain."+ }+ },+ "allOf": [+ {+ "$comment": "v2 (07-29, review round 4): `supply_state` ⇔ the contents of `chain`, in both directions. The predicate was stated once in spec §4.5 and quoted here, but nothing tied the rollup to the array it summarises, so `supply_state: \"ok\"` validated over a chain with no runnable member — the payload asserting 'this model is fine' while carrying the evidence that it is not. `ok` ⇒ at least one runnable member; the two blocked values ⇒ none.",+ "if": { "properties": { "supply_state": { "const": "ok" } }, "required": ["supply_state"] },+ "then": {+ "properties": {+ "chain": {+ "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] }+ }+ }+ }+ },+ {+ "if": { "properties": { "supply_state": { "enum": ["waiting", "interrupted"] } }, "required": ["supply_state"] },+ "then": {+ "properties": {+ "chain": {+ "not": { "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] } }+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): and the waiting/interrupted split, which is where §4.5's asymmetry becomes checkable. `waiting` is the AND-branch — non-empty chain, EVERY blocker a cooldown — so a chain holding one revoked key cannot be reported as one that heals itself, which is exactly the suppressed action_required push the round-3 correction was about. `interrupted` is the OR-branch: empty chain, or at least one member the user has to fix. In that order the two are total over every blocked chain.",+ "if": { "properties": { "supply_state": { "const": "waiting" } }, "required": ["supply_state"] },+ "then": {+ "properties": {+ "chain": {+ "minItems": 1,+ "not": { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } }+ }+ }+ }+ },+ {+ "if": { "properties": { "supply_state": { "const": "interrupted" } }, "required": ["supply_state"] },+ "then": {+ "properties": {+ "chain": {+ "anyOf": [+ { "maxItems": 0 },+ { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } }+ ]+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): open menus resolve a PREFIXED request to a BARE upstream id (api.md → identifier rules), so the two are never byte-equal and the 'null when it equals model_id' shorthand can never apply for opencode. Pinned rather than left to prose because a null here would be read as 'sent zhipuai/glm-5.2 upstream', which is the silent-miss this file's identifier rules exist to prevent.",+ "if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },+ "then": {+ "properties": {+ "chain": { "items": { "properties": { "resolved_model_id": { "type": "string" } } } }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): the converse of the item-level `via_mapping: true ⇒ resolved_model_id: string` rule, which completes it into a biconditional — but ONLY for fixed menus, and the scoping is the substance of the finding rather than a caveat on it. `resolved_model_id` is documented as 'null only when byte-identical to model_id', and for claude/codex the menu identifier IS the upstream id, so a mapping is the only thing that can make them differ (spec §4.3 step 1 is the sole rewrite mechanism at this grain). A fixed-menu item reporting `via_mapping: false` with a non-null resolved id therefore claims a rewrite that nothing performed, and the UI marks that chip 经映射 off `via_mapping` while rendering 实际跑的模型 off this field — so the two disagreeing puts a different model in the chip and in the label. The blanket converse would be WRONG and is deliberately not written: opencode resolves a prefixed request to a bare upstream id (`zhipuai/glm-5.2` → `glm-5.2`) with no mapping involved, so `via_mapping: false` with a non-null resolved id is the normal, required shape there — already pinned by the member above. Stated per backend family, the two members leave no combination undefined: open menus always carry a resolved id, fixed menus carry one exactly when a mapping produced it.",+ "if": { "properties": { "backend": { "enum": ["claude", "codex"] } }, "required": ["backend"] },+ "then": {+ "properties": {+ "chain": {+ "items": {+ "allOf": [+ {+ "if": { "properties": { "via_mapping": { "const": false } }, "required": ["via_mapping"] },+ "then": { "properties": { "resolved_model_id": { "type": "null" } } }+ }+ ]+ }+ }+ }+ }+ }+ ],+ "examples": [+ {+ "contract_version": 2,+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "chain": [+ {+ "source_id": "src_claudepro1",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "cooldown",+ "runnable": false,+ "retry_at": "2026-07-29T04:00:00Z"+ },+ {+ "source_id": "src_anthkey01",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "healthy",+ "runnable": true,+ "retry_at": null+ }+ ],+ "supply_state": "ok"+ },+ {+ "contract_version": 2,+ "backend": "claude",+ "model_id": "claude-haiku-4-5",+ "chain": [],+ "supply_state": "interrupted"+ },+ {+ "contract_version": 2,+ "backend": "codex",+ "model_id": "gpt-5.3-codex",+ "chain": [+ {+ "source_id": "src_codexplus1",+ "via_mapping": false,+ "resolved_model_id": null,+ "health": "cooldown",+ "runnable": false,+ "retry_at": "2026-07-29T09:15:00Z"+ }+ ],+ "supply_state": "waiting"+ }+ ]+}diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 14abde3db..8ac0205d4 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 status & configuration (spec §4.3, frames 01r/04/05r).",+ "description": "Per-backend supply strategy & status (spec §4.2, frames V6 01–04 / M01–M02). v2: this record OWNS the spend order. Ordering is a consumption property — each backend keeps its own ordered subset of the sources it is eligible for. There is no global priority list.","type": "object","required": ["backend", "mode", "menu_kind"],"additionalProperties": false,@@ -13,20 +13,99 @@"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."},"menu_kind": { "enum": ["fixed", "open"] },+ "selected_by_agent": {+ "type": ["string", "null"],+ "description": "v2 (07-29, review round 4): the Vibe Agent whose `model` produced `selected_model_id`, by name — or null when the value came from the backend default (`agents.<backend>.default_model`) because that Agent pins no model. WHY THIS EXISTS: model selection does not live at the backend grain. Several enabled Vibe Agents can share one backend and each carry their own `model` (SQLite `agents.backend` + `agents.model`; on this machine today three enabled Agents share backend `claude` with three different models), and routing follows the selected Vibe Agent, not the backend (AGENTS.md → Agent routing model). The shipped projection already resolves ONE Agent — the global default, and only if its backend matches (`core/controller.py::default_vibe_agent_model`) — so this record has always answered for exactly one route while looking like it answered for the backend. Naming the Agent makes that scope readable instead of implied: a caller can see whose model it is, and knows it is not a claim about every turn on this backend. A per-Agent answer for any OTHER Agent is obtained the way every other model-scoped question already is — by passing that Agent's model explicitly to `GET /chain?model=` or `POST /probe {model}` (api.md → grain of the agent record). Derived, never persisted; null while mode=direct.",+ "examples": ["pm", "evm-contract-audit"]+ },+ "selected_model_id": {+ "type": ["string", "null"],+ "description": "v2 (07-29, review round 3): THE SELECTED MODEL of the route named by `selected_by_agent`, as the caller-facing MENU identifier — the built-in id for fixed menus, the prefixed vendor/model id for open menus. NOT a backend-wide fact (grain corrected 07-29, review round 4): it is the routed Vibe Agent's `model`, falling back to the backend default when that Agent pins none, and a different enabled Agent on the same backend can request a different model on its very next turn. Every projection below that depends on a model — `current`, `supply_status`, and the probe's default — therefore inherits that scope and answers for this route alone. Hoisted out of `current` in round 3, where round 2 had put it as `menu_model_id`. The bug was not merely that the selection was nested: `current` is null whenever nothing is runnable (`waiting` / `interrupted`), so the selection vanished from the payload in exactly the two states where the UI needs it most — 「当前无可用来源」 has to name the model it is talking about, the chain drill-in has to query one, and the probe has to default to one. A client would have had to remember the last non-null `current` and hope, or issue a second call. The two fields answer different questions and have different lifetimes: this one is a persisted user CHOICE that survives every supply state, while `current` is a momentary fact about the next turn. Nesting a choice inside a fact made the choice inherit the fact's nullability. null only when mode=direct (no hub selection exists). OPTIONAL here / required at the API boundary once the serializer emits it (README → required-vs-optional). Absent from this file's `examples` on purpose — they round-trip byte-faithfully through the shipped v1 serializer, which has no such field; the worked v2 payload including the `current: null` case lives in api.md.",+ "examples": ["claude-opus-4-6", "zhipuai/glm-5.2"]+ },"current": {"type": ["object", "null"],- "description": "What the next turn would use (frame 01r composite pill). null when mode=direct.",+ "description": "What the next turn of THIS ROUTE would use (frame V6 01 supply row) — i.e. the first runnable candidate in this backend's chain for `selected_model_id`, which is the model of the Agent named by `selected_by_agent`. Inherits that grain: a different enabled Vibe Agent on the same backend requesting a different model has a different chain, and this field does not describe it (round 4). NULL IN THREE CASES, not one: (a) mode=direct; (b) `supply_status: \"waiting\"` — every candidate is cooling; (c) `supply_status: \"interrupted\"` — no candidate can recover unattended. In (b) and (c) the serializer MUST emit null rather than the last-used source: a stale `current` would render 使用中 for a source that will not be called, which is exactly the lie the taxonomy exists to prevent. Non-null ⇒ `supply_status` is ok or degraded. Carries only facts about that candidate — the selection itself is `selected_model_id`, one level up, because it outlives every one of these three nulls.","required": ["model_id", "source_id", "channel"],"additionalProperties": false,"properties": {- "model_id": { "type": "string" },+ "model_id": {+ "type": "string",+ "description": "The RESOLVED upstream model id, mapping applied — what actually gets sent (e.g. `glm-5.2`). A property of this attempt, not of the selection, which is why it stays here while the selection moved out. NOT a valid input to the chain query or the probe: for open-menu backends the caller-facing identifier is prefixed (`zhipuai/glm-5.2`), so passing this value through would miss. Use the top-level `selected_model_id` for that. Equal to `selected_model_id` whenever no mapping applied and the menu is fixed — the two differing is the 「我选的模型」 vs 「实际跑的模型」 distinction the UI surfaces, so they are never collapsed."+ },"source_id": { "type": "string" },"channel": { "enum": ["native_cli", "hub"] }}},+ "sources": {+ "type": ["object", "null"],+ "description": "v2 (2026-07-29): this backend's source order — the ordered SUBSET of sources it spends, plus the policy that governs the order (spec §4.2). Replaces v1's global priority.schema.json. Optional in this schema only because the shipped v1 serializer predates it; it becomes REQUIRED at the API boundary in the serializer PR that lands per-agent ordering (README → Required-vs-optional). null while mode=direct.",+ "required": ["policy", "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.",+ "items": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "uniqueItems": true+ },+ "eligibility": {+ "type": ["array", "null"],+ "description": "v2: server-authoritative eligibility, one entry per existing source (spec §4.4). Exists so the UI chokepoint isSourceEligible (ui/src/components/settings/models/menus/identifiers.ts, self-documented as ESCALATED) becomes a pure projection instead of a second hand-written copy of the compatibility matrix. Drives the 未启用 / 不适用 sections of the agent drawer. REQUIRED AND NON-NULL whenever `sources` is an object (07-29, review round 5) — see the conditional at the bottom of this file; a null here would hand the matrix back to the UI, which is the duplication this projection deletes. Two coverage rules the schema cannot state and a mechanical guard therefore must (api.md → Serializer completeness): one entry per EXISTING source, and every id in `order` present with `eligible: true`, since a source this backend cannot use must never appear in the order it spends.",+ "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.",+ "if": {+ "properties": { "eligible": { "const": false } },+ "required": ["eligible"]+ },+ "then": {+ "required": ["reason_key"],+ "properties": {+ "reason_key": { "type": "string", "minLength": 1 }+ }+ }+ },+ {+ "if": {+ "properties": { "eligible": { "const": true } },+ "required": ["eligible"]+ },+ "then": {+ "properties": {+ "reason_key": { "type": "null" }+ }+ }+ }+ ],+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "eligible": { "type": "boolean" },+ "reason_key": {+ "type": ["string", "null"],+ "description": "i18n key explaining an ineligible source (e.g. models.eligibility.subscription_wrong_client, models.eligibility.opencode_api_key_only, models.eligibility.consent_required). REQUIRED and non-null when `eligible` is false, null when it is true — both pinned by the conditionals above (07-29, review round 4), because 不适用 with no cause is a row the drawer cannot act on."+ }+ }+ }+ }+ }+ },+ "supply_status": {+ "type": ["string", "null"],+ "enum": ["ok", "degraded", "waiting", "interrupted", null],+ "description": "v2: derived per-agent health rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent` — not for every model this backend can be asked for (§4.5 'two grains, one taxonomy'; grain of the selection itself corrected in round 4). Split on the SAME question as source status — does it heal itself: ok = serving from the intended head of the chain; degraded = serving via a fallback and/or some chain members are down (still running); waiting = nothing runnable right now but every blocker is a cooldown, so it recovers unattended at the earliest `retry_at` (UI: 「暂时全部在冷却」, feed only, NEVER an IM push); interrupted = nothing runnable and at least one blocker needs the user (needs_action / error), or the capability chain is structurally EMPTY (UI: 「当前无可用来源」, `severity: action_required`, proactive push). waiting exists precisely so an all-cooling agent does not trip the push path — pushing there would contradict the rule that self-healing states never interrupt the user. interrupted is otherwise the state v1 could not express: a populated source list while this particular agent has nothing to call. null when mode=direct."+ },"mappings": {"type": "array",- "description": "fixed-menu backends only; per-agent scope (spec §4.2). Absent entry = 跟随原生 (identity).",+ "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"],@@ -40,7 +119,7 @@},"menu": {"type": ["object", "null"],- "description": "open-menu backends only (frame 05r).",+ "description": "open-menu backends only (frame V4 05r).","required": ["view", "checked"],"additionalProperties": false,"properties": {@@ -53,9 +132,113 @@}}},+ "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.",+ "items": {+ "type": "object",+ "required": ["model_id", "chain_length"],+ "additionalProperties": false,+ "properties": {+ "model_id": {+ "type": "string",+ "description": "The identifier this backend's menu uses: the built-in id for fixed menus, the prefixed identifier (vendor/model) for open menus."+ },+ "chain_length": {+ "type": "integer",+ "minimum": 0,+ "description": "Length of the CAPABILITY chain — how many sources in this backend's order can supply this model at all, mapping applied — matching `AgentChain.chain`, cooling members included. Deliberately NOT a count of currently-runnable candidates: this drives a menu row's 「无来源可供」 flag, which is a structural fact about the model, and it must not flicker because an account is mid-cooldown. 0 ⇒ flag the row; transient unavailability is `supply_status` (waiting) instead."+ }+ }+ }+ },"builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): fixed-menu backends only — real built-in model ids, server-populated from vibe/backend_model_catalog.py; null for open-menu backends. UI must not hardcode menus." },"standard_vendors": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): opencode only — server-populated mirror of STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py) so the UI never hand-mirrors vendor lists; null otherwise." }},+ "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).",+ "if": { "properties": { "mode": { "const": "direct" } }, "required": ["mode"] },+ "then": {+ "properties": {+ "selected_model_id": { "type": "null" },+ "selected_by_agent": { "type": "null" },+ "current": { "type": "null" },+ "sources": { "type": "null" },+ "supply_status": { "type": "null" },+ "model_supply": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): the two BLOCKED rollup values guarantee nothing is runnable, so `current` — 'what the next turn would use' — has nothing true to say and must be null. Round 3 documented this as three cases the serializer MUST honour and left all three writable; a stale `current` surviving into `waiting` renders 使用中 for a source that will not be called, which is the single lie the whole taxonomy was built to prevent (spec §4.5: `current` is null in both states, so neither ever renders a stale 使用中).",+ "if": { "properties": { "supply_status": { "enum": ["waiting", "interrupted"] } }, "required": ["supply_status"] },+ "then": { "properties": { "current": { "type": "null" } } }+ },+ {+ "$comment": "v2 (07-29, review round 4): and the converse the field already claimed ('Non-null ⇒ supply_status is ok or degraded'), plus the mode half. A record that names a serving source while reporting a blocked rollup is contradictory in the other direction, and either half alone leaves that payload writable. PRESENCE DELIBERATELY NOT REQUIRED here (07-29, review round 5), the one declared exception to the rule that a non-null `then` constraint must also require its field: this file's frozen examples carry `current` with no `supply_status` at all — they round-trip byte-faithfully through the SHIPPED v1 serializer, which has no such field — so `required: [\"supply_status\"]` would fail the contract gate rather than strengthen it. The obligation moves to the API boundary, where the v2 serializer emits it (README → required-vs-optional). Absence is also the fail-safe direction: no rollup means no claim about health and no push, whereas the dangerous absences (`severity` on a needs_action event, `current` under an ok rollup) are all required above. The exception is enforced as a declared entry in the round-5 presence checker, so 'missing on purpose' cannot decay into 'missing by accident' (api.md → Serializer completeness).",+ "if": { "properties": { "current": { "type": "object" } }, "required": ["current"] },+ "then": {+ "properties": {+ "supply_status": { "enum": ["ok", "degraded"] },+ "mode": { "const": "hub" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): the RUNNABLE half of the rollup ⇒ `current`, which round 4 left open at both ends. It pinned 'blocked ⇒ current null' and 'current non-null ⇒ not blocked', and those two together still admit `supply_status: \"ok\"` with `current: null` — a record claiming 正在从链首供给 while refusing to name the source doing it. That is not a hypothetical shape: it is what a serializer produces the moment the rollup and the candidate are computed by different code paths and one of them returns early, and the drawer would render 使用中 with an empty source row. `ok` and `degraded` are DEFINED by something being served (§4.5: serving from the head of the chain / serving via a fallback), so the candidate exists by construction and the payload must carry it. `required` is part of the fix, not decoration: draft-07 `properties` only validates fields that are PRESENT, so a `then` naming `current` without requiring it passes any record that just omits the key — which is how the whole class of round-4 conditionals ended up weaker than it read. With this member the pair `supply_status` × `current` is total: each of the four rollup values determines whether a candidate is named, in both directions.",+ "if": { "properties": { "supply_status": { "enum": ["ok", "degraded"] } }, "required": ["supply_status"] },+ "then": {+ "required": ["current"],+ "properties": {+ "current": { "type": "object" },+ "mode": { "const": "hub" }+ }+ }+ },+ {+ "$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.",+ "if": { "properties": { "menu_kind": { "const": "fixed" } }, "required": ["menu_kind"] },+ "then": {+ "properties": {+ "menu": { "type": "null" },+ "standard_vendors": { "type": "null" }+ }+ }+ },+ {+ "if": { "properties": { "menu_kind": { "const": "open" } }, "required": ["menu_kind"] },+ "then": {+ "properties": {+ "builtin_models": { "type": "null" },+ "mappings": { "maxItems": 0 }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): menu shape is a property of the BACKEND, not a free choice — spec §4.2 names them one by one (open menus i.e. OpenCode; fixed menus i.e. Claude Code and Codex). Pinned so the pairing cannot drift per payload; a new backend joining the enum is a contract change that comes here to declare which kind it is.",+ "if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },+ "then": { "properties": { "menu_kind": { "const": "open" } } }+ },+ {+ "if": { "properties": { "backend": { "enum": ["claude", "codex"] } }, "required": ["backend"] },+ "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.",+ "if": { "properties": { "sources": { "type": "object" } }, "required": ["sources"] },+ "then": {+ "properties": {+ "sources": {+ "required": ["eligibility"],+ "properties": {+ "eligibility": { "type": "array" }+ }+ }+ }+ }+ }+ ],"examples": [{"backend": "claude",diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex a11bb81d1..57c9e8329 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -2,38 +2,755 @@All endpoints live under `/api/models/`. Envelope: success `{ok: true, ...}`;failure `{ok: false, error: <machine_code>, detail?: <i18n key or safe text>}`.-Every response includes `contract_version: 1`. Auth follows existing UI-server+Every response includes `contract_version: 2`. Auth follows existing UI-serversession auth; localhost curl is rejected the same way as other `/api/*` routes.+**`detail` is a string, and structured failure data goes in a named sibling+key** (normative, 07-29 review round 3). The shipped client types it as one —+`ApiErr.detail?: string` and `ApiCallError.detail?: string`+(`ui/src/components/settings/models/types.ts`, `modelsApi.ts`) — and every+existing producer fills it with an i18n key or a safe fragment. An error that+needs a payload therefore adds its own typed field next to `error`, exactly as+success responses nest `probe` / `agent` / `provenance`, instead of widening+`detail` to `string | object`. A union there would break both live consumers on+the first structured error and force every future reader to type-check a field+whose only job is to be rendered.++> **v2 target, not current runtime.** Contracts land before implementation+> (the v1 precedent). The shipped-but-dormant v1 serializers still emit+> `contract_version: 1` and still expose `PUT /api/models/priority`; the+> serializer PR that lands per-agent ordering bumps the envelope and removes+> that route in one change. Read this file as the destination.+| Method & path | Req / Resp schema | Notes || --- | --- | --- |-| GET `/api/models/sources` | → `{sources: Source[]}` | list, ordered by priority |-| POST `/api/models/sources` | `SourceCreate` (kind, vendor, base_url?, key? / oauth flow ref) → `Source` | api_key create validates + discovers models (test-and-add, frame 06r). The pasted key is TRANSIENT: L2 provisions it into the engine-owned store (`provision_credential`) and persists only the returned `credential_ref`; on persist failure it revokes. Secrets never enter config, logs, or any response. |-| PATCH `/api/models/sources/<id>` | partial Source (display_name, base_url) → `Source` | never accepts credential material in plaintext beyond initial create |-| DELETE `/api/models/sources/<id>` | → `{ok}` | refuses while source is the only supplier of a checked/ mapped model unless `force=true` |+| GET `/api/models/sources` | → `{sources: Source[]}` | **v2:** an unordered asset inventory. Sources carry no position, rank, or priority field; the array order is display convenience only (never a spend order). Each source does carry immutable `created_at`, which is what 跟随推荐 sorts by — a stored fact about the source, not a position in this array. |+| POST `/api/models/sources` | `SourceCreate` (kind, vendor, base_url?, key? / oauth flow ref) → `{source: Source, adopted_by: AdoptedBy[]}` | api_key create validates + discovers models (test-and-add, frame V4 06r). The pasted key is TRANSIENT: L2 provisions it into the engine-owned store (`provision_credential`) and persists only the returned `credential_ref`; on persist failure it revokes. Secrets never enter config, logs, or any response. **v2:** the server stamps immutable `created_at` here — it is server-assigned and never accepted from the client, since a client-supplied value could reorder 跟随推荐. **v2 `adopted_by`** closes the "so what now?" loop in the same response — see below. |+| PATCH `/api/models/sources/<id>` | partial Source (display_name, base_url) → `Source` | metadata only — never credential material. Replacement has its own route below, because "rename it" and "hand me a new key" are different operations with different failure modes. |+| **PUT** `/api/models/sources/<id>/credential` | `{key}` → `{source: Source, recovered: boolean, interrupted_pairs: SupplyGap[]}` | **v2 (07-29, review round 3).** Replaces the credential of an existing `api_key` source in place. **The sequence, the response shape and the refusal case are defined once, under 「Credential replacement and re-auth」 below** — rewritten there 07-29, review round 6, because three rounds of corrections had left this cell carrying two incompatible orderings of the same steps, the leading one unimplementable against the frozen adapter. **This route exists because spec §4.5 promises the interrupted-source card a one-tap 「换一个 Key」 and there was nowhere to send that tap:** create-a-new-source is not the same operation — it strands the old row, drops the source's position in every backend's `sources.order`, and loses its `created_at`, so 跟随推荐 silently reshuffles as a side effect of fixing a key. Replacement keeps the identity and the order. Same transient-secret rule as create: the plaintext never enters config, logs, or any response. |+| **POST** `/api/models/sources/<id>/reauth` | → `{flow: OAuthFlow}` | **v2 (07-29, review round 3).** The subscription counterpart: re-runs OAuth **bound to an existing source** rather than creating one, for `credential_expired` / `credential_revoked`. Thin by design — it is `POST /api/models/oauth/start` with `source_id` instead of `{vendor, channel}`, and the adapter surface it needs already exists (`start_oauth(source_id)` with deterministic source binding, adapter-interface v1.1). The flow then polls `/api/models/oauth/status/<flow_id>` like any other; its completion response is defined under 「OAuth completion responses」 below and its repair tail under 「Credential replacement and re-auth」, which is where the channel-specific rule for where the refreshed credential lands also lives. |+| DELETE `/api/models/sources/<id>` | → `{ok}`, or `{ok: false, error: "source_last_supplier", would_interrupt: SupplyGap[]}` | refuses while the source is the last supplier of a SELECTED model unless `force=true` — "selected" is wider than 「已勾选/已映射」, see the round-5 note at the end of this cell. **v2 re-scopes what "last" counts over:** per affected backend, over that backend's **enabled order** (`sources.order`) — never over eligible inventory. With per-agent ordered subsets a source can be eligible for a backend while absent from its order, so the v1 inventory scan would count an unreachable source as the replacement, allow the delete without `force`, and leave that agent `interrupted` on the next turn (`kind: supply_interrupted`, `reason: no_enabled_source`). **The guard is per (backend, model), not per backend** (corrected 07-29, review round 3): refuse if the delete would leave ANY protected model of ANY affected backend with no runnable supplier, and the confirm copy names those (backend, model) pairs. **Which models are protected, what 「no runnable supplier」 means, and what the refusal carries are ONE definition, stated once under 「The supply guard」 below** (07-29, review round 7) — this cell and the credential routes reference it rather than restating it. Round 6 wrote the test here as `model_supply[].chain_length` becoming 0, which is structural emptiness and a strictly weaker question than the one the guard asks: a chain still holding one revoked key is not empty and cannot serve, so the delete passed unguarded and the agent went `interrupted` on its next turn — the exact surprise this guard exists to prevent, reintroduced by counting rows instead of asking whether any row could run. Round 2 wrote it as "zero enabled suppliers" for the backend, which is a strictly weaker test than the sentence it was meant to implement: a backend with four enabled sources loses nothing by that test, yet deleting the only one that supplies `claude-haiku-4-5` silently starves that model and the user finds out on the next turn. Backend-level emptiness is simply the special case where every protected model hits zero at once. **"checked/mapped" is the wrong protected set — it is every SELECTED model** (corrected 07-29, review round 5): that phrase came from the V4 fixed-menu drawer, where a model earns protection by being checked in the menu or by owning a mapping row. Both tests miss the model a backend is actually running. `agents.<backend>.default_model` is a selection in its own right; so is `agents.<name>.model` for each enabled Vibe Agent; and a fixed-menu model that resolves by IDENTITY (`selected_model_id == resolved_model_id`, no mapping row — `agent-chain.schema.json` → `via_mapping: false`) is mapped in effect while being invisible to any mapping scan. Composed, those gaps let a source be the only supplier of the model the user's `pm` Agent runs on, hold no mapping row, sit unchecked in a menu the user never opened, and be deleted without `force` — the interruption arriving on `pm`'s next turn as `kind: supply_interrupted`, `reason: no_enabled_source`, which is the class of surprise this guard exists to prevent. The protected set is therefore a UNION of four selection facts, enumerated with its identifier namespace under 「The supply guard」 below — where 「mapping targets」 is corrected to the mapping's MENU side (07-29, review round 7): a mapping row rewrites `claude-opus-4-6 → glm-5.2`, so protecting the *target* protects a resolved id the user never selected, loses the built-in model the selection actually names, and coalesces every menu model mapped onto one upstream id into a single gap the client cannot attribute. The fourth term is the frozen per-Agent grain doing its job (see `selected_by_agent` above): with per-Agent ordered subsets there is no single "the backend's model" to test, so the guard has to close over the Agents — and the confirm copy names the Agents, not only the pairs, because 「删除后 pm 将没有可用来源」 is a sentence the user can act on while 「claude / claude-opus-4 将没有可用来源」 is not, when four Agents share that backend. Disabled Agents are deliberately excluded — they cannot take a turn, so their model is not a live capability — but a disabled Agent's model that is ALSO the backend default stays protected through the default term, which is the overlap the union is built to absorb. `force=true` still overrides the whole set; widening the guard changes what the user is warned about, never what they are forbidden. **The refusal is machine-readable** (07-29, review round 6): round 5 promised confirm copy naming the pairs and the Agents but declared no shape for either, so the client had nothing to render it from and no code to switch on. The refusal is `ok: false`, `error: "source_last_supplier"`, with the affected pairs in `would_interrupt` — the `SupplyGap` shape defined under 「The supply guard」 below, whose `agents` member is what 「删除后 pm 将没有可用来源」 is composed from. Also drops the id from every backend's `sources.order`. || POST `/api/models/sources/<id>/test` | → `{ok, discovered: n}` | re-discovery |-| PUT `/api/models/priority` | `Priority` → `Priority` | authoritative full order; server re-echoes canonical order |-| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | includes `current` per backend. Response agents[] carry server-populated read-only `builtin_models` / `standard_vendors` (integration 2026-07-24). |+| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | includes `current`, **v2** `sources` (policy + order + eligibility), `supply_status`, and `model_supply` per backend. Response agents[] carry server-populated read-only `builtin_models` / `standard_vendors` (integration 2026-07-24). |+| **PUT** `/api/models/agents/<backend>/sources` | `{policy, order}` → `AgentSupply` | **v2, replaces `PUT /api/models/priority`.** Authoritative: the server re-echoes the full canonical order. See semantics below. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `AgentSupply` | hub⇄direct switch; never silent (plan §4) || PUT `/api/models/agents/<backend>/mappings` | `{mappings}` → `AgentSupply` | fixed-menu backends only || PUT `/api/models/agents/opencode/menu` | `{menu}` → `AgentSupply` | open menu config |-| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `Source` | appends manual-provenance model entry (frame 08) |+| **GET** `/api/models/agents/<backend>/chain?model=<id>` | → `AgentChain` | **v2.** The capability chain for that (agent, model) — cooling members included, flagged `runnable: false`. An empty `chain` is `ok: true` with `chain: []`, not an error. Carries `supply_state` (`ok`/`waiting`/`interrupted`) at the MODEL grain: the single answer every model-scoped consumer reads, including the probe's `supply` sibling and `TurnProvenance.model_supply_state`, so none of them consults the backend rollup for a question it cannot answer. The `waiting`/`interrupted` split is spec §4.5's predicate, stated there once — `interrupted` when at least one blocker needs the user, `waiting` only when every blocker is a cooldown. `model` is a **menu identifier** (see identifier rules below). **Hub-mode route** (07-29, review round 9): this row is defined for `mode: hub` and the client must not offer it for a Direct backend. `agent-supply.schema.json` nulls `sources`, `selected_model_id` and `model_supply` in Direct, so there is no order to walk and no default model to fill in — the honest answer is not `chain: []`, because the empty-chain rule above means 「Hub has nothing that can serve this」 and a Direct backend's native CLI may be running that model perfectly well. Presenting Hub starvation for a backend that is not on Hub is a worse failure than refusing the question. What Direct *should* answer — a documented error or a mode-specific payload — is **AC-7** in `docs/plans/model-hub-implementation.md` §8 and is not decided here. |+| **POST** `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | **v2.** One minimal dry-run request through the current chain (「试跑一次」). `model` is a **menu identifier** and defaults to `selected_model_id`. The result is NESTED under `probe`, never spread into the envelope — see below. **Hub-mode route** (07-29, review round 9), for the same reason as the chain row and one of its own: in Direct there is no `selected_model_id` to default to, and a `ProbeResult` requires a non-nullable `source_id`, which a Direct turn has no Hub source to name — the implementation would have to fabricate one to return a valid object. Scoped to `mode: hub`; the Direct representation is **AC-7**. |+| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `Source` | appends manual-provenance model entry (frame V4 08) || DELETE `/api/models/custom-models` | `{source_id, model_id}` → `Source` | |-| GET `/api/models/events?limit=n&before=<id>` | → `{events: ResolutionEvent[]}` | adapter-owned feed (最近切换) |-| POST `/api/models/oauth/start` | `{vendor, channel}` → `OAuthFlow` | runtime-declared presentation |-| GET `/api/models/oauth/status/<flow_id>` | → `OAuthFlow` | 2s polling, server holds flow |-| POST `/api/models/oauth/submit` | `{flow_id, value}` → `OAuthFlow` | value = pasted code or callback URL per `presentation.expects` |+| GET `/api/models/events?limit=n&before=<id>` | → `{events: ResolutionEvent[]}` | adapter-owned feed (最近切换). **v2:** each event carries `severity`; the IM push layer keys off `severity == "action_required"` and never re-derives urgency from `kind`. **That field decides WHETHER to interrupt, not WHOM** (07-29, review round 5): no event carries a recipient, channel, or platform, and recipients are resolved at push time from the event's `agent` against the live routing table — spec §4.5 → 「Who receives an action-required push」 is normative, and this feed stays a record of what happened to supply rather than an outbox. Adds `kind: supply_interrupted`, the only agent-scoped kind — see the worked payload below. |+| POST `/api/models/oauth/start` | `{vendor, channel}` → `{flow: OAuthFlow}` | runtime-declared presentation. Creates a NEW source on success; re-authenticating an existing one is `POST /api/models/sources/<id>/reauth`. **v2 stamps `flow.intent`** so the completion response shape is a total function of the flow — see 「OAuth completion responses」 below. |+| GET `/api/models/oauth/status/<flow_id>` | → `{flow: OAuthFlow}`, plus the completion fields on the terminal success poll | 2s polling, server holds flow. **The terminal poll carries the flow's OUTCOME, not only its state** (07-29, review round 6) — the created source and its `adopted_by` for a create flow, the repair result for a reauth flow. See below. |+| POST `/api/models/oauth/submit` | `{flow_id, value}` → same shape as `status` | value = pasted code or callback URL per `presentation.expects`. A submit that terminates the flow carries the same completion fields, so a form-A paste needs no extra poll to learn what it produced. || POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | |-| POST `/api/models/migration/scan` | → `MigrationScan` | read-only |+| POST `/api/models/migration/scan` | → `MigrationScan` | read-only. Unaffected by the v2 ordering ruling — native-config import is an onboarding feature, not a priority mechanism. || POST `/api/models/migration/apply` | `{item_ids: []}` → `{applied: n, sources: Source[]}` | copy-only; originals untouched (tested) |+| **GET** `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` | **v2.** What served one turn, incl. every attempt in order (spec §4.5 turn provenance). `outcome` has FOUR values, not three (07-29 round 3): `served` / `exhausted` / `failed_terminal` / `no_candidate`, where `failed_terminal` covers the non-fallback errors of spec §4.3 — param, protocol, tool-compat, and anything after the first streamed token — recorded in a `terminal_error` slot beside `served`. Read-only. `turn_not_found` when the turn is unknown or predates the feature. || GET `/api/models/runtime/status` | → `RuntimeDependency` | engine manifest + health |-Error codes (minimum set): `source_not_found`, `flow_not_found`, `flow_expired`,-`discovery_failed`, `invalid_priority_order` (must be a permutation),-`mapping_target_unavailable`, `mode_switch_blocked`, `engine_down`,-`consent_required` (hub-held subscription paths while the experimental flag is-unset), `migration_item_conflict`.+Removed in v2: `PUT /api/models/priority` (the global spend order). Its schema+file survives only as a tombstone — see `priority.schema.json`.++## Identifier rules (v2)++Two namespaces exist and mixing them silently misses:++- **menu identifier** — what the user picked and what every menu renders: the+ built-in id for fixed-menu backends (`claude-opus-4-6`), the prefixed+ `vendor/model` form for open menus (`zhipuai/glm-5.2`, per+ `opencode-overlay.md`).+- **resolved model id** — what goes upstream after mapping, always bare+ (`glm-5.2`).++Rule: **every request parameter is a menu identifier; every "what actually ran"+field is a resolved id.** So `chain?model=`, `probe {model}`,+`AgentChain.model_id`, `AgentSupply.selected_model_id` and+`TurnProvenance.requested_model_id` take menu identifiers, while+`AgentChain.resolved_model_id`, `ProbeResult.model_id`,+`AgentSupply.current.model_id` and every `resolved_model_id` in+`TurnProvenance` — `failed_attempts[]`, `served`, `terminal_error` — report+resolved ids. (Round 2 replaced that record's single `attempts[]` array with+those three slots; the reference here was not updated with it.)++Consequence worth stating because it is the easy bug: `current.model_id` is a+resolved id, so it is **not** a valid default for the chain query or the probe. For+OpenCode it is bare (`glm-5.2`) while the chain expects `zhipuai/glm-5.2`, and the+lookup would fail or, worse, match a different vendor's identically-named model.+Defaults therefore read `AgentSupply.selected_model_id`, which is also the only+one of the two that still exists when nothing is runnable — `current` is null in+precisely the `waiting` / `interrupted` states where the drawer most needs to name+the selected model (round 3 hoisted it out of `current` for that reason).++### `selected_model_id` answers for ONE route, not for the backend++`AgentSupply` is keyed by backend, so `selected_model_id` reads as "the model this+backend will use". It is not (grain corrected 07-29, review round 4). A Vibe Agent+row in SQLite carries **both** `backend` and `model`, so `pm` and+`evm-contract-audit` can share the `claude` backend on different models, and+routing follows the selected Vibe Agent (`AGENTS.md` → Agent routing model). One+backend therefore has as many "selected models" as it has Agents.++What the shipped projection actually resolves is one specific route:+`core/controller.py::default_vibe_agent_model` takes the **global default** Vibe+Agent and returns its `model` only if that Agent's backend matches, else null —+whereupon `core/handlers/model_hub/service.py::requested_model` falls back to+`agents.<backend>.default_model`. So the field has always answered for a single+route while being named as if it answered for the backend. That is why v2 adds+`selected_by_agent`: the Agent whose `model` produced the value, or null when it+came from the backend default. The pair is honest about its own grain, and a UI+rendering 「当前模型」 can say whose.++Per-Agent questions have per-Agent routes already: `GET …/chain?model=<id>` and+`POST …/probe {model}` both take an explicit model, so anything that needs another+Agent's answer asks for it rather than reading this rollup.++**REQUIRED on every hub-mode response** (07-29, review round 5). A payload may not+publish `selected_model_id`, `current` or `supply_status` while leaving out the+route they describe: all three inherit this grain, so without the field a client+can render the global-default Agent's model as a backend-wide fact — the exact+ambiguity `selected_by_agent` was added to remove, reintroduced by omission. Both+worked payloads below now carry it. `null` is a legitimate value and means one+specific thing — the model came from `agents.<backend>.default_model` because the+resolved Agent pins none — so it is written explicitly rather than left absent; a+missing key would be indistinguishable from a serializer that forgot.++The obligation is stated here rather than as `required` in+`agent-supply.schema.json` for the standing reason (README → required-vs-optional):+that file's two frozen examples are `mode: hub` and predate every v2 field,+because they round-trip byte-faithfully through the SHIPPED serializer, so a+`required` under a hub branch would fail the contract gate instead of tightening+it. This is the same boundary that makes `sources`, `supply_status` and `severity`+optional in their schemas and mandatory at the API — the schema describes what+today's serializer can emit, this file describes what the v2 API owes its+callers. Enforcement therefore lands with the serializer PR, as a response-shape+assertion next to the ones listed under Serializer completeness.++**Open decision for the owner, deliberately not settled in this PR:** whether the+Models page should surface per-Agent model selection as a first-class control+(one row per Vibe Agent, not per backend). That is a product-surface question with+its own frames, and the frozen ordering ruling — order is a per-Agent subset, no+global list — is untouched either way; naming the grain here does not pre-empt it.++## `PUT /api/models/agents/<backend>/sources` semantics++**The request body is its own shape, not an `AgentSupply.sources` instance.** In+the response object both `policy` and `order` are required, because the server+always knows the canonical order; in the request `order` is required only under+`policy: "custom"`, because under `follow` there is nothing for the client to say.+Spelling that out here rather than reusing one schema for both directions is+deliberate — a client that had to send an ignored `order` to select 跟随推荐 would+be inventing data, and the next reader could not tell whether it mattered.++Request is the whole intended state, never a delta:++```json+{ "policy": "custom", "order": ["src_anthkey01", "src_claudepro1", "src_relay9c1x"] }+```++```json+{ "policy": "follow" }+```++Validation (`invalid_source_order` on any failure, with `detail` naming the first+offending id):++1. every id exists and is not deleted;+2. every id is **eligible** for `<backend>` (§4.4 matrix — server-authoritative);+3. ids are unique;+4. it is a **subset**, not a permutation: omitting an eligible source is the+ normal way to say 未启用, and is not an error.++Policy handling:++- `{"policy": "follow"}` — `order` MUST be omitted; the server recomputes from the+ recommendation rule **defined once in spec §4.2** and echoes the result. This is+ the wire form of 「恢复推荐顺序」. The rule is deliberately NOT restated here+ (corrected 07-29, review round 4): round 3 carried an abbreviated parenthetical+ — "own-vendor subscription → api_key by `created_at` ascending → id tie-break" —+ which silently dropped §4.2's channel clause, that a sanctioned `native_cli`+ subscription precedes a hub-held one for the same own vendor. With both+ present the abbreviation fell through to the id tie-break and could put the+ experimental hub credential first, i.e. the paraphrase did not merely omit the+ clause, it contradicted it. That is what a second home for a predicate costs,+ so the fix is one home rather than a better copy: §4.2 states the rule, and+ every other file cites it.+ An `order` sent alongside `follow` is rejected with `invalid_source_order` rather+ than silently dropped: accepting and ignoring it would let a client believe it+ had set an order it did not set.+- `{"policy": "custom", "order": [...]}` — `order` is required (an empty array is+ legal and means 全部未启用); stored verbatim and never reordered by the server+ afterwards (spec §2 promise 4).+- Sending `policy: "custom"` with an `order` equal to the current recommendation is+ still a fork to custom — the user asked to own it.++Response is the full `AgentSupply` for that backend, so one round trip refreshes+the drawer, the row's order chips, and `supply_status`.++```json+{+ "ok": true,+ "contract_version": 2,+ "agent": {+ "backend": "claude",+ "mode": "hub",+ "menu_kind": "fixed",+ "selected_by_agent": "pm",+ "selected_model_id": "claude-opus-4-6",+ "current": {+ "model_id": "claude-opus-4-6",+ "source_id": "src_anthkey01",+ "channel": "hub"+ },+ "sources": {+ "policy": "custom",+ "order": ["src_anthkey01", "src_claudepro1", "src_relay9c1x"],+ "eligibility": [+ { "source_id": "src_anthkey01", "eligible": true, "reason_key": null },+ { "source_id": "src_claudepro1", "eligible": true, "reason_key": null },+ { "source_id": "src_relay9c1x", "eligible": true, "reason_key": null },+ { "source_id": "src_chatgptplus", "eligible": false,+ "reason_key": "models.eligibility.subscription_wrong_client" }+ ]+ },+ "supply_status": "degraded",+ "model_supply": [+ { "model_id": "claude-opus-4-6", "chain_length": 2 },+ { "model_id": "claude-haiku-4-5", "chain_length": 0 }+ ]+ }+}+```++## Interrupted agent payload (`current: null`)++The case worth writing out, because it is the one that motivated hoisting the+selection out of `current` (round 3): the backend has nothing runnable, so+`current` is null, yet the drawer still has to name the model it is complaining+about, offer its chain drill-in, and default 「试跑一次」 to it.++```json+{+ "ok": true,+ "contract_version": 2,+ "agent": {+ "backend": "codex",+ "mode": "hub",+ "menu_kind": "fixed",+ "selected_by_agent": null,+ "selected_model_id": "gpt-5.3-codex",+ "current": null,+ "supply_status": "interrupted",+ "sources": {+ "policy": "follow",+ "order": ["src_chatgptplus"],+ "eligibility": [+ { "source_id": "src_chatgptplus", "eligible": true, "reason_key": null }+ ]+ },+ "model_supply": [ { "model_id": "gpt-5.3-codex", "chain_length": 1 } ]+ }+}+```++Read it together: one enabled source, which *can* supply the model+(`chain_length: 1`), but it is `needs_action`, so nothing is runnable and+`supply_status` is `interrupted` rather than `waiting`. `current` is null because+naming a source here would render 使用中 for one that will not be called;+`selected_model_id` survives because the user's choice did not change. The two+payloads show both values of `selected_by_agent`: `"pm"` above, where a named Vibe+Agent pins that model, and `null` here, where no Agent on this backend pins one+and the value came from `agents.<backend>.default_model`. Null is a fact about+provenance, not a missing field — the drawer says 「后端默认」 instead of naming an+Agent, and 「当前模型」 is never attributed to an Agent that did not choose it.++This payload lives here rather than in `agent-supply.schema.json`'s `examples`+for the standing reason (README → required-vs-optional): those examples+round-trip byte-faithfully through the shipped v1 serializer, so a v2 field in+them would assert that dormant v1 code already speaks v2.++## `adopted_by` on source create++```json+{ "ok": true, "contract_version": 2,+ "source": { "id": "src_zhipukey01", "kind": "api_key", "...": "..." },+ "adopted_by": [ { "backend": "codex", "policy": "follow", "position": 2 } ] }+```++One entry per backend that picked the new source up **automatically** — i.e. those+on `policy: "follow"`, where `position` is its 1-based slot in the recomputed+order. Backends on `custom` are absent from the list, which is exactly the set the+success state offers one-tap enable for (「Claude Code 未启用此来源」). Eligible-for-nobody+sources yield `adopted_by: []`.++`position` is computed with the full recommendation rule, tie-break included, so+the server must have written the source's immutable `created_at` before answering —+`adopted_by` is the first consumer of that field.++## The supply guard: `SupplyGap` and `would_interrupt`++Two destructive operations can starve a model someone is running on: deleting a+source, and rotating a healthy source onto a credential that sees fewer models.+**They share one predicate, one shape and one refusal code, defined here once**+(07-29, review round 7). Round 6 gave the shape a home under credential replacement+and left the predicate paraphrased in the DELETE cell, where it drifted into a+structural test — and a guard two routes describe differently is not one guard+(README → 「A predicate has exactly one home」).++**The shape.** `SupplyGap` is `{backend, model_id, agents: string[]}`, all three+required, and it is what both keys carry: `would_interrupt` on a refusal (what WOULD+be starved), `interrupted_pairs` on a completed repair (what WAS). One shape, two+keys, because the two facts differ only in mood.++**Namespace: menu identifiers throughout** (see the identifier rules above).+`model_id` is a menu identifier — `claude-opus-4-6`, `zhipuai/glm-5.2` — never the+resolved id it maps to, so the protected set, the gap report and the confirm copy all+live in the namespace the user selected in and every menu renders. Mapping is applied+*inside* the supply computation and nowhere else: to decide whether `claude-opus-4-6`+is still supplied you resolve it through its mapping row and test the chain of+`glm-5.2`, then report the gap as `claude-opus-4-6`.++**What is protected: a backend's EFFECTIVE selections** — the union of four facts,+each named as a menu identifier:++1. every entry in an **open** menu's `menu.checked` (07-29, review round 9). Round 5+ wrote this term as 「every checked fixed-menu model」, which names state that does not+ exist: `agent-supply.schema.json` permits `menu` — and therefore `checked` — only for+ `menu_kind: open`, and gives a fixed menu `builtin_models`, which is the+ server-populated CATALOG, not a selection. Both readings of the old wording were+ wrong. Skipping the term drops real protection from the one menu kind that *does*+ persist a checked set, so deleting a source could starve a model the user ticked in+ the OpenCode menu. Treating a fixed menu's catalog as checked refuses deletes over+ dozens of models nobody selected and some the backend cannot even run, which trains+ the user to pass `force=true` reflexively and hollows out the whole guard. A fixed+ menu therefore contributes nothing here and is protected by terms 2-4 — which is+ exactly right, because a fixed-menu model the user actually selected either owns a+ mapping row, is the backend default, or is some enabled Agent's effective model.+ `menu.checked` entries are already prefixed menu identifiers (`zhipuai/glm-5.2`), so+ they enter the union in the namespace above with no translation;+2. every model that owns a mapping row, named by its MENU side (`builtin_id`), never+ by the target it rewrites to;+3. `agents.<backend>.default_model`;+4. for every ENABLED Vibe Agent on that backend, its **effective model**: its own+ `model` when it has one, otherwise `agents.<backend>.default_model` — inheritance+ is a selection, not the absence of one.++Disabled Agents are excluded: they cannot take a turn, so their model is not a live+capability. A disabled Agent's model that is *also* the backend default stays+protected through term 3, which is the overlap the union exists to absorb.++**The gap predicate: no runnable supplier, not an empty chain.** A protected pair is+a gap when, AFTER the change, its capability chain holds no `runnable: true`+member — `runnable` exactly as `agent-chain.schema.json` defines it (healthy, or+cooling with `retry_at` already past; never `needs_action`, never `error`).+Equivalently: the pair's `supply_state` would stop being `ok`. `chain_length > 0` is+NOT the test, and that was the round-6 defect: a chain of one revoked key is+non-empty and cannot serve, so the structural test passed the delete and the agent+went `interrupted` on its next turn.++**One boundary, stated so nobody re-derives it.** This predicate is deliberately not+the `interrupted` predicate. A pair whose remaining members are all merely cooling is+`waiting`, not `interrupted` (spec §4.5) — and it IS reported here, because the guard+asks 「删完之后现在还有能跑的来源吗」, which is false in both cases, while+`waiting`/`interrupted` answers the different question 「要不要你处理」. The guard+over-warns by exactly that one case, on purpose: it is a confirmation prompt,+`force=true` overrides it either way, and a client that wants to distinguish 暂时+from 需处理 reads that pair's `supply_state` from the chain query. Nothing here+forbids an operation; it decides what the user is told before they confirm.++**`agents` names the Agents that would actually break, INCLUDING the ones that+inherit the backend default** (07-29, review round 7). Membership is by effective+model, term 4 above: an enabled Vibe Agent belongs in `agents` when the starved pair+is the model it would actually run on, whether it names that model itself or inherits+it from `agents.<backend>.default_model`. **This reverses round 6's parenthetical**,+which emptied the list for a gap protected only through the backend default;+recorded as an orchestrator ruling, open to owner veto at final review. The reason+for the reversal: the field answers 「谁会坏」, and round 6's rule answered 「谁明确+写了这个模型」 — a different question whose answer is `[]` on a real interruption.+That is not a neutral omission but false reassurance, since the client then renders+「无 Agent 受影响」 for a refusal that exists *because* an Agent is about to stop+working, and 中断必须点名成因与受影响方 is the whole reason the member was added.+`agents` may still be legitimately empty — an open menu's checked-but-unassigned model,+or a mapping row no Agent runs on — and after this ruling that is the only way it+empties.++## Credential replacement and re-auth++Two routes share one repair: `PUT …/sources/<id>/credential` (paste a new key) and+the completion of `POST …/sources/<id>/reauth` (re-run OAuth on an existing source).+**This section states the PROPERTIES that repair must satisfy, not the steps it+takes** (rewritten 07-29, review round 7). Rounds 3–6 each corrected the step list,+and each correction bred the next round's findings: an ordered list of five steps+admits an unbounded supply of 「what about between 3 and 4」 questions, and round 7+asked four of them at once — where the guard runs, when the engine learns about the+swap, whether the steps are executable on the default channel at all, and what+counts as recovered. The invariants below are finite and total; the sequence that+satisfies them belongs to the implementing lane, and one is sketched+non-normatively at the end.++**The commit point.** Every invariant is stated against one named instant. The+**commit point** is the single write that makes the replacement live: `credential_ref`+swapped, `masked_credential` refreshed, the discovered list merged into+`Source.models`, `state.retry_at` and `state.detail_key` cleared, affected chain state+recomputed, **and the engine's own source table synchronised to the new ref**+(`sync_sources`, the last step of the frozen adapter's canonical flow). Those happen+together or not at all. The engine sync is INSIDE the commit phase, not after it,+because a swap the engine has not seen is not a repair — round 7's finding was+precisely that: persist-then-revoke with the sync left implicit lets the engine keep+serving turns from a handle we just revoked, so a successful repair breaks the next+turn.++1. **Atomicity.** There is exactly one commit point. Before it the prior state is+ fully recoverable and still serving; after it the replacement is fully in effect.+ No intermediate state is observable to a turn — there is no instant at which the+ source's `credential_ref` and the engine's binding disagree, and no half-applied+ repair to reconcile later.+2. **No revoked-credential window.** The engine must never hold a reference to a+ revoked credential. The old ref is revoked only AFTER the commit point — that is,+ only once the engine's source table reflects the swap — never before it and never+ inside it. A revoke that then fails must not undo a completed repair: it leaves an+ orphaned handle in the engine store, which is a cleanup problem, not a supply+ problem.+3. **Failure preserves the prior state.** Any failure before the commit point leaves+ the original credential active and serving, and revokes whatever temporary+ replacement ref the attempt minted; the route answers `discovery_failed`.+ **Temporary refs never outlive the operation** — success revokes the old one,+ failure revokes the new one, and no path leaves two live handles for one source.+ 「Prior state」 means the state this contract owns: the `Source` row and the+ engine-owned credential store (see invariant 5 for the channel where that+ boundary bites).+4. **Guard before commit.** `would_interrupt` is evaluated against the POST-swap+ world — the model set the new credential actually discovered — and evaluated+ BEFORE the commit point. A refusal therefore happens with the prior state intact,+ with nothing to roll back beyond invariant 3's temporary ref, and it is+ unrepresentable for this route to commit a swap and *then* find it was not allowed+ to: the guard is a precondition, not a postcondition. Which pairs count, and what+ counts as starved: 「The supply guard」 above, the same definition DELETE uses.++5. **Per-channel executability.** Every supply channel must have a path that+ satisfies the invariants above through the surfaces it actually has (round 4 made+ this channel-specific; round 7 asked whether the default channel could execute the+ steps at all). What a credential *is* differs by channel:+ - **`api_key` sources and consented hub-held subscriptions** hold an engine-owned+ handle. Repair mints a replacement ref, discovers through it, swaps at the+ commit point. This is the only channel where invariants 2 and 3 have refs to+ talk about.+ - **`native_cli` subscriptions hold no engine ref at all** — the Source contract+ pins `credential_ref: null`, because the credential lives in the CLI's own+ sanctioned store. **Replacement there IS re-auth of that store**, performed at+ the CLI's own surface; the engine-ref steps do not apply and must not be+ simulated, since there is nothing to provision, nothing to swap and nothing of+ ours to revoke. Writing the hub behaviour as universal would put a non-null ref+ on a source whose channel forbids it, failing validation on the path most users+ take. What the commit point writes there is the state half only — the discovered+ list, the cleared `state` fields, the recomputed chain, the engine sync — and+ invariants 1, 4 and 6 hold unchanged, evaluated on the same `Source` row.++ Two boundaries keep that honest rather than hand-waved. **Discovery reads through+ the CLI's store**, not through a ref we hold, so 「discover before committing」 is+ still satisfiable: the CLI is authoritative for the credential, we are+ authoritative for the row. And **invariant 3's rollback is bounded by what this+ contract owns**: a completed CLI re-auth has already replaced the user's login+ inside a store we do not manage, and no adapter surface can put the previous login+ back. So a post-re-auth discovery failure leaves the `Source` row untouched and+ answers `discovery_failed` — the row keeps its prior state, which is what invariant+ 3 promises — while the CLI store keeps whatever the user just authorised. That+ asymmetry is declared, not accidental: pretending we could restore the old login+ would be inventing an adapter surface, and re-authenticating a CLI is something the+ user did at the vendor's own prompt, not a transaction we brokered.++ **Read that as a statement about the row, not about the user's supply** (07-29,+ review round 8). On this channel the preserved row is intact and no longer TRUE: its+ `models` and `state` describe the login that has just been replaced, so the next+ native turn runs on the new account against a row describing the old one, and a+ refusal that 「preserves the prior supply」 preserves a supply that no longer exists.+ Invariant 3 is therefore satisfiable here only in its weak sense — we corrupt+ nothing — and the strong sense it carries on the ref-holding channel, that a failed+ repair leaves the user no worse off, is not available once the login is gone. Two+ ways close it: require confirmation BEFORE the irreversible login, or commit the+ swap and report the resulting gaps instead of refusing. Both have a UI consequence,+ so the choice is the owner's, recorded as **AC-2** in `model-hub-implementation.md`+ and NOT decided here. What is decided: this channel must not present a+ post-re-auth refusal as though the prior supply were intact. **What+ 「recovered」 observes there** is exactly what it observes everywhere — whether this+ operation cleared the source's blocker state (invariant 6). Nothing in that+ definition reads a credential handle, which is why it needs no channel-specific+ case.+6. **Recovery symmetry.** `recovered` is true when the operation cleared a BLOCKER+ state, and 「blocker」 is the same set the chain classifier uses: `state.status` of+ `needs_action` **or** `error` — the two values `agent-chain.schema.json` counts in+ the branch that makes a chain `interrupted`, and the two whose `retry_at` is null+ because nothing clears them unattended. One definition, referenced, never+ re-enumerated. Round 6 wrote 「cleared a `needs_action`」, a strict SUBSET of that+ set, so repairing a source sitting in `error` — a state round 6 itself promoted to+ a blocker in the same commit — would have reported `recovered: false`, filing a+ real repair as an elective rotation: it suppresses the `recover` event the user is+ owed and sends the operation down the stricter refusal branch below for a source+ that was already unusable. A cooldown is deliberately NOT a blocker here, because+ it heals itself: replacing a key while a source is merely cooling is an elective+ rotation.++**"Healthy" here is `active` or `standby`, recomputed — never a literal** (round 4).+Round 3 wrote `state.status: "healthy"`, which is not in the enum, so a literal+implementation would have made every SUCCESSFUL replacement fail Source validation.+Nor is the fix a third literal: `active` vs `standby` is a display rollup over "is+this source serving any agent right now", so the commit point clears the two detail+fields and lets the rollup resolve. A route that hard-coded either would be asserting+a fact about every backend's order from inside a single-source operation.++**`Source.models` merge rule:** entries with `provenance: discovered` are REPLACED by+the new discovery, entries with `provenance: manual` are PRESERVED. The model list of+an `api_key` source is a property of the CREDENTIAL, not of the base URL — a+replacement key on a different plan, project or tier can legitimately see fewer+models — while a hand-added id is the user's assertion, and swapping a key does not+withdraw it. A subscription can likewise come back on a different plan than it went+in on, so re-auth runs the same refresh.++**The response names what the repair cost**, which is what round 6 found missing: the+prose promised every newly starved (backend, model) pair while the declared shape was+only `{source, recovered}`. `recovered` answers invariant 6; `interrupted_pairs`+reports the protected pairs the repair left with no runnable supplier — the same+predicate and the same `SupplyGap` shape as 「The supply guard」 above — and is `[]`,+present and empty, when the repair cost nothing:++```json+{ "ok": true, "contract_version": 2,+ "source": { "id": "src_relay9c1x", "kind": "api_key", "...": "..." },+ "recovered": true,+ "interrupted_pairs": [+ { "backend": "claude", "model_id": "claude-haiku-4-5", "agents": ["pm"] }+ ] }+```++**Illustrative sequence for the ref-holding channel (NON-NORMATIVE).** Offered+because the frozen adapter surface forces most of it, and because rounds 3–5 argued+about an ordering that cannot be written: `discover_models` takes a `credential_ref`+and `provision_credential` is the only thing that mints one+(`adapter-interface.py`), so 「validate the key, *then* provision it」 has no handle to+validate with — provisioning IS how a key is validated, and the docstring's canonical+flow is already **provision → discover → persist → sync**, which shipped+`create_source` implements. Round 5 was right that discovery must precede the swap and+expressed it as discovery preceding the *provision*; both halves are satisfied by+provisioning a replacement ref that is not yet the source's. A conforming walk:+provision the pasted or newly authorised credential into the engine store, yielding a+replacement ref while the source still points at its old one and still serves from it+→ discover through the replacement ref → evaluate the guard against what was+discovered → commit → revoke the old ref. Any failure or refusal before the commit+revokes the replacement ref and answers with the prior state intact. **This is an+example, not the contract**: an implementation that satisfies the six invariants by+another route is conforming, and a step list that reads better while violating one is+not.++**A predicted gap gates by intent, not by severity.** Repairing a blocked source+(`recovered == true`, invariant 6) PROCEEDS and reports through `interrupted_pairs` —+refusing would trap the user in the exact state 「换一个 Key」 exists to escape, and a+narrower working key is strictly better than a revoked one. An elective rotation of an+already-serving source (`recovered == false`) is refused unless `force=true`, with the+same `source_last_supplier` + `would_interrupt` shape DELETE uses, because there the+user has a working supply and no reason to be surprised out of part of it. Both+branches read the same guard (invariant 4); only the response to it differs.++**`kind: recover` is CONDITIONAL on the prior state, not on success** (round 5). The+route already answers "did this clear a blocker" in `recovered`, and the same+success can happen to a perfectly healthy source — a scheduled key rotation. Emitting+`recover` unconditionally publishes a restoration for a source that was never+interrupted: the timeline gains a 「已恢复」 entry with nothing to recover from, and+severity promotion can push it to the user as news. So emit `kind: recover` **iff+`recovered == true`**, with `to_source: <this source>` — `recover` is the one kind whose+subject sits on the WINNING side. When `recovered == false` the routes emit **no+resolution event at all**, and that is deliberately NOT a 9th `kind`: the enum names+*resolutions of supply state*, and a rotation that starts healthy and ends healthy+resolves nothing, while a new value would force every consumer's switch to grow a+branch that renders nothing.++## OAuth completion responses++`POST /api/models/oauth/start` and `POST …/sources/<id>/reauth` both return a flow,+and the UI polls `GET /api/models/oauth/status/<flow_id>` (2s, 15-min timeout). **The+terminal `state: "success"` response carries the flow's OUTCOME alongside the flow**+(07-29, review round 6). Round 5 left that shape undefined, which made the two+creation paths inconsistent: `POST /sources` closes the 「so what now?」 loop with+`adopted_by`, while a subscription added through OAuth — the *default* way a+subscription is added — returned only a flow state. The closing loop is a v2 product+commitment for BOTH creation paths, so the shape is declared rather than left to the+implementing lane.++The response is a total function of `flow.intent`, which v2 adds to `OAuthFlow`:++```json+{ "ok": true, "contract_version": 2,+ "flow": { "flow_id": "oaf_claude01", "intent": "create", "state": "success",+ "source_id": "src_claudepro1", "...": "..." },+ "source": { "id": "src_claudepro1", "kind": "subscription", "...": "..." },+ "adopted_by": [ { "backend": "claude", "policy": "follow", "position": 1 } ] }+```++- `intent: "create"` → `{flow, source, adopted_by}`, with `source` and `adopted_by`+ carrying exactly the `POST /sources` semantics, because it is the same event: a new+ source exists and the backends on 跟随推荐 picked it up. Auto-creation on flow+ success is already the shipped behaviour; what round 6 adds is that the created+ source stops being discarded from the response.+- `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}` — the repair tail+ above, field for field, because it is the same repair reached through a different+ door. `adopted_by` is deliberately **absent** here rather than `[]`: the source+ already existed and no order changed, whereas `[]` on the create path asserts the+ real fact 「eligible for nobody」.++`intent` is what makes the shape derivable from the payload instead of from client+memory of which button was pressed. `source_id` cannot serve: hub-channel *create*+flows also set it, for the pending source they bind to, so it does not discriminate+creation from repair. A non-terminal poll, and a flow that ends `failed` or+`cancelled`, carry `flow` alone — there is no source and no repair to report. The+field is OPTIONAL in `oauth-flow.schema.json` for the standing reason (README →+required-vs-optional): the shipped flow payloads are validated against that file by+`tests/test_model_hub_api.py`, and they predate the field, so a `required` there+would fail the contract gate instead of tightening it. The server always emits it+from v2 on, which is a response-shape assertion in the serializer PR.++## Probe response nesting++```json+{ "ok": true, "contract_version": 2,+ "probe": { "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2",+ "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted",+ "via_mapping": true, "contract_version": 2, "backend": "claude" } }+```++The latency is **measured, not null** (corrected 07-29, review round 4). A+`balance_exhausted` is learned FROM a completed upstream response — the server+answered and told us the credit is gone — and `latency_ms: null` is reserved for+attempts that never completed at all, which the UI renders as 未完成. A frozen+example carrying that pair teaches every implementation and example-driven test+to show a completed billing answer as an unfinished request, so+`probe-result.schema.json` now makes the pair unrepresentable: any+`models.source.needs_action.*` error requires an integer latency. null belongs to+the transport family (`models.source.cooldown.network` / `.timeout`), which has+its own example on that schema.++`ProbeResult` is **nested**, and its outcome field is `reachable`, not `ok`. Both+halves of that matter. `reachable` means **the upstream completed the request+usably** — 能不能用, the question 「试跑一次」 asks — and NOT "the upstream answered"+(wording corrected 07-29, review round 6: that phrasing survived from round 4 and+contradicted both the corrected schema definition and the example directly above,+where a `balance_exhausted` is learned FROM a completed 402 and is `reachable:+false`). The schema makes the alignment mechanical: `reachable: true` requires a+null `error`, so `true` is exactly "a usable completion for this (source, model)".+Transport failures and completed-but-refused responses are both `false`, and+`reachable: false` beside a measured `latency_ms` is the normal shape of the second.+Whether the attempt completed at all is still answerable from the same object —+`latency_ms != null` — so the two questions stay separable without a second flag.+The envelope's `ok`, meanwhile, means the API call succeeded: a probe that cleanly+establishes the source is broken is a *successful* call reporting `reachable: false`+— spreading the object into the envelope would collide two different questions on+one key, and every client would eventually read the wrong one.++`ok: false` on this route is reserved for the call itself failing:+`probe_no_candidate`, `engine_down`, an unknown backend.++```json+{ "ok": false, "contract_version": 2, "error": "probe_no_candidate",+ "detail": "models.probe.no_candidate.waiting",+ "supply": { "supply_state": "waiting", "retry_at": "2026-07-29T09:15:00Z" } }+```++The structured half lives in its own `supply` key, **not in `detail`** (corrected+07-29, review round 3): round 2 put the object there, which contradicts the+envelope rule above and the two shipped client types that already declare+`detail?: string`. A client would have rendered `[object Object]` next to the one+error whose whole purpose is to explain itself. `detail` keeps doing its one job —+an i18n key, here varying with the state so the string alone is already showable.++`supply.supply_state` is the requested model's `AgentChain.supply_state`, so the copy+can be 「该模型的来源都在冷却,约 09:15 恢复」 for `waiting` and 「该模型暂无可用来源,需处理」+for `interrupted`. `supply.retry_at` is the earliest across that chain and is null for+`interrupted`, because nothing in it recovers on a timer. `supply` is present on+`probe_no_candidate` and on no other error code — a per-error typed sibling is+cheap precisely because it does not have to generalise.++## Agent-interrupted event payload++```json+{ "id": "evt_20260729c", "ts": "2026-07-29T06:55:10Z", "agent": "codex",+ "kind": "supply_interrupted", "model_id": "gpt-5.3-codex",+ "from_source": null, "to_source": null, "reason": "no_enabled_source",+ "severity": "action_required",+ "human_zh": "Codex:启用的来源已全部移除,现在无法运行 —— 去「模型」页加一个来源",+ "human_en": "Codex: every enabled source was removed, so it cannot run — add one on the Models page" }+```++The one event kind scoped to an **agent** rather than a source (spec §4.5). It fires+on the transition into `supply_status: interrupted` when no source changed state —+typically the last member of that backend's order being deleted or unchecked — which+is the case a source-keyed feed structurally cannot express. `from_source` and+`to_source` are null: nothing switched, the chain emptied. `severity` is+`action_required` by contract (schema conditional), never a judgement call at emit+time, so this is always ELIGIBLE for a proactive push and never feed-only. Emitted once+per transition, never per starved turn. Note what the payload does not carry: no+recipient, no channel, no platform. `agent: "codex"` is the addressing input — the push+layer resolves it to the scopes whose routing currently selects a Codex Vibe Agent (spec+§4.5 → 「Who receives an action-required push」). This kind is the clearest case for+resolving at delivery rather than at emit: it typically fires from a Web UI settings+mutation, which has no originating conversation to reply into.++It lives in `api.md` rather than as a `resolution-event.schema.json` example for the+same reason `severity` does — the round-trip test drives every example in that file+through the shipped v1 `ResolutionEvent`, which has no `severity` field yet (README →+required-vs-optional discipline).++## Error codes (minimum set)++`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,+`invalid_source_order` (the four rules above, plus `order` sent with+`policy: "follow"`), `source_last_supplier` (**added 07-29, review round 6** — the+guard that refuses a destructive change while it is the last supplier of a selected+model had prose, a `force=true` override and no code, so a client could not tell it+apart from a generic failure. Carries `would_interrupt: SupplyGap[]`. Raised by+DELETE without `force`, and by an elective credential rotation that would starve a+pair), `mapping_target_unavailable`, `mode_switch_blocked`,+`engine_down`, `consent_required` (hub-held subscription paths while the+experimental flag is unset), `migration_item_conflict`, `turn_not_found`,+`probe_no_candidate` (probe requested while this backend has no **runnable**+candidate for the model. The typed `supply` sibling names which case, since 「稍等即可」+and 「需处理」 are different answers for the user — and it is read from the REQUESTED+model's own chain (`AgentChain.supply_state`), never from the backend's+`supply_status` rollup. The+rollup answers for the backend's *current* model, so probing a starved non-current+menu item while the selected model is healthy would report `ok` and leave `supply`+unable to say anything true. Probing a cooling source is not offered: it would spend+a request against an account we already know is exhausted).++Removed in v2: `invalid_priority_order`.Serializer completeness: every field in these schemas must round-trip through`config_to_payload` (or the runtime status assembler) and is covered by the CIcompleteness guards (issue #939 pattern) in the same PR that introduces it.+Derived, never-persisted fields (`supply_status`, `model_supply`,+`sources.eligibility`, `AgentChain`, `ProbeResult`, `TurnProvenance`) are exempt+from config round-tripping but must still be covered by an API-payload test.+`created_at` is the opposite case — persisted, immutable, and therefore inside the+completeness guard the moment the serializer emits it.++**Mechanical guards the schemas cannot carry** (07-29, review round 5). Round 5 pushed+every invariant it could into the schemas themselves — closed enums instead of prefix+patterns, biconditionals instead of one-way implications, `required` alongside every+non-null `then`. What is listed here is the residue: invariants JSON Schema draft-07+cannot state at all. Each one ships as a check in the contract test that already walks+these files, in the same PR that introduces the field it guards. They are recorded+here so a reader can tell "draft-07 cannot express this" from "nobody thought of it":++| Guard | Why not in the schema |+| --- | --- |+| `probe-result.error` enum ≡ ALL THREE of `source.state.detail_key`'s enforced status vocabularies — cooldown ∪ needs_action ∪ the single `error` key (widened 07-29, review round 7) | cross-file identity; a bare `Draft7Validator` resolves no `$ref` across files, and two hand-kept lists drift. Round 6 widened two files and left this one asserting an identity it no longer had, so a source could enter `error` while no probe had a legal value to report it. Round 7's correction is mechanical, not editorial: the comparison now runs across files for EVERY vocabulary any of these schemas claims to mirror, from the table in `README.md` → 「Vocabulary mirrors and their blast radius」 |+| `source.state.detail_key.examples` ≡ the union of the enforced per-status enums | `examples` is documentation, so the human-readable list can silently outlive the enforced one — this already happened once in round 4, and again in round 6. The round-6 recurrence needed a second fix in the CHECKER, not the schema: the `error` key is pinned as a `const`, and a checker that collects only `enum` lists cannot see a closed vocabulary of size one, so its own union came up one key short and the comparison passed vacuously. `const` now counts as an enum of cardinality one |+| every vocabulary shared across these files is a registered row with a mechanical rule — equality, a documented projection (`chain[].health`, `supply_state`, `model_supply_state`), or a total partition (`turn-provenance.failed_attempts[].reason` against `resolution-event.reason`) | all of them are cross-file, and the non-equality ones are worse than cross-file: they are relations between vocabularies at different grains, which no schema keyword expresses in either direction. The rules and their reasons live in `README.md` → 「Vocabulary mirrors and their blast radius」; the partition is what makes a new `reason` a decision rather than a default, since it fails until the new value is either mirrored or excluded on the record |+| the INVERSE: a field whose description names another contract file must appear in that table (07-29, review round 7) | this is the half that closes the class rather than the instance. Round 6's three drifted mirrors were each asserted in prose and compared by nothing; only the pair someone had thought to check was checked. Detection is by schema STEM, not by the `.schema.json` suffix and not by the word "mirror" — the claim round 7 missed (`turn-provenance` → `failed_attempts[].reason`, naming "the resolution-event `reason` vocabulary") used neither |+| every non-null `then` constraint is accompanied by `required` for the field it constrains | draft-07 `properties` validates only fields that are PRESENT, so a conditional over an optional field is toothless when it is absent. The checker carries exactly two declared exceptions (`agent-supply` → `supply_status`, `resolution-event` → `severity`), each one a fail-SAFE absence forced by a frozen example, and fails if a declared exception stops being needed |+| `AgentChain.chain` has unique `source_id` values | `uniqueItems` compares whole items, so the same source twice with different health flags passes — and inflates `chain_length` into counting one credential as two fallbacks |+| `AgentChain.chain` preserves the relative order of `sources.order` | ordering of a *different* document is not expressible |+| every id in `sources.order` appears in `sources.eligibility` with `eligible: true` | one field constraining another; draft-07 has no `$data` |+| `channel_switch` events have `from_source == to_source` | same reason — equality between two sibling values |+| `selected_by_agent` is present on every hub-mode `AgentSupply` response | a `required` here would fail the byte-faithful round-trip on that file's two frozen examples (see the response-shape assertion above) |+| `model_supply` holds exactly one row per menu model: `model_id` values are UNIQUE and the set COVERS that backend's whole menu (07-29, review round 6) | both halves are inexpressible. `uniqueItems` compares whole items, so two rows for one model differing only in `chain_length` validate — and then a `0` row sits beside a `2` row for the same id, with every consumer reading whichever it hits first, which is worse than a missing row: the 「无来源可供」 flag becomes a coin flip. Coverage is a relation to a different document (the backend's menu), which draft-07 cannot reach. Recorded as a server-validated invariant in spec §4.4 |+| the `reason`↔`detail_key` correspondence between `resolution-event` and `source.state` is a BIJECTION over the five non-self-healing causes (07-29, review round 6) | cross-file identity again, and here it is load-bearing rather than tidy: a source state with no event reason is a blocker that cannot be announced, and an event reason with no source state is a push whose 「去处理」 lands on a row that renders nothing. The five pairs are listed at `resolution-event.schema.json` → `reason` |+| `intent` is present on every v2 `OAuthFlow` response | same boundary as `selected_by_agent`: the shipped flow payloads are validated against that schema by `tests/test_model_hub_api.py` and predate the field, so `required` would fail the gate rather than tighten it |diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.jsonindex 60ecad2e7..499fd2fff 100644--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json@@ -8,6 +8,10 @@"additionalProperties": false,"properties": {"flow_id": { "type": "string" },+ "intent": {+ "enum": ["create", "reauth"],+ "description": "v2 (07-29, review round 6): what this flow is FOR, and therefore what its terminal success response carries — `create` → `{flow, source, adopted_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 `adopted_by` 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: hub-channel CREATE flows also set it, for the pending source they bind to, so both intents can carry one. 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."+ },"source_id": { "type": ["string", "null"], "description": "v1.1: pending Source this flow binds to (deterministic association; hub-channel flows always set it)" },"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)" },diff --git a/docs/plans/model-hub-contracts/priority.schema.json b/docs/plans/model-hub-contracts/priority.schema.jsonindex dab60adf8..d355269cd 100644--- a/docs/plans/model-hub-contracts/priority.schema.json+++ b/docs/plans/model-hub-contracts/priority.schema.json@@ -1,8 +1,8 @@{"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/priority.schema.json",- "title": "Priority",- "description": "The single global spend order (spec §4.2). Authoritative and fully ordered: the server always returns the complete order after any mutation; clients never compute partial reorders (S1 freeze item: authoritative ordered priority). Per-request candidates = this order filtered by 'source supplies the requested model' and channel eligibility.",+ "title": "Priority (REMOVED in contract v2 — v1 tombstone, DO NOT IMPLEMENT)",+ "description": "REMOVED IN CONTRACT v2 (owner ruling 2026-07-28/29). The single global spend order was a product-model error: ordering is a CONSUMPTION property, so it now lives per agent backend in agent-supply.schema.json → `sources` {policy, order}. Nothing in v2 reads or writes this shape, and `PUT /api/models/priority` is gone from api.md. This file survives only as a v1 tombstone: the shipped-but-dormant v1 code still emits this payload and tests/test_model_hub_api.py still validates against it, so deleting the file today turns CI red for a shape v2 does not use. The lane that removes the endpoint and ModelHubConfig.priority_order deletes this file in the same PR and replaces that one assertion with an inline shape check. Text below is frozen v1 and must not be extended.","type": "object","required": ["contract_version", "order"],"additionalProperties": false,@@ -10,7 +10,7 @@"contract_version": { "const": 1 },"order": {"type": "array",- "description": "source ids, position 0 = spend first; MUST contain every non-deleted source exactly once",+ "description": "v1 only: source ids, position 0 = spend first; MUST contain every non-deleted source exactly once. v2's replacement is a per-backend SUBSET, not a permutation.","items": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },"uniqueItems": true}diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonnew file mode 100644index 000000000..07e488cf9--- /dev/null+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -0,0 +1,146 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/probe-result.schema.json",+ "title": "ProbeResult",+ "description": "v2 (2026-07-29): outcome of one dry-run request through an agent's current chain — 「试跑一次」 in the agent drawer footer (spec §10.1). Answers 'is this actually working right now' without making the user start a real turn, and replaces the session-level source pinning we explicitly do not build (spec §9). Inherits the resolution-event redaction invariant: classified outcomes only, never raw upstream error bodies. NOTE the outcome field is `reachable`, not `ok`: this object is nested under the standard envelope (`{ok: true, probe: ProbeResult}`), where `ok` already means 'the API call itself succeeded'. A probe that cleanly establishes the upstream is broken is a successful API call reporting `reachable: false` — the two must not share a name.",+ "type": "object",+ "required": ["contract_version", "backend", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],+ "additionalProperties": false,+ "properties": {+ "contract_version": { "const": 2 },+ "backend": { "enum": ["claude", "codex", "opencode"] },+ "reachable": {+ "type": "boolean",+ "description": "Whether this source can serve a turn RIGHT NOW — request success, not transport reachability (definition corrected 07-29, review round 5). The round-4 wording was 'whether the upstream actually answered', which contradicted this file's own frozen example: a `balance_exhausted` is learned FROM a completed 402, so the upstream did answer, yet the example reports `reachable: false` and must — 「试跑一次」 asks 能不能用, and a source that answers only to refuse is not usable. An implementer following the old sentence would have emitted `reachable: true` with a required `error`, which the true branch forbids, leaving that probe with no valid representation at all. THE NAME IS RETAINED DELIBERATELY: it is load-bearing in api.md's explanation of why this field is not called `ok`, and the transport question it appears to ask is still answerable from this object without a second field — `latency_ms != null` means the attempt completed. So the two questions are separable: `reachable` = usable, `latency_ms` = completed. Never conflate either with the envelope's `ok`."+ },+ "source_id": {+ "type": "string",+ "minLength": 1,+ "description": "The source that served (or failed) the probe — the first runnable candidate in this backend's chain for the probed model. NON-NULLABLE (07-29, review round 4): returning this object already means a candidate was resolved and attempted, because the no-candidate case is the separate `probe_no_candidate` error envelope. The v1 draft made it nullable 'for defensive serialization', which only bought the right to answer 「跑不通」 without saying what was tried — the one thing a probe exists to report."+ },+ "model_id": {+ "type": "string",+ "minLength": 1,+ "description": "The model actually sent upstream, mapping applied (the resolved id, not the menu identifier the caller passed in). Non-nullable for the same reason as `source_id`."+ },+ "latency_ms": {+ "type": ["integer", "null"],+ "minimum": 0,+ "description": "Round trip of the minimal request. THE ONLY NULLABLE FIELD besides `error`, and deliberately so: it is the one value that depends on the attempt finishing. null means the attempt never completed — the UI renders 未完成, never 0 ms. WHICH failures completed is a total function of `error`, not an emitter judgement (07-29, review round 5): exactly two keys in the closed vocabulary are transport failures (`models.source.cooldown.network` / `.timeout`) and null is reserved for those two. Every other key — the whole needs_action family AND the response-based cooldowns (429 rate limit, cycle quota exhausted, upstream 5xx) — was learned FROM a completed upstream response, so it has a measured duration. Round 4 pinned only the needs_action half, which left a 429 free to report `latency_ms: null` and render a measured response as 未完成; the partition below closes the whole set in both directions."+ },+ "error": {+ "type": ["string", "null"],+ "enum": [+ null,+ "models.source.cooldown.network",+ "models.source.cooldown.timeout",+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified"+ ],+ "description": "i18n key when reachable=false, mirroring the source `state.detail_key` vocabulary. Never raw upstream text. A CLOSED ENUM, not a prefix pattern (07-29, review round 5): round 4 used `^models\\.source\\.(cooldown|needs_action)\\..+` believing that enforced the redaction invariant, but `.+` accepts anything after a trusted-looking prefix — `models.source.cooldown.network: <raw upstream body>` matched it and would have carried an upstream payload into the API and the UI. A prefix check is a naming convention, not a boundary. The outcome set is finite and already enumerated (five self-healing causes, four that need the user, one unclassified), so the vocabulary is closed and a new cause is a contract change that comes here to declare its remedy. VOCABULARY HOME: `source.schema.json` → `state.detail_key` owns these keys — ALL THREE status families, cooldown + needs_action + the single `error` key it pins as a `const`; this is a mirror, because draft-07 has no cross-file `$ref` the contract test can resolve. `models.source.error.unclassified` was added here in round 7: round 6 introduced the `error` status and its key in `source.schema.json` alone, leaving a probe that hit an unmappable failure with no legal value for a REQUIRED field — the source could enter `error` but no probe could report why, and the mirror claim in this very sentence made the omission a documented self-contradiction rather than a gap. The lists must stay identical, and that is checked mechanically ACROSS files, not trusted — see the vocabulary mirror table in README.md and api.md → Serializer completeness. Explicitly null when reachable=true, so clients never distinguish absent from null."+ },+ "via_mapping": {+ "type": "boolean",+ "description": "true when a per-agent mapping rewrote the requested model id for this probe. Non-nullable (07-29, review round 4): it is known the moment a candidate resolves, so it is answerable on every object that gets returned."+ }+ },+ "allOf": [+ {+ "$comment": "v2 (07-29, review round 3): the nullability above was per-field and therefore too loose in combination — `reachable: true` with a null `source_id` and a non-null `error` validated, i.e. 'it answered, we don't know who, and here is why it didn't'. ROUND 4 moved the identity half UP to the type level: `source_id` / `model_id` / `via_mapping` are now plainly non-nullable, which is strictly stronger than pinning them in each branch and removes the branch bookkeeping entirely — a returned ProbeResult always identifies what was tested, in BOTH directions, and no future branch can reintroduce the hole. What is left here is genuinely conditional: `latency_ms` null means 'the attempt never completed', which a reachable probe contradicts by definition, so 未完成 belongs to the false branch alone.",+ "if": { "properties": { "reachable": { "const": true } }, "required": ["reachable"] },+ "then": {+ "properties": {+ "latency_ms": { "type": "integer" },+ "error": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 3): the converse half. `error` is the field the UI renders instead of a latency, so an unreachable probe that carries no key leaves the drawer with nothing to say — the same 'required but nullable' gap, at the other end. `latency_ms` stays nullable on this branch on purpose: an attempted failure may or may not have completed.",+ "if": { "properties": { "reachable": { "const": false } }, "required": ["reachable"] },+ "then": { "properties": { "error": { "type": "string" } } }+ },+ {+ "$comment": "v2 (07-29, review round 4; made TOTAL in round 5): which failures completed is decided by the error key, not by the emitter. Round 4 pinned the needs_action family alone — every one of those is learned FROM a completed upstream response (402/401/403 telling us the balance is out, the key is revoked, the account is banned), so `latency_ms: null` there would render a completed billing answer as 未完成. But the cooldown family is MIXED, and round 4 treated it as if it were uniformly transport: `rate_limited` (429), `quota_exhausted` and `server_error` (5xx) are all completed responses too, so they were left free to report null and reproduce the exact defect one family over. The partition is by key, and only `network` / `.timeout` are transport. Listing the completed keys explicitly rather than negating the transport pair is deliberate: with a closed enum both forms are equivalent today, but an added key would silently inherit 'completed' from a negation, whereas this list forces the contract change to say which side it is on — and round 7 is that mechanism working as designed: `models.source.error.unclassified` joined the enum and had to declare a side here. It is COMPLETED. An unclassified failure is one the adapter could not map, which means something came back to be unmappable; a request that never finished is not unclassified at all, it is `network` or `timeout` by definition.",+ "if": {+ "properties": {+ "error": {+ "enum": [+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified"+ ]+ }+ },+ "required": ["error"]+ },+ "then": { "properties": { "latency_ms": { "type": "integer" } } }+ },+ {+ "$comment": "v2 (07-29, review round 5): the converse, which is what makes the partition total instead of one-directional. Round 4's shape said 'these keys require a latency' and stopped, so 未完成 remained writable for anything not named — the open half is how the 429 case survived a round whose whole purpose was closing this class. Stated from the null side there is nothing left over: a probe that never completed MUST be one of the two transport failures, because those are the only two ways an attempt can fail to finish. Any other key with a null latency is now unrepresentable rather than merely discouraged. Round 5 also claimed this left 「no undefined combination in either direction」; that claim was false, and the branch below is the direction it missed.",+ "if": { "properties": { "latency_ms": { "type": "null" } }, "required": ["latency_ms"] },+ "then": {+ "properties": {+ "error": {+ "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 9): transport failures require a NULL latency — the half round 5 thought it had closed. Both prior branches read from one side only: 'these eight completed keys need an integer' and 'a null latency must be transport'. Neither forbids `error: models.source.cooldown.timeout` with `latency_ms: 287`, so a request that never finished could validate carrying a measured round trip, and the drawer would render 超时 next to 287ms — a completed-looking answer for the one class of failure that by definition did not complete. Stated in both directions the pair is finally a partition: transport ⇔ null, the other eight keys ⇔ integer, `reachable: true` ⇔ integer with no error. No example changes; the transport example already carries null.",+ "if": {+ "properties": {+ "error": {+ "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]+ }+ },+ "required": ["error"]+ },+ "then": { "properties": { "latency_ms": { "type": "null" } } }+ }+ ],+ "examples": [+ {+ "contract_version": 2,+ "backend": "codex",+ "reachable": true,+ "source_id": "src_chatgptplus",+ "model_id": "gpt-5.6",+ "latency_ms": 412,+ "error": null,+ "via_mapping": false+ },+ {+ "contract_version": 2,+ "backend": "claude",+ "reachable": false,+ "source_id": "src_relay9c1x",+ "model_id": "glm-5.2",+ "latency_ms": 287,+ "error": "models.source.needs_action.balance_exhausted",+ "via_mapping": true+ },+ {+ "contract_version": 2,+ "backend": "claude",+ "reachable": false,+ "source_id": "src_relay9c1x",+ "model_id": "glm-5.2",+ "latency_ms": null,+ "error": "models.source.cooldown.timeout",+ "via_mapping": true+ }+ ]+}diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.jsonindex 14c366e5d..1c4b5471d 100644--- a/docs/plans/model-hub-contracts/resolution-event.schema.json+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json@@ -9,19 +9,151 @@"properties": {"id": { "type": "string" },"ts": { "type": "string", "format": "date-time" },- "agent": { "enum": ["claude", "codex", "opencode", "system"] },- "kind": { "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"] },+ "agent": {+ "enum": ["claude", "codex", "opencode", "system"],+ "description": "A BACKEND identifier, not a Vibe Agent name (07-29, review round 7): the enum is the three agent backends, while Avibe routing selects NAMED Vibe Agents (`pm`, and any the user creates) whose backend is one of these. The two grains coincide only for the default Agent of each backend, which is why one-hop readings of 'the event names an Agent' looked correct. Consumers that need Agents or scopes MUST expand: backend → Vibe Agents currently enabled on that backend → scopes whose routing selects them (spec §4.5 → 'Who receives an action-required push' is the normative rule). `system` is not a backend at all: it is the emitter for events no backend produced (a settings mutation, a manual recovery), and it expands to no Agent and therefore to no recipient — those events are feed-and-page records, which is the zero-scope outcome spec §4.5 declares correct."+ },+ "kind": {+ "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch", "needs_action", "supply_interrupted"],+ "description": "v2 adds two. `needs_action`: a SOURCE stopped being usable in a way that will not heal itself (OAuth expired, balance exhausted, key revoked, or — round 6 — an unclassified failure, which promises no recovery either) — without it the feed would have to file such a source under `cooldown`, which promises an automatic recovery that is never coming. Its scope is 「a source went dead and stays dead until someone acts」; WHICH way it died is `reason`, which is why round 6 closed the `error`-status hole by adding a cause rather than a kind. `supply_interrupted` (07-29, review round 2): an AGENT's chain became structurally unrunnable — every other kind here is scoped to a source, and an agent can go `interrupted` with no source changing state at all (its last enabled source is removed from the order, or its selected model stops being supplied by anything in that order). The spec requires an `action_required` push for that transition (§4.5); without this kind the emitter would have to borrow a credential/quota reason and misstate the cause, or stay silent about the one state that always needs the user. Scoped to the agent: `from_source`/`to_source` are null, because nothing switched — the chain emptied. Emit on the TRANSITION only, never per starved turn. Like `needs_action`, this is a v2 target the shipped emitter predates."+ },"model_id": { "type": "string" },- "from_source": { "type": ["string", "null"] },- "to_source": { "type": ["string", "null"] },+ "from_source": {+ "type": ["string", "null"],+ "description": "v2 (07-29, review round 5): DEFINED here for the first time — the pair carried no description at all, which is the root of the round-5 finding and of the round-4 one before it. With the meaning unstated, every kind's endpoint shape was an open question and each review round found another kind nobody had pinned (round 4: `switch` had two blanks; round 5: `needs_action` had no source at all). The events split into two families and the pair serves both: TRAFFIC events say where the traffic went (`switch`, `channel_switch`, `recover`), STATE events name the one source they are about. `from_source` is the LOSING side: the source traffic moved away from, or — for a state event that moves no traffic — the source that became unusable (`cooldown`, `needs_action`, `skip`). Non-null for all four of those plus `channel_switch`; null only for the agent-scoped `supply_interrupted`, where nothing switched and no single source is the subject. A `needs_action` event without it is what the round-5 review caught: the push it mandates would have no machine-readable source to hand to the credential/reauth routes, and the localized sentence is not a safe thing to parse.",+ "examples": ["src_claudepro1"]+ },+ "to_source": {+ "type": ["string", "null"],+ "description": "v2 (07-29, review round 5): the WINNING side — the source traffic moved to, or, for `recover`, the source that became usable again. Non-null for `switch`, `channel_switch` and `recover`; null for the pure degradations (`cooldown`, `needs_action`, `skip`), where nothing gained traffic, and for `supply_interrupted`. `recover` is why the subject of a state event cannot simply always be `from_source`: it is the one restoration in the enum, so its subject enters service rather than leaving it, and filing it under 'from' would invert the sentence the feed renders. `channel_switch` carries the SAME id at both ends by design — the channel changed, the source did not (see the `allOf` note).",+ "examples": ["src_anthkey01"]+ },"reason": {- "enum": ["quota_exhausted", "rate_limited", "server_error", "network", "recovery", "manual", "mapping"],- "description": "Canonical error classification lives in the adapter (S1 gap ①): param/protocol/tool-compat errors surface to the caller and never produce switch events."+ "enum": [+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ "recovery",+ "manual",+ "mapping",+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "unclassified_error",+ "no_enabled_source",+ "no_eligible_source",+ "model_unsupported"+ ],+ "description": "Canonical error classification lives in the adapter (S1 gap ①): param/protocol/tool-compat errors surface to the caller and never produce switch events. The last three are the `supply_interrupted` causes (07-29), and they are three rather than one because each names a different one-tap fix: `no_enabled_source` = this backend's order is empty or just lost its last member (add one to the order, or switch back to 跟随推荐), `no_eligible_source` = nothing in the whole inventory is eligible for this backend (add a source), `model_unsupported` = the order is populated but nothing in it supplies the selected model (pick another model, or map this one). Agent-scoped by construction — they are never valid for a source-scoped kind. PRECEDENCE IS NORMATIVE, not emitter preference (07-29, review round 3): these three overlap, so evaluate them in this order and emit the FIRST that matches — (1) `no_eligible_source`, (2) `no_enabled_source`, (3) `model_unsupported`. Ineligibility subsumes emptiness: if nothing in the inventory is eligible for this backend then its enabled order is necessarily empty too, and both predicates match. Picking `no_enabled_source` there would offer 「加到顺序里」 for a set of candidates that does not exist, sending the user to a drawer with nothing to enable, when the real fix is to add a source. `model_unsupported` comes last because it presupposes a populated, eligible order. `reason` is required, so v2 also adds the four needs_action causes — without them a `kind: needs_action` event would have to borrow a self-healing reason like `quota_exhausted` and the feed would misstate what happened. FIVE, as of 07-29 review round 6: `unclassified_error` is the counterpart of source `state.status: \"error\"`, and it closes a hole the review named. `error` is a BLOCKER that needs the user — `agent-chain.schema.json` pins `runnable: false` for it and counts it in the OR-branch that makes a chain `interrupted`, exactly like `needs_action` — so an interruption caused by the last runnable source going `error` obliges an action_required push (spec §4.5), and there was no reason in this enum that could carry it. The emitter's only options were to misclassify (borrow `credential_revoked` and assert a cause nobody established) or stay silent (drop the one alert the user is owed, on the state we understand least). Neither is acceptable, so the vocabulary grew by one rather than the obligation shrinking. It is deliberately NOT a widening of `supply_interrupted`, which nulls both endpoints: this interruption HAS a source — the one that failed — and stripping the push of its machine-readable source is the exact defect round 5 fixed for `needs_action`. Nor is it a 9th `kind`: the state is 「a source stopped being usable and will not heal itself」, which is what `needs_action` already means; only the cause differs, and cause is what `reason` is for. THE FIVE MAP 1:1 ONTO source `state.detail_key`, and with this one the correspondence is a BIJECTION over every non-self-healing key: credential_expired→models.source.needs_action.oauth_expired, credential_revoked→.credential_revoked, balance_exhausted→.balance_exhausted, account_banned→.account_banned, unclassified_error→models.source.error.unclassified. Totality in both directions is the property that matters — a source state with no reason cannot be announced, and a reason with no state sends 「去处理」 to a row that renders nothing — and it is checked mechanically (api.md → Mechanical guards). Note the deliberate pair: `quota_exhausted` is a subscription cycle running out (self-healing, resets) while `balance_exhausted` is prepaid credit hitting zero (needs a top-up). THIS FIELD IS A VOCABULARY HOME with a computed downstream (07-29, review round 7): `turn-provenance.schema.json` → `failed_attempts[].reason` holds exactly this set minus the three resolution-shaped values (`recovery`, `manual`, `mapping`) minus the three that classify an agent's whole supply rather than one candidate's attempt (`no_enabled_source`, `no_eligible_source`, `model_unsupported`) — a set equality, checked across files (README.md → vocabulary mirror table). So adding a value here is never a local edit: it lands in the attempt-failure set by default, and keeping it out requires putting it in one of the two documented exclusions. Round 6 added `unclassified_error` here alone, which left that mirror one value short and an unmappable fallback with no legal reason to report."+ },+ "billing_note": { "enum": [null, "entered_metered", "left_metered"], "description": "drives the gold dot in frame V6 01" },+ "severity": {+ "type": ["string", "null"],+ "enum": ["info", "action_required", null],+ "description": "v2 (2026-07-29): the notification tier, decided once at emit time (spec §4.5). info = self-healing (switch/cooldown/recover) — appears in the 最近切换 feed ONLY, never an IM push. action_required = the user owes an action (needs_action sources, an interrupted agent chain) — proactive IM push in colleague voice. The push layer MUST key off this field rather than re-deriving urgency from `kind`, so 'when do we interrupt the user' has exactly one definition. Because it is the sole input to that decision, the two kinds the spec puts in the action-required tier — `needs_action` and `supply_interrupted` — pin it to `action_required` by CONDITIONAL (see `allOf`), not by emitter discipline: those are the events whose whole purpose is to reach the user, so 'emitted correctly but never delivered' must not be a representable state. Every OTHER kind is `info` by conditional too (07-29, review round 4) — the §4.5 table has exactly two action-required rows, so the tier is a total function of `kind` and no emitter judgement enters: 'emitted a self-healing state as an interruption' is likewise unrepresentable. SEVERITY ANSWERS WHETHER TO INTERRUPT, NEVER WHOM (07-29, review round 5): it is a tier, not an address, which is why this event carries no recipient, channel, platform, or audience field. Recipients are resolved AT DELIVERY from the event's `agent` (source-scoped kinds resolve to the agents whose `sources.order` contains that source) against the live routing table — spec §4.5 → 'Who receives an action-required push' is the normative rule. Putting them here instead would freeze a routing snapshot into an append-only feed: a scope re-pointed at a different agent afterwards would still be addressed by the old event, and a scope added later would never be. So `action_required` makes an event ELIGIBLE for delivery rather than constituting delivery, and an eligible event resolving to zero scopes is correctly delivered nowhere. Optional in this schema only because the shipped v1 emitter predates it; it becomes REQUIRED at the API boundary in the serializer PR (README → Required-vs-optional)."},- "billing_note": { "enum": [null, "entered_metered", "left_metered"], "description": "drives the gold dot in frame 01r" },"human_zh": { "type": "string", "maxLength": 200 },"human_en": { "type": "string", "maxLength": 200 }},+ "allOf": [+ {+ "$comment": "v2 (07-29): agent-scoped kind ⇒ agent-scoped shape. Stated as a conditional rather than prose so a contradictory event cannot validate: nothing switched, so no source endpoints; the state always needs the user, so the tier is not a judgement call at emit time.",+ "if": { "properties": { "kind": { "const": "supply_interrupted" } }, "required": ["kind"] },+ "then": {+ "required": ["severity"],+ "properties": {+ "severity": { "const": "action_required" },+ "from_source": { "type": "null" },+ "to_source": { "type": "null" },+ "reason": { "enum": ["no_enabled_source", "no_eligible_source", "model_unsupported"] }+ }+ }+ },+ {+ "$comment": "v2 (07-29): and the converse, so the three agent-scoped reasons cannot be attached to a source-scoped kind.",+ "if": {+ "properties": { "reason": { "enum": ["no_enabled_source", "no_eligible_source", "model_unsupported"] } },+ "required": ["reason"]+ },+ "then": { "properties": { "kind": { "const": "supply_interrupted" } } }+ },+ {+ "$comment": "v2 (07-29, review round 3): `needs_action` gets the same treatment as `supply_interrupted`, for the same reason. `severity` is the SOLE input to the push layer (api.md → events), and the spec puts needs_action in the action-required tier unconditionally (§4.5 notification table). Leaving `info`/null writable here would let a semantically invalid event validate and silently cost the user the one alert they are owed — a revoked key that never notifies. Its causes are pinned too: a needs_action event carrying `quota_exhausted` would describe a state that heals itself, which is exactly the confusion this kind exists to end. FIVE causes as of round 6, not four — `unclassified_error` joins them so the source status `error`, which `agent-chain` already treats as a user-owed blocker, has a representable action-required event instead of forcing the emitter to misclassify or stay silent (see `reason`). Source-scoped, so `from_source`/`to_source` are deliberately NOT constrained here — the round-5 member below requires `from_source` for this kind, which is what gives the push something to open.",+ "if": { "properties": { "kind": { "const": "needs_action" } }, "required": ["kind"] },+ "then": {+ "required": ["severity"],+ "properties": {+ "severity": { "const": "action_required" },+ "reason": { "enum": ["credential_expired", "credential_revoked", "balance_exhausted", "account_banned", "unclassified_error"] }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): the tier is now decided for EVERY kind, not just the two that push. Round 3 pinned `needs_action` and `supply_interrupted` to `action_required` and left the rest 'the emitter's choice', which meant a `switch` or a `cooldown` could still carry `action_required` and interrupt the user about a state that heals itself in minutes — the exact failure the `waiting` class was invented to prevent (spec §4.5: self-healing states are feed-only, NEVER an IM push). The spec's notification table has exactly two rows and names exactly two action-required causes, so every other kind is `info` by that table, not by judgement. With both halves pinned, `severity` is fully determined by `kind` — which is the point: the push layer reads one field, and no emitter can disagree with the table. PRESENCE DELIBERATELY NOT REQUIRED on this branch (07-29, review round 5), unlike the two action-required branches above which do require it: this file's frozen example is a `switch` carrying no `severity` at all — it round-trips byte-faithfully through the shipped v1 emitter, which predates the field — so requiring it here would fail the contract gate. The asymmetry is not a compromise, it is the right way round. An absent `severity` on an info kind means no push, which is what the info tier asks for anyway; an absent `severity` on `needs_action` would mean a revoked key that never alerts anyone, so that is exactly where presence IS required. Enforced as a declared exception in the round-5 presence checker so it cannot decay into an accident (api.md → Serializer completeness).",+ "if": {+ "properties": {+ "kind": { "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"] }+ },+ "required": ["kind"]+ },+ "then": { "properties": { "severity": { "const": "info" } } }+ },+ {+ "$comment": "v2 (07-29, review round 4; widened to five in round 6): the NON-SELF-HEALING causes cannot be filed under a SELF-HEALING kind. `cooldown` promises an automatic recovery and `recover` reports one, so 'cooling because the key was revoked' and 'recovered by account ban' are both contradictions — and the first is precisely the misfiling `needs_action` was added to end (a dead source dressed as a timer, with an `info` tier and no alert). `unclassified_error` is in the same class and joins for the same reason: an unclassified failure carries no promise about when it lapses (`source.schema.json` pins `retry_at` null for `error`), so filing it as a cooldown would invent a recovery time the adapter explicitly does not have. NOTE the deliberately narrow scope, unchanged: these reasons ARE valid on `switch`, because falling back AWAY from a revoked — or unclassifiably broken — source is a real self-healing switch whose cause is that failure, and turn-provenance keeps the same causes in its FALLBACK vocabulary for that reason. A blanket 'these reasons imply kind == needs_action' converse would make that switch unrepresentable and force the emitter to relabel the cause of a switch it correctly performed; the two events are emitted together (one `switch`, info + one `needs_action`, action_required), each true about its own subject.",+ "if": {+ "properties": {+ "reason": { "enum": ["credential_expired", "credential_revoked", "balance_exhausted", "account_banned", "unclassified_error"] }+ },+ "required": ["reason"]+ },+ "then": { "properties": { "kind": { "not": { "enum": ["cooldown", "recover"] } } } }+ },+ {+ "$comment": "v2 (07-29, review round 4; presence added in round 5): a `switch` has two ends by definition — it is the one kind whose whole content is 'from here to there', and the feed line 「A 额度用完 → 已切到 B」 cannot be written without both. Left free, a switch with null endpoints would render as a sentence with two blanks. ROUND 5: `required` was missing, and neither endpoint is in the top-level `required` list, so this whole conditional was decorative — a switch that simply omitted both keys validated, which is the same defect the review named on source.schema.json's `credential_ref` and is fixed the same way. `then: {properties: …}` never enforces presence in draft-07.",+ "if": { "properties": { "kind": { "const": "switch" } }, "required": ["kind"] },+ "then": {+ "required": ["from_source", "to_source"],+ "properties": {+ "from_source": { "type": "string" },+ "to_source": { "type": "string" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): every SOURCE-SCOPED kind must name its source, which round 4 left open for four of the eight kinds after pinning it for `switch`. `needs_action` is the one that costs the user something real and is what the review named: it is the action_required tier, so its whole purpose is to reach the user with 「去处理」 — and with both endpoints null the push has nothing to open, nothing to hand the credential/reauth routes, and only a localized sentence, which is not a safe thing to parse. `cooldown` and `skip` are the same shape and are fixed in the same member rather than waiting to be reported: all three are degradations, so the subject is the LOSING side and `to_source` stays null because nothing gained traffic. Fixing the reported kind alone would have left two instances of the identical hole one line away.",+ "if": { "properties": { "kind": { "enum": ["needs_action", "cooldown", "skip"] } }, "required": ["kind"] },+ "then": {+ "required": ["from_source"],+ "properties": {+ "from_source": { "type": "string" },+ "to_source": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): `recover` is the one RESTORATION in the enum, so its subject enters service instead of leaving it and belongs on the winning side — this is exactly why 'the subject of a state event is always from_source' would have been the wrong rule to write. `from_source` is deliberately NOT constrained: a recovery reached by switching back from a fallback has one (「已切回 A」), while a recovery that only restores availability — the credential-replacement route in api.md, where nothing was serving because the source was needs_action — has nothing on the losing side, and both are true events.",+ "if": { "properties": { "kind": { "const": "recover" } }, "required": ["kind"] },+ "then": {+ "required": ["to_source"],+ "properties": {+ "to_source": { "type": "string" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): `channel_switch` keeps the source and changes how it is consumed (native_cli ↔ hub), so both ends exist and carry the SAME id — the shape was already documented in the round-4 note and was the last source-scoped kind with no constraint at all. The equality itself is not expressible in draft-07 (no `$data`, so one field cannot reference another) and is a mechanical guard instead (api.md → Serializer completeness); what IS enforced here is that neither end is empty, so 「已改为中枢通道」 can always name its source. With this member the endpoint shape is a total function of `kind`: two ends for the traffic events, the losing end for the degradations, the winning end for the restoration, neither end for the agent-scoped `supply_interrupted`. ONE kind is deliberately left unconstrained: `mapping_applied` is decided at spec §4.3 step 1, BEFORE any candidate is selected, so it has no endpoint of its own and its feed line names models rather than sources (「claude-opus-4-6 → glm-5.2(经映射)」). An emitter that attaches the serving source is stating a true fact about a different subject, so neither shape is a contradiction and pinning one would be inventing a rule the spec does not have.",+ "if": { "properties": { "kind": { "const": "channel_switch" } }, "required": ["kind"] },+ "then": {+ "required": ["from_source", "to_source"],+ "properties": {+ "from_source": { "type": "string" },+ "to_source": { "type": "string" }+ }+ }+ }+ ],"examples": [{"id": "evt_20260723a",diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex ae6fdd5bd..0b1d6622e 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -13,6 +13,7 @@"supply_channel","billing","state",+ "credential_ref","models"],"additionalProperties": false,@@ -21,6 +22,14 @@"type": "string","pattern": "^src_[a-z0-9]{8,}$"},+ "created_at": {+ "type": [+ "string",+ "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)."+ },"kind": {"enum": ["subscription",@@ -63,7 +72,7 @@"null"],"format": "date-time",- "description": "Set iff this is a hub-held subscription the user explicitly consented to (subscription_hub_experimental). null otherwise."+ "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."},"billing": {"enum": [@@ -77,28 +86,161 @@"status"],"additionalProperties": false,+ "allOf": [+ {+ "$comment": "v2 (07-29, review round 4): ONE conditional per `status`, covering all five, so the status↔detail correlation is unwritable-wrong rather than merely documented. Round 3 pinned only the `needs_action` branch, which left every other status free to carry a stale `retry_at` or a mismatched `detail_key` — the same class of gap the round-4 review named in three other files. The two healthy values carry neither: a healthy source has nothing to wait for and nothing to explain, so a leftover cooldown stamp here would make the row promise a recovery for a source that is already serving.",+ "if": {+ "properties": {+ "status": {+ "enum": [+ "active",+ "standby"+ ]+ }+ },+ "required": [+ "status"+ ]+ },+ "then": {+ "properties": {+ "retry_at": {+ "type": "null"+ },+ "detail_key": {+ "type": "null"+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4; vocabulary closed in round 5): `cooldown` is the ONLY status whose `retry_at` is non-null — spec §4.5 defines it as 'self-healing, `retry_at` known', and 「约 09:15 恢复」 is the whole copy of the state. A cooldown with a null stamp leaves the UI able to say only 暂不可用 with no recovery time, which is indistinguishable to the user from 需处理 — the one distinction this taxonomy exists to make. `detail_key` stays optional here (the recovery time is the load-bearing fact, the cause is a nicety) but its vocabulary is now a CLOSED ENUM rather than the `^models\\.source\\.cooldown\\..+` pattern round 4 used. The round-5 review named that bypass on probe-result's `error`, where the identical construction let `models.source.cooldown.network: <raw upstream body>` validate; the same prefix-plus-`.+` shape was here too and is the same hole, so it is closed in both files rather than only where it was spotted. `.+` after a trusted prefix is a naming convention, not a redaction boundary — the whole point of `detail_key` is that raw upstream text never reaches config or the UI. The five keys are the self-healing causes the adapter classifies; `needs_action` keys remain unwritable here, so a dead source still cannot be filed under a status that promises recovery.",+ "if": {+ "properties": {+ "status": {+ "const": "cooldown"+ }+ },+ "required": [+ "status"+ ]+ },+ "then": {+ "required": [+ "retry_at"+ ],+ "properties": {+ "retry_at": {+ "type": "string"+ },+ "detail_key": {+ "enum": [+ null,+ "models.source.cooldown.network",+ "models.source.cooldown.timeout",+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error"+ ]+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 3; vocabulary closed in round 4): `detail_key` is mandatory for `needs_action` because a state whose whole point is 'the user must act' is unrenderable without naming the action. Round 3 accepted any non-empty string, which let a cooldown key or a typo validate while leaving the action-required row without a usable remedy — the UI switches on exactly these four keys to choose re-auth / top-up / key-replacement / vendor-contact, so 'some other key' has no behaviour to fall back on. The vocabulary is therefore an enum here, not a pattern: a new cause is a contract change (a new one-tap remedy has to be designed), not something an emitter may invent.",+ "if": {+ "properties": {+ "status": {+ "const": "needs_action"+ }+ },+ "required": [+ "status"+ ]+ },+ "then": {+ "required": [+ "detail_key"+ ],+ "properties": {+ "detail_key": {+ "enum": [+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned"+ ]+ },+ "retry_at": {+ "type": "null"+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): `error` is the UNCLASSIFIED failure, and round 4 read that as a reason to leave `detail_key` unconstrained — 'the point of the value is that we do not know the cause', recorded as a deliberate non-constraint. That reasoning was wrong, and the round-5 review is right that it was: not knowing the CAUSE is not permission to widen the CHANNEL. An unconstrained `detail_key` on the one status an adapter reaches when it cannot classify a failure is precisely where a raw upstream body lands — an auth response, a token-bearing diagnostic — and this field is persisted to config and rendered in the UI, so the redaction invariant (README invariant 1) would be waived at exactly the path most likely to carry secret material. Being unclassified makes redaction MORE load-bearing, not less. The vocabulary is therefore a single generic key, which is the honest cardinality: there is nothing to distinguish, so a richer set would be inventing causes the adapter by definition could not name, and any new one is a contract change with a designed remedy. It is REQUIRED rather than nullable for the same reason the needs_action keys are — the row must have something to render — and a null would be a second way to say the one thing this status says. The raw diagnostic keeps its home in scrubbed logs, never here. `retry_at` stays pinned null: an unclassified failure carries no promise about when it lapses, and offering one would be a guess rendered as a fact. ROUND 6 pins the other end of this status too: because `retry_at` is null and nothing will clear it unattended, `error` is a blocker that NEEDS THE USER — `agent-chain.schema.json` already counts it in the OR-branch that makes a chain `interrupted`, alongside `needs_action` — so an interruption caused by the last runnable source landing here is owed an action_required push. `resolution-event.schema.json` therefore carries `reason: unclassified_error`, which maps onto this exact key and makes the reason↔detail_key correspondence a bijection over all five non-self-healing keys. Without it the emitter had to choose between misclassifying the cause and staying silent on the state we understand least.",+ "if": {+ "properties": {+ "status": {+ "const": "error"+ }+ },+ "required": [+ "status"+ ]+ },+ "then": {+ "required": [+ "detail_key"+ ],+ "properties": {+ "retry_at": {+ "type": "null"+ },+ "detail_key": {+ "const": "models.source.error.unclassified"+ }+ }+ }+ }+ ],"properties": {"status": {"enum": ["active","standby","cooldown",+ "needs_action","error"- ]+ ],+ "description": "Classified by whether the state heals itself (spec §4.5). cooldown = 暂不可用, self-healing, `retry_at` known; needs_action = 需处理, will NEVER recover unattended (v2, 2026-07-29) — the conditional above makes `detail_key` mandatory there, because a state whose whole point is 'the user must act' is unrenderable without naming the action; error = unclassified failure — and, pinned in round 6, a BLOCKER rather than a third class: its `retry_at` is null and nothing clears it unattended, so it counts WITH `needs_action` in the OR-branch that makes a chain `interrupted` (`agent-chain.schema.json`), and the interruption it causes is announced as `kind: needs_action`, `reason: unclassified_error`. 'We could not classify the failure' describes our knowledge of the cause, never a promise about recovery. active/standby are the two HEALTHY values and are a source-global DISPLAY ROLLUP, not a per-agent fact: active = 使用中, i.e. serving at least one agent right now; standby = 备用, healthy but currently serving nobody. A source can be at the head of Claude's order and third in Codex's, so per-agent role is read from position in `agent-chain.schema.json` and is never stored here. Health itself is genuinely source-global: quota and reachability are properties of the account, so one cooldown pool is shared across backends (core/handlers/model_hub/service.py::_cooldown). NOTE: `needs_action` is a v2 TARGET value — config/v2_config.py's loader whitelist still rejects it until the serializer PR lands it."},"retry_at": {"type": ["string","null"],- "format": "date-time"+ "format": "date-time",+ "description": "When a cooldown lapses. NON-NULL FOR EXACTLY ONE STATUS — `cooldown` — and null for the other four, by the conditionals above rather than by emitter discipline: `needs_action` and `error` never recover on a timer, and a healthy source has nothing to wait for. Same predicate as `retry_at` in agent-chain.schema.json, which mirrors this field per chain member."},"detail_key": {"type": ["string","null"],- "description": "i18n key, never raw upstream error text"+ "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 so the row can offer one tap to fix it, and the four keys are required: models.source.needs_action.oauth_expired (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).",+ "examples": [+ "models.source.cooldown.network",+ "models.source.cooldown.timeout",+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified"+ ]}}},@@ -127,6 +269,14 @@"null"],"description": "ISO 4217. Default and product standard is USD (owner ruling 2026-07-25): upstream vendors bill in USD, so UI must never fall back to a local currency. Other codes are honored only when the backend explicitly reports them."+ },+ "projected_exhaust_at": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "v2 (2026-07-29), subscription sources only: linear projection of when the CYCLE QUOTA runs out, from recent usage. Drives the sub-line 「按近 7 天用量,预计周三用完」. Pinned null for `kind: api_key` by the source-level conditional below (07-29, review round 4) — a metered key has no cycle to exhaust, so a timestamp there would render a subscription-style forecast on a pay-as-you-go source and tell the user their key expires on Wednesday. PHASED DELIBERATELY — the contract is frozen in v2, the projection itself may land later, and null MUST render as simply absent (never 0, never '未知'). Frozen here so the field never has to be retrofitted through the serializer completeness guard twice."}}},@@ -139,6 +289,28 @@"provenance"],"additionalProperties": false,+ "allOf": [+ {+ "$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": {+ "const": "manual"+ }+ },+ "required": [+ "provenance"+ ]+ },+ "then": {+ "properties": {+ "discovered_at": {+ "type": "null"+ }+ }+ }+ }+ ],"properties": {"id": {"type": "string",@@ -172,7 +344,7 @@"string","null"],- "description": "Opaque handle. Secret material NEVER appears in any payload (README invariant 1). null for native_cli sources (credential lives in the CLI's own store)."+ "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."},"account_label": {"type": [@@ -189,6 +361,148 @@"description": "v1.1 (07-23 12:10, L4 finding): non-reversible display mask for api_key sources, computed by L2 ONCE at provisioning from the transient secret (rule: ≤7-char prefix + '…' + last 4, e.g. 'sk-ant-…8f2A') and persisted as display data only. Never re-derivable, never secret material."}},+ "allOf": [+ {+ "$comment": "v2 (07-29, review round 4): EXHAUSTIVE SWEEP of the kind / channel / credential correlations this file states in prose. Round 4 named two instances of the class (`projected_exhaust_at` unconstrained by `kind`, native-CLI reauth able to acquire a `credential_ref`); patching only those two would leave the rest of the same class writable, so every 'X only' / 'null for Y' sentence in this file is now a conditional. Three correlations are deliberately NOT constrained, recorded here so a later reader can tell judgement from oversight: `account_label` (display identity, may be populated for either kind by a later adapter rev — the prose scopes its PURPOSE to subscriptions, it does not forbid the field elsewhere); `usage.cycle_used_pct` / `month_spend_cents` against `billing` (a metered relay can bill in monthly cycles, and no rule here says otherwise); and `billing` against `kind` (a prepaid subscription and a monthly-invoiced key both exist upstream). Constraining those would be inventing product rules under cover of a review fix.",+ "if": {+ "properties": {+ "kind": {+ "const": "subscription"+ }+ },+ "required": [+ "kind"+ ]+ },+ "then": {+ "properties": {+ "base_url": {+ "type": "null"+ },+ "masked_credential": {+ "type": "null"+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): the api_key shape. `supply_channel: hub` is not a default here but the only possibility — `native_cli` means the sanctioned CLI holds an OAuth credential in its own store (README 07-23 ruling), and a pasted key is provisioned into the engine-owned store instead, which is the hub channel by definition. `projected_exhaust_at` is pinned null for the reason at the field itself.",+ "if": {+ "properties": {+ "kind": {+ "const": "api_key"+ }+ },+ "required": [+ "kind"+ ]+ },+ "then": {+ "properties": {+ "supply_channel": {+ "const": "hub"+ },+ "usage": {+ "properties": {+ "projected_exhaust_at": {+ "type": "null"+ }+ }+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 4): the `credential_ref` half of the channel rule, and the contract half of the round-4 finding on native re-auth (api.md → sources/<id>/reauth). A `native_cli` source's credential lives in the CLI's own store, so this handle has nothing to point at; a hub source's credential lives in the engine store, so a null handle there means the source cannot be called at all. Making both directions conditionals means a re-auth route that swaps in an engine credential ref for a native source produces a payload that fails validation instead of one that quietly relocates a sanctioned credential.",+ "if": {+ "properties": {+ "supply_channel": {+ "const": "native_cli"+ }+ },+ "required": [+ "supply_channel"+ ]+ },+ "then": {+ "properties": {+ "credential_ref": {+ "type": "null"+ }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 5): the hub direction now has teeth. Presence is guaranteed by the top-level `required` list (see the field description for why it belongs there and not in this branch), so this constraint fires on every hub source instead of only on the ones that happened to include the key — which is the whole of the round-5 finding: round 4 stated the invariant and shipped a check that a missing field walked straight past.",+ "if": {+ "properties": {+ "supply_channel": {+ "const": "hub"+ }+ },+ "required": [+ "supply_channel"+ ]+ },+ "then": {+ "properties": {+ "credential_ref": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ },+ {+ "$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": [{"id": "src_claudepro1",diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonnew file mode 100644index 000000000..43642cee5--- /dev/null+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -0,0 +1,240 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/turn-provenance.schema.json",+ "title": "TurnProvenance",+ "description": "v2 (2026-07-29): what served one turn — read via GET /api/models/turns/<turn_id>/provenance, rendered as the per-turn detail the conversation surface reveals on demand (spec §4.5). Frozen in v2 because the spec promises per-turn inspectability and a promise with no interface cannot be implemented consistently: this file is where that promise says what it means. Distinct from resolution-event.schema.json, which is the account-wide 最近切换 feed keyed on state CHANGES; this is keyed on a TURN and always exists, switch or not. Storage is the implementing lane's decision, with one constraint: written when the turn resolves and readable after the process exits — 'which source paid for this turn' is a billing question the user asks days later. Same redaction invariant as every other payload here: ids and i18n keys, never credential material or raw upstream error bodies. SHAPE RULING (07-29, review round 2): the winning attempt lives in `served` and NOWHERE ELSE, so 'at most one attempt served' and 'the served attempt is last' are not invariants a validator or a test has to defend — they are unrepresentable. Round 1 had one `attempts` array carrying an `outcome` per item, which let a payload claim two winners, a winner in the middle, or a top-level projection naming a source the array never mentions. The full attempt sequence is still recoverable, in order, as `failed_attempts` ++ [the terminating attempt], where the terminating attempt is `served`, `terminal_error`, or neither (nothing was ever tried). Round 3 generalised the ruling rather than bending it: a turn ends exactly one way, so the attempt that ENDED it lives in exactly one slot, and at most one of `served`/`terminal_error` is ever non-null.",+ "type": "object",+ "required": ["contract_version", "turn_id", "ts", "agent", "requested_model_id", "outcome", "failed_attempts", "served", "terminal_error", "model_supply_state"],+ "additionalProperties": false,+ "properties": {+ "contract_version": { "const": 2 },+ "turn_id": {+ "type": "string",+ "description": "The turn this describes, in whatever id space the session store already uses. Opaque here — this contract does not invent a new identifier."+ },+ "ts": {+ "type": "string",+ "format": "date-time",+ "description": "When the turn resolved (served or gave up), not when it started."+ },+ "agent": {+ "enum": ["claude", "codex", "opencode"],+ "description": "A BACKEND identifier, not a Vibe Agent name (07-29, review round 7): the enum is the three agent backends, while Avibe routing selects NAMED Vibe Agents (`pm`, and any the user creates) whose backend is one of these. The two grains coincide only for the default Agent of each backend, which is why one-hop readings of 'the event names an Agent' looked correct. Consumers that need Agents or scopes MUST expand: backend → Vibe Agents currently enabled on that backend → scopes whose routing selects them (spec §4.5 → 'Who receives an action-required push' is the normative rule). Mirrors `agent-supply.schema.json` → `backend` exactly; the name is historical and kept for round-trip fidelity with the shipped payload."+ },+ "requested_model_id": {+ "type": "string",+ "description": "What the caller asked for, as the caller-facing MENU identifier (prefixed for open menus) — before mapping. Recorded because 「我选的模型」 and 「实际跑的模型」 differing is precisely what the user is inspecting."+ },+ "outcome": {+ "enum": ["served", "exhausted", "failed_terminal", "no_candidate"],+ "description": "How the turn ended, as one field instead of something the reader infers by comparing two others. served = one attempt COMPLETED the turn successfully. Not 'produced output' (corrected 07-29, review round 4): a source that emits one token and then dies has produced output, and §4.3 rules that same turn `failed_terminal` with `stream_interrupted` — so the loose reading made both outcomes true of the one scenario whose whole point is that it is NOT a success, and the field exists precisely to stop the reader inferring the answer. Partial output followed by a failure is `failed_terminal` with `stream_started: true`; that pair is how the record says 'the user saw a half-written answer', and it is the only honest way to say it. exhausted = fallback was walked to the end and every attempt failed for a fallback cause (`failed_attempts` non-empty, everything else null). failed_terminal (07-29, review round 3) = an attempt hit a NON-fallback error and the turn stopped there, recorded in `terminal_error`. no_candidate = the pipeline never tried anything (`failed_attempts` EMPTY) because this (agent, model) chain had nothing runnable — an empty chain, or every member blocked. `failed_terminal` closes a hole round 2 left open: spec §4.3 says param/protocol/tool-compat errors surface to the caller instead of producing a fallback, and that once streaming has started there is no transparent retry — so such a turn is neither `served` nor `no_candidate`, and calling it `exhausted` would be a lie twice over (the chain was NOT exhausted, and the emitter would have to borrow a fallback reason like `server_error` to fill a required field, misfiling a broken request as a supply problem and pointing the user at their account instead of the actual bug). A record with no honest value for its own outcome field is worse than no record. `no_candidate` is the reason `failed_attempts` has no minItems: a turn that gave up before touching a source is exactly the turn the user most needs to inspect, so fabricating a phantom attempt to satisfy a schema would corrupt the record it exists to preserve."+ },+ "failed_attempts": {+ "type": "array",+ "description": "Every candidate that was tried and did NOT serve, in the order it was tried. May be empty (see `outcome: no_candidate`). Candidates SKIPPED before being tried (cooling, ineligible, needs_action) are not attempts and are absent — the chain query answers 'what else exists'. Every item here failed, by construction: there is no per-item outcome to disagree with the top level.",+ "items": {+ "type": "object",+ "required": ["source_id", "resolved_model_id", "channel", "via_mapping", "reason"],+ "additionalProperties": false,+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "resolved_model_id": {+ "type": "string",+ "description": "The id actually sent upstream for this attempt, mapping applied."+ },+ "channel": { "enum": ["native_cli", "hub"] },+ "via_mapping": { "type": "boolean" },+ "reason": {+ "enum": [+ "quota_exhausted",+ "rate_limited",+ "server_error",+ "network",+ "credential_expired",+ "credential_revoked",+ "balance_exhausted",+ "account_banned",+ "unclassified_error"+ ],+ "description": "Why this attempt failed, from the resolution-event `reason` vocabulary narrowed to the FALLBACK causes — every value here is a cause that made the resolver move to the next candidate. NOT nullable and NOT free text: a failed attempt with no reason was the round-1 shape's other unrepresentable-should-have-been, and the classification already exists adapter-side (S1 gap ①). Param/protocol/tool-compat errors are absent from this enum by construction, because they do not produce a fallback (spec §4.3 error taxonomy) — they end the turn, and their home is `terminal_error`. The narrowing is MECHANICAL, not editorial (07-29, review round 7): this set is exactly `resolution-event.reason` minus the three resolution-shaped values that are not attempt failures (`recovery`, `manual`, `mapping`) minus the three that classify the agent's own supply rather than one candidate's attempt (`no_enabled_source`, `no_eligible_source`, `model_unsupported`), so it is a computed set equality and a new `reason` cannot be added without deciding which side it falls on. `unclassified_error` was missing until round 7: round 6 added it to `resolution-event` as a fallback-producing cause and stopped there, so an adapter that fell back from an unmappable failure had no legal value for a REQUIRED field and the only way to emit a valid record was to misreport the cause as `server_error`. `timeout` is legitimately absent — it is not in `resolution-event.reason` either; a timed-out attempt reports `network`."+ }+ }+ }+ },+ "served": {+ "type": ["object", "null"],+ "description": "The attempt that COMPLETED the turn — the record of the winner, not a projection of it. 'Completed', not 'produced output' (07-29, review round 4): an attempt that started streaming and then failed belongs in `terminal_error` with `stream_started: true`, never here, so the two slots stay disjoint on the mid-stream case as well as the clean ones. NULL for all three failure outcomes. Carries the same fields as a failed attempt minus `reason`, so the render walks `failed_attempts` then appends this one.",+ "required": ["source_id", "resolved_model_id", "channel", "via_mapping"],+ "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" }+ }+ },+ "terminal_error": {+ "type": ["object", "null"],+ "description": "v2 (07-29, review round 3): the attempt that ENDED the turn with a non-fallback error — the counterpart to `served`, in the same slot-per-terminating-attempt shape and for the same reason. NULL unless `outcome` is `failed_terminal`. Carries the same identity fields as an attempt, so the render still walks `failed_attempts` and appends this one; the difference is the `reason` vocabulary, which is disjoint from the fallback vocabulary by construction. This is deliberately NOT an entry in `failed_attempts`: everything in that array is a step the resolver took and then moved past, and folding a turn-ending error in would make the array mean two things and re-open the 'which item was decisive' ambiguity the round-2 shape ruling closed.",+ "required": ["source_id", "resolved_model_id", "channel", "via_mapping", "reason", "stream_started"],+ "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" },+ "reason": {+ "enum": ["invalid_parameter", "protocol_error", "tool_incompatible", "stream_interrupted"],+ "description": "The non-fallback causes of spec §4.3's error taxonomy, kept in their own vocabulary so no reader has to know which values of the other enum are 'the ones that don't fall back'. `invalid_parameter` / `protocol_error` / `tool_incompatible` are the three the taxonomy names as surfacing to the caller. `stream_interrupted` is the fourth because §4.3 also rules that once streaming has started there is no transparent retry: the same underlying 5xx that would have been `server_error` and a fallback before the first token becomes terminal after it, so the phase — not the status code — decides, and the record must be able to say so."+ },+ "stream_started": {+ "type": "boolean",+ "description": "Whether any output had reached the caller when the error hit. Load-bearing rather than derivable: it is the fact §4.3's no-transparent-retry rule turns on, and the fact §4.5's copy obligation turns on (a half-written answer needs different words than a request that never started). Independent of `reason` for the first three — a tool call can arrive malformed mid-stream — and therefore pinned true only for `stream_interrupted`, where false would be a contradiction."+ }+ },+ "allOf": [+ {+ "if": { "properties": { "reason": { "const": "stream_interrupted" } }, "required": ["reason"] },+ "then": { "properties": { "stream_started": { "const": true } } }+ }+ ]+ },+ "model_supply_state": {+ "type": ["string", "null"],+ "enum": ["waiting", "interrupted", null],+ "description": "v2 (07-29, review round 2): why nothing was tried, as the MODEL-SCOPED supply state of this (agent, requested_model) chain — the same value `supply_state` in agent-chain.schema.json would carry for this pair, under spec §4.5's single definition of the predicate: `interrupted` when the chain is empty or AT LEAST ONE blocker needs the user, `waiting` when every blocker is a cooldown and the turn would have succeeded later unattended. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which is not the spec's predicate and left the mixed chain (one cooling, one revoked) fitting neither value — see agent-chain.schema.json → supply_state for the full note. Non-null IFF `outcome` is `no_candidate`; null otherwise, on the same pattern as `retry_at` in agent-chain.schema.json. Deliberately NOT the agent-level `supply_status` rollup from agent-supply.schema.json: that rollup answers for the backend's CURRENT model, and a turn can request a different one (see api.md → probe, same distinction). Same three-class taxonomy, evaluated at the (agent, model) grain — 「稍等即可」 and 「需处理」 are different answers and the turn record must not blur them."+ }+ },+ "allOf": [+ {+ "$comment": "One conditional per `outcome`, and each one pins EVERY optional slot — including the ones it forbids. Naming only the slots an outcome uses would leave the others writable, which is how a payload ends up with both a winner and a terminal error.",+ "if": { "properties": { "outcome": { "const": "served" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "served": { "type": "object" },+ "terminal_error": { "type": "null" },+ "model_supply_state": { "type": "null" }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "exhausted" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "served": { "type": "null" },+ "terminal_error": { "type": "null" },+ "failed_attempts": { "minItems": 1 },+ "model_supply_state": { "type": "null" }+ }+ }+ },+ {+ "$comment": "v2 (07-29, review round 3): no `minItems` on `failed_attempts` here, deliberately. The FIRST candidate can hit a param error, in which case nothing fell back and the array is legitimately empty; a later one can hit it after real fallbacks, in which case it is not. Both are honest records of the same outcome, and requiring one shape would force the emitter to falsify the other.",+ "if": { "properties": { "outcome": { "const": "failed_terminal" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "served": { "type": "null" },+ "terminal_error": { "type": "object" },+ "model_supply_state": { "type": "null" }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "no_candidate" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "served": { "type": "null" },+ "terminal_error": { "type": "null" },+ "failed_attempts": { "maxItems": 0 },+ "model_supply_state": { "type": "string" }+ }+ }+ }+ ],+ "examples": [+ {+ "contract_version": 2,+ "turn_id": "turn_01k9x2m4",+ "ts": "2026-07-29T06:32:11Z",+ "agent": "claude",+ "requested_model_id": "claude-opus-4-6",+ "outcome": "served",+ "failed_attempts": [+ {+ "source_id": "src_claudepro1",+ "resolved_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+ },+ "terminal_error": null,+ "model_supply_state": null+ },+ {+ "contract_version": 2,+ "turn_id": "turn_01k9x33p",+ "ts": "2026-07-29T06:41:02Z",+ "agent": "opencode",+ "requested_model_id": "zhipuai/glm-5.2",+ "outcome": "exhausted",+ "failed_attempts": [+ {+ "source_id": "src_relay9c1x",+ "resolved_model_id": "glm-5.2",+ "channel": "hub",+ "via_mapping": false,+ "reason": "balance_exhausted"+ }+ ],+ "served": null,+ "terminal_error": null,+ "model_supply_state": null+ },+ {+ "contract_version": 2,+ "turn_id": "turn_01k9x3zq",+ "ts": "2026-07-29T06:48:20Z",+ "agent": "codex",+ "requested_model_id": "gpt-5.3-codex",+ "outcome": "no_candidate",+ "failed_attempts": [],+ "served": null,+ "terminal_error": null,+ "model_supply_state": "waiting"+ },+ {+ "contract_version": 2,+ "turn_id": "turn_01k9x4b7",+ "ts": "2026-07-29T07:02:44Z",+ "agent": "claude",+ "requested_model_id": "claude-opus-4-6",+ "outcome": "failed_terminal",+ "failed_attempts": [+ {+ "source_id": "src_claudepro1",+ "resolved_model_id": "claude-opus-4-6",+ "channel": "native_cli",+ "via_mapping": false,+ "reason": "quota_exhausted"+ }+ ],+ "served": null,+ "terminal_error": {+ "source_id": "src_anthkey01",+ "resolved_model_id": "claude-opus-4-6",+ "channel": "hub",+ "via_mapping": false,+ "reason": "stream_interrupted",+ "stream_started": true+ },+ "model_supply_state": null+ }+ ]+}diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex 004b92606..f495c3e15 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -5,6 +5,16 @@ 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: 2`). Anything below that assumes a global priority list is+> historical. The v2 lane plan is cut as a separate document; this one is not+> being rewritten in place, only annotated where it would otherwise contradict+> the frozen contracts. **§8 is the exception: it is v2-current and binding** —+> the acceptance criteria the spec-v2 review loop handed to implementation+> instead of answering them with more spec.+---## 0. Ground rules for this effort@@ -54,10 +64,14 @@ orchestrator only.protocol, base_url?, display_name, billing(monthly|metered), state(active|standby|cooldown{retry_at}), usage(cycle_pct?|month_spend?),models[] (supplied model ids), custom_models[].-2. `priority.schema.json` — ordered source-id list (single global list).+2. ~~`priority.schema.json` — ordered source-id list (single global list).~~+ **Removed in contract v2**: the global list is gone; the file remains only as a+ v1 tombstone. The order lives in `agent-supply.schema.json` → `sources`.3. `agent-supply.schema.json` — per backend: mode(hub|direct), menu_kind(fixed|open), current{model_id, source_id}?, mappings[] (fixed-menu only:- builtin_id → target_model_id), menu{featured|full, checked_ids[]} (open only).+ builtin_id → target_model_id), menu{featured|full, checked_ids[]} (open only);+ **v2** also `sources`{policy(follow|custom), order[]} — this backend's ordered+ source subset — plus `supply_status` and `model_supply`.4. `resolution-event.schema.json` — 最近切换 entry: ts, agent, from_source,to_source?, reason(quota|error|recovery|cooldown_skip), billing_impact?.5. `oauth-flow.schema.json` — flow_id, form(A_paste_code|B_device_code|@@ -66,13 +80,19 @@ orchestrator only.6. `migration-scan.schema.json` — per backend: detected items(kind, maskeddetail, action(import|reauth|controlled_import), selected).7. `api.md` — REST endpoint list (paths, verbs, request/response schema refs,- error envelope): sources CRUD + test/discovery, priority reorder, agent- mode switch, mappings CRUD, menu config, custom models, events feed,- migration scan/apply, oauth start/status/submit/cancel.+ error envelope): sources CRUD + test/discovery, per-backend source order+ (v2: `PUT /api/models/agents/<backend>/sources`, replacing the v1 global+ `PUT /api/models/priority`), agent mode switch, mappings CRUD, menu config,+ custom models, events feed, migration scan/apply,+ oauth start/status/submit/cancel.8. `opencode-overlay.md` — generated provider entries (standard vendor ids +`custom/`), transport redirection, gateway token injection, serveconfig-hash restart rule; identifier stability invariant stated as a testrequirement.+9. **v2 additions** (2026-07-29): `agent-chain.schema.json` (capability chain per+ (agent, model)), `probe-result.schema.json` (「试跑一次」), and+ `turn-provenance.schema.json` (per-turn model@source record). All three are+ read-only surfaces with no v1 implementation, so every field is required.## 3. Lanes@@ -122,8 +142,9 @@ L6 M, L7 M.- **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, priority reorder takes- effect next turn, mapping applies to CC only, OpenCode identifier stability+ 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 stabilityacross mode switch, migration non-destructiveness, OAuth forms A/B/C happypath + timeout/cancel. Scenario IDs appear in PR descriptions.- **Behavioral (Incus)**: real backend turns in both modes; 最近切换 log@@ -137,6 +158,291 @@ L6 M, L7 M.3. `design.pen` V4 frames must be saved (Cmd+S) before L4/L5 dispatch — lanesverify against the exported frames.+## 8. Implementation acceptance criteria (review rounds 8-11, 2026-07-29)++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+section generated the next round's findings; round 8 was pre-committed to stop that.+So the split here is mechanical rather than editorial: **a finding that was two+statements in these docs contradicting each other was fixed in the spec** (AC-5, AC-6,+plus the retractions noted under AC-1 to AC-3), and **a finding that would need a new+route, a new enum value, or a product decision is recorded here verbatim** instead of+being designed inside a review reply by an author who wants the thread closed.++**Round 9** returned six more findings, one P1 and five P2, under the same rule and was+pre-committed as the last round answered with edits. Five were true contradictions and+were fixed in place: the missing converse in `probe-result.schema.json` (a transport+failure could carry a measured latency), §10 still defining `reachable` as 「the upstream+answered」, the version conflict this section itself carried, source fan-out testing raw+`sources.order` instead of the chain grain, and a protected-set term naming fixed-menu+selection state the contract does not persist. The sixth is fixed only as far as a+document can fix it — the chain and probe routes are now scoped to Hub mode — and the+Direct-mode representation it asks for is recorded below as **AC-7**.++**Round 10** returned six more findings, two P1 and four P2, on that same head, and+they are **recorded, not fixed**: round 9 was the last round answered with edits, and+appending criteria is the only edit this round permits. Each was checked against the+line it cites before being written down — none is a strictness complaint, and none was+already covered by AC-1 to AC-7 — and they arrive in three pairs worth naming for+whoever picks them up. **A definition written for one purpose, reused where the+tolerance differs:** the delete guard's protected set is deliberately wide, because a+model the user ticked deserves protection from a silent delete, but reusing that union+to decide who gets an interruption push makes it too wide (**AC-9**), and letting it+count mapping rows the resolver ignores makes even the guard too wide (**AC-8**). **A+contract file restating something the normative side already settled elsewhere:**+`source_id` promises `Source` identity without `Source`'s pattern (**AC-10**), and a+schema description sends `system`-emitted source events to nobody while §4.5 routes+them from their source (**AC-11**). **A promise the same document cannot keep:** two+credential invariants that cannot both hold (**AC-12**), and a `force=true` retry with+no request field to carry it (**AC-13**). Nothing in this round was answered with new+prose in `model-hub.md` or the contracts.++**Round 11** returned six more findings, two P1 and four P2, and is the first round+whose findings are all about **this section rather than the spec**: round 10's record+carried four acceptance tests that cannot be run as written and two bookkeeping cells+that contradict the criterion above them. So the answer is neither a spec edit nor a new+AC — appending AC-14 to AC-19 would leave the defective tests standing beside notes+saying they are defective, and ship a document arguing with itself. Each is corrected+where it sits, annotated 「corrected 07-29, review round 11」 at the point of change, and+none of it touches `model-hub.md`, a contract file, or a standing ruling: AC-9's two+phases could not both run on one fixture, AC-10 asked frozen examples to survive a bump+it performs itself, AC-11 drove its test from a trigger `api.md` documents as a+different event, AC-12 let an in-memory queue pass for 「durable」, and AC-9's and+AC-13's owner-call cells read `no` where their own criteria say a decision governs. Two+of the six had one cause: the versioning paragraph keyed off 「changes a shape」 when the+freeze protocol keys off editing a frozen file, which is why AC-8 and AC-12 were+exempted wrongly. That root is fixed once, below, and both invariants the round exposed+now carry a mechanical check.++These are not suggestions and not backlog. Each is a test the implementing lane must+pass. **This PR does not reopen v2 — and a lane that closes an AC by changing a frozen+shape publishes a new contract version** (07-29, review round 9). Those two halves were+in conflict as written: round 8 said the contracts 「stay at `contract_version: 2`」 and+then told AC-4 to grow the `outcome` vocabulary and AC-1 to add a no-source+representation 「against the frozen contract」, which would ship two mutually+incompatible v2 shapes with no signal a client could switch on — precisely what the+freeze protocol in `model-hub-contracts/README.md` exists to prevent (「lanes cite,+never edit; changes go through the orchestrator and bump `contract_version`」).+Mechanically, **the trigger is editing a frozen file, not changing a JSON shape**+(07-29, review round 11). Round 10 drew the line at 「changes a shape」 and wrote three+exemptions on that reading; all three were wrong, because the protocol above forbids+lanes from editing these files at all, so any edit is the version event — a `pattern`+that narrows what validates, a prose invariant that changes when a route refuses, and+a new field are one class. AC-8 rewrites the protected set in frozen `api.md` and so+changes when DELETE returns `source_last_supplier`; AC-12 rewrites that file's+credential invariants; AC-2's remedy edits its re-auth flow whichever UX the owner+picks. So the v3 set is **every AC whose surface is a file under+`model-hub-contracts/`** — AC-1, AC-2, AC-4, AC-7, AC-8, AC-10, AC-11, AC-12, AC-13 —+plus **AC-3**, whose remedy adds a route to the contracts even though its surface is+the spec. The first of them to land goes through the orchestrator, bumps+`contract_version` to **3**, updates the mirror table, and states the client-visible+delta in its PR description; the others ride that version if they land in the same+release and bump again if they do not. Two of the round-10 three narrow what already+validates — AC-10 adds a `pattern`, AC-11 forbids `system` on a backend-scoped kind —+so a payload a v2 serializer emits today can stop validating, which is exactly the+client-visible delta the bump exists to announce. **AC-5, AC-6 and AC-9 stay on v2**:+their surface is the spec, and they change guard and fan-out semantics no contract+file states. AC-5 and AC-8 are the same guard from two sides, so a lane owning both+lands the `api.md` half inside the v3 bump and the spec half outside it.++| AC | Sev | Finding | Surface | Owed by | Owner call needed |+| --- | --- | --- | --- | --- | --- |+| **AC-1** | P1 | Define provenance for Direct-mode turns | `turn-provenance.schema.json` | L2 (contract + route) with L7 scenario | no |+| **AC-2** | P1 | Reconcile irreversible native re-auth before returning failure | `api.md` | L1 (re-auth orchestration) + L4 (confirm copy) | **yes — product decision** |+| **AC-3** | P1 | Allow blocked sources to be re-tested after user action | `model-hub.md` | L2 (route + state clearing) with L7 scenario | no |+| **AC-4** | P2 | Represent canceled turns in provenance | `turn-provenance.schema.json` | L2 (contract) with L7 scenario | no |+| **AC-5** | P1 | Protect the menu-side model in deletion guards | `model-hub.md` | L2 (guard) with L7 scenario | no |+| **AC-6** | P1 | Resolve source events for every affected backend | `model-hub.md` | L2 (event fan-out) with L7 scenario | no |+| **AC-7** | P1 | Represent chain and probe for Direct-mode backends | `api.md` | L2 (route scoping) + L4 (drawer affordance) with L7 scenario | no |+| **AC-8** | P2 | Exclude disabled mapping rows from the protected set | `api.md` | L2 (guard) with L7 scenario | no |+| **AC-9** | P2 | Fan out source events only through Agents that use the affected model | `model-hub.md` | L2 (event fan-out) with L7 scenario | **yes — zero-scope fallback** |+| **AC-10** | P2 | Constrain `ProbeResult.source_id` to the canonical `src_*` format | `probe-result.schema.json` | L2 (contract + serializer guard) | no |+| **AC-11** | P1 | Route `system`-emitted source events from their source | `resolution-event.schema.json` | L2 (schema + delivery) with L7 scenario | no |+| **AC-12** | P2 | Reconcile a failed old-credential revocation | `api.md` | L2 (repair invariants) | no |+| **AC-13** | P1 | Give the `force` override a request contract on both repair routes | `api.md` | L2 (routes) + L4 (confirm dialog) with L7 scenario | **yes — via AC-2** |++**Three ACs wait on an owner call, not on engineering** (07-29, review round 11): AC-2+outright, plus the half of AC-13 and of AC-9 that each one's own criterion already says+a decision governs. AC-13's re-auth confirmation is one of the two answers AC-2's+decision picks between; AC-9's narrowing makes a menu-only failure resolve to zero+scopes by construction, so the standing zero-scope fallback decision settles whether+that failure is announced anywhere outside the feed and the 「模型」 page. Both keep an+implementable half that can land first — AC-13's declared override field on+`PUT …/credential`, and AC-9's fan-out narrowing itself — so only AC-2 blocks a lane+outright. The other ten are implementable as written. Four groups must be owned+together, because each is one question on more than one surface and independent answers+will disagree:++- **AC-1 + AC-4** — both touch `turn-provenance.schema.json`; 「which terminal states+ exist」 is the same question twice.+- **AC-1 + AC-7** — what a Hub-shaped contract says about a backend that is not on Hub.+- **AC-6 + AC-9 + AC-11** — all three are the action-required delivery rule: which+ backends are affected, which Agents inside them are, and who receives an event no+ backend emitted. AC-6 narrows the first hop, AC-9 the second, AC-11 fixes the case+ where the emitter is `system`.+- **AC-2 + AC-13** — one repair path. AC-13's 「resumable confirmation for re-auth+ completion」 is exactly where AC-2's 「pre-login confirmation that can still abort」+ would live, and AC-2's owner decision picks between them.++**AC-5 + AC-8** are also the same guard from two sides — the namespace of the protected+set and its membership — so whoever fixes one should re-read the other's test.++### AC-1 — Define provenance for Direct-mode turns++Review round 8, P1, on `docs/plans/model-hub-contracts/turn-provenance.schema.json`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864623). Verbatim:++> **Define provenance for Direct-mode turns**+>+> Direct remains the existing-user default and can run entirely from native configuration without any Model Hub `Source`, but a successful provenance record must contain a `src_*` identifier here. A successful post-feature Direct turn therefore cannot validate: the implementation must either fabricate a source or return `turn_not_found`, despite the contract promising provenance for each turn. Add an explicit Direct/no-source representation, or explicitly scope the endpoint and conversation affordance to Hub-mode turns.++**Spec action at round 8.** `model-hub.md` §4.5 「Turn provenance」 now states that the frozen interface covers Hub-mode turns and names this as AC-1; the schema is unchanged.++**Acceptance.** A successful Direct-mode turn is inspectable without any `Source` row existing: either the response validates against a documented no-source representation, or `GET …/provenance` answers a documented 「此回合无中枢记录」 error and the per-turn affordance renders that state. A test asserts a post-feature Direct turn never yields a payload that fails `turn-provenance.schema.json`, and never yields a fabricated `src_*` id.++### AC-2 — Reconcile irreversible native re-auth before returning failure++Review round 8, P1, on `docs/plans/model-hub-contracts/api.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864639). Verbatim:++> **Reconcile irreversible native re-auth before returning failure**+>+> For `native_cli`, OAuth has already replaced the credential in the CLI-owned store before post-login discovery or the supply guard runs, and these lines acknowledge that the old login cannot be restored. Nevertheless, the shared repair contract later permits discovery failure or an elective-gap refusal while retaining the old `Source` row as though the prior supply were intact. The next native turn then uses the new CLI account while the persisted models and state still describe the old one. Native re-auth needs confirmation before the irreversible login, or it must commit and report the resulting gaps instead of using the rollback/refusal semantics of engine-owned credentials.++**Spec action at round 8.** `api.md` invariant 5 now scopes invariant 3's guarantee on this channel to its weak sense and forbids presenting a post-re-auth refusal as though the prior supply were intact; the remedy is deliberately not chosen there.++**Acceptance.** For a `native_cli` source, no path leaves the persisted `models`/`state` describing an account the CLI no longer holds. Whichever remedy the owner picks, a test drives a re-auth whose post-login discovery fails and asserts the observable end state matches the chosen semantics — a pre-login confirmation that can still abort, or a committed swap whose response reports the resulting gaps. Silent divergence between row and store fails the test.++### AC-3 — Allow blocked sources to be re-tested after user action++Review round 8, P1, on `docs/plans/model-hub.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864631). Verbatim:++> **Allow blocked sources to be re-tested after user action**+>+> 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.++**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.++### AC-4 — Represent canceled turns in provenance++Review round 8, P2, on `docs/plans/model-hub-contracts/turn-provenance.schema.json`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864628). Verbatim:++> **Represent canceled turns in provenance**+>+> 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.++**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.++### AC-5 — Protect the menu-side model in deletion guards++Review round 8, P1, on `docs/plans/model-hub.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864615). Verbatim:++> **Protect the menu-side model in deletion guards**+>+> For a mapping such as `claude-opus-4-6 → glm-5.2`, this top-level spec says the protected set contains the mapping target, while `api.md`'s normative single-home definition requires the mapping's menu-side `builtin_id`. Following this wording tests a resolved ID in the menu namespace, so deletion can miss the actually selected built-in model, proceed without `force`, and interrupt the Agent on its next turn. Replace “mapping targets” with the menu-side models that own mapping rows.++**Spec action at round 8.** FIXED IN SPEC at round 8: `model-hub.md` now protects the menu-side `builtin_id` of every mapping row, matching `api.md`'s single definition of the guard. No implementation debt — this criterion exists so the fix cannot regress.++**Acceptance.** With a single mapping `claude-opus-4-6 → glm-5.2` and one source supplying the target, DELETE of that source is refused without `force`, and the confirm copy names the Agent that would break. A guard that compares resolved ids against menu identifiers matches nothing and must fail this test.++### AC-6 — Resolve source events for every affected backend++Review round 8, P1, on `docs/plans/model-hub.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669864611). Verbatim:++> **Resolve source events for every affected backend**+>+> 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.** FIXED IN SPEC: `model-hub.md` §4.5 defines the affected backends as a SET — for source-scoped kinds, every backend the failed source actually supplies; for `supply_interrupted`, the named backend. Round 8 wrote 「actually supplies」 as `sources.order` membership, and round 9 corrected it to the (backend, model) chain grain the supply guard already uses, because a `follow` order holds every eligible source: an API-key source that no chain on that backend can run would otherwise interrupt its scopes. No implementation debt; guards the fix.++**Acceptance.** 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: every scope routed to an Agent on EITHER backend receives exactly one push. A one-hop implementation notifies only the discovering backend's scopes and must fail this test. The round-9 half is the negative case — the same source in Codex's order but in no Codex chain (a GLM-only key while Codex runs `gpt-5.6`) must produce NO push to Codex-routed scopes, which a raw-order implementation fails.++### AC-7 — Represent chain and probe for Direct-mode backends++Review round 9, P1, on `docs/plans/model-hub-contracts/api.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3669986813). Verbatim:++> **Scope chain and probe endpoints away from Direct mode**+>+> Existing users remain in Direct mode, where `sources` and `selected_model_id` are null and there is no Model Hub source order, yet these endpoints are declared without a mode restriction. A chain request must therefore return an empty `interrupted` chain for a model the native CLI can run, while a probe has neither a default model nor the required `src_*` identity for a valid `ProbeResult`. Define a Direct-specific representation or error and keep the chain/probe affordances from presenting Hub starvation for Direct backends.++**Spec action at round 9.** Half fixed, half recorded. `api.md` now scopes both route rows to `mode: hub` and says why an empty chain is the wrong answer rather than a harmless one: `chain: []` means 「Hub has nothing that can serve this」, which is a false alarm about a backend whose native CLI is running that model fine. What Direct returns *instead* is a shape decision — a documented `direct_mode` error the drawer renders as 「该后端未接入模型中心」, or a mode-specific payload naming the native model with no chain — and this document chooses neither, because either choice edits `api.md` and belongs to the lane that also answers AC-1. Whichever is chosen publishes `contract_version: 3` per the versioning rule above.++**Acceptance.** With `mode: direct`: a chain request for the model that backend is actually running returns the chosen Direct representation and never `ok: true, chain: []`; a probe request returns the same representation and never a `ProbeResult` with a fabricated `source_id`; and the agent drawer offers neither 「试跑一次」 nor a chain view for that backend. An implementation that leaves the Hub-shaped 200 in place fails the first two, and a UI that keeps the affordances and renders the refusal as 中断 fails the third.++### AC-8 — Exclude disabled mapping rows from the protected set++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**+>+> When a persisted mapping has `enabled: false`, the resolver treats the built-in model as identity (`core/handlers/model_hub/resolver.py` checks `item.enabled`), but this definition protects every mapping row regardless of that flag. If the disabled row's model is not otherwise selected, deleting or rotating its only source will be refused with `source_last_supplier` even though no live selection would break; only enabled mapping rows should contribute through this term.++**Spec action at round 10.** RECORDED, not fixed. The premise checks out on all three sides: `agent-supply.schema.json` requires `enabled` on every mapping row and its frozen example carries `enabled: false`; `resolver.py` applies a row only when `item.enabled`; and term 2 of the protected set says 「every model that owns a mapping row」 with no filter. **The direction is not open, though** — the same paragraph already rejects over-protection in its own words: treating models nobody selected as protected 「trains the user to pass `force=true` reflexively and hollows out the whole guard」. A disabled row is exactly that case, so this is the guard's own principle applied to the term it was written next to.++**Acceptance.** One backend, one mapping row `claude-opus-4-6 → glm-5.2` with `enabled: false`, `claude-opus-4-6` selected by no Agent and not the backend default, and one source supplying `glm-5.2`. DELETE of that source succeeds **without** `force`, and an elective `PUT …/credential` onto a narrower key is not refused. Flipping the row to `enabled: true` must make both refuse with `source_last_supplier` — the same test run twice, which fails an implementation that reads mapping rows without their flag and equally fails one that drops mapping protection altogether.++### AC-9 — Fan out source events only through Agents that use the affected model++Review round 10, P2, on `docs/plans/model-hub.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099009). Verbatim:++> **Restrict source-event fan-out to Agents using the affected model**+>+> When a source appears only in the chain of an unassigned `menu.checked` entry, an unused mapping, or an unused backend default, this rule marks the backend affected; the preceding two-hop rule then notifies every scope routed to every enabled Agent on that backend. That recreates the irrelevant action-required pushes this round is intended to eliminate, because the protected-model union deliberately includes models with `SupplyGap.agents: []`. Resolve affected named Agents from their effective models and fan out only through those Agents, leaving menu-only failures in the feed/settings surface.++**Spec action at round 10.** RECORDED, not fixed — and it is the round-9 narrowing one level deeper, on the hop round 9 did not touch. Round 9 narrowed hop 1 (which backends are affected) from `sources.order` membership to the chain of a protected model; this narrows hop 2 (which Agents inside an affected backend) to the Agents whose effective model is the one that lost supply. The second hop is still too wide because the protected set is *deliberately* wider than the live selections — it protects a model the user ticked and assigned to nobody, which is right for refusing a delete and wrong for sending a push, which is why `SupplyGap.agents` is allowed to be empty. **This reverses nothing already ruled:** the two hops still run from every affected backend, and `SupplyGap.agents` still includes the Agents that inherit the backend default — those Agents do use the model, so they stay recipients. **It does interact with the standing open decision:** once the recipient set is narrowed this way, a menu-only failure resolves to zero scopes by construction, so whichever way the owner settles the zero-scope fallback decides whether it is announced anywhere outside the feed and the 「模型」 page. Implement the two together or they will disagree.++**Acceptance.** Two cases from independent fixtures, not two phases on one (corrected 07-29, review round 11: a failed source stays `needs_action` until the user acts and its health is source-global, so round 10's 「fail X again」 produces no second transition to observe). Case A: a backend with one enabled Agent running `gpt-5.6`, plus an OpenCode-menu model the user ticked and assigned to no Agent, supplied only by source X. X fails: the scope routed to that Agent receives **no** action-required push, while the failure still appears in the feed and on the 「模型」 page. Case B: the same fixture with that Agent pointed at the ticked model — from fresh state, or after X is explicitly repaired and recovered — and X fails: that scope receives exactly one push. An implementation that fans out over every enabled Agent on the affected backend passes B and fails A.++### AC-10 — Constrain `ProbeResult.source_id` to the canonical `src_*` format++Review round 10, P2, on `docs/plans/model-hub-contracts/probe-result.schema.json`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099013). Verbatim:++> **Constrain probe source IDs to the canonical Source format**+>+> For every Hub-mode probe, `source_id` is supposed to identify the attempted `Source`, whose contract uses `^src_[a-z0-9]{8,}$`; the chain and provenance schemas enforce the same format. Here any nonempty string validates, so a serializer can emit values such as `"direct"` or an adapter label and still pass the promised API-payload contract test, while the UI cannot correlate the probe with a source row. Apply the canonical pattern here and add the corresponding referential-existence guard.++**Spec action at round 10.** RECORDED, not fixed. Verified: `source.schema.json`, `agent-chain`, `agent-supply` (twice), `priority` and `turn-provenance` (three times) all pin `^src_[a-z0-9]{8,}$`, while `probe-result.source_id` carries `minLength: 1` alone. The two halves land in different places and only the first is a schema change. The `pattern` belongs in this file. The **referential-existence** half — that the id names a row that exists — sits outside draft-07 on the same boundary this PR already declared for `model_supply` uniqueness, so it belongs in `model-hub.md` §4.4's server-validated invariant list and as a row in `api.md`'s mechanical-guard table, not as a schema keyword nobody can write. Note the edge this removes: `"direct"` is exactly the string a well-meaning serializer would invent for AC-7's Direct case, so an implementation that closes AC-7 by faking a probe payload is caught by a contract test instead of by a bug report.++**Acceptance.** `{"source_id": "direct", …}` and `{"source_id": "cli-anthropic", …}` are both rejected by `probe-result.schema.json`; every example in that file validates against it after the v3 bump, with `contract_version` the only field the bump changes — the existing `source_id` values (`src_chatgptplus`, `src_relay9c1x`) already satisfy the new `pattern`, so it costs no example a rewrite (corrected 07-29, review round 11: round 10 asked the frozen examples to 「still validate byte-identically」, which this AC's own `const: 2` → `const: 3` bump makes unsatisfiable); and a probe response whose `source_id` is well-formed but names no `Source` row is rejected by the server-side guard, with the mechanical checker asserting that guard is declared. A serializer test that only asserts 「a nonempty string」 fails all three.++### AC-11 — Route `system`-emitted source events from their source++Review round 10, P1, on `docs/plans/model-hub-contracts/resolution-event.schema.json`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099015). Verbatim:++> **Route system-originated source events by their source**+>+> When an action-required source event is produced by a Web UI/settings mutation, its historical emitter can legitimately be `agent: "system"`, but this description says every such event expands to no Agent and therefore no recipient. That contradicts the normative delivery rule in `model-hub.md`, which says source-scoped events derive affected backends from `from_source` and that Web mutations and mid-turn failures resolve recipients identically, so following this schema text drops the required push. Reserve the zero-recipient interpretation for events with no affected source, route source-scoped `system` events from their source, and disallow `system` on backend-scoped `supply_interrupted`.++**Spec action at round 10.** RECORDED, not fixed, and this is the one round-10 finding where the two texts are flatly opposed. The schema says `system` 「expands to no Agent and therefore to no recipient」; §4.5 says 「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. A key the user revokes on the settings page is source-scoped with a `system` emitter, so the two rules disagree about whether its `needs_action` push is delivered — and the schema's reading is the one that drops it. §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.++**Acceptance.** 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). Every scope routed to an Agent that uses the affected model receives exactly one action-required push — the same recipients and the same count as when the identical failure is discovered mid-turn, and that equality is the assertion. A `supply_interrupted` event carrying `agent: "system"` is rejected by the schema. An implementation that reads the current description literally delivers zero pushes for the re-discovery case and fails.++### AC-12 — Reconcile a failed old-credential revocation++Review round 10, P2, on `docs/plans/model-hub-contracts/api.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099017). Verbatim:++> **Reconcile failed old-credential revocations**+>+> When the post-commit revocation of the old credential fails, invariant 2 explicitly leaves that handle live as an orphan, but the next invariant promises that success revokes the old handle and that no path leaves two live handles for one source. An implementation cannot satisfy both statements, and treating the failure as an unspecified cleanup problem can retain upstream credentials indefinitely. Define a durable pending-revocation record and retry/reconcile it, or weaken the latter invariant to acknowledge that recorded failure state.++**Spec action at round 10.** RECORDED, not fixed. Both sentences sit in the same invariant list: invariant 2 says a failed revoke 「leaves an orphaned handle in the engine store, which is a cleanup problem, not a supply problem」, and invariant 3 says 「no path leaves two live handles for one source」. The orphan IS a second live handle, so invariant 3's 「no path」 is false as written. Which side gives way is the lane's call, but it is narrower than it looks: invariant 3 is load-bearing for the property that a rotated-away credential stops working upstream, so weakening it to 「except a recorded pending revocation」 preserves that property only if the record is durable and actually retried. Silently tolerating the orphan is the one option this criterion forbids — a credential the user believes they rotated away would keep working indefinitely, which is a security outcome, not a cleanup backlog.++**Acceptance.** A credential replacement whose post-commit revoke fails leaves a durable, observable pending-revocation record for the old handle; the service is then **reconstructed against the same persisted state** — a fresh instance, or the process restarted — and only that new instance runs the reconcile pass, which revokes the handle (corrected 07-29, review round 11: asserting the record and then reconciling on the same instance passes with an in-memory queue, which is the one implementation 「durable」 exists to forbid). The source serves normally throughout, because this failure is not a supply problem. No end state exists in which the old handle is live and nothing records that it is. A test that injects a revoke failure and asserts only 「the repair succeeded」 does not satisfy this: it must read the record back after reconstruction, and assert the handle is gone after that instance's reconcile.++### AC-13 — Give the `force` override a request contract on both repair routes++Review round 10, P1, on `docs/plans/model-hub-contracts/api.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670099019). Verbatim:++> **Define how clients submit the force override**+>+> When an elective replacement of a healthy credential discovers a narrower model set, this branch requires the client to retry with `force=true`, but the declared credential request is only `{key}`, the re-auth route has no request body, and the status poll is read-only. The UI therefore has no contracted way to confirm `source_last_supplier`—especially after an OAuth flow has already completed—so implementations must either strand the repair or invent incompatible wire semantics. Add the override to the request contract and define a resumable confirmation path for re-auth completion.++**Spec action at round 10.** RECORDED, not fixed. Verified against the route table: `PUT …/sources/<id>/credential` declares `{key}`, `POST …/sources/<id>/reauth` declares no request body, and `GET …/oauth/status/<flow_id>` is a poll. The elective branch nevertheless refuses 「unless `force=true`」 using DELETE's refusal shape — a shape DELETE can carry because DELETE takes a query parameter and these two routes have nowhere to put one. The key half is a one-field addition. **The re-auth half is the hard one, and it is not a naming problem:** by the time the refusal is computed the user's login has already been replaced, so 「retry with `force=true`」 cannot mean 「send the request again」 — re-running OAuth on `native_cli` is the irreversible act AC-2 is about. It needs a confirmation that resumes the completed flow, which is why this criterion and AC-2 belong to one lane: AC-2's 「pre-login confirmation that can still abort」 and this criterion's 「resumable confirmation after the fact」 are two answers to one question, and the owner's AC-2 decision picks which one gets built.++**Acceptance.** 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, a completed flow whose guard refuses can be confirmed and committed without a second OAuth round trip, or is refused before the login it cannot undo, per AC-2's answer. A UI that must re-run the OAuth flow to confirm fails this test, and so does one that cannot confirm at all.+## 7. Kickoff checklist (orchestrator)- [ ] Owner approves this plan (lanes, sequencing, gates).diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 80ad2bb08..3595db3ab 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -1,13 +1,62 @@# Model Hub — Product Spec-Status: **signed** (2026-07-23 02:58) · amended v1.1 (2026-07-23 10:40) per spike-S2 findings — subscription supply channels & the consent-gated experimental flag-(owner decision 10:33: hybrid supply by default; hub-held Claude subscription-login offered ONLY as a consent-gated experimental feature)-Owner decisions incorporated through: 2026-07-23 10:33 (+08:00)-Design source: `../avibe-docs/design.pen`, frames `产品改造 V4 01r – V4 09` (Light)-Discussion record: Show Page of session `sesb7r2qwb4z4` (rounds 1–10, with superseded-explorations V2/V3 archived inline)+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: 2`.+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.++Subscriptions are untouched by all of this: they stay bound to their own vendor's+backend in both channels (S2/ToS, §4.4).---@@ -27,14 +76,21 @@ base URLs, protocol conversion, account pools or routers.## 2. Product promise (user-facing, locked)-1. Connect a source once — every Agent can use it.+1. Connect a source once — every Agent that can use it, can use it.2. Subscriptions are consumed first (already paid); when quota runs outAvibe switches to the next source automatically and switches back on- recovery. Work never stalls. (Mechanism, v1.1: per-turn channel dispatch —+ 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.1/§4.2.)-3. Priority order is user-owned: the list order **is** the spending order.- Nothing is hard-coded; paid sources are always visibly marked.+ 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.Core persona: individual users who already pay for Claude Pro/Max or ChatGPTPlus/Pro ("spend what I bought first"). Secondary: API-key-only users.@@ -46,31 +102,39 @@ operations console.| 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) |-| Spend order | 优先级 | Priority | One global draggable list; order = spend order |+| 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). "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).+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: upstream / hub / downstream+## 4. Architecture: supply, consumption, resolution-### 4.1 Upstream — Sources (global, will keep growing)+The v2 split, stated once: **sources supply; agents consume; ordering lives on+the consumer.**-Each source carries: kind (subscription | api_key), credential, protocol-(anthropic | openai | openai_compatible …), an editable base URL (api_key-kind; prefilled for known vendors), a **model list** it can supply-(auto-discovered where possible, e.g. `/models`; manually extendable via-custom model entries), billing type (包月 | 按量 ¥), state-(active | standby | cooling-down with retry ETA), and usage (subscription-cycle % / monthly spend).+### 4.1 Supply — Sources (global assets, no ordering)-**Supply channel (amended v1.1, per S2 ToS review).** Each source has a-`supply_channel`:+Each source carries: kind (subscription | api_key), vendor, credential+reference, protocol (anthropic | openai | openai_compatible …), an editable base+URL (api_key kind; prefilled for known vendors), a **model list** it can supply+(auto-discovered where possible, e.g. `/models`; manually extendable via custom+model 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.++**Supply channel.** Each source has a `supply_channel`:- `native_cli` — the credential lives in the CLI's own sanctioned store andquota is consumed by launching the CLI in its native form. Default for@@ -85,37 +149,134 @@ cycle % / monthly spend).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 the-global priority list arbitrates.--### 4.2 Hub — request resolution (step 0 + three steps)--0. **Channel dispatch (amended v1.1)** — per turn, before launch: if the- top-priority eligible source for the requesting agent 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.+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 → actual model. Identity by default.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.-2. **Candidates** — all sources able to supply that model, ordered by the- single global priority list (filtered per request; no per-model priority).+2. **Candidates (v2)** — start from **this agent's ordered subset** (§4.2), in+ its order, then filter in two stages:+ - **capability** (structural, stable): a. the source supplies the (mapped)+ model id; 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.+ 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; switch back on recovery.- Convert protocol when needed. Every switch is appended to the- human-readable 最近切换 log.+ 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 then retry; 429 / explicit quota-exhaustion / transient 5xx / network → cooldown + next candidate. Once-streaming has started, no transparent retry.+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 quotagone → serve GPT") stays an experimental, default-off advanced flag with@@ -123,15 +284,423 @@ visible per-event marking, pending capability/ToS verification. Architecturereserves `allowed_origins` to restrict which clients a subscriptioncredential may serve.-### 4.3 Downstream — Agents+**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):++| 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+now carries a per-source eligibility signal (`eligible` + `reason_key`) computed+once on the server. The UI stops deciding: the chokepoint `isSourceEligible`+(`ui/src/components/settings/models/menus/identifiers.ts`), which self-documents+as ESCALATED precisely because it hand-mirrors backend logic, becomes a pure+projection of server truth. This pays down a debt the v1 lanes escalated and never+closed — 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.+- **`model_supply`** — exactly **one row per menu model**: `model_id` values are+ unique, and the set covers that backend's whole menu. Duplicates are the dangerous+ direction: two rows for one model let `chain_length: 0` sit beside `chain_length: 2`+ for the same id, and since consumers read the first match, the 「无来源可供」 flag+ becomes a coin flip rather than a fact. A missing row is milder but still leaves the+ drawer unable to say anything about a model the menu offers. Neither half is+ expressible — `uniqueItems` compares whole items, so rows differing only in+ `chain_length` pass, and coverage is a relation to a different document.+- **`AgentChain.chain`** — `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`.++### 4.5 State taxonomy — classified by "does it heal itself"++Three classes, because the action owed by the user differs in each.++**Source-level `state.status`:**++| Status | zh (UI) | Heals itself | Meaning |+| --- | --- | --- | --- |+| `active` | 使用中 | — | currently serving |+| `standby` | 备用 | — | healthy, not at the head of some order |+| `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+row can offer **one tap to fix it** (re-auth, top up, replace key) instead of a+dead-end error string.++**`error` is a blocker, not a third class** (07-29, review round 6). This table+first wrote its self-healing column as 「unknown」, and that word was the root of a+real gap: `error` carries no `retry_at`, so nothing will clear it unattended, and the+chain contract has always counted it WITH `needs_action` in the branch that makes a+chain `interrupted` (`agent-chain.schema.json`). What we could not classify is the+**cause**; that is never a promise about **recovery**. Read as 「unknown」 it left one+transition unrepresentable — the last runnable source of a chain landing in `error` —+which is an interruption the notification rule below owes the user a push for, while+the event vocabulary had no cause that could carry it. The emitter's only options were+to borrow a cause nobody had established or to stay silent about the state we+understand least. So the vocabulary gained a fifth non-self-healing cause rather than+the obligation being quietly dropped: that transition is announced as+`kind: needs_action` with `reason: unclassified_error`, which is the exact counterpart+of `state.detail_key: models.source.error.unclassified`. It is not a new event kind —+「a source went dead and stays dead until someone acts」 is what `needs_action` already+means, and *which* way it died is what `reason` is for — and not a widening of+`supply_interrupted`, which nulls both endpoints and would strip the push of the one+source it needs to open. The five non-self-healing source keys and the five+non-self-healing event causes are a bijection, checked mechanically rather than+promised (`api.md` → 「Mechanical guards the schemas cannot carry」).++Two of those three taps need a route that v1 never had, so v2 freezes them:+`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+and needs no *replacement* route of ours — no credential of ours changes; it is a+link 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.++**Agent-level derived `supply_status`** (computed, never stored):++Derived from the same question, so the agent level splits where the source level+splits — on whether the user owes an action:++| Value | zh (UI) | Heals itself | Meaning |+| --- | --- | --- | --- |+| `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` 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+「当前无可用来源」 with a cause breakdown and exactly two exits — fix the+`needs_action` items, or add a source.++`waiting` exists to keep the notification rule below consistent. An agent whose+sources are *all* mid-cooldown has nothing runnable, but nothing is owed either —+it heals itself in minutes. Collapsing that into `interrupted` would push the user+an alert about a problem that resolves before they can read it, 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 使用中.++**Two grains, one taxonomy.** `supply_status` above is the **agent** rollup, and it+answers for that backend's *currently selected* model. The same three classes are+also evaluated per **(agent, model)** pair, as `supply_state` on the chain+(`agent-chain.schema.json`) — because the user routinely asks about a model that is+not the selected one: inspecting a chain, probing a menu item, reading why a turn+gave up. The rollup cannot answer those. A backend whose selected model is healthy+reports `ok` while some *other* menu model has nothing runnable at all, so anything+model-scoped that consults the rollup reports the wrong thing with confidence. Every+model-scoped consumer therefore reads the model-scoped field — the chain drill-in,+the probe's typed `supply` sibling, the turn record's `model_supply_state` — and the+rollup stays what its name says. One taxonomy, two grains, and only one definition of+「稍等即可」 vs 「需处理」 at each.++The predicate itself is stated **once, here**, and every contract that carries either+grain points back at this table rather than restating it: `interrupted` when the chain+is empty **or at least one blocker needs the user**, `waiting` only when every blocker+is a cooldown. The asymmetry is deliberate and load-bearing — `interrupted` is the+OR-branch, `waiting` the AND-branch, so a chain holding one cooling source and one+revoked key is `interrupted`. Reading it as "every member needs the user" leaves that+mixed chain matching neither value and, worse, drops the alert the user is owed for the+revoked key on the grounds that something else in the chain is merely cooling.++**Notification tiers** (the colleague test: interrupt only when action is owed):++| Class | Surface |+| --- | --- |+| self-healing (`cooldown`, `waiting`, recovery, in-turn switch) | 最近切换 feed only — never an IM push |+| `needs_action`, `error`, `interrupted` | proactive IM push, colleague voice, e.g. 「relay 余额不足,已切备用;点此处理」 |++`error` is named in the second row explicitly (07-29, review round 6). It was+implicitly 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 reviewer+ends up asking, correctly, which tier an unclassified failure belongs to.++Resolution events therefore carry `severity: info | action_required`, and the push+layer keys off that field rather than re-deriving urgency from `kind`. The two+tiers are cause-based, never count-based: "zero runnable candidates" is not by+itself a reason to interrupt anyone.++**Who receives an action-required push** (07-29, review round 5). The tier says an+interruption is owed. It does not say to whom — and with several IM platforms,+per-channel Agent overrides, and state changes made from the Web UI, that is not+self-evident. Two shapes were available: carry recipients on the event, or resolve+them at delivery. **Recipients are resolved at delivery, and the event carries no+recipient, channel, platform, or audience field:**++- the event names an **Agent** (a source-scoped kind resolves to the Agents on the+ backends the failed source actually supplies — the fan-out bullet below states that+ test once and normatively), and Avibe already routes each scope to a+ selected Vibe Agent — so the recipient set is *every scope whose routing currently+ selects an affected Agent*, computed at push time against the live routing table+- **the expansion is two hops, because 「Agent」 on the event and 「Agent」 in routing+ are different grains** (07-29, review round 7): `resolution-event.agent` is a+ BACKEND identifier — its enum is `claude` / `codex` / `opencode` (plus `system`) —+ while routing selects a NAMED Vibe Agent such as `pm`. Normatively, then:+ **recipients resolve by expanding each affected backend into the Vibe Agents currently+ enabled on that backend, then into the scopes whose routing selects any of those+ Agents.** Both hops read live state at push time. The gap hid because the default+ Agent of each backend happens to be named after it, so a one-hop reading works until+ a user renames an Agent or enables a second one on the same backend — at which point+ it silently addresses nobody. This sentence fixes only the expansion; **whether a+ zero-scope result falls back to a 「home」 scope, and whether long-idle scopes are+ filtered out, remain the standing open owner decision below** and are deliberately+ not answered here+- **「Each affected backend」 is a SET, and it is not always the one the event names**+ (07-29, review round 8): a **source-scoped** kind affects every backend the failed+ source actually supplies, because source health is a property of the source, not of+ the backend that happened to discover it. One hub key shared by Claude and Codex+ fails once and starves both; reading `agent` as the whole affected set would push to+ the discovering backend's scopes and silently drop the other's from a notification+ this section already promised them. **「Actually supplies」 is the chain grain, not+ order membership** (07-29, review round 9): round 8 wrote the test as 「every backend+ whose `sources.order` contains `from_source`」, and 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. Failing during a+ Claude turn, it would have interrupted every Codex-routed scope over a source that+ could never have served or disrupted them, and an alert that arrives for supply you+ do not use teaches the user to dismiss the ones that matter. The test is the one+ `api.md`'s supply guard already computes at the (backend, model) grain: **a backend is+ affected when the failed source appears in the capability chain of at least one of its+ protected models** (that document's four-fact union). Order membership is necessary+ and not sufficient — a source absent from the order is in no chain either — so this+ narrows over-notification without dropping anyone the round-8 rule protected. It+ refines which backends are affected and nothing else: the two hops still run from+ every backend in the resulting set, and `SupplyGap.agents` still includes the Agents+ that inherit the backend default. A **backend-scoped** kind (`supply_interrupted`,+ whose cause is that backend's own order or selection) affects exactly the backend it+ names. The two hops above then run from every backend in that set, deduped per scope+ as below+- delivery is **once per scope**, deduped: one revoked key that starves three Agents+ sharing a channel is one message naming the source, not three+- an event caused by a settings mutation has no originating conversation, and that is+ not a special case here, because origin was never the addressing key. A Web UI+ mutation and a mid-turn failure resolve their recipients identically+- resolving to **zero scopes is a correct outcome, not a dropped alert**: nothing is+ routed to that Agent right now, so nothing is interrupted right now. The state+ still shows on the 「模型」 page and still lands in the feed++Carrying recipients on the event would have frozen a routing snapshot into an+append-only feed: a scope re-pointed at a different Agent afterwards would still be+addressed by the old event, and a scope added later would never be. The feed is a+record of what happened to supply; it is not an outbox.++**Open decision for the owner, deliberately not settled here** (delivery-layer+policy — neither answer changes the event contract or the feed): whether an+action-required event resolving to zero scopes should fall back to a designated+「home」 scope, so a key revoked while nothing is routed there is still announced+rather than waiting to be discovered; and whether *every* scope routed to an affected+Agent is a recipient, or only recently-active ones — a channel configured months ago+is technically routed, and pushing a credential problem into it may read as noise+rather than as a colleague speaking up.++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**, `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 provenance.** Each turn records the model@source that served it, and that+record is inspectable from the conversation surface as per-turn detail — available+on demand, never noise in the transcript. Mid-stream failure, where no transparent+retry is permitted (§4.3), must say exactly 「下一回合已自动换线,直接重试即可」:+the user's next action is one retry, so the copy states that instead of describing+the fault.++This promise needs an interface, not just a paragraph, so v2 freezes one:+`turn-provenance.schema.json` + `GET /api/models/turns/<turn_id>/provenance`.+It defines *what* is recorded and *how it is read*; where it is stored is the+implementing lane's call, with one constraint — provenance is written when the turn+resolves and stays readable after the process exits, because "which source paid for+this turn" is a billing question the user asks days later, not just live. A turn+that switched sources mid-flight lists every attempt in order, so the record+explains the switch rather than merely naming the winner.++**That interface covers Hub-mode turns** (07-29, review round 8): a `served` record+requires a `source_id` matching `^src_`, and a Direct-mode turn runs from native+configuration 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.+Whether a Direct turn gets a no-source provenance representation or the route answers+「此回合无中枢记录」, and what the per-turn affordance shows then, is an implementation+requirement recorded as **AC-1**. 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.+The terminating attempt is recorded in exactly one place — failed+attempts in an ordered list, the served attempt in its own field, the terminal error+in a third, at most one of the latter two ever populated, the full sequence+reconstructible by appending. That is a shape decision rather than a validation one:+it makes 「两个成功者」, 「成功者不在最后」 and 「摘要指向列表里没有的来源」 impossible to+write 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.7 Downstream — Agents| Agent | Menu | Notes || --- | --- | --- |-| Claude Code | fixed (built-in model IDs) | wants another vendor's model ⇒ per-agent mapping in its 模型菜单 |+| 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 || Codex | fixed | same || OpenCode + future in-house agents | open | follows upstream model lists; supports user-defined custom model entries |-### 4.4 OpenCode identifier scheme (locked 07-23)+### 4.8 OpenCode identifier scheme (locked 07-23, unchanged in v2)OpenCode models are `provider/model-id`. Rules:@@ -141,29 +710,42 @@ OpenCode models are `provider/model-id`. Rules:back to a single `custom/` provider.- Hub mode merely redirects those providers' transport to the local hub inthe generated runtime config overlay. Therefore **identifiers are stable- across Hub/Direct switches and across source add/remove/failover** —- never encode a concrete source into the provider segment.+ across Hub/Direct switches, across source add/remove/failover, and — new in+ v2 — across any per-agent reordering**; never encode a concrete source into+ the 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 V4 frames)+## 5. Surfaces (design.pen V6 frames)-| # | Frame | Content contract |-| --- | --- | --- |-| 01r | 设置 · 模型 main page | One page, two bands. **来源**: global list; drag handle + priority number; per-row icon, name, mono sub (account/key id; cooldown ETA lives here), usage column (subscription progress bar / monthly ¥), fixed-width aligned chip columns 包月/按量¥ and 使用中/备用/暂不可用; supply list appears ONLY as hover tooltip on icon/title; header = one-line policy sentence + status pill; 添加来源 button in card header. **Agent**: one row per backend — name + 菜单固定/菜单开放 badge, current supply as a composite pill `model | ● source` (UI, not copy; friendly names here), mode chip 中枢 Hub / 直连 Direct, action 模型菜单 / 接入中枢. Below: 最近切换 (3 rows, human phrasing, view-all) and a single 高级 row (跨厂商自动顶替 default-off · 请求日志 · 诊断). |-| 02 | 后端 · Claude Code | 供给方式 card: two radio options — 中枢模式 Hub (推荐·默认; supply managed on Models page; native config untouched; "打开模型页") and 直连模式 Direct (legacy behavior preserved verbatim; detect strip "检测到既有直连配置 → 导入中枢…"). CLI path + connectivity test cards unchanged from current page. |-| 03 | 迁移对话框 | Non-destructive: per-item checklist grouped by backend. API keys + base URLs → direct import; subscription OAuth → **keep_native** by default (v1.1: 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 (file-import deferred; with the experimental flag on, re-auth in-engine via the connect flow instead). Footer promise: originals never modified/deleted; Direct always available. Triggers: first open after upgrade, setup wizard, backend-page banner. |-| 06r/07 | 添加来源 | Dropdown menu on the button (no type-chooser dialog): 连接 Claude 订阅 / 连接 ChatGPT 订阅 / 添加 API Key…. The API Key form is the only form dialog: vendor select (official vendors prefill base URL; 自定义 for compatible endpoints), key, base URL, test-and-add with model-discovery feedback ("发现 23 个可用模型"). |-| 09 | 连接订阅 | Reuses the existing `BackendOAuthPanel` / `AgentAuthService` state machine (start → 2s-poll → awaiting → verifying → success/failed/cancelled; 15-min timeout; cancel). Three declared flow forms, one shell: **A** paste auth code (Claude), **B** device code, self-completing (ChatGPT/Copilot), **C** paste redirected callback URL for replay (loopback unreachable from remote browsers). URL and device code always carry copy buttons (remote/phone operation). New OAuth subscriptions = declare a form, inherit the shell. |-| 04 | 模型菜单 · Claude Code | Mapping table: left = built-in real model IDs (mono, not editable), right = supply (default 跟随原生 · 按优先级供给; override e.g. → `glm-5.2` with per-row reset and a persistent capability warning: thinking/cache/tool semantics not fully equivalent). Per-agent scope. 恢复全部默认 in footer. |-| 05r | 模型菜单 · OpenCode | Grouped BY provider prefix (`anthropic/` · `openai/` · `zhipuai/` + plain-language annotation) — one taxonomy, full identifier visible by construction (group prefix + mono row ID); friendly name is secondary text. 精选/全量 toggle (default featured); checkbox = appears in OpenCode's model picker; colored dots = supplying sources; custom rows carry 自定义 badge + edit. |-| 08 | 添加自定义模型 | Fields: source, model ID, optional display name → live identifier preview with the vendor-id rule above. |--Pending mocks (not blocking sign-off): first-run empty state, Dark variants,-mobile, plus a full copy pass under the rule **"if UI style can express it,-don't write copy"** (established 07-22 and applied to 01r).+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.++| 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@@ -176,9 +758,19 @@ don't write copy"** (established 07-22 and applied to 01r).`settings.json` etc.), useful for diagnostics and self-managed setups.- Backends can differ in mode; the Models page Agent rows surface per-backendmode with one-click 接入中枢.-- Migration is copy-only and reversible; see frame 03 contract above.--## 7. Security boundaries (amended v1.1)+- **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.++## 7. Security boundaries- Three credential rings, never mixed: management key (Avibe→engine adminAPI), local gateway token (the only thing backends receive), upstream@@ -186,10 +778,12 @@ don't write copy"** (established 07-22 and applied to 01r).flag — subscription OAuth tokens; engine-held, local runtime dir withrestricted permissions, not `~/.cli-proxy-api`). By default the enginenever holds subscription OAuth tokens: `native_cli` subscriptions keep- their credential in the CLI's own sanctioned store (spec §4.1).+ their credential in the CLI's own sanctioned store (§4.1).- 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+ events: it reports classified outcomes, never raw upstream error bodies.## 8. Data plane@@ -197,45 +791,149 @@ The hub's 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/manage-UI are **not** product surface. The capability matrix (supported OAuth-vendors, protocol conversions, model-fallback plugin maturity) was a-point-in-time survey and MUST be re-verified from source/docs at-implementation time; subscription reuse across clients/vendors additionally-requires billing/quota/ban-risk and ToS review before any default-on-behavior.--## 9. Explicit non-goals (v1)--- No per-model priority ordering (global list only, filtered per request).-- No automatic cross-vendor substitution by default (advanced flag,- experimental, visible marking).+UI are **not** product surface.++**v2 requires no engine change.** Failover is ours, not the engine's: the engine+runs 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+the 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.+- **No health-scoring or smart auto-reordering.** No latency ranking, no learned+ preference, no cost optimizer. This is the §2.4 predictability promise — a+ product decision, not a missing feature.+- **No session-level source pinning.** "Run just this turn on that source" is a+ diagnostic need, served by Direct mode plus the dry-run probe — not by a+ per-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 billing-grade accounting, multi-tenant pools, or operator consoles.- No third source category ("relay" merged into API Key).## 10. Open items-1. Remaining mocks: empty state / Dark / mobile / copy pass (§5 pending);- plus V4-01r/06r/09 touch-ups for supply channels: source-row 原生供给- note, experimental marking, and the consent dialog for- `subscription_hub_experimental` (copy from S2 §9).-2. ~~ToS + billing verification~~ **Done (spike S2, 2026-07-23)** —- `model-hub-tos-review.md`; verdicts folded into §4.1/§4.2/§7. Residual:- keep the consent copy in sync with vendor terms at release time.-3. ~~Data-plane capability re-verification~~ **Done (spike S1, 2026-07-23)**- — `model-hub-engine-survey.md`; engine pinned v7.2.95, OAuth is- runtime-declared (contracts), adapter owns error classification & events.-4. Naming final check in EN locale: Hub / Direct wording in en.json- (中文已定: 中枢/直连; alternates 托管/自管、统一/独立 were considered and- dropped).-5. Implementation plan & lane split (separate doc once this spec is signed).-6. Deferred capability: engine-owned OAuth import (adapter rev) — prerequisite+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 the L2 rebuild.+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+ L2 rebuild shows what turn-level accounting we actually hold.+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 `contract_version: 3` (a fixed-menu backend gains+ user-added entries alongside `mappings`). 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 (separate doc; the v1+ `model-hub-implementation.md` describes the shipped v1 and is superseded for+ anything touching ordering).+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) — prerequisitefor any future auth-file controlled_import; revisit only with a concrete need.## 11. Owner acceptance checklist (~10 min)-- [ ] §2 promises and §3 vocabulary match intent; nothing else leaks into UI copy.-- [ ] §4.2 resolution rules: mapping/priority split, error taxonomy, no-retry-after-stream.-- [ ] §4.4 identifier rules (vendor ids, `custom/` fallback, stability guarantee).-- [ ] §5 frame contracts match the V4 mocks you reviewed (01r/02/03/04/05r/06r/07/08/09).-- [ ] §6 Direct mode preservation + migration triggers acceptable.-- [ ] §8 data-plane posture (managed dependency, re-verify caveat) acceptable.+- [ ] §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 notification rule,+ including `waiting` — an all-cooling agent stays in the feed and is never+ pushed, because it fixes itself.+- [ ] §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.