Skip to content

armgit / avibe

Public Imported from GitHub
0

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

docs(model-hub): OpenCode v4 — bare menu ids, native_protocol, per-protocol overlay (#1858)

Call White1a312487f8cc
diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.md
index 0c3594e72..d2fd6d3ff 100644
--- a/docs/plans/backend-model-catalogs.md
+++ b/docs/plans/backend-model-catalogs.md
@@ -1,6 +1,6 @@
# Backend Model Catalogs
-Status: implementation contract — v1 shipped in #1814; **v2 (compose from providers) below is the current definition of done, approved by the owner on 2026-09-03; C1–C7 are normative**
+Status: implementation contract — v1 shipped in #1814; v2 (compose from providers) shipped in #1830/#1837/#1839/#1843/#1846; **v3 (OpenCode: bare ids, per-protocol overlay) below is the current definition of done, approved by the owner on 2026-09-04; C1–C13 are normative, with v3 superseding the v2 sentences it names for OpenCode**
## Outcome
@@ -478,3 +478,160 @@ renders 23px tall against the frame's 19px chip, which stacks a picker row to 60
frame B‴ measures 52 — retuning the pill would move every pill in the Model Hub — and the
narrow-viewport footer orders its two buttons the other way, which is the shared `Dialog`
primitive's own narrow layout. Neither hides nor clips anything.
+
+## v3 — OpenCode: bare ids, per-protocol overlay (2026-09-04)
+
+Owner decisions of 2026-09-04, recorded here because they change what an OpenCode row *is*.
+Normative text lives in `model-hub.md` §4.8 (v4) and `model-hub-contracts/opencode-overlay.md`
+(v4); this section binds the catalog product model to them and supersedes, for OpenCode only,
+these v2 sentences: question 1's `vendor/model` candidate identity, question 6's
+"OpenCode requires `vendor/model`", question 7's `custom/<query>` typeahead item and the
+"three buckets" manual rule, C7's OpenCode clause (the models.dev-filled id is
+`<provider>/<model>` through the vendor normalization — under v3 the filled id is the selected
+match's model id as models.dev states it), and the `vendor/model` clauses of the candidates
+read and the admission predicate — and C5's unchanged-runtime guarantee, superseded for
+OpenCode row projections (C8), the removed `standard_vendors` projection (C9), and the
+OpenCode overlay (C10) only.
+
+### Outcome
+
+A user who puts OpenCode on the Gateway sees, in OpenCode, exactly the models they composed in
+the Model Hub and nothing else; each is addressed as `avibe-openai/<id>` or
+`avibe-anthropic/<id>`; an Anthropic request reaches a same-protocol upstream with an
+identical body, a Responses request keeps its input and reasoning (the engine's Codex executor
+edits the envelope, S3). In Avibe the OpenCode list looks like the Codex list: bare ids,
+display names, no protocol chatter.
+
+### Product model deltas
+
+- **Identity (q1, q6).** An OpenCode candidate and menu id is the bare canonical model id,
+ deduplicated exactly as for Codex; two Sources supplying the same id are one candidate with
+ two suppliers. Admission is the Codex rule (canonical form, length).
+- **Native protocol (new).** Selection derives `native_protocol` from the id's vendor family
+ through `vibe/data/model_vendors.json` at add time; the editor's last field (`API`, OpenCode
+ rows only) lets the user change it. No other surface shows it.
+- **Custom model editor (q7, C7).** The typeahead's last item is the plain
+ `Use "{{query}}" as the model ID`; choosing a models.dev match fills the match's model id;
+ the id is stored as typed after canonicalization. The OpenCode-only repair buckets and the
+ `<provider>/<model>` fill are retired.
+- **Overlay (C7 → opencode-overlay.md v4).** One provider per downstream protocol,
+ `enabled_providers` naming them, every menu row projected (C1's empty-Route rows included),
+ Chat Completions retired downstream.
+
+### Contract deltas (normative; lanes cite these by number)
+
+- **C8 — `BackendModel.native_protocol`** (`openai_responses | anthropic`; `gemini` reserved,
+ refused) is required on OpenCode rows and absent on other backends. It travels like every
+ other proposed value (C2): the server derives it from the id's vendor family into every
+ picker `Candidate` (C4) and every models.dev match (C7); the editor defaults a typed id to
+ `openai_responses`; the `PUT` stores the request literally and refuses an OpenCode row
+ without it or with an unknown value. Row projections carry it so the editor can show it.
+ Artifact change: `backend-model.schema.json` gains the optional `native_protocol` property
+ with the closed enum; because that row schema has no backend discriminator, the containing
+ `catalog_models` arrays enforce the backend condition; the `types.ts` mirror follows
+ (artifact checklist below).
+- **C9 — OpenCode ids are bare.** Every schema, pattern, and validator that required
+ `^[a-z0-9_-]+/.+$` for an OpenCode id now applies the canonical-id rule; the
+ `standard_vendors` projection of agent-supply is removed (no consumer remains).
+- **C10 — Overlay shape** per opencode-overlay.md v4 (providers, `enabled_providers`,
+ variants per SDK, fixed provider ids, reserved `avibe-` prefix).
+- **C11 — Engine passthrough (API-key Sources).** Engine config for API-key upstreams sets
+ `disable-claude-cloak-mode: true`, credential `cloak.mode: never`, and
+ `rebuild-mid-system-message: false` (S3), so a same-protocol Anthropic request body is
+ forwarded unchanged apart from the mandatory `model` rewrite to the stored hop's model id
+ (user-configured substitutions stay authoritative, `model-hub.md` §4.5); transport headers
+ and upstream auth are the engine's own. Responses bodies toward a `codex-api-key` upstream
+ are rewritten by the engine (S3): the implementation verifies each real `openai_responses`
+ Source still serves such requests and files the engine follow-up. A Hub-held Claude
+ subscription (OAuth credential) keeps the engine's cloaking: the vendor accepts those tokens
+ only from the Claude Code identity the cloak reproduces, so rows served by a subscription
+ get the reasoning-preserving path of S4, not the body-identical guarantee. The engine has one
+ process-wide configuration, so the controls are applied per credential, not globally:
+ `cloak.mode: never` and `rebuild-mid-system-message: false` on every API-key `claude-api-key`
+ entry, OAuth credential records left at the engine default (or given an explicit
+ `cloak.mode: always` if a global flag turns out to be required for the API-key path). One
+ test runs both credential classes in one engine process and asserts S3's diff is empty for
+ the API-key hop while the OAuth hop still carries the cloak.
+- **C12 — No upgrade handling (owner ruling 2026-09-05).** Per `model-hub-contracts/README.md`
+ no bump converts anything: a pre-v4 OpenCode section is invalid input under C8/C9 and takes
+ the existing invalid-config path. No migration, parking, notice, discriminator, or
+ compatibility fixture exists.
+- **C13 — `contract_version` 7 → 8 (prospective).** This spec pre-bumps nothing: every
+ registered version location still reads 7 on this head, and the implementation change moves
+ all of them to 8 in one tested head under the existing version closure.
+
+### Contract artifact changes (v3; the contracts lane's checklist)
+
+| Artifact | Change |
+| --- | --- |
+| `backend-model.schema.json`, `ui/src/components/settings/models/types.ts` | optional `native_protocol` property (closed enum `openai_responses | anthropic`) on the row shape (C8). |
+| `agent-supply.schema.json` (`catalog_models`), `api-response.schema.json` (`AgentCatalogResponse.catalog_models`) | backend-conditional item constraints on `catalog_models`: `native_protocol` required for `opencode` rows and forbidden for `claude`/`codex` rows — the row schema has no backend discriminator, so the containing arrays enforce it; invalid-backend fixtures for both (C8). |
+| candidates read (C4) and models.dev read (C7) response shapes | `Candidate` and each models.dev match carry the server-derived `native_protocol` (C8). |
+| `agent-supply.schema.json` | `menu.checked` items follow the canonical-id rule (no `/` requirement); the `standard_vendors` projection is removed (C9). |
+| `mirror-registry.json` | registers the `native_protocol` enum and the fixed provider-id mapping (`openai_responses` → `avibe-openai`, `anthropic` → `avibe-anthropic`). |
+| `api.md` | identifier rule (done in this revision); response-registry rows for the models `PUT`/read carrying `native_protocol`. |
+| `opencode-overlay.md` | v4 (done in this revision). |
+| `README.md` version closure + every registered location (`service.py`, `provenance.py`, `types.ts`, tests) | 7 → 8 in the implementation head (C13). |
+
+### Deletions (the lanes remove these outright; no shim, alias, or fallback stays)
+
+- `core/handlers/model_hub/identifiers.py`: `STANDARD_OPENCODE_VENDOR_IDS`,
+ `opencode_provider_id`, `opencode_model_id`, `parse_opencode_model_id`, and their consumers
+ in `resolver.py` (`opencode_model_id` use, `opencode_inventory_menu_ids` projection) and
+ `service.py` (`standard_vendors` projection).
+- `config/v2_config.py`: `canonical_opencode_menu_identity` and every prefixed-id branch in
+ route/hop handling.
+- `modules/agents/model_hub.py`: `OpenCodeOverlay.provider_id` (singular) and
+ `_source_prefix`-composed runtime model ids; `vibe/opencode_config.py`:
+ `MODEL_HUB_RUNTIME_PROVIDER_PREFIX` and `model_hub_runtime_provider_id` (the digest id).
+- `modules/agents/opencode/server.py`: single-provider overlay state and its catalog filter.
+- `ui/src/components/settings/models/menus/identifiers.ts` (`inferProvider`,
+ `buildIdentifier`) and the editor's OpenCode "three buckets" repair; every unit/e2e fixture
+ that carries a prefixed OpenCode id.
+
+### Copy (English source; `zh.json` mirrors 1:1)
+
+| Where | String |
+| --- | --- |
+| Editor, last field (OpenCode rows only) | label `API` · options `OpenAI Responses` · `Anthropic Messages` |
+| OpenCode provider names (visible only inside OpenCode) | `Avibe · OpenAI` · `Avibe · Anthropic` |
+
+No new string anywhere else; nothing explains the mechanism.
+
+### Acceptance (properties)
+
+1. For every OpenCode menu row — empty Route chain included — the overlay holds exactly one
+ model entry, under the provider named by its `native_protocol`; every generated provider
+ holds at least one entry, the overlay holds no other provider, and `enabled_providers`
+ equals the set of generated provider ids.
+2. A menu id is byte-identical across Gateway⇄Direct switches, Source add/remove/reorder,
+ failover, route edits, and engine restarts; it changes only when the user renames the row.
+3. When the serving hop is an API-key Source whose protocol equals the row's
+ `native_protocol`, an Anthropic request body reaches the upstream JSON-identical apart from
+ the `model` field rewritten to
+ the stored hop's model id; a Responses request keeps its `input`, `reasoning`, and
+ `prompt_cache_key` while the engine's Codex executor edits the envelope as S3 records; when
+ the protocols differ, a Responses `reasoning.effort` reaches an `anthropic` upstream as
+ `output_config.effort` (S4). Known and accepted: an Anthropic-native row served through an
+ `openai_chat` hop loses its effort.
+4. In Gateway mode, a user configuration declaring other providers with keys surfaces no
+ model outside Avibe's providers in `/config/providers`; in Direct mode no overlay exists.
+5. No compatibility path exists: a pre-v4 OpenCode section is rejected as invalid input, and
+ no code reads, converts, or parks it.
+6. No Avibe list, picker, row, or chip renders the protocol; the editor's `API` field is the
+ only place it appears, for OpenCode rows only.
+7. Creating a user custom provider with an `avibe-*` id is refused; an existing one stays
+ readable and editable.
+8. `contract_version` 8 satisfies the version closure test.
+
+### Delivery plan
+
+Spike done (S1–S6 recorded in opencode-overlay.md v4). Lanes: **backend** — identity,
+`native_protocol`, the overlay writer and the whole OpenCode launch seam it changes
+(`modules/agents/model_hub.py` provider set, `modules/agents/opencode/server.py` provider-set
+filtering, `modules/agents/opencode/agent.py` addressing), the engine credential controls
+(C11), the C12 rejection of pre-v4 input, the deletions listed above, contract artifacts and
+version 8 · **UI** — bare-id rows, editor `API` field, retired prefixing
+and buckets, e2e fixtures · **docs mirror**. Gemini ships in its own later revision with a
+Gemini Source protocol.
+
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 88f319ec3..d499c0b11 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -230,8 +230,9 @@ non-empty user list with a managed declaration emits exactly one redacted
- The API boundary also verifies referential existence where a new reference is
emitted or accepted. JSON Schema can validate format, not cross-document existence.
- Claude and Codex requests use fixed-menu built-in ids.
-- OpenCode requests use a prefixed `vendor/model` menu id. The prefix chooses the
- provider; the resolver sends the bare model id upstream.
+- OpenCode requests use the bare canonical menu id (spec §4.8 v4). The overlay provider
+ is a function of the row's `native_protocol`; the resolver sends the exact stored hop's
+ model id upstream.
- Add-time matching may suggest a sanctioned alias or mapping, but it materializes the
accepted result as an exact `{source_id, model_id}` hop before commit. Runtime neither
resolves aliases nor substitutes a model.
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
index de5c8708c..600270462 100644
--- a/docs/plans/model-hub-contracts/opencode-overlay.md
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -1,61 +1,129 @@
-# OpenCode overlay contract
+# OpenCode overlay contract (v4, 2026-09-04)
<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->
-How Avibe generates the OpenCode runtime config overlay (`OPENCODE_CONFIG`) in
-Gateway mode. Owner-locked identifier rules (spec §4.8) restated as testable
-requirements.
+How Avibe generates the OpenCode runtime config overlay in Gateway mode. Owner-locked
+identifier rules (spec §4.8 v4) restated as testable requirements. Supersedes the 07-23
+contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that shape survives.
+
+## Delivery
+
+- The overlay is injected at `opencode serve` launch as `OPENCODE_CONFIG` (the overlay file)
+ and `OPENCODE_CONFIG_CONTENT` (OpenCode's runtime-override tier: the overlay composed with
+ Avibe's managed runtime policy, today the native-Skill restrictions). The recorded content
+ hash covers that composed inline content, so a change in either input restarts the server.
+ OpenCode merges its own configuration layers underneath; Avibe never writes the user's
+ `opencode.json`.
+- `enabled_providers` lists exactly the provider ids the overlay generates, so providers from
+ the user's own configuration or from environment keys are not loaded and their models never
+ appear in `/config/providers`. In Direct mode no overlay exists.
+- **Addressing.** In Gateway mode Avibe addresses OpenCode with `providerID` = the fixed
+ provider id of the selected row's `native_protocol` from the table below
+ (`openai_responses` → `avibe-openai`, `anthropic` → `avibe-anthropic`) and `modelID` = the
+ menu id; the Direct-mode `agents.opencode.default_provider` setting is not consulted. A
+ selector naming no menu row keeps the existing no-chain handling.
+- The overlay content hash is recorded at launch; when the effective overlay changes (menu
+ edit, `native_protocol` edit, gateway credential rotation) Avibe waits for active work to
+ finish, then restarts the serve process. Restarts are config events: no `resolution-event`
+ of kind `channel_switch`/`switch` is emitted.
+- **Nothing projectable.** When the OpenCode menu is empty (the last checked row was
+ removed), Avibe writes no overlay and drains and stops
+ the serve process; it relaunches with a fresh overlay when a projectable row exists again.
+ In Gateway mode a serve process never runs without an overlay, so the user's providers are
+ never exposed and a stale provider set never lingers in `/config/providers`.
## Provider entries
-- One provider entry per normalized **provider id** referenced by OpenCode's stored
- menu Route chains: `anthropic`, `openai`, `zhipuai`, … Models whose provider
- cannot be identified use the single `custom` provider id. Provider normalization
- occurs at Add/edit time and the stored result is authoritative.
-- No `avibe-` namespace anywhere (owner 07-23). Identifiers read exactly like
- native OpenCode: `anthropic/claude-opus-4-6`, `zhipuai/glm-5.2`,
- `custom/<model-id>`.
-- Each generated entry uses the OpenAI-compatible Chat frontend and redirects it to
- the local Gateway (`127.0.0.1:<port>/v1`), injecting the **local gateway token**
- (never upstream credentials). This frontend transport is stable for the provider
- entry even when its models resolve to Sources with different stored protocols. The
- Gateway uses the exact configured hop to reach an upstream whose protocol is one of
- `anthropic | openai_responses | openai_chat`. A custom `base_url`, not a fourth
- protocol, represents a relay or self-hosted upstream.
-- Any Hub-held subscription may supply OpenCode through an exact configured hop.
- A `native_cli` Source remains bound to its sanctioned backend and therefore cannot
- materialize as an OpenCode provider.
+- One provider entry per downstream protocol used by at least one checked menu row, so no
+ generated provider is ever empty and `enabled_providers` equals the generated set. When the
+ OpenCode menu is empty the existing `mapping_target_unavailable` refusal applies, no overlay
+ is written, and the serve process is stopped (Delivery):
+
+ | `native_protocol` | provider id | `name` | `npm` | downstream endpoint |
+ | --- | --- | --- | --- | --- |
+ | `openai_responses` | `avibe-openai` | `Avibe · OpenAI` | `@ai-sdk/openai` | Gateway `/v1/responses` |
+ | `anthropic` | `avibe-anthropic` | `Avibe · Anthropic` | `@ai-sdk/anthropic` | Gateway `/v1/messages` |
+ | `gemini` (reserved) | `avibe-gemini` | — | — | not generated |
+
+ `options.apiKey` is the local gateway token (never an upstream credential);
+ `options.baseURL` is the local Gateway base for that SDK (exact path per SDK recorded from
+ the spike, S1/S2). No `@ai-sdk/openai-compatible` provider is generated: downstream Chat
+ Completions is retired for OpenCode. Direct-mode user-defined providers are out of scope.
+- `avibe-` is reserved for **creation**: Avibe's Direct-mode custom-provider creation refuses a
+ new id with that prefix (existing reserved-id error). An existing entry that already carries
+ such an id stays readable and editable exactly as today — the reservation never hides or
+ rejects released configuration.
+ Avibe does not detect a hand-authored collision: a user who declares an `avibe-*` provider
+ in their own OpenCode configuration gets OpenCode's merge behaviour, which is unsupported.
+- Provider ids are fixed strings — never derived from a token digest, a Source, or a hop.
## Menu projection
-- The generated provider entries enumerate exactly the checked menu models with a
- stored nonempty Route chain (plus display names). `featured|full` is a UI view
- state; it cannot add a model to the overlay.
-- Custom model entries (`origin: manual`) appear under their Source's normalized provider
- prefix, or `custom/` when the vendor is unidentifiable.
+- `provider[<id>].models` is keyed by the bare menu id and enumerates exactly the checked menu
+ rows whose `native_protocol` maps to that provider — an empty Route chain does not remove a
+ row (C1 lets a user add a model no Source supplies; invoking it takes the existing no-chain
+ handling) — with the row's display name, context/output limits, modalities, tool and
+ reasoning support. `featured|full` is a UI view state; it cannot add a model to the overlay.
+- Reasoning variants are emitted in the shape the provider's SDK consumes (S4):
+ `avibe-openai` → `variants[effort] = { "reasoningEffort": effort }` (reaches the wire as
+ `reasoning.effort`); `avibe-anthropic` → `variants[effort] = { "effort": effort }` (reaches the
+ wire as `output_config.effort`, exact on a same-protocol hop). The legacy
+ `thinking.budgetTokens` shape is not used: the engine folds it into a bucketed effort, and
+ `thinking: {type, effort}` silently becomes a 1024-token budget. A row with
+ `supports_reasoning: false` has no variants.
- The invocation selects the exact stored `(source_id, model_id)` hop. Runtime never
- normalizes a provider, matches inventory, or substitutes a model.
+ normalizes a provider, matches inventory, or substitutes a model. The same-protocol
+ guarantee is protocol-specific: **Anthropic** — when the hop's Source protocol is
+ `anthropic`, the request body reaches the upstream unchanged apart from the `model` field,
+ which the Gateway rewrites to the stored hop's model id (a user-configured substitution,
+ `model-hub.md` §4.5, is invoked as written); **Responses** — when the hop's Source protocol
+ is `openai_responses`, `input`, `reasoning`, and `prompt_cache_key` reach the upstream intact
+ while the engine's Codex executor edits the envelope (below). The Anthropic guarantee is
+ body-level (S3): with the engine flags
+ `disable-claude-cloak-mode: true`, credential `cloak.mode: never`, and
+ `rebuild-mid-system-message: false`, an Anthropic-frontend body reaches an `anthropic`
+ upstream byte-identical; the engine's transport headers remain its own (a Claude-CLI
+ fingerprint: `User-Agent`, `Anthropic-Beta`, `X-Stainless-*`, session id) and upstream auth
+ is the engine's Bearer form. A Responses-frontend body reaching a `codex-api-key` upstream
+ is rewritten by the engine's Codex executor regardless of flags (`max_output_tokens`
+ dropped; `parallel_tool_calls: true`, `instructions: ""`, and an `image_generation` tool
+ added) — a known engine limitation the implementation verifies against each real
+ `openai_responses` Source before enabling the route, and tracks as an engine follow-up.
+ When the hop's protocol differs, the engine's automatic translation applies; S4 records what
+ survives: Responses-frontend effort reaches an `anthropic` upstream intact, an
+ Anthropic-frontend `output_config.effort` is dropped on the way to an `openai_chat` upstream
+ (a second reason models are grouped by native protocol, not by supplier).
## Add-time matching (`matching-v1`)
-OpenCode matching occurs once while adding a Source, adding a menu model, or reconciling
-a newly available built-in, using the inventory owned by that write. An exact checked identifier wins. Otherwise a bare model id is
-accepted only when exactly one checked identifier ends with `/<bare>`; zero matches and
-ambiguous matches are left unconfigured. The stored Route carries the concrete upstream
-model id and this normalization is never repeated by runtime or refresh.
+OpenCode matching occurs once while adding a Source or a menu model, using the inventory
+owned by that write. An exact model id wins; there is no prefix to strip or repair. The stored
+Route carries the concrete upstream model id and this normalization is never repeated by
+runtime or refresh.
## Stability invariant (test requirement, L7)
-For a fixed set of checked models, the generated identifier strings are
-byte-identical across: Gateway⇄Direct mode switches, Source-order edits, Source
-cooldown/failover, and engine restarts. Adding/removing a Source without changing the
-stored OpenCode Route chains also leaves identifiers byte-identical. A scenario test
-asserts this by diffing generated overlays under each perturbation.
+For a fixed set of checked rows with fixed `native_protocol` values, the generated overlay is
+byte-identical across: Source-order edits, Source cooldown/failover, route-chain edits,
+engine restarts, and gateway token rotation apart from
+`options.apiKey`. Adding/removing a Source without changing the stored Route chains also
+leaves it byte-identical. A scenario test asserts this by diffing generated overlays under
+each perturbation.
+
+## Upgrade — none
+
+Model Hub is pre-release (owner, 2026-09-05; `README.md`: no bump carries a migration,
+compatibility reader, conversion, or version discriminator). A stored OpenCode section in the
+pre-v4 shape is invalid input under the v4 schema and is handled by the existing invalid-config
+path; nothing converts it.
-## Long-lived `opencode serve`
+## Spike record (S1–S6; evidence captured 2026-09-04 on OpenCode 1.18.18 and CLIProxyAPI 7.2.105 `4a2eb54d`, the binary Avibe's manifest pins, with the repo mock upstream recording path/headers/body)
-The overlay content hash is recorded in process metadata at launch. When the
-effective overlay changes (menu edit, source vendor set change), Avibe waits
-for active work to finish, then restarts the serve process; a
-`resolution-event` of kind `channel_switch`/`switch` is NOT emitted for
-restarts (they are config events, not supply switches).
+| # | Question | Evidence |
+| --- | --- | --- |
+| S1 | `@ai-sdk/openai` + custom `baseURL` calls `/v1/responses` | Yes: `options.baseURL = <gateway>/v1`; a prompt through `avibe-openai/gpt-5` hit the mock at `/v1/responses` with `model: gpt-5`. No option exists or is needed to force Responses; the custom-provider path calls the SDK's `languageModel()`, which is Responses. |
+| S2 | `@ai-sdk/anthropic` + custom `baseURL` calls `/v1/messages`; client auth header | Yes: `/v1/messages`, sent with `X-Api-Key` and `Anthropic-Version: 2023-06-01`. The engine accepts its client key as `x-api-key` or `Authorization: Bearer` (200/200; wrong key 401). Toward a `claude-api-key` upstream it sends Bearer. |
+| S3 | Same-protocol passthrough | Not by default: the engine added `metadata.user_id`, split `system` into billing/identity/Claude-Code-prompt segments and moved OpenCode's system text into a user `<system-reminder>`. With `disable-claude-cloak-mode: true` + credential `cloak.mode: never` + `rebuild-mid-system-message: false` the inbound and upstream bodies are JSON-identical. Headers stay fingerprinted (Claude-CLI `User-Agent`, `Anthropic-Beta`, `X-App`, `X-Claude-Code-Session-Id`, `X-Stainless-*`); `fingerprint-profile` does not exist in this version. Responses → `codex-api-key` is rewritten regardless of `codex.identity-confuse`/`optimize-multi-agent-v2` (see Menu projection). |
+| S4 | Variant shapes and cross-protocol survival | OpenAI `{ "reasoningEffort": "high" }` → `reasoning: {effort: high, summary: auto}`, preserved to a Codex upstream. Anthropic top-level `{ "effort": "high" }` → `output_config: {effort: high}`, preserved on a same-protocol hop. Anthropic `{ thinking: {type: enabled, budgetTokens: 4096} }` → engine folds to `thinking: adaptive` + `output_config.effort: medium`; `thinking: {type: enabled, effort: high}` → a 1024-token budget read back as `effort: low` (wrong). Cross-protocol: Responses effort `high` → `anthropic` upstream gets adaptive thinking + `effort: high`; Anthropic budget 4096 → `openai_chat` upstream gets `reasoning_effort: medium`; Anthropic top-level effort → `openai_chat` upstream gets nothing. |
+| S5 | `enabled_providers` hides user/env providers | Yes: with a scratch global config declaring `global-other` with an API key and the overlay's `enabled_providers: ["avibe-openai","avibe-anthropic"]`, `/config/providers` listed only the two Avibe providers. |
+| S6 | Canonical reference and display | `/config/providers` shows each provider's overlay `name` and keys its models by the bare id; a prompt carries `providerID` and `modelID` separately, so the canonical reference string is `avibe-anthropic/claude-opus-5`. |
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index 29326362d..4d88c9b1e 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -1,5 +1,23 @@
# Model Hub — Implementation Plan
+> **2026-09-04 override — OpenCode v4 (`model-hub.md` §4.8 v4, `opencode-overlay.md` v4,
+> `backend-model-catalogs.md` v3).** This document is a historical lane plan. Wherever a row,
+> acceptance criterion, fixture, or handoff below says that an OpenCode menu id is
+> `provider/model` or `vendor/model`, that OpenCode add-time matching uses an exact checked
+> identifier or a unique bare-suffix match, or that the overlay carries normalized provider ids,
+> the v4 rule governs instead: OpenCode menu ids are bare canonical model ids matched by literal
+> equality, each OpenCode row carries `native_protocol`, and the Gateway-mode overlay generates
+> one provider per downstream protocol (`avibe-openai`, `avibe-anthropic`) with
+> `enabled_providers`; the `standard_vendors` projection of agent-supply is removed (catalogs
+> spec v3, C9), so any disposition below that keeps it mode-independent is retired with it.
+> The v4 backend lane (catalogs spec v3, delivery plan) owns the launch
+> seam this shape changes — `modules/agents/model_hub.py` (`OpenCodeOverlay` carries a provider
+> set, not one `provider_id`), `modules/agents/opencode/server.py` (overlay provider set,
+> runtime-catalog filtering to that set), `modules/agents/opencode/agent.py`
+> (`resolve_opencode_model_dict` addressing from the row's `native_protocol`) — and their tests,
+> irrespective of the closed I1/I7/L3 assignments recorded below.
+
+
Status: **v3.0 implementation addendum** · 2026-08-09 · supersedes v2 lane authority;
follows product spec v3.0
Spec: `docs/plans/model-hub.md`
@@ -92,8 +110,9 @@ orchestrator only.
`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, serve
+8. `opencode-overlay.md` — **v4 (2026-09-04):** bare menu ids, one generated provider per
+ downstream protocol (`avibe-openai`, `avibe-anthropic`) with `enabled_providers`,
+ transport redirection, gateway token injection, serve
config-hash restart rule; identifier stability invariant stated as a test
requirement.
9. **v2 additions** (2026-07-29): `agent-chain.schema.json` (capability chain per
@@ -877,7 +896,7 @@ external resolver importers.
| **FC-08** | `turn-provenance.schema.json` | Gateway turn records contain no route-policy discriminator; they record exact requested/configured model ids, exact Source attribution, ordered attempts, and the closed outcome set owned by §4.5's authoritative Turn-outcome copy matrix. `requested_model_changed` is derived from those exact ids and is never persisted. The schema mirrors the outcome set without reproducing its branches. A canceled in-flight attempt carries no fabricated Source failure. No separate mapping field, compatibility discriminator, or internal-version conversion state exists. |
| **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. |
| **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. |
-| **FC-11** | `opencode-overlay.md` | Keeps stable normalized provider ids for menu identity and add-time match suggestions, supports the three protocols, and pins the exact configured Source/model hop per invocation. Runtime performs no provider matching, and no vendor metadata chooses a saved protocol. |
+| **FC-11** | `opencode-overlay.md` | **Superseded 2026-09-04 by `model-hub.md` §4.8 v4 and `opencode-overlay.md` v4: OpenCode menu identity is the bare canonical model id, add-time matching is literal equality, and the overlay generates one provider per downstream protocol — no normalized provider ids anywhere.** Former shape: keeps stable normalized provider ids for menu identity and add-time match suggestions, supports the three protocols, and pins the exact configured Source/model hop per invocation. Runtime performs no provider matching, and no vendor metadata chooses a saved protocol. |
| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, exact route GET/PUT, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting `route_replace` removal is ordinary success; only protected-supply interruption enters that guard. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |
| **FC-13** | `migration-scan.schema.json` | Describes only the user-facing copy-only import of existing Claude, Codex, and OpenCode local configuration. Its action enum and one contract example/fixture per value mirror §6's authoritative Native-config import action matrix, including the `keep_native` default and the rejected/deferred `reauth` and `controlled_import` cases. Successful `keep_native` and `import` items run Add Source's one-time match and sole §4.2 placement policy, then report the same visible `added_to` positions. Originals are never modified or deleted, duplicate native selection fails before OAuth or partial commit, and it contains no Model Hub internal contract/data conversion. |
| **FC-14** | `runtime-dependency.schema.json` | Defines the single local engine asset, immutable version/SHA, loopback binding, lifecycle/health, management and Gateway tokens, and fail-closed behavior. `installing` is exactly the unverified non-listening shape with null installed version; any verified/listening runtime settles outside that transition. Engine availability is local Gateway health and never mutates an upstream Source cooldown. This entry does not widen the GA asset-mirror or platform-matrix research scope. **Installing-shape revision: 2026-08-11 23:09 K4.** |
@@ -1419,7 +1438,7 @@ Review round 10, P2, on `docs/plans/model-hub.md`, [thread](https://github.com/a
**Spec action at round 10, settled 07-29 10:54.** RECORDED, not fixed — and it was 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 was 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 announcing an interruption, which is why `SupplyGap.agents` is allowed to be empty. **With push cut, the finding's delivery half is void and its grain half survives intact.** There is no recipient set to narrow; what remains is the distinction between 「a model some Agent actually runs lost supply」 and 「a ticked-but-unassigned menu model lost supply」, which the feed, the row's status pill and the agent-facing 需处理 state must still tell apart — a menu-only failure must not render an Agent as interrupted. Ruling #4 stands unchanged: `SupplyGap.agents` includes the Agents inheriting `agents.<backend>.default_model`, because they do use the model; it is guard and confirm payload — the *rule* for resolving 「谁受影响」, which the UI applies to answer the same question from `agent-supply`, not a payload the UI receives on a source failure. The standing open decision this block used to defer to (zero-scope fallback) no longer exists.
-**Acceptance** (delivery half deleted 07-29 10:54; fixture repaired per AC-15). 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). The backend is **OpenCode with prefixed selections**, because a fixed-menu backend cannot own an OpenCode menu and a bare `gpt-5.6` is not a legal OpenCode selection under `api.md`'s identifier rules. **The assertions are on the live projection, not on the record** (07-29, review round 3): `SupplyGap` is contracted as a **mutation-refusal** payload (`api.md`, the DELETE/PUT guard responses), and `resolution-event.schema.json` carries no gap field, so 「the recorded gap names Agent Y」 asserts a shape no source-failure record has — the same record-vs-derivation confusion AC-6 was downgraded to remove. What a source failure produces is one unattributed record; who it is *about* is read from `agent-supply`'s per-Agent `supply_status` and the 「模型」 page's attribution. Case A: one enabled Agent running `openai/gpt-5.6`, plus a menu model `zhipuai/glm-5.2` the user ticked and assigned to no Agent, supplied only by source X. X fails: that Agent's `supply_status` stays `ok`, the 「模型」 page attributes the failure to the **menu model and no Agent**, and the failure still appears in the 最近切换 feed. Case B: the same fixture with that Agent pointed at `zhipuai/glm-5.2` — from fresh state, or after X is explicitly repaired and recovered — and X fails: that Agent's `supply_status` becomes `interrupted` and the page names exactly that Agent. `SupplyGap.agents` is asserted where it is actually returned — **AC-5's DELETE refusal**, which is the contracted home of the empty-list case and already carries that assertion. An implementation that resolves affected Agents over every enabled Agent on the affected backend passes B and fails A.
+**Acceptance** (delivery half deleted 07-29 10:54; fixture repaired per AC-15). 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). The backend is **OpenCode with bare selections (v4; the fixture ids below were prefixed before 2026-09-04)**, because a fixed-menu backend cannot own an OpenCode menu and, under v4, only a bare id such as `gpt-5.6` is a legal OpenCode selection (`api.md`); the prefixed form is what is rejected. **The assertions are on the live projection, not on the record** (07-29, review round 3): `SupplyGap` is contracted as a **mutation-refusal** payload (`api.md`, the DELETE/PUT guard responses), and `resolution-event.schema.json` carries no gap field, so 「the recorded gap names Agent Y」 asserts a shape no source-failure record has — the same record-vs-derivation confusion AC-6 was downgraded to remove. What a source failure produces is one unattributed record; who it is *about* is read from `agent-supply`'s per-Agent `supply_status` and the 「模型」 page's attribution. Case A: one enabled Agent running `gpt-5.6`, plus a menu model `glm-5.2` the user ticked and assigned to no Agent, supplied only by source X. X fails: that Agent's `supply_status` stays `ok`, the 「模型」 page attributes the failure to the **menu model and no Agent**, and the failure still appears in the 最近切换 feed. Case B: the same fixture with that Agent pointed at `glm-5.2` — from fresh state, or after X is explicitly repaired and recovered — and X fails: that Agent's `supply_status` becomes `interrupted` and the page names exactly that Agent. `SupplyGap.agents` is asserted where it is actually returned — **AC-5's DELETE refusal**, which is the contracted home of the empty-list case and already carries that assertion. An implementation that resolves affected Agents over every enabled Agent on the affected backend passes B and fails A.
**Remedy surface, added 07-29 review round 5 — L1's coordinated v3.** Round 3 retargeted
these assertions onto a per-Agent projection that **no contracted read payload serves**, so
@@ -1538,12 +1557,12 @@ Review round 12, P2, on `docs/plans/model-hub-implementation.md`, [thread](https
Review round 12, P2, on `docs/plans/model-hub-implementation.md`, [thread](https://github.com/avibe-bot/avibe/pull/1081#discussion_r3670273198). Verbatim:
> **Use a valid backend/model fixture for AC-9**
->
+> *[Superseded for OpenCode on 2026-09-04: menu ids are bare canonical model ids (§4.8 v4); the prefixed form no longer exists.]*
> The fixture combines a bare `gpt-5.6` selection with an “OpenCode-menu” entry on the same backend, but `api.md`'s identifier rules require OpenCode selections to use prefixed `vendor/model` IDs, while a fixed-menu Codex backend cannot also own an OpenCode menu. Consequently Case B cannot point this Agent at the described ticked model without changing backend/menu semantics; define the fixture as OpenCode with a prefixed selection such as `openai/gpt-5.6`, or use a fixed-menu-only scenario.
-**Disposition.** Repairs **AC-9's acceptance fixture**, applied above: one OpenCode backend with prefixed selections (`openai/gpt-5.6` running, `zhipuai/glm-5.2` ticked-but-unassigned). The previous fixture asked a fixed-menu backend to own an OpenCode menu, which `api.md`'s identifier rules forbid, so Case B could not be reached at all. AC-9's criterion and the round-9/round-10 narrowing rulings are unchanged. Independent of the 10:54 push cut — it repairs the fixture, which the surviving grain half still needs.
+**Disposition.** Repairs **AC-9's acceptance fixture**, applied above: one OpenCode backend with bare selections (`gpt-5.6` running, `glm-5.2` ticked-but-unassigned — v4 ids; they were `openai/gpt-5.6` and `zhipuai/glm-5.2` before 2026-09-04). The previous fixture asked a fixed-menu backend to own an OpenCode menu, which `api.md`'s identifier rules forbid, so Case B could not be reached at all. AC-9's criterion and the round-9/round-10 narrowing rulings are unchanged. Independent of the 10:54 push cut — it repairs the fixture, which the surviving grain half still needs.
-**Acceptance.** Contract/integration layer, owed by **L3** with the AC-9 tests it repairs. Every identifier in AC-9's fixture validates against `api.md`'s identifier rules for the backend that owns it, and Case B is constructible without changing backend or menu semantics mid-test. Fails today: `gpt-5.6` unprefixed on an OpenCode-menu backend is rejected by those rules, so the fixture cannot be built as written.
+**Acceptance.** Contract/integration layer, owed by **L3** with the AC-9 tests it repairs. Every identifier in AC-9's fixture validates against `api.md`'s identifier rules for the backend that owns it, and Case B is constructible without changing backend or menu semantics mid-test. Under v4 the bare id is the only admissible OpenCode form — a prefixed id such as `openai/gpt-5.6` is rejected — so the fixture is built exactly as written.
### AC-16 — Remove the nonexistent Agent from AC-5's assertion
@@ -1613,7 +1632,7 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/agent-supply.schema.json
but the final five projections are `selected_model_id`, `sources`, `routes`,
`supply_status`, and `model_supply`. `mappings` is not a final field. `selected_by_agent` and
`current` remain legitimately nullable, and `menu`, `builtin_models`, and
-`standard_vendors` remain mode-independent.
+`standard_vendors` remain mode-independent. *[Retired 2026-09-04: the `standard_vendors` projection is removed by catalogs spec v3 C9; see the v4 override at the top of this document.]*
**Acceptance.** I1 builds every fixture from an otherwise-valid payload. A Hub payload
with any of the five final projections explicitly null is rejected by the Hub branch;
@@ -2609,7 +2628,7 @@ architecture inputs to S-1, not sealed-ledger deferrals.
| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. I1 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) |
| **Assign the actual auth-setup scenario file**<br><br>Fresh evidence after the recorded auth-scenario thread is the repository layout: repo-wide search finds the harness at `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`, while this lane assigns the nonexistent `tests/test_auth_setup_scenarios.py`. Because I5 owns only the Model Hub scenario tree, the real closed-loop OAuth/setup test remains outside every active lane and can stay stale while the listed work completes; correct the path and ownership here and in the landing ledger.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I3 |
| **Assign the shared backend launch seam to an active lane**<br><br>**Closed by PM rulings 2026-08-11 22:37 and 2026-08-12 02:00.** Through #1312, I1 owns `modules/agents/model_hub.py`. After K4, #1312, and K6 merge, I7 exclusively owns that shared classification/state seam plus the narrow Model Hub failure callbacks in Claude, Codex, and OpenCode. Backend callbacks supply raw failure shape and exact `stream_started` phase, whose boundary is the first user-visible model-output byte; I7 removes the native 30-second persistent network cooldown and implements AC-50's live-backoff/event-only totality, consuming K6's G-34 Turn-outcome row for the post-output same-current-hop case. I2 retains only managed-Gateway raw phase facts. Exact cross-backend phase fixtures and mechanical signature consumers are named in the binding table and landing checklist, leaving one active owner and one three-way activation edge.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 + AC-50 | `modules/agents/model_hub.py`; Model Hub callbacks in `modules/agents/{base,claude_agent}.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`; `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server,test_claude_cli_path,test_multi_platform_runtime}.py` | I7 after K4 + #1312 + K6 merge |
-| **Specify the add-time model matching algorithm**<br><br>**Closed by owner ruling 2026-08-09: `matching-v1`.** The Add Source path transcribes the former resolver semantics: Claude native aliases use discovered-only inventory and the deterministic `(version_tuple, date_or_zero, model_id)` maximum; OpenCode uses exact checked identifiers or a unique bare suffix; Codex and non-native sources use literal equality. The stored hop is the concrete upstream id and runtime never repeats matching. | AC-22 | `model-hub.md` §4.2 `matching-v1`, `opencode-overlay.md`, `api.md`, `core/handlers/model_hub/{service,resolver}.py`, and backend fixtures in `tests/test_model_hub_{api,resolution}.py` | I1 |
+| **Specify the add-time model matching algorithm**<br><br>**Closed by owner ruling 2026-08-09: `matching-v1`. Amended 2026-09-04 (§4.2, §4.8 v4): the OpenCode branch — exact checked identifier or unique bare-suffix match — is retired; OpenCode menu ids match by literal model-id equality exactly like Codex.** The Add Source path transcribes the former resolver semantics: Claude native aliases use discovered-only inventory and the deterministic `(version_tuple, date_or_zero, model_id)` maximum; OpenCode (v4), Codex, and non-native sources use literal equality. The stored hop is the concrete upstream id and runtime never repeats matching. | AC-22 | `model-hub.md` §4.2 `matching-v1`, `opencode-overlay.md`, `api.md`, `core/handlers/model_hub/{service,resolver}.py`, and backend fixtures in `tests/test_model_hub_{api,resolution}.py` | I1 |
| **Assign the controller gate removal to I1**<br><br>Fresh evidence beyond the resolved default-off thread is that this landing row promises an available Models controller but assigns only handler files and `vibe/ui_server.py`; neither the active lane scopes nor the complete checklist includes `core/controller.py` or `tests/test_controller_model_hub_gate.py`. The current controller returns early when `VIBE_MODEL_HUB_ENABLED` is absent, and that test explicitly expects `model_hub_runtime is None`, so I1 can satisfy every named file/test while fresh installations still have no runtime. Add the controller and its gate test to I1's owned transition.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L145-L147) | AC-22 + AC-31 | `core/controller.py`; `tests/test_controller_model_hub_gate.py` | I1 |
**Forward stop.** After the S-1 head, if a review reports at least three findings in the same
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index b78ec9789..111f3bd7c 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1,12 +1,16 @@
# Model Hub — Product Spec
-Status: **v3.0** (2026-08-09) · supersedes v2.0 (2026-07-29) outright
-Owner decisions incorporated through: 2026-08-09 (+08:00)
+Status: **v3.1** (2026-09-05): §4.8 replaced by the OpenCode v4 identifier scheme and §4.2's
+OpenCode branch retired · v3.0 (2026-08-09) supersedes v2.0 (2026-07-29) outright
+Owner decisions incorporated through: 2026-09-05 (+08:00)
Design source: `../avibe-docs/design.pen`. The V6 frames remain the visual baseline;
the v3 interaction draft for the two-module information architecture is owner-approved
as the implementation baseline (2026-08-07 afternoon). The design lane still owes
production-complete desktop/mobile states.
-Contracts: `model-hub-contracts/` remain unchanged by this docs-only revision.
+Pre-release (owner, 2026-09-05): Model Hub has not shipped; no revision of its persisted
+state or contracts carries migration or compatibility handling (see `model-hub-contracts/README.md`).
+Contracts: v3.1 changes `model-hub-contracts/api.md` (OpenCode identifier rule) and rewrites
+`model-hub-contracts/opencode-overlay.md` (v4); every other contract file is unchanged.
`model-hub-implementation.md` records the exhaustive final-shape handoff. Its mechanical
closure must coexist on one tested PR head; all remaining consumers and evidence must
land before release.
@@ -498,7 +502,7 @@ and is never re-run by refresh, restart, health changes, or turn execution.
| Backend/source case | Candidate set | Accepted match and tie-break |
| --- | --- | --- |
| Claude fixed-menu id on a native `anthropic` Source | The Source's `discovered` models observed by this add transaction | A dated request is literal only. An undated version request matches the same family and exact version tuple; a bare `opus`, `sonnet`, or `haiku` alias matches that family at any version. Select `max(version_tuple, date_or_zero, model_id)`. `fable` has no bare alias. |
-| OpenCode menu id | The Source's observed models projected through its normalized provider id | Exact checked id first; otherwise a bare model id matches only when exactly one checked identifier ends with `/<bare>`. Zero or multiple matches is rejected as ambiguous. |
+| OpenCode menu id (v4, 2026-09-04) | The Source's observed models | Literal model-id equality only, exactly as Codex. The retired `provider/model` projection has no matching branch. |
| Codex fixed-menu id, or any non-native Source | The Source's observed models | Literal model-id equality only. Explicit user route edits may name an exact model, but runtime never infers or substitutes one. |
The resulting hop always contains the selected concrete upstream model id, never the menu
@@ -517,10 +521,7 @@ for each configuration-eligible Source added in this transaction:
for each backend menu model M:
candidates = observed.discovered_models
- if backend == opencode:
- checked = M if M is checked else the unique checked identifier ending with "/" + M
- match = the unique candidate whose normalized provider/model identifier equals checked
- elif backend == claude and Source is native anthropic:
+ if backend == claude and Source is native anthropic:
match = native_claude_alias(M, candidates)
else:
match = literal_model_id(M, candidates)
@@ -533,9 +534,9 @@ for each configuration-eligible Source added in this transaction:
`native_claude_alias` is the literal former resolver rule: dated requests are literal;
undated version requests require an equal version tuple; bare aliases match a family;
-the total order is `(version_tuple, date_or_zero, model_id)`. `exact_checked_identifier`
-and the unique suffix rule are the OpenCode overlay rule. No other backend gets an
-alias family, and explicit user-authored Route edits remain literal configuration.
+the total order is `(version_tuple, date_or_zero, model_id)`. No other backend gets an
+alias family — OpenCode menu ids match literally (v4, 2026-09-04) — and explicit
+user-authored Route edits remain literal configuration.
**Routing configuration is per backend and per model; health is Source-global.** Quota
and reachability belong to the Source, not the Agent that touched it. §4.3 reads the
@@ -1460,24 +1461,49 @@ current execution position added.
| Codex | fixed | same |
| OpenCode + future in-house agents | open | uses exact configured route chains; supports user-defined model entries |
-### 4.8 OpenCode identifier scheme (locked 07-23, retained in v3)
-
-OpenCode models are `provider/model-id`. Rules:
-
-- The provider segment uses the **standard vendor id** (`anthropic/`,
- `openai/`, `zhipuai/`, …) — identical to native OpenCode usage. No
- `avibe-` namespace (owner: keep it simple). Unrecognizable vendors fall
- back to a single `custom/` provider. Add Source may use this normalized id when it
- proposes a one-time match; runtime reads only the stored exact hop.
-- Gateway mode merely redirects those providers' transport to the local Gateway in
- the generated runtime config overlay. Therefore **identifiers are stable
- across Gateway/Direct switches, across source add/remove/failover, and — new in
- v3 — across any configured-chain edit**; never encode a concrete Source into
- the provider segment.
-- Users never hand-assemble the string. Menu checkboxes pick models; the
- custom-model form generates and previews the identifier (source + model ID
- in → `zhipuai/glm-5.2-air` out). A custom model entry is, in data terms, a
- supplement to that source's supply list.
+### 4.8 OpenCode identifier scheme (v4, owner-approved 2026-09-04; supersedes the 07-23 lock)
+
+An OpenCode menu id is the **bare canonical model id** — the same identity rule Codex uses
+(`canonical_model_id`), unique per backend, slashes allowed when the upstream id carries them
+(`moonshotai/kimi-k2`). The `provider/model` scheme of 07-23 (standard vendor segment, single
+`custom/` fallback) is retired: it existed to keep ids stable across Gateway/Direct switches,
+and under v4 the two modes no longer share a namespace at all (§4.8.3).
+
+1. **Native protocol is a field, not a prefix.** Every OpenCode `BackendModel` row carries
+ `native_protocol ∈ {openai_responses, anthropic}` (`gemini` is a reserved future value and is
+ not admissible until `avibe-gemini` ships). The server derives it from the model id's
+ vendor family through the repo-owned vendor map, looked up on the id's last `/`-separated
+ segment so a namespaced id (`anthropic/claude-sonnet-4-6`) finds its family (`anthropic`
+ family → `anthropic`, everything else → `openai_responses`), and proposes it with every
+ picker candidate and models.dev match; a typed id defaults to `openai_responses`; the save
+ stores what the client sends. It is editable only in the model editor, as its last
+ field, shown for OpenCode rows only. It is never shown in a list, picker, row, chip, or
+ badge: it is a mechanism of the product, not information the user acts on.
+2. **Canonical OpenCode reference = `<overlay provider id>/<menu id>`.** The overlay provider
+ id is a fixed function of `native_protocol`: `avibe-openai` for `openai_responses`,
+ `avibe-anthropic` for `anthropic` (`avibe-gemini` reserved). This composite is how Avibe
+ addresses OpenCode (its `providerID`/`modelID` split on the first `/`, its config `model`
+ field, its session records). Avibe's own surfaces show the menu id; the composite appears
+ only where a user needs to reference the model outside Avibe.
+3. **Two modes, two worlds.** In Gateway mode OpenCode runs with Avibe's overlay and
+ `enabled_providers` naming exactly Avibe's providers, so the user's own providers are not
+ loaded (opencode-overlay.md). In Direct mode Avibe injects nothing and OpenCode reads its own
+ configuration — OpenCode's behaviour, not Avibe's. Avibe never writes the user's
+ `opencode.json`, so switching modes leaves nothing to clean up.
+4. **Stability.** A menu id changes only when the user renames the row. Its overlay provider
+ changes only when the user edits `native_protocol`. Neither depends on Sources, Source order,
+ route chains, health, failover, or engine restarts.
+5. **Users never assemble a prefixed string.** The picker adds candidates by bare id; the
+ custom-model editor's `Model` field takes an id as typed (typeahead proposals included) and
+ applies the Codex admission rule; the retired "three buckets" repair of `custom/` prefixes
+ does not exist. Two different vendors' models that share an id cannot coexist in one
+ OpenCode menu — the same rule Codex already has.
+
+History: 07-23 locked `provider/model` with a standard-vendor segment and no `avibe-`
+namespace so ids read like native OpenCode and survived Gateway⇄Direct switches. 09-04 the
+owner ruled that Gateway mode owns the whole OpenCode model list, that downstream Chat
+Completions is retired in favour of one provider per downstream protocol, and that the
+native protocol is recorded per model rather than inferred from a Source's API.
## 5. Surfaces — two modules, one understandable handoff