Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(model-hub): integration close-out — server builtin_models/standard_vendors, flags on (LI) (#987)

Call White5d97d442c383
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index c6d8ae644..f5e589467 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -44,7 +44,12 @@ from .events import (
build_resolution_event,
contains_credential_material,
)
-from .identifiers import opencode_model_id, opencode_provider_id, parse_opencode_model_id
+from .identifiers import (
+ STANDARD_OPENCODE_VENDOR_IDS,
+ opencode_model_id,
+ opencode_provider_id,
+ parse_opencode_model_id,
+)
from .migration import (
MigrationConflictError,
apply_native_migration,
@@ -267,12 +272,22 @@ def _validated_base_url(value: object) -> Optional[str]:
return value
+def _builtin_model_ids(backend: str) -> tuple[str, ...]:
+ """Real built-in model ids for a fixed-menu backend, from the bundled catalog.
+
+ Single source of truth for both the native-subscription supply list
+ (_native_model_ids) and the agents endpoint's read-only builtin_models
+ projection (agent-supply.schema.json v1.2), so the two never diverge.
+ """
+ catalog = load_bundled_catalog()
+ return tuple(entry["id"] for entry in backend_model_entries(backend, catalog))
+
+
def _native_model_ids(vendor: str) -> tuple[str, ...]:
backend = _NATIVE_VENDOR_BACKENDS.get(vendor)
if backend is None:
return ()
- catalog = load_bundled_catalog()
- return tuple(entry["id"] for entry in backend_model_entries(backend, catalog))
+ return _builtin_model_ids(backend)
def _default_protocol(vendor: str) -> str:
@@ -919,9 +934,8 @@ class ModelHubService:
def _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:
current = None
- if agent.mode == "hub":
- if agent.backend == "opencode" and (agent.menu is None or not agent.menu.checked):
- return {**agent.to_payload(), "current": None}
+ opencode_menu_empty = agent.backend == "opencode" and (agent.menu is None or not agent.menu.checked)
+ if agent.mode == "hub" and not opencode_menu_empty:
provider = None
target = next((mapping.target_model_id for mapping in agent.mappings if mapping.enabled), None)
if target is None and agent.menu and agent.menu.checked:
@@ -942,7 +956,19 @@ class ModelHubService:
if model is not None:
current = {"model_id": model.id, "source_id": source.id, "channel": source.supply_channel}
break
- return {**agent.to_payload(), "current": current}
+ # Read-only projections (agent-supply.schema.json v1.2, integration 2026-07-24):
+ # fixed-menu backends expose their built-in catalog; opencode exposes the
+ # standard vendor prefixes. Both are populated straight from the backend
+ # modules so the UI never hand-mirrors a menu or vendor list. Not persisted
+ # config — injected here exactly like `current`.
+ builtin_models = list(_builtin_model_ids(agent.backend)) if agent.menu_kind == "fixed" else None
+ standard_vendors = sorted(STANDARD_OPENCODE_VENDOR_IDS) if agent.backend == "opencode" else None
+ return {
+ **agent.to_payload(),
+ "current": current,
+ "builtin_models": builtin_models,
+ "standard_vendors": standard_vendors,
+ }
def list_agents(self) -> list[dict]:
config = self.store.load()
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index 3e6e74810..14abde3db 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -52,7 +52,9 @@
"uniqueItems": true
}
}
- }
+ },
+ "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." }
},
"examples": [
{
@@ -61,7 +63,9 @@
"menu_kind": "fixed",
"current": { "model_id": "claude-opus-4-6", "source_id": "src_claudepro1", "channel": "native_cli" },
"mappings": [ { "builtin_id": "claude-opus-4-6", "target_model_id": "glm-5.2", "enabled": false } ],
- "menu": null
+ "menu": null,
+ "builtin_models": ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],
+ "standard_vendors": null
},
{
"backend": "opencode",
@@ -69,7 +73,9 @@
"menu_kind": "open",
"current": { "model_id": "glm-5.2", "source_id": "src_zhipukey01", "channel": "hub" },
"mappings": [],
- "menu": { "view": "featured", "checked": ["anthropic/claude-opus-4-6", "openai/gpt-5.6", "zhipuai/glm-5.2", "zhipuai/glm-5.2-air"] }
+ "menu": { "view": "featured", "checked": ["anthropic/claude-opus-4-6", "openai/gpt-5.6", "zhipuai/glm-5.2", "zhipuai/glm-5.2-air"] },
+ "builtin_models": null,
+ "standard_vendors": ["anthropic", "deepseek", "github-copilot", "google", "groq", "kimi", "minimax", "mistral", "moonshot", "openai", "openrouter", "together", "xai", "zhipuai"]
}
]
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 242e0e45d..a11bb81d1 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -13,7 +13,7 @@ session auth; localhost curl is rejected the same way as other `/api/*` routes.
| DELETE `/api/models/sources/<id>` | → `{ok}` | refuses while source is the only supplier of a checked/ mapped model unless `force=true` |
| 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 |
+| 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). |
| 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 |
diff --git a/docs/plans/model-hub-engine-survey.md b/docs/plans/model-hub-engine-survey.md
new file mode 100644
index 000000000..94b5ed5f2
--- /dev/null
+++ b/docs/plans/model-hub-engine-survey.md
@@ -0,0 +1,557 @@
+# Model Hub Engine Survey: CLIProxyAPI and Managed Runtime Reuse
+
+Status: S1 + S3 implementation spike, verified 2026-07-23
+
+## Scope and evidence boundary
+
+This survey evaluates CLIProxyAPI (CPA) as the first replaceable Model Hub
+data-plane engine and audits Avibe's Show Runtime installer for reuse. It uses
+the signed product spec at `docs/plans/model-hub.md` (SHA256
+`0bf53910fd14c4afb8c18a10d0a8d5f5bb43c64516bcb81a8c0fcaf4743d13b8`) and
+the implementation plan at `docs/plans/model-hub-implementation.md` (SHA256
+`35f336d5d0b063e000dbe5dbf16e752d997ccf80dec03873a76ed7ec018b93d5`).
+Those two inputs were untracked in the source checkout at survey time, so their
+content hashes, rather than an Avibe commit, identify the reviewed snapshots.
+
+CPA was cloned at release tag `v7.2.95`, exact commit
+[`f71ec0eb6776854457892452cf28c47f0d658251`](https://github.com/router-for-me/CLIProxyAPI/commit/f71ec0eb6776854457892452cf28c47f0d658251).
+All CPA source links below are pinned to that commit. The Show Runtime audit is
+pinned to Avibe commit
+[`e71890a78209f13ae8579d25800282e40469df38`](https://github.com/avibe-bot/avibe/commit/e71890a78209f13ae8579d25800282e40469df38).
+The branch was fast-forwarded to `origin/master` commit
+`8f9268c6afdcfa47658dced2194b9e7e2092902e` before commit; that intervening
+change only touched an unrelated Show annotation plan.
+
+No real vendor OAuth login or billable inference request was performed because
+the spike had no credentials and must not create or expose them. OAuth and
+upstream behavior claims are therefore source-verified, not live-account-
+verified. Asset hashes, binary versions, archive layouts, targeted source tests,
+and Avibe installer tests were verified locally as described in Verification.
+
+## Executive decision
+
+CPA is viable as a protocol and credential engine, but its built-in routing must
+not be the Model Hub policy authority. CPA automatically advances to another
+eligible credential for more error classes than the signed spec permits, and it
+does not expose a safe, first-class selection/switch event stream. The Avibe
+adapter should own mapping, ordered candidate selection, retry taxonomy, and the
+resolution-event log. It can isolate one source per CPA call by assigning every
+source a unique `prefix`, enabling `force-model-prefix`, and addressing the
+candidate as `<private-prefix>/<model>`. CPA then owns credential refresh,
+protocol translation, upstream execution, and per-source cooldown signals.
+
+For installation, reuse the Show Runtime manifest/download/verification design
+after extracting a generic managed-archive installer. Do not copy the existing
+Show-specific class and do not make the engine a special case inside it. This is
+a medium L1 change.
+
+## S1. CLIProxyAPI capability re-verification
+
+### 1. Official repository and pinned release
+
+The repository is
+[`router-for-me/CLIProxyAPI`](https://github.com/router-for-me/CLIProxyAPI).
+Its Go module is `github.com/router-for-me/CLIProxyAPI/v7`, and its current
+release series is v7.x, matching the project named in the prior survey. At
+During the 2026-07-23 03:05-04:00 UTC+08 verification window, the latest
+non-draft release was
+[`v7.2.95`](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v7.2.95),
+published 2026-07-22 14:47:25 UTC. The tag resolves to source commit
+`f71ec0eb6776854457892452cf28c47f0d658251`. Sources:
+[`go.mod`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/go.mod),
+[`v7.2.95` release](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v7.2.95).
+
+Pinned Model Hub L1 assets:
+
+| Platform | Release asset | Download bytes | MiB | Extracted executable bytes | SHA256 |
+| --- | --- | ---: | ---: | ---: | --- |
+| macOS ARM64 | [`CLIProxyAPI_7.2.95_darwin_aarch64.tar.gz`](https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_darwin_aarch64.tar.gz) | 14,384,655 | 13.72 | 43,626,210 | `c7ccc28b7db5d1799999a9e22725ccc6bd0e36d9aa023da6b52b7c1a71aad978` |
+| Linux AMD64 | [`CLIProxyAPI_7.2.95_linux_amd64.tar.gz`](https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_linux_amd64.tar.gz) | 15,401,775 | 14.69 | 46,901,896 | `826604e2dbf11913b0f373047f7bca1829eb2bab8a45d3a1916cc2534c7a9fd5` |
+
+Both archives were downloaded from the release, hashed locally, and matched the
+release's [`checksums.txt`](https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/checksums.txt).
+The release also publishes Darwin AMD64, Linux ARM64, Windows ARM64/AMD64,
+FreeBSD variants, and Linux `no-plugin` variants. Those additional assets were
+not downloaded or independently hashed in this spike and are not part of this
+pin.
+
+### 2. OAuth vendors and connect-dialog forms
+
+The built-in authentication manager registers Codex, Claude, Antigravity, Kimi,
+and xAI. Vertex is a service-account import, not OAuth. The binary also parses
+existing `gemini-cli` auth files, but it has no built-in Gemini login command or
+Management API OAuth-start endpoint at this tag. Plugins can add providers, so
+the contract must remain extensible. Sources:
+[`internal/cmd/auth_manager.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/cmd/auth_manager.go),
+[`cmd/server/main.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/cmd/server/main.go#L84-L105),
+[`sdk/auth/filestore.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/filestore.go#L210-L265).
+
+Form mapping is based on the actual Management API path that Avibe can call,
+not on a human parsing the standalone CLI's stdout:
+
+| Vendor / provider | Current flow shape | Spec form | Decision |
+| --- | --- | --- | --- |
+| Claude (`anthropic` session, `claude` auth) | PKCE URL redirects to `localhost:54545`; Management API callback replay accepts a full redirect URL or tracked `state` + pasted `code` | **C** natively; A can be adapter-compatible | The signed spec says A. Prefer C in the contract/UI; accepting a raw code in the same submit endpoint is a compatibility enhancement, not the primary flow. |
+| Codex / ChatGPT (`codex`) | Management API uses PKCE localhost callback on port 1455 | **C** | The signed spec says B. A separate `-codex-device-login` CLI mode is B, but no Management API endpoint exposes that device flow. Do not parse CLI stdout in L1. |
+| Google Antigravity (`antigravity`) | Browser OAuth redirects to `localhost:51121/oauth-callback`; callback replay is supported | **C** | This is the current built-in Google subscription path and supplies Gemini-family models. |
+| Kimi (`kimi`) | Device authorization returns URL/user code and background polling self-completes | **B** | Direct fit. |
+| xAI / Grok (`xai`) | Device authorization returns URL/user code and background polling self-completes | **B** | Direct fit. |
+| Gemini CLI (`gemini-cli`) | Existing auth-file parsing only; no built-in start flow | **None** | Import/reuse may be possible, but acquisition is not implemented by CPA. Do not advertise it as a CPA connect flow. |
+| Vertex (`vertex`) | Service-account JSON import | **None** | Model this as controlled credential import, not subscription OAuth. |
+
+The common callback endpoint accepts `redirect_url` or `code` + `state`, which
+is why Claude can tolerate a Form A-style raw-code submission even though its
+native redirect flow is Form C. Kimi and xAI start responses explicitly return
+`flow: "device"`; Codex device mode exists only in the standalone authenticator.
+Sources:
+[`Management OAuth handlers`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/auth_files.go#L1971-L2665),
+[`oauth_callback.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/oauth_callback.go),
+[`sdk/auth/claude.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/claude.go#L35-L205),
+[`sdk/auth/codex.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/codex.go#L35-L220),
+[`sdk/auth/codex_device.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/codex_device.go),
+[`sdk/auth/kimi.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/kimi.go),
+[`sdk/auth/xai.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/xai.go).
+
+Live vendor consent screens, entitlement restrictions, and end-to-end token
+exchange were not verified. S2 must still gate product defaults.
+
+### 3. API-key upstreams and protocol conversion
+
+CPA has first-class config sections for Gemini, Google Interactions, Claude,
+Codex, xAI, Vertex-compatible, and named OpenAI-compatible providers. Each entry
+can carry an API key, base URL where applicable, model list/aliases, excluded
+models, custom headers, proxy, prefix, and priority according to provider type.
+Sources:
+[`config.example.yaml`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/config.example.yaml#L208-L405),
+[`internal/config/config.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/config/config.go#L448-L688),
+[`internal/config/vertex_compat.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/config/vertex_compat.go).
+
+The relevant client-to-upstream conversion matrix is:
+
+| Client request protocol | Anthropic Messages upstream | OpenAI Responses/Codex upstream | Gemini/Antigravity upstream | Generic OpenAI-compatible upstream |
+| --- | --- | --- | --- | --- |
+| Anthropic Messages | Native | Yes | Yes | Yes, converted to Chat Completions |
+| OpenAI Chat Completions | Yes | Yes | Yes | Native |
+| OpenAI Responses | Yes | Native for Codex/xAI | Yes | Yes, normally converted to Chat Completions |
+
+CPA additionally translates Google Interactions and Gemini client forms. The
+generic OpenAI-compatible executor targets `/chat/completions`; only the
+non-streaming `responses/compact` alternate path targets `/responses/compact`.
+The registry contains both streaming and non-streaming transforms for the
+matrix above. Sources:
+[`internal/translator/init.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/translator/init.go),
+[`OpenAI Responses -> Claude registration`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/translator/claude/openai/responses/init.go),
+[`Claude -> OpenAI registration`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/translator/openai/claude/init.go),
+[`openai_compat_executor.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/runtime/executor/openai_compat_executor.go#L82-L160).
+
+Streaming caveats:
+
+- Generic OpenAI-compatible streaming expects SSE `data:` lines. A non-SSE
+ error/body after a nominal stream start becomes a 502. The executor requests
+ `stream_options.include_usage=true` and synthesizes `[DONE]` if a clean
+ upstream close omits it.
+- CPA buffers through the first meaningful stream payload. Before that payload,
+ refresh/fallback can occur. After it returns the wrapped stream to the HTTP
+ handler, later chunk errors are forwarded and are not transparently replayed,
+ matching the signed no-retry-after-stream-start rule.
+- Syntax conversion is implemented and heavily tested, but thinking,
+ prompt-cache, tool, image/audio, service-tier, and provider-specific semantics
+ are not capability-equivalence guarantees. Model Hub must retain the visible
+ mapping warning from the spec.
+
+Sources:
+[`openai_compat_executor.go` stream path](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/runtime/executor/openai_compat_executor.go#L314-L460),
+[`conductor.go` stream bootstrap](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L1840-L1965).
+
+### 4. Model listing and discovery
+
+CPA exposes a merged effective catalog at `GET /v1/models` and a Gemini-shaped
+catalog at `GET /v1beta/models`. The Management API also exposes
+`GET /auth-files/models?name=<auth-file-or-id>`, which reads models registered
+for that specific auth, plus `GET /model-definitions/:channel` for static model
+metadata. These are sufficient for an effective per-source supply list and the
+"found N models" result after an OAuth auth record is registered. Sources:
+[`internal/api/server.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/server.go#L510-L575),
+[`GetAuthFileModels`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/auth_files.go#L398-L445),
+[`model_definitions.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/model_definitions.go).
+
+This is not a uniform live entitlement-discovery API. OAuth providers often
+register a built-in or remotely maintained catalog; API-key and generic
+OpenAI-compatible entries normally declare their `models` in configuration.
+The broad `POST /v0/management/api-call` helper can attach an auth token and
+call an arbitrary upstream `/models`-like URL, but it has no vendor-neutral
+schema or host allowlist. Avibe must not expose that generic primitive to the UI.
+For API-key source tests, L2 should implement vendor-specific, allowlisted
+discovery adapters and record `declared`, `effective`, or `live` provenance and
+observation time in the source model. Source:
+[`api_tools.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/api_tools.go#L54-L175).
+
+Actual account-specific model entitlement was not live-verified.
+
+### 5. Credential layout, schema, relocation, and refresh
+
+`auth-dir` defaults to `~/.cli-proxy-api`, supports `~`, and can be set to a
+different absolute or relative path. Avibe must always pass a dedicated engine
+credential directory under its own runtime/state root; it must never depend on
+or mutate the user's default CPA directory. The file store scans JSON records
+and uses the top-level `type` to select a provider. Sources:
+[`config.example.yaml`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/config.example.yaml#L41-L48),
+[`internal/util/util.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/util/util.go),
+[`sdk/auth/filestore.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/filestore.go).
+
+Current built-in persisted schemas, omitting optional adapter metadata such as
+`disabled`, `priority`, `prefix`, `note`, headers, proxy, and cloak fields:
+
+| Provider | Top-level credential fields |
+| --- | --- |
+| Claude | `type`, `id_token`, `access_token`, `refresh_token`, `last_refresh`, `email`, `expired` |
+| Codex | Claude fields plus `account_id` |
+| Antigravity | `type`, `access_token`, `refresh_token`, `expires_in`, `timestamp`, `expired`, optional `email`, `project_id` |
+| Kimi | `type`, `access_token`, `refresh_token`, `token_type`, `scope`, `device_id`, `expired` |
+| xAI | `type`, `access_token`, `refresh_token`, optional `id_token`, expiry/refresh fields, identity, base/token endpoints, `auth_kind` |
+| Vertex import | `type`, embedded `service_account`, `project_id`, `email`, optional `location`, `prefix` |
+
+Sources:
+[`Claude token`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/claude/token.go),
+[`Codex token`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/codex/token.go),
+[`Antigravity auth`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/antigravity.go#L180-L215),
+[`Kimi token`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/kimi/token.go),
+[`xAI token`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/xai/token.go),
+[`Vertex credential`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/vertex/vertex_credentials.go).
+
+CPA runs a background refresh scheduler (default check interval 5 seconds,
+default concurrency 16) and persists refreshed credentials. Provider lead times
+at this tag are Claude 4 hours, Codex 5 days, Antigravity 5 minutes, Kimi 5
+minutes, and xAI 5 minutes. A request that receives 401 also attempts one
+refresh-and-retry before normal error handling. Sources:
+[`conductor.go` refresh constants](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L74-L90),
+[`StartAutoRefresh`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L5820-L5850),
+[`refresh registry`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/refresh_registry.go),
+[`unauthorized stream path`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L1860-L1920).
+
+Security gap: built-in provider `SaveTokenToFile` methods create the parent with
+0700 but use `os.Create` for token JSON, so a new file's mode follows the process
+umask rather than being explicitly fixed to 0600. The generic metadata-only
+path does use 0600. L1 must create the engine directory as 0700 and atomically
+enforce 0600 on every credential file after create/import/refresh, with a startup
+audit that fails closed on broader permissions. Sources:
+[`Claude SaveTokenToFile`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/auth/claude/token.go#L50-L93),
+[`FileTokenStore`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/auth/filestore.go#L75-L150).
+
+### 6. Management API, live configuration, and state
+
+The Management API is enabled only when a management secret exists. Every
+request, including loopback, requires `Authorization: Bearer <key>` or
+`X-Management-Key`. Non-loopback access additionally requires remote management
+permission. `MANAGEMENT_PASSWORD` acts as a runtime secret and also overrides
+the remote-management gate, so Avibe must bind CPA explicitly to `127.0.0.1`
+and never rely on the gate alone. Sources:
+[`handler.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/handler.go#L65-L90),
+[`management middleware`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/handler.go#L262-L315),
+[`config.example.yaml`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/config.example.yaml#L1-L39).
+
+The registered surface includes:
+
+- whole-config read/write; debug/logging/retry/cooldown/routing/quota settings;
+- proxy client API keys and API-key upstream CRUD for every built-in type;
+- OpenAI-compatible providers, model aliases/exclusions, and model definitions;
+- auth-file list, model list, upload, delete, disable, metadata-field patch, and
+ Vertex import;
+- OAuth start/status/cancel and callback replay;
+- logs/request logs, usage queue/API-key usage, generic authenticated upstream
+ calls, and plugin/store management.
+
+Source: [`registerManagementRoutes`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/server.go#L850-L1028).
+
+Management mutations save YAML and trigger an asynchronous config reload. The
+reload path updates clients, retry/cooldown/routing, aliases, executors, plugins,
+and config-derived auths without a process restart. Source inspection does not
+show listener host/port/TLS or the watched auth-directory root being rebound;
+L1 should treat those as startup-owned even though they are fields in the YAML.
+That startup-only conclusion was not live-mutated in this spike. Sources:
+[`persistLocked`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/handler.go#L395-L425),
+[`service config reload`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/service.go#L1300-L1370).
+
+`GET /auth-files` exposes useful auth-level projection fields: provider/type,
+status/message, disabled/unavailable, success/failure counters, recent request
+summary, priority, last refresh, and aggregate `next_retry_after`. It does not
+include the internal per-model `ModelStates`. If `save-cooldown-status` is
+enabled, CPA writes per-auth `.cds` files containing model, status, reason,
+quota, last error, and retry time, but there is no Management API endpoint for
+those files. Sources:
+[`buildAuthFileEntry`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/auth_files.go#L520-L650),
+[`cooldown_state.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/cooldown_state.go).
+
+CPA multiplexes an authenticated Redis RESP protocol on the same listener.
+`SUBSCRIBE errors` yields per-failure auth/model cooldown snapshots, and
+`SUBSCRIBE usage` yields per-attempt usage when usage statistics are enabled.
+There is still no first-class "source selected" or "source changed" event.
+Worse, the usage payload includes the inbound proxy `api_key` verbatim. Model
+Hub must not enable or consume that feed until CPA removes that field or L1
+ships a reviewed redaction patch. The error feed is useful only after the
+adapter strips bodies and projects an allowlisted reason/status shape. Sources:
+[`redis_queue_protocol.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/redis_queue_protocol.go),
+[`error_events.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/error_events.go),
+[`usage queue payload`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/redisqueue/plugin.go#L20-L145).
+
+### 7. Routing, fallback, and plugins
+
+CPA supports `round-robin` and `fill-first`. All eligible auths are first
+partitioned by integer `priority`, and the highest integer wins. `fill-first`
+then chooses deterministically; equal-priority auths are ordered by auth ID,
+not config-list order. Assigning unique descending priorities can project the
+global list, but priority alone does not fix the error taxonomy below. Sources:
+[`config.example.yaml` routing](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/config.example.yaml#L108-L188),
+[`selector.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/selector.go#L190-L305).
+
+The blocking mismatch is automatic failover. In one execution CPA keeps picking
+untried eligible credentials until one succeeds or all are exhausted. It stops
+early only for its request-invalid heuristics: selected 400 error strings,
+request-scoped 404, 422, and a narrow 500 case. A failed 401 after refresh,
+402/403, ordinary 404, many 400s, and other errors can move to the next source.
+Its state machine also assigns 30-minute cooldowns to 401 and 402/403 and 12
+hours to 404. This is broader than the signed spec, which allows fallback only
+for explicit quota/429, transient 5xx, and network failure, and requires
+parameter/protocol/tool errors to surface. Sources:
+[`executeMixedOnce`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L2465-L2660),
+[`isRequestInvalidError`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L4525-L4575),
+[`MarkResult`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L3710-L3870).
+
+The clean compensation is adapter-owned selection, not an expanding set of CPA
+error overrides. Every source receives a stable private prefix; L1 sets
+`force-model-prefix: true`, and the adapter sends a single candidate-specific
+model name per attempt. Prefixes apply to both OAuth auth files and API-key
+config auths, are removable before upstream execution, and can be updated for
+OAuth files through the metadata-field API. The adapter can then apply the
+signed taxonomy, know the exact attempted/selected source, and write the event
+log without observing CPA secrets. Generated config must also avoid repeated
+OpenAI-compatible aliases that create an internal upstream-model pool; one
+private candidate name must resolve to one Model Hub source. Sources:
+[`applyModelPrefixes`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/service.go#L2415-L2460),
+[`rewriteModelForAuth`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/sdk/cliproxy/auth/conductor.go#L3175-L3210),
+[`PatchAuthFileFields`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/api/handlers/management/auth_files.go#L1486-L1720).
+
+CPA's plugin system is real but is not a declarative Model Hub fallback product:
+
+- trusted in-process dynamic-library plugins are globally disabled by default;
+- a `ModelRouter` can target a built-in provider or plugin executor and is
+ ordered by plugin priority;
+- a separate Scheduler capability can pick an auth ID or delegate to built-in
+ fill-first/round-robin;
+- examples and tests exist, but the only model-router example is specialized
+ Claude web-search routing, and the scheduler is an example plugin;
+- there is no shipped YAML cross-vendor fallback rule engine or native
+ default-off cross-vendor policy flag.
+
+Do not make plugins an L1 dependency. Enforce the experimental cross-vendor flag
+when the adapter constructs candidates. Keep CPA plugins disabled for the
+initial runtime. Sources:
+[`config.example.yaml` plugins](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/config.example.yaml#L49-L80),
+[`model_router.go`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/pluginhost/model_router.go),
+[`plugin examples`](https://github.com/router-for-me/CLIProxyAPI/tree/f71ec0eb6776854457892452cf28c47f0d658251/examples/plugin),
+[`scheduler example`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/examples/plugin/scheduler/README.md).
+
+### 8. License, cadence, and executable posture
+
+CPA is MIT licensed. The standard release archive contains one executable plus
+LICENSE, README/README_CN, and `config.example.yaml`; no language runtime or
+sidecar daemon is required. The standard binaries include dynamic-plugin
+support. The inspected macOS ARM64 executable is Mach-O ARM64 and links only to
+macOS system libraries/frameworks. The Linux AMD64 executable is a stripped
+ELF, dynamically linked to glibc system libraries (`libdl`, `libresolv`,
+`libpthread`, `libc`), so "single binary" does not mean a fully static Linux
+artifact. Sources:
+[`LICENSE`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/LICENSE),
+[`release assets`](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v7.2.95),
+[`plugin support`](https://github.com/router-for-me/CLIProxyAPI/blob/f71ec0eb6776854457892452cf28c47f0d658251/internal/pluginhost/support.go).
+
+Release cadence is unusually high: the latest 30 non-draft releases at survey
+time span v7.2.66 through v7.2.95 in about 11.4 days, often multiple releases
+per day. That reinforces immutable version + SHA pinning and argues against
+"latest" resolution at runtime. Maintainer signing, artifact notarization, and
+whether GitHub release assets are operationally immutable were not verified;
+SHA mismatch must fail closed regardless.
+
+### 9. Risks and adapter compensations
+
+| Priority | Gap against the signed spec | Compensation / owner |
+| --- | --- | --- |
+| P0 | CPA performs broader credential/source fallback than the spec's no-blind-fallback taxonomy. | L1/L2 adapter owns candidate loop. Use a unique forced prefix per source so each CPA call can hit only that source. Retry only quota/429, transient 5xx, or network failures; refresh+retry 401 once; stop after first emitted stream payload. |
+| P0 | No safe selection/switch event. Error RESP has failures only; usage feed exposes the inbound proxy API key and is unacceptable. | Adapter writes `resolution-event` from its own candidate loop. Keep usage statistics/feed disabled. Optionally consume the error RESP feed through an allowlist projector that drops body/IDs not required by the contract. |
+| P1 | OAuth form assumptions in the spec do not match CPA Management API: Claude is naturally C, and Codex B exists only as a CLI command. | Make OAuth flow form runtime-declared. Ship Claude and Codex as C for this engine; accept raw Claude code as a compatibility input; add B for Codex only after a Management API device-flow endpoint exists. |
+| P1 | Per-source model listing is effective catalog data, not uniformly live entitlement discovery; generic OpenAI-compatible discovery is manual. | Store model provenance (`declared`, `effective`, `live`) and observation time. Implement allowlisted vendor discovery adapters; never expose generic `/api-call`. |
+| P1 | `/auth-files` omits model-level cooldown state; `.cds` has it but has no API. | Project auth-level chips from `/auth-files`; consume sanitized error events for model-level changes; keep adapter state authoritative for current candidate/recovery events. Do not read undocumented `.cds` files as a contract. |
+| P1 | Token JSON file modes depend on umask in provider save paths. | Dedicated 0700 directory; atomic 0600 enforcement after every write/import/refresh; startup permission audit and fail closed. |
+| P1 | Management API includes high-risk primitives and credential-bearing endpoints. | Bind loopback, generate a runtime-only management key, implement a narrow internal client, never proxy Management API routes to browser/IM, and allowlist response fields. |
+| P2 | Higher integer is higher priority; equal-priority fill-first uses auth ID order. | Adapter remains source of truth; if priorities are projected into CPA, assign unique descending integers and never rely on ties. |
+| P2 | Cross-vendor fallback has no native default-off policy control. | Candidate construction enforces the flag and tags adapter-generated events. Leave CPA plugins disabled. |
+| P2 | Very fast upstream release cadence and no verified signing/notarization policy. | Pin tag, commit, URL, byte size, SHA256, and license in Avibe's dependency manifest; upgrade only through reviewed PR + contract/scenario tests. |
+
+## S3. Managed runtime-dependency reuse audit
+
+### 10. What Show Runtime currently provides
+
+The current implementation is `core/show_runtime.py`, not a
+`vibe/show_runtime/` package. Its official `manifest-cache` path provides:
+
+- schema v1 with `runtime_version`, `runtime_source`, `minimum_node`, and an
+ `archives` map keyed by six Avibe platform tags; each archive has `name`,
+ immutable URL, SHA256, and byte size;
+- a packaged manifest embedded in the Avibe wheel; HTTPS/file downloads;
+ size + SHA256 verification before cache promotion; safe tar extraction;
+- content-addressed downloads at
+ `${AVIBE_HOME:-~/.avibe}/runtime/show-runtime/downloads/<sha256>.tgz`;
+- installs at
+ `.../versions/<runtime-version>/<platform>/<manifest+archive fingerprint>/`,
+ per-install `.vibe-show-runtime.json`, and `current.json`;
+- verified-cache offline mode, status/probe diagnostics, a clean command, and
+ retention of the current install plus one prior packaged-manifest install;
+- `vibe runtime prepare --force`, which re-extracts/reinstalls even when install
+ metadata matches, while still reusing a verified download cache;
+- failure fallback to an already verified install where possible.
+
+Sources:
+[`core/show_runtime.py`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/core/show_runtime.py#L35-L970),
+[`config/paths.py`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/config/paths.py#L1-L125),
+[`generate_show_runtime_manifest.py`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/scripts/generate_show_runtime_manifest.py),
+[`runtime CLI`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/vibe/cli.py#L11190-L11360).
+
+The current parser validates schema version, runtime version, and the existence
+of archives, but it does not retain or validate the generated `runtime_source`
+object. The generic dependency schema must make upstream repository, source
+commit, release tag, and license first-class verified metadata rather than an
+ignored informational field. Source:
+[`_load_runtime_manifest`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/core/show_runtime.py#L768-L835).
+
+The release workflow resolves an exact Show Runtime commit, builds all six
+platform archives, generates the manifest, embeds only the manifest in the
+wheel, uploads archives beside the Avibe release, and refuses to overwrite a
+same-tag runtime asset unless it is byte-identical. Source:
+[`publish.yml`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/.github/workflows/publish.yml#L45-L310).
+
+### 11. Reusable core and concrete coupling
+
+The following behavior should be reused: manifest parsing, platform selection,
+immutable URL/size/SHA checks, content-addressed cache, HTTPS/file download,
+offline semantics, safe extraction, versioned install metadata/current pointer,
+rollback retention, status/probe output, and force/clean lifecycle.
+
+It cannot be reused by constructing `ShowRuntimeManager` with different values.
+Concrete coupling points are:
+
+1. The manager mixes installation with Show server start/health/request/prewarm,
+ Node command discovery, workspace/cache flags, logs, and orphan-process
+ sweeping.
+2. Archive command resolution is fixed to
+ `node_modules/@avibe/show-runtime/dist/cli.js` and requires the manifest's
+ `minimum_node`; CPA needs a native executable locator and executable-mode
+ check, not Node.
+3. Constants, environment variables, metadata filename, diagnostic reasons,
+ user agent, log messages, and cleanup patterns are all Show-named.
+4. The extractor supports `.tar.gz` only. Current CPA target assets are tar.gz,
+ but a future Windows target would require zip support.
+5. Platform names and archive names differ (`darwin-arm64` vs
+ `darwin_aarch64`, `linux-x64` vs `linux_amd64`), so manifest generation must
+ accept an explicit mapping rather than infer only from a Show prefix.
+6. `vibe runtime status/prepare/clean`, printed output, post-upgrade prepare,
+ Doctor repair, and strict-success logic address Show and other dependencies
+ through hand-written branches rather than a dependency registry.
+7. The release workflow assumes six Show archives built from Show Runtime main;
+ CPA should consume or mirror a reviewed upstream release, not run CPA's build
+ as if it were first-party source.
+8. Most installer regressions live inside `tests/test_ui_show_pages.py`, so the
+ reusable cases must move to focused generic installer tests before adding
+ engine-specific tests.
+
+Sources:
+[`core/show_runtime.py`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/core/show_runtime.py),
+[`runtime CLI`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/vibe/cli.py#L11190-L11595),
+[`Show manifest tests`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/tests/test_ui_show_pages.py#L3330-L4195),
+[`manifest generator tests`](https://github.com/avibe-bot/avibe/blob/e71890a78209f13ae8579d25800282e40469df38/tests/test_show_runtime_manifest.py).
+
+### 12. Recommendation for L1
+
+**Yes, reuse the machinery by extraction; effort M (roughly 3-5 engineer-days
+including workflow and focused tests).**
+
+Extract a small generic component, for example
+`core/managed_archive_dependency.py`, parameterized by:
+
+- dependency ID, runtime root, manifest resource, supported schema/platform map;
+- archive type and executable locator/validator;
+- optional prerequisite validator (Node for Show, none for CPA);
+- metadata/error namespace and rollback count;
+- download user agent and optional post-install permissions hook.
+
+Keep `ShowRuntimeManager` responsible for Show process behavior and make a new
+Model Hub engine manager responsible for CPA config generation, loopback port,
+management key injection, credential root, process supervision, health, and
+shutdown. Both compose the generic installer. Extend runtime
+status/prepare/clean through a dependency registry rather than adding another
+top-level special-case branch.
+
+For the engine manifest, pin at least dependency ID, schema version, upstream
+repo, release tag, source commit, license, archive URL, platform, byte size, and
+SHA256. The release workflow should either mirror the already-hashed upstream
+assets into the Avibe release with the existing immutability gate or retain the
+upstream immutable URL plus checksum; mirroring is preferred for availability
+and release provenance. Never resolve CPA `latest` on the user's machine.
+
+## Contract changes required before implementation lanes open
+
+1. **`oauth-flow.schema.json`:** separate engine flow capability from UI
+ presentation. Add `provider`, `engine_provider`, `flow_kind`
+ (`pkce_callback`, `device_code`, `credential_import`), `submission`
+ (`redirect_url`, `code`, or both), tracked opaque `state`, callback timeout,
+ and extensible provider metadata. Freeze CPA v7.2.95 mappings as Claude C
+ (raw-code compatible), Codex C, Antigravity C, Kimi B, xAI B; Gemini CLI and
+ Vertex are not A/B/C connect flows. Keep product vendor identity distinct
+ from the engine provider key, especially Gemini supply through CPA's
+ `antigravity` provider.
+2. **`resolution-event.schema.json`:** make this adapter-owned. Add
+ `request_id`, `requested_model`, `resolved_model`, ordered `attempts[]`,
+ final/selected source, precise reason taxonomy, `stream_committed`, recovery
+ marker, and `cross_vendor`. Explicitly forbid tokens, API keys, auth-file
+ paths, raw upstream bodies, and engine management identifiers not needed by
+ the UI.
+3. **`source.schema.json`:** split `models[]` into a projection that records
+ provenance (`declared|effective|live`) and `observed_at`; represent auth-level
+ and optional model-level cooldown separately. Add an opaque adapter-owned
+ engine binding (`provider`, `auth_index` or stable equivalent) that is never
+ returned by public/UI APIs.
+4. **`priority.schema.json`:** keep the ordered source-ID list authoritative.
+ State that CPA integer priority is only a projection and ties are forbidden.
+ Candidate ordering and retry decisions remain adapter behavior.
+5. **`api.md`:** specify that source test/discovery is vendor-allowlisted, that
+ Management API is never a browser passthrough, and that submit accepts either
+ a callback URL or raw code when the declared flow allows it.
+6. **Add a managed dependency contract:** freeze the engine manifest/status
+ payload (version, platform, asset SHA, install state, health, last error) so
+ L1 and L2 do not couple directly to Show Runtime types or CPA's config schema.
+
+The contracts should be committed before L1/L2/L4 start. At survey time the
+signed spec and implementation plan were not present in `origin/master`; their
+snapshot hashes are recorded at the top of this document, but a hash in a survey
+is not a substitute for versioned contract files.
+
+## Verification
+
+Performed against the pinned sources and assets:
+
+- `git show-ref --verify refs/tags/v7.2.95` resolved to
+ `f71ec0eb6776854457892452cf28c47f0d658251`.
+- Local SHA256 and byte-size checks passed for both pinned archives and matched
+ CPA `checksums.txt`.
+- The macOS binary reported `7.2.95`, commit `f71ec0eb`, build time
+ `2026-07-22T14:48:18Z`; archive layout and platform executable types were
+ inspected locally.
+- CPA focused tests passed for Management API, SDK auth, auth conductor,
+ plugin host, the entire translator tree, and runtime executors.
+- Avibe UI build passed to provide required package data. Focused Show Runtime
+ manifest/prepare/clean tests passed: 10 passed, 187 deselected. Pytest emitted
+ the repository's known temporary locked-directory cleanup warnings; no test
+ failed.
+
+Not verified: live OAuth exchanges, live model entitlements, billable provider
+requests, vendor ToS/billing, macOS notarization/code signing, maintainer release
+signatures, or mutation behavior of startup-owned CPA config fields.
diff --git a/docs/plans/model-hub-tos-review.md b/docs/plans/model-hub-tos-review.md
new file mode 100644
index 000000000..405ee7545
--- /dev/null
+++ b/docs/plans/model-hub-tos-review.md
@@ -0,0 +1,333 @@
+# Model Hub — Subscription-Reuse ToS / Billing / Ban-Risk Review (Spike S2)
+
+Status: spike report v1 · 2026-07-23 · research-only, no code
+Blocks: *defaults* for subscription flows (impl plan §4 product gates), not the build
+Spec: `docs/plans/model-hub.md` (§2, §4.2, §8, §9, §10.2)
+Impl plan: `docs/plans/model-hub-implementation.md` (§1 S2, §4)
+All URLs accessed **2026-07-23** unless noted. Confidence tags: **[VERIFIED]** = primary
+vendor doc / primary artifact (official terms, the actual PR/issue); **[DOC-IMPLIED]** =
+reasoned inference from official docs; **[ANECDOTAL]** = community report / secondary blog.
+
+---
+
+## 0. TL;DR (one line per scenario)
+
+| Scenario | Claude (Anthropic) | ChatGPT (OpenAI) |
+| --- | --- | --- |
+| **(a)** same-vendor, same-user, own agent **via the Hub proxy** | **Do-not-ship default-on.** This is the exact pattern Anthropic blocks server-side and bans for. Compliant Claude-subscription path is **Direct mode only**. Experimental-flag + explicit ban-risk consent if offered at all. | **Consent-gated experimental.** Currently works, "not officially supported," ToS-ambiguous, no crackdown yet. |
+| **(b)** cross-client (sub consumed by a non-native client, e.g. OpenCode) | **Do-not-ship.** Explicitly prohibited; server-blocked; OpenCode removed it under Anthropic legal demand. | **Experimental-flag only**, consent-gated, ban-risk warning. Gray/unsanctioned (OpenClaw pattern). |
+| **(c)** cross-vendor substitution | **Keep default-off experimental** (spec §9 already). ToS/ban risk *inherited* from whichever subscription it draws on + capability-equivalence risk. | Same. |
+
+**The single most important finding:** the product promise in spec §2 ("subscriptions
+consumed first, auto-failover **through the hub**") is in direct conflict with Anthropic's
+live ToS **even for the default same-vendor same-user case (a)**, because the spec §7
+credential model has the *engine hold the subscription OAuth token and re-originate the
+request*, which is precisely "routing requests through Pro/Max credentials" that Anthropic
+prohibits and now enforces. API-key sources carry **no such gate** and are the safe backbone.
+
+---
+
+## 1. Scope definitions (why the proxy, not just the vendor, decides the verdict)
+
+The question is not only "which vendor" but "**does a credential-holding proxy sit in the
+path**." Three request shapes matter:
+
+- **Direct (official binary, no proxy):** the official `claude` / `codex` CLI talks straight
+ to the vendor with its own OAuth token. This is "ordinary use of the native app."
+- **Transparent passthrough (hypothetical):** the official binary keeps its own OAuth and a
+ local relay forwards bytes unchanged. Legally grayer than Direct; **not** what the current
+ spec builds (see §4).
+- **Credential-holding hub (what spec §7 builds):** the engine holds the subscription OAuth
+ token; backends receive only a local gateway token; the engine re-originates upstream calls
+ with the subscription credential. **This is the pattern vendors prohibit / enforce against.**
+
+Scenario mapping used throughout:
+- **(a)** Claude sub → Claude Code, or ChatGPT sub → Codex — the user's own native agent, on
+ the user's own machine, *through the Hub*.
+- **(b)** a subscription consumed by a **non-native** client (Claude sub → OpenCode; ChatGPT
+ sub → OpenCode / any non-Codex client).
+- **(c)** cross-vendor substitution ("Claude quota gone → serve GPT"), spec §9 default-off.
+
+---
+
+## 2. Anthropic (Claude Pro / Max) — **[VERIFIED, high confidence]**
+
+### 2.1 The operative ToS language (primary, verbatim)
+
+Anthropic's Claude Code "Legal and compliance" page states, under **Authentication and
+credential use** [VERIFIED, [code.claude.com/docs/en/legal-and-compliance](https://code.claude.com/docs/en/legal-and-compliance)]:
+
+> "**OAuth authentication** is intended exclusively for purchasers of Claude Free, Pro, Max,
+> Team, and Enterprise subscription plans and is designed to support ordinary use of Claude
+> Code and other native Anthropic applications."
+>
+> "**Developers** building products or services that interact with Claude's capabilities,
+> including those using the Agent SDK, should use API key authentication … **Anthropic does
+> not permit third-party developers to offer Claude.ai login or to route requests through
+> Free, Pro, or Max plan credentials on behalf of their users.**"
+>
+> "Anthropic reserves the right to take measures to enforce these restrictions and may do so
+> without prior notice."
+
+The same page ties quota to individual use: "Advertised usage limits for Pro and Max plans
+assume ordinary, individual usage of Claude Code and the Agent SDK." Governing terms are the
+[Consumer Terms of Service](https://www.anthropic.com/legal/consumer-terms) (Free/Pro/Max) and
+the [Usage Policy](https://www.anthropic.com/legal/aup). The Register reports the underlying
+"no third-party harness" clause (ToS §3.7) has existed since ~Feb 2024; February 2026 only made
+it explicit [VERIFIED-secondary, [theregister.com](https://www.theregister.com/2026/02/20/anthropic_clarifies_ban_third_party_claude_access/)].
+
+### 2.2 Server-side enforcement (the decisive operational fact)
+
+On **2026-01-09** Anthropic deployed a server-side check that rejects subscription-OAuth
+requests not originating from the official client, returning: *"This credential is only
+authorized for use with Claude Code and cannot be used for other API requests."* The check
+keys on Claude-Code client identity (e.g. the `claude-code-20250219` beta header / native
+system prompt / telemetry). Tools that spoofed those headers (OpenCode, Cline, RooCode) broke
+overnight [ANECDOTAL/secondary but consistent across sources, [mindstudio.ai](https://www.mindstudio.ai/blog/anthropic-openclaw-ban-oauth-authentication); corroborated by [ridakaddir.com](https://ridakaddir.com/blog/post/did-anthropic-kill-opencode-claude-subscription-ban)].
+
+Anthropic engineer Thariq Shihipar (quoted by The Register): "Third-party harnesses using
+Claude subscriptions … are prohibited by our Terms of Service," and they "generate unusual
+traffic patterns without any of the usual telemetry that the Claude Code harness provides"
+[VERIFIED-secondary, [theregister.com](https://www.theregister.com/2026/02/20/anthropic_clarifies_ban_third_party_claude_access/)].
+
+**Implication for the Hub proxy (case a-Claude).** Two failure modes, both bad: (1) if the hub
+does *not* perfectly reproduce Claude Code's client fingerprint, the server check rejects it;
+(2) if it *does* spoof the fingerprint to pass, that is squarely the prohibited harness-spoofing
+behavior — and the telemetry/traffic gap can still flag the account. There is no configuration
+of a credential-holding proxy that is both functional and clearly compliant for Claude
+subscriptions. **The only clean Claude-subscription path is Direct mode** (official binary,
+direct connection) [DOC-IMPLIED, high confidence].
+
+### 2.3 Quota / billing semantics
+
+Dual-layer per plan: a **5-hour rolling window** (starts on first message) **and** a **weekly
+cap** (fixed reset). Approx Pro ~45 msgs / 5h, Max 5x ~225, Max 20x ~900 (figures drift). Usage
+across claude.ai, Claude Code and Claude Desktop **shares the same limit**
+[ANECDOTAL/secondary, [truefoundry.com](https://www.truefoundry.com/blog/claude-code-limits-explained), [usecarly.com](https://www.usecarly.com/blog/claude-code-usage-limits/)].
+Billing behavior when proxied: requests that pass the fingerprint draw from the normal
+subscription windows; requests that fail are **rejected** (not silently re-billed as API) per
+the Jan-9 error string. Anthropic's sanctioned programmatic path is **API keys** (metered,
+per-token, on a separate Console account) — a consumer suspension does not affect Console API
+access [DOC-IMPLIED].
+
+---
+
+## 3. OpenAI (ChatGPT Plus / Pro) via Codex — **[gray zone, medium confidence]**
+
+### 3.1 What OpenAI actually says
+
+- Official: signing into Codex with a ChatGPT account charges usage to the subscription; the
+ ChatGPT **Terms of Use / Privacy Policy** apply; `codex login` uses a browser OAuth callback
+ (default `localhost:1455`) with a **device-code** flow for headless use; token cached at
+ `~/.codex/auth.json` [VERIFIED, [learn.chatgpt.com/docs/auth](https://learn.chatgpt.com/docs/auth) (redirect from developers.openai.com/codex/auth); [help.openai.com](https://help.openai.com/en/articles/11369540-using-codex-with-your-chatgpt-plan)].
+- The auth docs **recommend API keys "for programmatic Codex CLI workflows, such as CI/CD
+ jobs"** and even acknowledge LLM proxies for **API-key** access
+ (`requires_openai_auth = true` "useful when you access OpenAI models through an LLM proxy
+ server") — but say **nothing** blessing routing the *subscription* credential through a
+ third-party proxy [VERIFIED, [learn.chatgpt.com/docs/auth](https://learn.chatgpt.com/docs/auth)].
+- OpenAI Terms of Use prohibit using the Services "automatically or programmatically" to
+ extract data/output and "circumventing any rate limits" — the same latent clause that makes
+ subscription-proxying ambiguous [VERIFIED, [openai.com/policies/row-terms-of-use](https://openai.com/policies/row-terms-of-use/)].
+- Asked directly whether a forked/modified Codex CLI using "Sign in with ChatGPT" is allowed,
+ an OpenAI maintainer confirmed the Apache-2.0 **code** is free to fork but **declined the
+ subscription-ToS question** ("I'm an engineer, not a lawyer"); the thread is marked
+ Unanswered and the community notes "many developers … are waiting for clear guidance"
+ [VERIFIED, [github.com/openai/codex/discussions/8338](https://github.com/openai/codex/discussions/8338)].
+
+### 3.2 Practical status
+
+Third-party subscription proxying (the "OpenClaw" pattern: localhost proxy mimicking the Codex
+CLI system prompt so the ChatGPT subscription pays) **currently works** and is "**not officially
+supported**"; secondary write-ups explicitly note Anthropic already killed the Claude equivalent
+and Google made a similar Gemini-CLI change — i.e. precedent that vendors *do* eventually clamp
+down [ANECDOTAL/secondary, [explainx.ai](https://explainx.ai/blog/login-with-chatgpt-codex-subscription-oauth-2026), [lumadock.com](https://lumadock.com/tutorials/openclaw-openai-codex-chatgpt-subscription)].
+No documented mass-suspension wave for OpenAI subscription-proxying was found (contrast with
+Anthropic). Third-party Codex OAuth 429s are reported but read as quota, not bans
+[ANECDOTAL, [github.com/openai/openai-python#2951](https://github.com/openai/openai-python/issues/2951)].
+
+### 3.3 Quota / billing semantics
+
+Since **2026-04-02** Codex meters against **API-token-equivalent credits**, not per-message; a
+**5-hour rolling window shared by local + cloud** plus a **weekly cap**. Plus ≈15–110 msgs/5h
+(model-dependent bands), Pro 5x/20x multiply; Plus/Pro can buy top-up credits; API-key route
+skips both caps and bills per token [ANECDOTAL/secondary, [morphllm.com/codex-pricing](https://www.morphllm.com/codex-pricing), [help.openai.com codex-rate-card](https://help.openai.com/en/articles/20001106-codex-rate-card)].
+
+**Net:** OpenAI is *softer than Anthropic today* — no explicit prohibition, no enforcement wave
+— but the direction of travel (docs steer automation to API keys; vendor precedent) means this
+is a **latent, not absent, risk**. Treat as consent-gated, not default-on-silent.
+
+---
+
+## 4. The architectural crux vs spec §7
+
+Spec §7 defines three credential rings: backends receive **only the local gateway token**;
+**upstream subscription OAuth tokens are engine-held** and injected upstream by the engine. That
+design *is* "a service routing requests through Pro/Max credentials on behalf of the user" —
+the prohibited pattern (§2.1) — regardless of it being the user's own machine and own
+credential. A narrower "transparent passthrough where the official client keeps its own OAuth
+and the hub adds nothing" would be legally grayer-but-arguable, yet it (i) contradicts §7, (ii)
+still shows the abnormal-telemetry signature Anthropic cites, and (iii) forfeits the hub's
+failover value for subscriptions anyway (you cannot fail a subscription request over to another
+source without the hub re-originating it). **Conclusion: there is no design that delivers
+hub-mediated failover for a Claude subscription while staying clearly ToS-compliant.** This is a
+product decision to escalate, not an implementation detail.
+
+API-key sources are unaffected: both vendors explicitly bless API keys for programmatic/proxy
+use, so **routing API-key sources through the Hub is fully compliant and should be the
+default-on backbone** of Model Hub.
+
+---
+
+## 5. Community / practical ban-risk signal
+
+- **[VERIFIED — primary artifacts]** OpenCode PR #18186 "anthropic legal requests" removed the
+ branded system prompt, the `opencode-anthropic-auth` plugin, the `claude-code-20250219` beta
+ header, and the Anthropic login hint — community reaction 4👍/40👎
+ [[github.com/anomalyco/opencode/pull/18186](https://github.com/anomalyco/opencode/pull/18186)].
+ This is hard evidence for the **(b)-Claude do-not-ship** verdict.
+- **[VERIFIED — primary artifact]** CLIProxyAPI issue #2211: a user running Claude Code creds
+ through the proxy with an `opencode` client reported *"Your account has been disabled after an
+ automatic review of your recent activities,"* pointing at ToS + Usage Policy and a Trust &
+ Safety appeal path [[github.com/router-for-me/CLIProxyAPI#2211](https://github.com/router-for-me/CLIProxyAPI/issues/2211); further reports in [discussion #2244](https://github.com/router-for-me/CLIProxyAPI/discussions/2244)].
+- **[ANECDOTAL]** Reported ban *triggers*: plan upgrades, payment-method changes, and unusual
+ usage spikes triggering automated review (one case: OAuth + Max 5x→20x upgrade → disabled in
+ ~20 min). "Usage limit reached" ≠ suspension; distinguish throttle from ban
+ [[autonomee.ai](https://autonomee.ai/blog/claude-code-account-suspended-banned-safe-usage/), [knightli.com](https://knightli.com/en/2026/05/09/claude-account-suspension-code-limit-guide/)].
+- **[ANECDOTAL]** No comparable OpenAI subscription-proxying suspension wave was found; signal
+ there is quota-429s, not disablement.
+
+**Summary:** ban risk for Claude subscription proxying/cross-client is **verified and
+demonstrated** (account disables + legal takedowns). For OpenAI it is **latent/anecdotal**
+(works today, unsanctioned, no enforcement wave observed).
+
+---
+
+## 6. cn-region vendors (LOW priority, one paragraph) — **[ANECDOTAL/secondary]**
+
+Zhipu (Z.AI) **GLM Coding Plan** and Moonshot **Kimi Coding Plan** sell flat-rate coding
+subscriptions (~US$18–30/mo entry) *distinct* from pay-as-you-go API keys, and both are moving
+to **first-party OAuth device-flow** onboarding. Critically, Zhipu's Coding-Plan keys are
+documented as **usable only inside supported coding tools and cannot make standalone API
+calls** — a tool-lock restriction that means routing a cn coding-plan credential through the
+Avibe Hub could violate *their* terms much like Anthropic's, and would need the same
+consent-gate rather than default-on. Treat cn subscription reuse as **experimental/consent-gated
+pending per-vendor confirmation**; cn **API keys** (pay-as-you-go) are unrestricted and fine for
+the Hub [ [jia.je coding_plan](https://jia.je/kb/en/software/coding_plan.html), [gsd-2#4642 (Kimi/GLM OAuth device-flow)](https://github.com/gsd-build/gsd-2/issues/4642), [aicoolies Kimi plan](https://aicoolies.com/tools/kimi-coding-plan) ].
+
+---
+
+## 7. Risk matrix
+
+Recommendation legend: **DEFAULT-ON** / **CONSENT-GATED** (ship, but explicit one-time
+informed opt-in per source) / **EXPERIMENTAL-FLAG** (advanced, default-off, visible marking) /
+**DO-NOT-SHIP**.
+
+| # | Scenario / source | ToS posture | Billing / quota behavior | Ban risk | Recommendation |
+| --- | --- | --- | --- | --- | --- |
+| a-Claude | Claude sub → Claude Code **via Hub** | **Prohibited pattern** (engine routes sub creds); server-blocked since 2026-01-09 [VERIFIED] | Draws sub 5h+weekly windows *iff* fingerprint passes; else rejected | **High, demonstrated** (disables) | **DO-NOT-SHIP default-on.** Claude sub = **Direct mode only**. If ever in Hub → EXPERIMENTAL-FLAG + ban-risk consent |
+| a-Claude(Direct) | Claude sub → Claude Code, **no proxy** | "Ordinary use of the native app" — allowed [VERIFIED] | Normal sub windows | Low | **DEFAULT-ON** (this is the compliant subscription story) |
+| a-OpenAI | ChatGPT sub → Codex **via Hub** | Unaddressed / ambiguous; automation steered to API keys [VERIFIED-doc] | Sub 5h+weekly (credit-metered); works today | **Latent/anecdotal** | **CONSENT-GATED**, experimental-leaning; Direct/official `codex login` is the safe path |
+| b-Claude | Claude sub → OpenCode / non-native | **Explicitly prohibited**; OpenCode removed under legal demand [VERIFIED] | Server-blocked | **High, demonstrated** | **DO-NOT-SHIP** |
+| b-OpenAI | ChatGPT sub → OpenCode / non-Codex | Ambiguous, unsanctioned ("OpenClaw pattern") [ANECDOTAL] | Sub windows; works today | Latent, higher than a-OpenAI | **EXPERIMENTAL-FLAG**, consent-gated, warning |
+| c | Cross-vendor substitution | No *new* per-vendor issue; inherits the drawn source's posture; + capability-equivalence risk (spec §4.2 warns thinking/cache/tool semantics differ) | Inherited | Inherited from source | **EXPERIMENTAL-FLAG default-off** (spec §9 already) |
+| ref | **API-key sources** (any vendor) → Hub | **Sanctioned** programmatic path (both vendors) [VERIFIED] | Metered per-token, standard API limits | None (ToS) | **DEFAULT-ON** — the safe backbone |
+
+---
+
+## 8. Recommended product posture (actionable)
+
+1. **Ship API-key sources through the Hub default-on.** This is compliant for every vendor and
+ already gate-free per impl plan §4. Make it the primary, fully-featured path.
+2. **Claude subscription = Direct mode only, and say so in the UI.** Do not offer Claude-sub
+ inside Hub-mediated failover by default. This means spec §2's "subscriptions consumed first +
+ auto-failover through the hub" **cannot be honored for Claude subscriptions** — escalate this
+ product tension to the owner. Option: for a Claude sub, run the official binary Direct and let
+ *API-key* sources be the failover tier the Hub arbitrates.
+3. **ChatGPT subscription in Hub = consent-gated experimental**, off by default, with a one-time
+ informed opt-in and a visible "unofficial / may stop working / small ban risk" marker.
+4. **Cross-client (b) and cross-vendor (c) subscription reuse = experimental-flag, default-off**,
+ visible per-event marking (spec §9 already covers c; extend the same treatment to b).
+5. **Use spec §4.2's `allowed_origins` reservation** to hard-restrict which local clients a
+ subscription credential may serve, so a Claude sub credential can *never* be silently used to
+ serve OpenCode etc. — enforce the (a)/(b) boundary in code, not just copy.
+6. **Never present subscription-via-Hub as "free extra quota."** Frame honestly: it reuses quota
+ the user already pays for, under the vendor's individual-use terms, at the user's own risk.
+
+---
+
+## 9. Consent copy points (for anything consent-gated: ChatGPT-sub-in-Hub, cross-client,
+cross-vendor, cn-sub)
+
+**中文 (zh):**
+- 该来源使用你**本人订阅**的登录凭据;厂商条款通常要求订阅仅供**个人在官方客户端**内使用,经由中枢代理转发属于**非官方用法**,可能违反其服务条款。
+- 存在**账号被风控、限流或封禁**的真实风险(已有 Claude 订阅经代理使用被自动封号的先例);是否启用由你自行决定并承担后果。
+- 追求最稳妥时,请对订阅使用**直连模式**(官方客户端直接连接),或改用 **API Key** 来源(厂商明确允许程序化/代理调用)。
+
+**English (en):**
+- This source uses **your own subscription** login. Vendor terms generally intend a subscription
+ for **personal use inside the official client**; routing it through the hub proxy is an
+ **unofficial use** that may violate those terms.
+- There is a **real risk of rate-limiting, review, or account suspension** (Claude subscriptions
+ used via proxies have been auto-disabled). Enabling this is your choice and at your own risk.
+- For the safest setup, use **Direct mode** for subscriptions (official client, direct
+ connection), or add an **API Key** source instead — vendors explicitly permit programmatic /
+ proxied use of API keys.
+
+---
+
+## 10. Citations (accessed 2026-07-23)
+
+**Primary — Anthropic / OpenAI official**
+- Claude Code Legal & compliance (verbatim OAuth policy): https://code.claude.com/docs/en/legal-and-compliance
+- Anthropic Consumer Terms of Service: https://www.anthropic.com/legal/consumer-terms
+- Anthropic Usage Policy (AUP): https://www.anthropic.com/legal/aup
+- Claude Code Authentication docs: https://code.claude.com/docs/en/authentication
+- OpenAI Terms of Use (RoW): https://openai.com/policies/row-terms-of-use/
+- Codex Authentication docs: https://learn.chatgpt.com/docs/auth (redirect from https://developers.openai.com/codex/auth)
+- OpenAI Help — Using Codex with your ChatGPT plan: https://help.openai.com/en/articles/11369540-using-codex-with-your-chatgpt-plan
+- OpenAI Help — Codex rate card: https://help.openai.com/en/articles/20001106-codex-rate-card
+
+**Primary — artifacts (enforcement / ban)**
+- OpenCode PR #18186 "anthropic legal requests": https://github.com/anomalyco/opencode/pull/18186
+- CLIProxyAPI issue #2211 (Claude subscription banned): https://github.com/router-for-me/CLIProxyAPI/issues/2211
+- CLIProxyAPI discussion #2244: https://github.com/router-for-me/CLIProxyAPI/discussions/2244
+- openai/codex discussion #8338 (ToS for forked/modified Codex CLI): https://github.com/openai/codex/discussions/8338
+- openai/openai-python issue #2951 (third-party Codex 429): https://github.com/openai/openai-python/issues/2951
+
+**Secondary — reporting / analysis**
+- The Register — Anthropic clarifies ban on third-party tool access (2026-02-20): https://www.theregister.com/2026/02/20/anthropic_clarifies_ban_third_party_claude_access/
+- MindStudio — OpenClaw ban / OAuth crackdown (Jan-9 server check + error string): https://www.mindstudio.ai/blog/anthropic-openclaw-ban-oauth-authentication
+- Rida Kaddir — Did Anthropic kill OpenCode: https://ridakaddir.com/blog/post/did-anthropic-kill-opencode-claude-subscription-ban
+- autonomee.ai — Claude Code account suspended, safe usage: https://autonomee.ai/blog/claude-code-account-suspended-banned-safe-usage/
+- knightli.com — Claude account suspension guide: https://knightli.com/en/2026/05/09/claude-account-suspension-code-limit-guide/
+- explainx.ai — Login with ChatGPT / Codex subscription OAuth (2026): https://explainx.ai/blog/login-with-chatgpt-codex-subscription-oauth-2026
+- lumadock.com — Codex on OpenClaw with ChatGPT subscription: https://lumadock.com/tutorials/openclaw-openai-codex-chatgpt-subscription
+
+**Quota semantics**
+- truefoundry — Claude Code limits explained: https://www.truefoundry.com/blog/claude-code-limits-explained
+- usecarly — Claude Code usage limits: https://www.usecarly.com/blog/claude-code-usage-limits/
+- morphllm — Codex pricing & usage limits: https://www.morphllm.com/codex-pricing
+
+**cn-region**
+- Jiegec KB — AI Coding Plan (GLM / Kimi tiers, tool-lock): https://jia.je/kb/en/software/coding_plan.html
+- gsd-2 issue #4642 — Kimi/GLM OAuth device-flow onboarding: https://github.com/gsd-build/gsd-2/issues/4642
+- aicoolies — Kimi Coding Plan: https://aicoolies.com/tools/kimi-coding-plan
+
+---
+
+## 11. Confidence & caveats
+
+- **High confidence:** Anthropic's prohibition of subscription-credential routing by
+ third-party services, its live server-side enforcement, and the demonstrated bans (primary
+ docs + primary artifacts).
+- **Medium confidence:** OpenAI's posture. It is *currently* permissive-by-silence, not
+ explicitly sanctioned; the ToS "automated/programmatic" clause + docs steering automation to
+ API keys + cross-vendor precedent make it a latent risk. No OpenAI subscription-proxying
+ suspension wave was found, but absence of evidence ≠ safety.
+- **Low confidence / one-paragraph:** cn-region specifics (secondary sources; verify per-vendor
+ terms at implementation time).
+- **Time-sensitivity:** vendor terms, quota numbers, and enforcement posture changed multiple
+ times across 2025–2026 (e.g. Anthropic Feb-2026 doc revision, OpenAI Apr-2026 pricing shift).
+ Re-verify §2.1/§3.1 language and the §7 architectural conclusion **immediately before**
+ enabling any subscription flow default-on. This memo gates *defaults*, per impl plan §4; the
+ build may proceed on API-key paths in parallel.
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index e7ad4ccbd..b7971e6a0 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -187,6 +187,29 @@ def _assert_envelope(payload: dict, *, ok: bool = True):
assert payload["contract_version"] == 1
+def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):
+ """Integration (2026-07-24): list_agents() carries the read-only builtin_models /
+ standard_vendors projections straight from the backend modules, so the UI never
+ hand-mirrors a fixed menu or the OpenCode vendor list (agent-supply v1.2)."""
+ from core.handlers.model_hub.identifiers import STANDARD_OPENCODE_VENDOR_IDS
+ from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog
+
+ service, _store, _adapter = _service(tmp_path)
+ agents = {agent["backend"]: agent for agent in service.list_agents()}
+ for agent in agents.values():
+ _assert_valid("agent-supply.schema.json", agent)
+
+ catalog = load_bundled_catalog()
+ for backend in ("claude", "codex"):
+ expected = [entry["id"] for entry in backend_model_entries(backend, catalog)]
+ assert expected, f"bundled catalog must list built-in {backend} models"
+ assert agents[backend]["builtin_models"] == expected
+ assert agents[backend]["standard_vendors"] is None
+
+ assert agents["opencode"]["builtin_models"] is None
+ assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)
+
+
def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
"""Scenarios: MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 6dabd7083..31ea4a381 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -51,7 +51,15 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():
for example in _schema("agent-supply.schema.json")["examples"]:
agent = ModelHubAgentSupplyConfig.from_payload(example)
- serialized = {**agent.to_payload(), "current": example.get("current")}
+ # `current`, `builtin_models` and `standard_vendors` are read-only
+ # endpoint projections (v1.2), not persisted config — reconstruct them
+ # the way `_agent_payload` merges them onto to_payload().
+ serialized = {
+ **agent.to_payload(),
+ "current": example.get("current"),
+ "builtin_models": example.get("builtin_models"),
+ "standard_vendors": example.get("standard_vendors"),
+ }
assert _canonical(serialized) == _canonical(example)
_assert_valid("agent-supply.schema.json", serialized)
diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.ts
index abbd32849..357ea3730 100644
--- a/ui/src/components/settings/models/featureFlags.ts
+++ b/ui/src/components/settings/models/featureFlags.ts
@@ -1,34 +1,35 @@
// Model Hub UI — feature flags.
//
-// This lane (L4) lands ahead of its backend dependencies (L2 REST API, L3
-// backend injection, L5 model-menu drawers). The flags below keep the surface
-// reviewable and pixel-checkable now while preventing fabricated data from
-// reaching end users until the real endpoints exist.
-//
-// Flip sequence when dependencies merge (orchestrator):
-// 1. L2 API merged → set MODELS_API_MODE = 'live'
-// 2. L2/L3 both merged → set MODEL_HUB_NAV_ENABLED = true (advertise nav)
-// 3. L5 menus merged → set MODEL_MENUS_ENABLED = true (wire 模型菜单)
+// All feature lanes are merged (L2 REST API #963, L3 injection #976, L4 page
+// #966, L5 menus #977) and the integration seams are closed (agent-supply v1.2
+// builtin_models / standard_vendors, so the UI no longer hardcodes any menu or
+// vendor list). The documented flip sequence below is therefore complete — the
+// surfaces ship ON against the real endpoints (integration LI, 2026-07-24):
+// 1. L2 API merged → MODELS_API_MODE = 'live' ✓ (done here)
+// 2. L2/L3 both merged → MODEL_HUB_NAV_ENABLED = true ✓ (done here)
+// 3. L5 menus merged → MODEL_MENUS_ENABLED = true ✓ (done here)
+// subscription_hub_experimental stays OFF — it is a consent-gated behavior, not
+// a UI-readiness flag. Live end-to-end verification is the post-merge Incus pass.
/**
- * Advertises the 设置 → 模型 entry in the admin sidebar. OFF by default so we
- * do not surface mock-backed data as a first-class destination. The route is
- * always registered (reachable by direct URL) for review + pixel verification.
+ * Advertises the 设置 → 模型 entry in the admin sidebar. ON now that the surface
+ * is backed by the real endpoints; the route is also reachable by direct URL.
*/
-export const MODEL_HUB_NAV_ENABLED = false;
+export const MODEL_HUB_NAV_ENABLED = true;
/**
* 'mock' serves typed fixtures from `mockData.ts`; 'live' calls the real
- * `/api/models/*` endpoints (L2). The client module switches on this value.
+ * `/api/models/*` endpoints (L2). Now 'live': all backend lanes are merged, so
+ * shipping the nav must serve real data — never fabricated mock sources. (Flip
+ * to 'mock' only for hermetic pixel/screenshot runs with no backend.)
*/
-export const MODELS_API_MODE: 'mock' | 'live' = 'mock';
+export const MODELS_API_MODE: 'mock' | 'live' = 'live';
/**
* Wires the 模型菜单 buttons on the Agent card to L5's mapping / menu drawers.
- * OFF until L5 lands — the buttons stay visible (pixel fidelity) but explain
- * that the menus are coming rather than opening a non-existent drawer.
+ * ON now that L5 is merged.
*/
-export const MODEL_MENUS_ENABLED = false;
+export const MODEL_MENUS_ENABLED = true;
/**
* Offers the consent-gated hub-held subscription option (`subscription_hub_
diff --git a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
index 79b7d309d..c9d344a04 100644
--- a/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
+++ b/ui/src/components/settings/models/menus/AddCustomModelDialog.tsx
@@ -23,7 +23,7 @@ import { useToast } from '@/context/ToastContext';
import { modelsApi } from '../modelsApi';
import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from '../vendorMeta';
import type { Source } from '../types';
-import { buildIdentifier } from './identifiers';
+import { buildIdentifier, type StandardVendors } from './identifiers';
const FieldLabel: React.FC<{ mono?: boolean; children: React.ReactNode }> = ({ mono, children }) => (
<span
@@ -108,11 +108,14 @@ const SourceSelect: React.FC<{
export const AddCustomModelDialog: React.FC<{
open: boolean;
sources: Source[];
+ /** Server-populated standard OpenCode vendor prefixes (agent-supply v1.2),
+ * so the live identifier preview byte-matches the backend. */
+ standardVendors: StandardVendors;
/** When set, prefill for editing an existing custom entry. */
edit?: { sourceId: string; modelId: string; displayName: string | null } | null;
onClose: () => void;
onSaved: (identifier: string) => void;
-}> = ({ open, sources, edit, onClose, onSaved }) => {
+}> = ({ open, sources, standardVendors, edit, onClose, onSaved }) => {
const { t } = useTranslation();
const { showToast } = useToast();
@@ -135,7 +138,7 @@ export const AddCustomModelDialog: React.FC<{
}, [open]);
const trimmedId = modelId.trim();
- const identifier = source && trimmedId ? buildIdentifier(source.vendor, trimmedId) : '';
+ const identifier = source && trimmedId ? buildIdentifier(source.vendor, trimmedId, standardVendors) : '';
const copyIdentifier = () => {
if (!identifier || !navigator.clipboard?.writeText) {
diff --git a/ui/src/components/settings/models/menus/MappingDrawer.tsx b/ui/src/components/settings/models/menus/MappingDrawer.tsx
index 4bff69a66..ff7427ea9 100644
--- a/ui/src/components/settings/models/menus/MappingDrawer.tsx
+++ b/ui/src/components/settings/models/menus/MappingDrawer.tsx
@@ -19,23 +19,11 @@ import { buildTargetModels, isSourceEligible, type TargetModel } from './identif
import { SupplyDots } from './supplyBits';
import { useCompactSourceLabel } from './sourceLabel';
-// Mock stand-in for the fixed-menu backend's built-in model catalog. The
-// contract stores only OVERRIDES in agent.mappings (absent entry = 跟随原生), so
-// the full row list needs the backend's built-in id list, which agent-supply
-// does not yet expose.
-const MOCK_BUILTINS: Record<'claude' | 'codex', string[]> = {
- claude: ['claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
- codex: ['gpt-5.6', 'gpt-5.6-mini'],
-};
-
-// SINGLE swap point for the built-in catalog. Decided 2026-07-23: agent-supply
-// gains an additive optional `builtin_models: string[] | null` (fixed-menu
-// backends only), server-populated from the existing backend-models resolver,
-// in the post-batch integration pass. When it lands, this becomes:
-// return agent.builtin_models ?? MOCK_BUILTINS[agent.backend] ?? [];
-// (a one-line change; nothing else in the drawer needs to move).
-const resolveBuiltinIds = (agent: AgentSupply): string[] =>
- MOCK_BUILTINS[agent.backend as 'claude' | 'codex'] ?? [];
+// Fixed-menu backends expose their built-in model catalog via agent.builtin_models
+// (real ids from vibe/backend_model_catalog.py, agent-supply v1.2). The contract
+// stores only OVERRIDES in agent.mappings (absent entry = 跟随原生), so the row list
+// comes from this server-populated catalog — the UI never hardcodes it.
+const resolveBuiltinIds = (agent: AgentSupply): string[] => agent.builtin_models ?? [];
const seedDraft = (agent: AgentSupply): AgentMapping[] => {
const byId = new Map((agent.mappings ?? []).map((m) => [m.builtin_id, m]));
diff --git a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
index cd4fb9bce..54bb4814e 100644
--- a/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
+++ b/ui/src/components/settings/models/menus/OpenCodeMenuDrawer.tsx
@@ -72,12 +72,16 @@ export const OpenCodeMenuDrawer: React.FC<{
const { showToast } = useToast();
const { Icon, accent } = backendVisual('opencode');
+ // Standard OpenCode vendor prefixes, server-populated (agent-supply v1.2) so
+ // identifiers byte-match the backend's opencode_model_id — never hand-mirrored.
+ const standardVendors = React.useMemo(() => new Set(agent.standard_vendors ?? []), [agent.standard_vendors]);
+
// Only OpenCode-eligible sources materialize as providers (isSourceEligible):
// API-key sources only — subscriptions (native_cli AND hub-held experimental)
// are excluded, matching the backend predicate, so we never offer a row the
// live `set_opencode_menu` would reject.
const eligibleSources = React.useMemo(() => sources.filter((s) => isSourceEligible(s, 'opencode')), [sources]);
- const groups = React.useMemo(() => buildMenuGroups(eligibleSources), [eligibleSources]);
+ const groups = React.useMemo(() => buildMenuGroups(eligibleSources, standardVendors), [eligibleSources, standardVendors]);
const allRows = React.useMemo(() => groups.flatMap((g) => g.rows), [groups]);
const [view, setView] = React.useState<'featured' | 'full'>(agent.menu?.view ?? 'featured');
@@ -228,6 +232,7 @@ export const OpenCodeMenuDrawer: React.FC<{
<AddCustomModelDialog
open={customOpen}
sources={eligibleSources}
+ standardVendors={standardVendors}
edit={editTarget}
onClose={() => setCustomOpen(false)}
onSaved={(identifier) => {
diff --git a/ui/src/components/settings/models/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.ts
index 3238c7f00..1dec1b05a 100644
--- a/ui/src/components/settings/models/menus/identifiers.ts
+++ b/ui/src/components/settings/models/menus/identifiers.ts
@@ -9,29 +9,12 @@ import type { Accent } from '../vendorMeta';
import { sourceAccent } from '../vendorMeta';
import type { AgentBackend, Source } from '../types';
-// Standard vendor ids that map 1:1 to an OpenCode provider prefix (identical to
-// native OpenCode usage — no `avibe-` namespace).
-//
-// MOCK MIRROR of the backend `STANDARD_OPENCODE_VENDOR_IDS`
-// (core/handlers/model_hub/identifiers.py). ESCALATED (2026-07-23): the UI
-// cannot import the Python list, so any divergence makes `set_opencode_menu`
-// reject identifiers in live mode. Authoritative source should be the backend
-// in the integration pass (surfaced via contract, like `builtin_models`); this
-// set is the interim mirror and the single swap point.
-const STANDARD_OPENCODE_VENDORS = new Set([
- 'anthropic',
- 'openai',
- 'zhipuai',
- 'kimi',
- 'moonshot',
- 'xai',
- 'google',
- 'deepseek',
- 'mistral',
- 'groq',
- 'openrouter',
- 'together',
-]);
+// The standard OpenCode vendor ids come from the backend via the opencode
+// agent's `standard_vendors` projection (agent-supply v1.2), server-populated
+// from STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py).
+// The UI threads that set through — it no longer hand-mirrors the list, so a
+// divergence that would make `set_opencode_menu` reject identifiers can't arise.
+export type StandardVendors = ReadonlySet<string>;
/**
* Provider segment for a source's model, per the FROZEN opencode-overlay.md
@@ -42,13 +25,13 @@ const STANDARD_OPENCODE_VENDORS = new Set([
* `mapping_target_unavailable`. So `relay.example` (vendor `custom`) supplying
* `glm-5.2-air` yields `custom/glm-5.2-air` (not `zhipuai/…`).
*/
-export function inferProvider(sourceVendor: string): string {
- return STANDARD_OPENCODE_VENDORS.has(sourceVendor) ? sourceVendor : 'custom';
+export function inferProvider(sourceVendor: string, standardVendors: StandardVendors): string {
+ return standardVendors.has(sourceVendor) ? sourceVendor : 'custom';
}
/** Full prefixed identifier for a (source vendor, model id). */
-export function buildIdentifier(sourceVendor: string, modelId: string): string {
- return `${inferProvider(sourceVendor)}/${modelId}`;
+export function buildIdentifier(sourceVendor: string, modelId: string, standardVendors: StandardVendors): string {
+ return `${inferProvider(sourceVendor, standardVendors)}/${modelId}`;
}
// Which backend a fixed-menu backend's own native subscription belongs to
@@ -108,11 +91,11 @@ export type MenuGroup = {
* order track the 来源 band. The same identifier supplied by several sources
* collapses into one row carrying every supplying source.
*/
-export function buildMenuGroups(sources: Source[]): MenuGroup[] {
+export function buildMenuGroups(sources: Source[], standardVendors: StandardVendors): MenuGroup[] {
const byIdentifier = new Map<string, MenuModelRow>();
for (const source of sources) {
for (const model of source.models) {
- const identifier = buildIdentifier(source.vendor, model.id);
+ const identifier = buildIdentifier(source.vendor, model.id, standardVendors);
let row = byIdentifier.get(identifier);
if (!row) {
row = {
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index 752a9c1c8..f1cbd3b13 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -142,6 +142,10 @@ export function buildMockAgents(): AgentSupply[] {
{ builtin_id: 'claude-haiku-4-5', target_model_id: '', enabled: false },
],
menu: null,
+ // Fixed-menu backends carry the server-populated built-in catalog
+ // (agent-supply v1.2); the mapping drawer renders these rows.
+ builtin_models: ['claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
+ standard_vendors: null,
},
{
backend: 'codex',
@@ -153,6 +157,8 @@ export function buildMockAgents(): AgentSupply[] {
{ builtin_id: 'gpt-5.6-mini', target_model_id: '', enabled: false },
],
menu: null,
+ builtin_models: ['gpt-5.6', 'gpt-5.6-mini'],
+ standard_vendors: null,
},
{
backend: 'opencode',
@@ -175,6 +181,14 @@ export function buildMockAgents(): AgentSupply[] {
'zhipuai/glm-5-flash',
],
},
+ builtin_models: null,
+ // Server mirror of STANDARD_OPENCODE_VENDOR_IDS (agent-supply v1.2), so the
+ // menu / custom-model identifiers byte-match the backend's opencode_model_id.
+ standard_vendors: [
+ 'anthropic', 'deepseek', 'github-copilot', 'google', 'groq', 'kimi',
+ 'minimax', 'mistral', 'moonshot', 'openai', 'openrouter', 'together',
+ 'xai', 'zhipuai',
+ ],
},
];
}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 0c59272f0..db62c45d5 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -107,6 +107,14 @@ export type AgentSupply = {
current?: AgentCurrent | null;
mappings?: AgentMapping[];
menu?: AgentMenu | null;
+ /** v1.2 read-only projection: fixed-menu backends only — the backend's real
+ * built-in model ids (from vibe/backend_model_catalog.py). null for open-menu
+ * backends. The mapping drawer renders these; the UI never hardcodes menus. */
+ builtin_models?: string[] | null;
+ /** v1.2 read-only projection: opencode only — server mirror of
+ * STANDARD_OPENCODE_VENDOR_IDS, so the UI never hand-mirrors vendor prefixes.
+ * null otherwise. */
+ standard_vendors?: string[] | null;
};
// ── migration-scan.schema.json ──────────────────────────────────────────