From 10a32cfdbe971799581533a0e583fdf77e4c7d2c Mon Sep 17 00:00:00 2001 From: Bellman <54757707+Yeachan-Heo@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:21:08 +0900 Subject: [PATCH] feat(models): repoint opus presets to claude-opus-5 (#3123) * feat(models): repoint opus presets to claude-opus-5 Anthropic shipped claude-opus-5 (2026-07-24) with the same published envelope as claude-opus-4-8: 1M context, 128k output, effort range low..max, 5/25 pricing. Repoint the opus-related built-in presets to it. - claude-opus: default/planner/critic/architect -> anthropic/claude-opus-5 with existing effort suffixes; executor stays anthropic/claude-sonnet-5 - opus-codex: default -> anthropic/claude-opus-5:xhigh; the durable anthropic/claude-sonnet-5 planner override is unchanged - fable-opus-codex: planner/critic -> anthropic/claude-opus-5; the fable default and codex roles are unchanged - Regenerate packages/ai/src/models.json so anthropic/claude-opus-5 resolves; zero providers or models removed - Extend the generator's Claude Opus vision normalization to opus-5, which upstream shipped without image input on three variants, and replace the duplicated substring guard with a shared exact-generation parser plus a tripwire test that fails when the catalog bundles an Opus generation newer than any reviewed one - Realign preset expectation tests and update docs; measured opus-4-8 figures in docs/multi-vendor-profiles.md stay attributed to opus-4-8 rather than silently transferring to an unmeasured model * fix(models): remove unrelated opus preset catalog drift --------- Co-authored-by: Yeachan-Heo --- docs/gpt-5.6-codex-preset-benchmark.md | 6 +- docs/models.md | 4 +- docs/multi-vendor-profiles.md | 30 +- packages/ai/scripts/generate-models.ts | 46 +- packages/ai/src/models.json | 526 +++++++++++++++++- packages/ai/test/claude-opus-vision.test.ts | 76 ++- packages/coding-agent/CHANGELOG.md | 3 + .../coding-agent/src/config/model-profiles.ts | 14 +- .../src/internal-urls/docs-index.generated.ts | 6 +- ...ent-session-profile-resume-default.test.ts | 14 +- .../agent-session-resilient-retry.test.ts | 4 +- .../model-preset-landing-redteam-qa.test.ts | 6 +- .../test/model-profile-activation.test.ts | 8 +- .../test/model-profiles-catalog.test.ts | 20 +- .../coding-agent/test/model-registry.test.ts | 2 +- 15 files changed, 677 insertions(+), 88 deletions(-) diff --git a/docs/gpt-5.6-codex-preset-benchmark.md b/docs/gpt-5.6-codex-preset-benchmark.md index 3dfc0bb250..b7403fc46c 100644 --- a/docs/gpt-5.6-codex-preset-benchmark.md +++ b/docs/gpt-5.6-codex-preset-benchmark.md @@ -9,7 +9,7 @@ Built-in role assignments are product judgments. The selected TypeScript edit ev - **Eco**: `terra:low` default, `luna:low` executor, `luna:high` planner, `terra:xhigh` critic, and `terra:high` architect. - **Medium**: `sol:low` default, `terra:low` executor, `terra:high` planner, `sol:xhigh` critic, and `sol:high` architect. - **Pro**: `sol:medium` default, `terra:medium` executor, `sol:high` planner, `sol:max` critic, and `sol:xhigh` architect. -- **Combos**: `opus-codex` uses the Medium Codex executor, critic, and architect roles, with the durable `anthropic/claude-sonnet-5` planner override; `codex-opencodego` uses Medium Codex default and architect roles; and `fable-opus-codex` uses Pro Codex executor and architect roles with `anthropic/claude-opus-4-8:medium` as planner. +- **Combos**: `opus-codex` uses the Medium Codex executor, critic, and architect roles, with the durable `anthropic/claude-sonnet-5` planner override; `codex-opencodego` uses Medium Codex default and architect roles; and `fable-opus-codex` uses Pro Codex executor and architect roles with `anthropic/claude-opus-5:medium` as planner. The edit benchmark does not measure default-agent interpretation, orchestration, explanation, or routing, and it does not measure planner, architect, or critic work. Those non-executor assignments are product judgments, not benchmark findings. @@ -119,9 +119,9 @@ The selected-task data show that Luna xhigh used more reported tokens than Luna | `codex-eco` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-luna:low` | `openai-codex/gpt-5.6-luna:high` | `openai-codex/gpt-5.6-terra:xhigh` | `openai-codex/gpt-5.6-terra:high` | | `codex-medium` | `openai-codex/gpt-5.6-sol:low` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-terra:high` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` | | `codex-pro` | `openai-codex/gpt-5.6-sol:medium` | `openai-codex/gpt-5.6-terra:medium` | `openai-codex/gpt-5.6-sol:high` | `openai-codex/gpt-5.6-sol:max` | `openai-codex/gpt-5.6-sol:xhigh` | -| `opus-codex` | `anthropic/claude-opus-4-8:xhigh` | `openai-codex/gpt-5.6-terra:low` | `anthropic/claude-sonnet-5` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` | +| `opus-codex` | `anthropic/claude-opus-5:xhigh` | `openai-codex/gpt-5.6-terra:low` | `anthropic/claude-sonnet-5` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` | | `codex-opencodego` | `openai-codex/gpt-5.6-sol:low` | `opencode-go/deepseek-v4-pro` | `opencode-go/kimi-k2.6` | `opencode-go/mimo-v2.5-pro` | `openai-codex/gpt-5.6-sol:high` | -| `fable-opus-codex` | `anthropic/claude-fable-5:high` | `openai-codex/gpt-5.6-terra:medium` | `anthropic/claude-opus-4-8:medium` | `anthropic/claude-opus-4-8:high` | `openai-codex/gpt-5.6-sol:xhigh` | +| `fable-opus-codex` | `anthropic/claude-fable-5:high` | `openai-codex/gpt-5.6-terra:medium` | `anthropic/claude-opus-5:medium` | `anthropic/claude-opus-5:high` | `openai-codex/gpt-5.6-sol:xhigh` | ## Limitations diff --git a/docs/models.md b/docs/models.md index b69b8a295a..9379cc91f1 100644 --- a/docs/models.md +++ b/docs/models.md @@ -231,11 +231,11 @@ Built-in profiles are grouped by provider mix and tier: - `codex-{eco,medium,pro}` — GPT-5.6 Sol/Terra/Luna role mixes tuned by tier and reasoning effort - `opencodego` — single OpenCode Go preset (Kimi default, DeepSeek executor/architect, Qwen planner, MiMo critic) -- `claude-opus` — Anthropic OAuth preset centered on `claude-opus-4-8` +- `claude-opus` — Anthropic OAuth preset centered on `claude-opus-5` - Single-provider tiers: `glm-{eco,medium,pro}`, `kimi-coding-plan-{eco,medium,pro}`, `mimo-{eco,medium,pro}`, `grok-{eco,medium,pro}`, `cursor-{eco,medium,pro}`, `minimax-{eco,medium,pro}` - Combos: `opus-codex`, `codex-opencodego`, and `fable-opus-codex` -The `eco`, `medium`, and `pro` Codex profile mappings are current product judgments: Eco assigns Terra low/Luna low/Luna high/Terra xhigh/Terra high to default/executor/planner/critic/architect; Medium assigns Sol low/Terra low/Terra high/Sol xhigh/Sol high; and Pro assigns Sol medium/Terra medium/Sol high/Sol max/Sol xhigh. `opus-codex` retains the Medium Codex executor, critic, and architect roles but uses `anthropic/claude-sonnet-5` for planner; `codex-opencodego` retains the Medium Codex default and architect roles; and `fable-opus-codex` uses the Pro Codex executor and architect roles with `anthropic/claude-opus-4-8:medium` for planner. The descriptive repeated local exact-edit evidence informs only selected executor-style TypeScript tasks; it does not evaluate or prove default, planner, architect, or critic performance. See [GPT-5.6 Codex preset benchmark](./gpt-5.6-codex-preset-benchmark.md). Effort suffixes are clamped to each model's supported thinking range at preview and activation time. Single-provider tiers pin each provider's current flagship (`zai/glm-5.2`, `kimi-code/kimi-k2.7-code`, `xiaomi/mimo-v2.5-pro`, `xai/grok-4.3`, `cursor/composer-1.5`, `minimax-code/minimax-m3`). User-defined profiles override built-ins by exact profile name. +The `eco`, `medium`, and `pro` Codex profile mappings are current product judgments: Eco assigns Terra low/Luna low/Luna high/Terra xhigh/Terra high to default/executor/planner/critic/architect; Medium assigns Sol low/Terra low/Terra high/Sol xhigh/Sol high; and Pro assigns Sol medium/Terra medium/Sol high/Sol max/Sol xhigh. `opus-codex` retains the Medium Codex executor, critic, and architect roles but uses `anthropic/claude-sonnet-5` for planner; `codex-opencodego` retains the Medium Codex default and architect roles; and `fable-opus-codex` uses the Pro Codex executor and architect roles with `anthropic/claude-opus-5:medium` for planner. The descriptive repeated local exact-edit evidence informs only selected executor-style TypeScript tasks; it does not evaluate or prove default, planner, architect, or critic performance. See [GPT-5.6 Codex preset benchmark](./gpt-5.6-codex-preset-benchmark.md). Effort suffixes are clamped to each model's supported thinking range at preview and activation time. Single-provider tiers pin each provider's current flagship (`zai/glm-5.2`, `kimi-code/kimi-k2.7-code`, `xiaomi/mimo-v2.5-pro`, `xai/grok-4.3`, `cursor/composer-1.5`, `minimax-code/minimax-m3`). User-defined profiles override built-ins by exact profile name. Use `gjc --mpreset ` to activate a profile for the current session only. Activation hard-blocks when any provider listed in `required_providers` lacks credentials. Add `--default` to persist the selected profile as `modelProfile.default` in `config.yml`, so it applies at startup: diff --git a/docs/multi-vendor-profiles.md b/docs/multi-vendor-profiles.md index 04f2510bf9..e6f3df291b 100644 --- a/docs/multi-vendor-profiles.md +++ b/docs/multi-vendor-profiles.md @@ -2,7 +2,7 @@ A practical guide to picking models for GJC's roles, for every subscription situation — one vendor, two vendors, or the full multi-vendor set. It adds curated cross-vendor `profiles:` for `~/.gjc/agent/models.yml` and verified selector notes on top of the mechanism in [Model profiles](./models.md#model-profiles---mpreset). Everything here is **user config**; it complements the built-in `--mpreset` presets and overrides a built-in only when it shares its exact name. -> Selectors, prices, and "axis leaders" are catalog- and time-sensitive (observed 2026-06 on the current bundled catalog). Re-verify any selector with `gjc -p --no-session --no-tools --model "Reply OK"`. +> Selectors, prices, and "axis leaders" are catalog- and time-sensitive (selectors and prices observed 2026-07 on the current bundled catalog; the measured latency and single-message-limit notes below were observed 2026-06 on `claude-opus-4-8` and have not been re-measured on `claude-opus-5`). Re-verify any selector with `gjc -p --no-session --no-tools --model "Reply OK"`. ## The five roles @@ -36,7 +36,7 @@ profiles: daily: # everyday balance required_providers: [anthropic, openai-codex, google-antigravity, xai] model_mapping: - default: anthropic/claude-opus-4-8:medium + default: anthropic/claude-opus-5:medium executor: openai-codex/gpt-5.4:high planner: google-antigravity/gemini-3.1-pro-low:high architect: google-antigravity/gemini-3.1-pro-low:high @@ -45,8 +45,8 @@ profiles: ultimate: # cost-no-object, best per role required_providers: [anthropic, openai-codex, google-antigravity, xai] model_mapping: - default: anthropic/claude-opus-4-8:high - executor: anthropic/claude-opus-4-8:max + default: anthropic/claude-opus-5:high + executor: anthropic/claude-opus-5:max planner: openai-codex/gpt-5.5:xhigh architect: google-antigravity/gemini-3.1-pro-low:high critic: xai/grok-4.3:high @@ -54,7 +54,7 @@ profiles: eco: # cheapest delegated work; main loop stays on Opus required_providers: [anthropic, opencode-go, google-antigravity, xai] model_mapping: - default: anthropic/claude-opus-4-8:low + default: anthropic/claude-opus-5:low executor: opencode-go/deepseek-v4-flash planner: xai/grok-4-1-fast:high architect: google-antigravity/gemini-3.1-pro-low @@ -63,19 +63,19 @@ profiles: monorepo: # huge codebases (openai-codex excluded: 272k context cap) required_providers: [anthropic, google-antigravity, opencode-go] model_mapping: - default: anthropic/claude-opus-4-8:medium - executor: anthropic/claude-opus-4-8:high + default: anthropic/claude-opus-5:medium + executor: anthropic/claude-opus-5:high planner: google-antigravity/gemini-3.1-pro-low:high - architect: anthropic/claude-opus-4-8:high + architect: anthropic/claude-opus-5:high critic: opencode-go/glm-5.2 reviewer: # review/audit stance — the author-mode role split, inverted required_providers: [anthropic, openai-codex, google-antigravity] model_mapping: - default: anthropic/claude-opus-4-8:high # aggregator restraint: preserve raw reviewer verdicts + default: anthropic/claude-opus-5:high # aggregator restraint: preserve raw reviewer verdicts executor: openai-codex/gpt-5.5:high # support — repro PoCs, failing tests, harnesses planner: google-antigravity/gemini-3.1-pro-low:high # review checklists / audit scoping - architect: anthropic/claude-opus-4-8:high # lead 1 — primary code-review judge (effective long-context) + architect: anthropic/claude-opus-5:high # lead 1 — primary code-review judge (effective long-context) critic: openai-codex/gpt-5.5:high # lead 2 — merge gate, cross-family vs Claude-authored code ``` @@ -101,14 +101,14 @@ Current axis leaders and the cheaper second option, with metered price ($/1M in/ | Need | First pick | Cheaper option | | --- | --- | --- | -| Router / tool-calling (`default`) | `anthropic/claude-opus-4-8` (5/25) | `anthropic/claude-sonnet-5` (3/15) | -| Coding (`executor`) | `anthropic/claude-opus-4-8` — SWE-bench Verified ~88.6 (5/25) | `openai-codex/gpt-5.4` (2.5/15) · `opencode-go/deepseek-v4-flash` (0.14/0.28) | +| Router / tool-calling (`default`) | `anthropic/claude-opus-5` (5/25) | `anthropic/claude-sonnet-5` (3/15) | +| Coding (`executor`) | `anthropic/claude-opus-5` (5/25) — the prior `claude-opus-4-8` scored SWE-bench Verified ~88.6; no Opus 5 measurement yet | `openai-codex/gpt-5.4` (2.5/15) · `opencode-go/deepseek-v4-flash` (0.14/0.28) | | Reasoning (`planner`) | `openai-codex/gpt-5.5` (ARC-AGI-2) / `google-antigravity/gemini-3.1-pro-low:high` (GPQA) | `xai/grok-4-1-fast` (0.2/0.5) | -| Large context (`architect`) | `anthropic/claude-opus-4-8` (effective long-context) | `xai/grok-4-fast` (2M nominal, 0.2/0.5) | +| Large context (`architect`) | `anthropic/claude-opus-5` (effective long-context) | `xai/grok-4-fast` (2M nominal, 0.2/0.5) | | Multimodal review (`architect`) | `google-antigravity/gemini-3.1-pro-low:high` | `google-antigravity/gemini-3.5-flash` | | Independent critic | `xai/grok-4.3` (1.25/2.5) | `opencode-go/glm-5.2` · `google-antigravity/gemini-3.5-flash` | -On standard tasks, all current frontier models in the catalog are accurate; **pick by cost, latency, and role fit, not by raw accuracy on easy prompts.** As an indicative GJC-routed latency reference (`gjc -p`, identical coding + reasoning prompts, all correct): `grok-4.3` and `glm-5.2` ≈ 2–3s, `deepseek-v4-pro` ≈ 3–4s, `claude-opus-4-8` / `gpt-5.5` ≈ 4–7s, `gemini-3.1-pro-low:high` ≈ 7s. +On standard tasks, all current frontier models in the catalog are accurate; **pick by cost, latency, and role fit, not by raw accuracy on easy prompts.** As an indicative GJC-routed latency reference (`gjc -p`, identical coding + reasoning prompts, all correct): `grok-4.3` and `glm-5.2` ≈ 2–3s, `deepseek-v4-pro` ≈ 3–4s, `claude-opus-4-8` / `gpt-5.5` ≈ 4–7s, `gemini-3.1-pro-low:high` ≈ 7s. `claude-opus-5` shares Opus 4.8's published context/output envelope but has not been latency-measured here. ## Verified selector notes (current catalog) @@ -116,7 +116,7 @@ Observed via live `gjc -p` calls; useful when wiring the profiles above: - **Antigravity Gemini, high reasoning** → use `google-antigravity/gemini-3.1-pro-low:high`. The id `gemini-3.1-pro-high` returns HTTP 400 (no matching backend model); `thinkingLevel` is a per-request parameter, so raising it on `gemini-3.1-pro-low` invokes the model's native high-reasoning mode rather than a degraded one. - **openai-codex on a ChatGPT account** serves base GPT only (`gpt-5.5`, `gpt-5.4`). Standalone `-codex` variants (`gpt-5.3-codex`, `gpt-5.2-codex`, `gpt-5.1-codex-max` / `-mini`) return `not supported when using Codex with a ChatGPT account`. -- **Single-message input limit is separate from the context window.** `claude-opus-4-8` runs with a 1M window via multi-turn accumulation, but a single `@file` message above ~400k tokens returns 400 on `anthropic` / `google-antigravity`; `xai` / `opencode-go` accept larger single messages. Chunk very large inputs across turns instead of pasting one block. +- **Single-message input limit is separate from the context window.** Measured on `claude-opus-4-8` (not yet re-measured on `claude-opus-5`, which publishes the same 1M window): the model runs with a 1M window via multi-turn accumulation, but a single `@file` message above ~400k tokens returns 400 on `anthropic` / `google-antigravity`; `xai` / `opencode-go` accept larger single messages. Chunk very large inputs across turns instead of pasting one block. - **Some selectors come from a provider's live catalog, not the bundled snapshot.** `opencode-go/glm-5.2` and `google-antigravity/gemini-3.5-flash` resolved in `gjc -p` tests but are **not** in `packages/ai/src/models.json`; they appear only after the provider's online model discovery has populated the registry. `required_providers` verifies credentials at activation — it does **not** guarantee fresh, non-stale discovery — so activation can still fail with `selector did not resolve` until discovery runs (re-login or retry to refresh). If you hit that, substitute a bundled id: `opencode-go/deepseek-v4-pro` for the critic, or `zai/glm-5.2` (add `zai` to `required_providers`) for GLM 5.2. ## Activation diff --git a/packages/ai/scripts/generate-models.ts b/packages/ai/scripts/generate-models.ts index c4afe73f41..09764e3cba 100644 --- a/packages/ai/scripts/generate-models.ts +++ b/packages/ai/scripts/generate-models.ts @@ -281,14 +281,54 @@ function applyCodexPricingFallback(models: readonly Model[]): Model[] { }); } -// Catalog sources occasionally omit image input for Claude Opus 4.8 variants +// Catalog sources occasionally omit image input for recent Claude Opus variants // (e.g. kilo/venice "-fast" entries) even though every Claude Opus model is // vision-capable. Correct those so capability advertising stays consistent // across providers. Runs after the dynamic merge so it survives regeneration. +// +// The list is an explicit allowlist of reviewed generations rather than a +// `claude-opus-*` prefix match: a future generation must be reviewed before we +// assert capabilities for it. `claude-opus-vision.test.ts` imports this list and +// fails when the catalog bundles a newer Opus generation than any declared here. +export const VISION_CORRECTED_CLAUDE_OPUS_GENERATIONS: readonly number[] = [4.8, 5]; + +/** + * Known separator-less generation aliases. Upstream normally writes + * `claude-opus-4-5`, but a few catalogs collapse it to `claude-opus-45`. This is + * an explicit list so a future two-digit major (`claude-opus-10`) is read as + * generation 10 rather than silently as 1.0. + */ +const COMPACT_CLAUDE_OPUS_ALIASES: Readonly> = { + "41": 4.1, + "45": 4.5, + "46": 4.6, + "47": 4.7, + "48": 4.8, +}; + +/** + * Extract the Claude Opus generation from a model id, ignoring provider + * prefixes, region prefixes, and trailing aliases or date suffixes: + * `claude-opus-4-8` and `anthropic.claude-opus-4-8` -> 4.8, `claude-opus-5-fast` + * -> 5, `claude-opus-45` -> 4.5, `claude-opus-4-20250514` -> 4, + * `claude-opus-10` -> 10. Returns undefined when the id is not a Claude Opus + * model. + */ +export function claudeOpusGeneration(modelId: string): number | undefined { + const match = modelId + .toLowerCase() + .replace(/\./g, "-") + .match(/claude-opus-(\d+)(?:-(\d)(?![\d]))?/); + if (!match) return undefined; + const [, major, minor] = match; + if (minor !== undefined) return Number(major) + Number(minor) / 10; + return COMPACT_CLAUDE_OPUS_ALIASES[major] ?? Number(major); +} + function applyClaudeOpusVisionCorrections(models: readonly Model[]): Model[] { return models.map(model => { - const normalizedId = model.id.toLowerCase().replace(/\./g, "-"); - if (!normalizedId.includes("claude-opus-4-8")) { + const generation = claudeOpusGeneration(model.id); + if (generation === undefined || !VISION_CORRECTED_CLAUDE_OPUS_GENERATIONS.includes(generation)) { return model; } if (model.input.includes("image")) { diff --git a/packages/ai/src/models.json b/packages/ai/src/models.json index f413f714e2..9e196f7eea 100644 --- a/packages/ai/src/models.json +++ b/packages/ai/src/models.json @@ -7,12 +7,25 @@ "provider": "alibaba-token-plan", "baseUrl": "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", "reasoning": true, - "input": ["text"], - "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }, + "input": [ + "text" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, "contextWindow": 1000000, "maxTokens": 384000, - "compat": { "supportsDeveloperRole": false }, - "thinking": { "mode": "effort", "minLevel": "minimal", "maxLevel": "xhigh" } + "compat": { + "supportsDeveloperRole": false + }, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "xhigh" + } }, "glm-5.2": { "id": "glm-5.2", @@ -21,12 +34,25 @@ "provider": "alibaba-token-plan", "baseUrl": "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", "reasoning": true, - "input": ["text"], - "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }, + "input": [ + "text" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, "contextWindow": 1000000, "maxTokens": 131072, - "compat": { "supportsDeveloperRole": false }, - "thinking": { "mode": "effort", "minLevel": "minimal", "maxLevel": "xhigh" } + "compat": { + "supportsDeveloperRole": false + }, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "xhigh" + } }, "qwen3.8-max-preview": { "id": "qwen3.8-max-preview", @@ -35,12 +61,25 @@ "provider": "alibaba-token-plan", "baseUrl": "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", "reasoning": true, - "input": ["text"], - "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }, + "input": [ + "text" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, "contextWindow": 1000000, "maxTokens": 65536, - "compat": { "supportsDeveloperRole": false }, - "thinking": { "mode": "effort", "minLevel": "minimal", "maxLevel": "xhigh" } + "compat": { + "supportsDeveloperRole": false + }, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "xhigh" + } } }, "amazon-bedrock": { @@ -3142,6 +3181,198 @@ "minLevel": "minimal", "maxLevel": "high" } + }, + "anthropic.claude-opus-5": { + "id": "anthropic.claude-opus-5", + "name": "Anthropic Opus 5", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } + }, + "au.anthropic.claude-opus-5": { + "id": "au.anthropic.claude-opus-5", + "name": "Anthropic Opus 5 (AU)", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } + }, + "eu.anthropic.claude-opus-5": { + "id": "eu.anthropic.claude-opus-5", + "name": "Anthropic Opus 5 (EU)", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5.5, + "output": 27.5, + "cacheRead": 0.55, + "cacheWrite": 6.875 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } + }, + "global.anthropic.claude-opus-5": { + "id": "global.anthropic.claude-opus-5", + "name": "Anthropic Opus 5 (Global)", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } + }, + "jp.anthropic.claude-opus-5": { + "id": "jp.anthropic.claude-opus-5", + "name": "Anthropic Opus 5 (JP)", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } + }, + "us.anthropic.claude-opus-5": { + "id": "us.anthropic.claude-opus-5", + "name": "Anthropic Opus 5 (US)", + "api": "bedrock-converse-stream", + "provider": "amazon-bedrock", + "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max", + "levels": [ + "minimal", + "low", + "medium", + "high", + "max" + ] + } } }, "anthropic": { @@ -3661,6 +3892,31 @@ "minLevel": "minimal", "maxLevel": "high" } + }, + "claude-opus-5": { + "id": "claude-opus-5", + "name": "Anthropic Opus 5", + "api": "anthropic-messages", + "provider": "anthropic", + "baseUrl": "https://api.anthropic.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max" + } } }, "azure-openai": { @@ -10255,6 +10511,34 @@ "minLevel": "minimal", "maxLevel": "high" } + }, + "claude-opus-5": { + "id": "claude-opus-5", + "name": "Anthropic Opus 5", + "api": "anthropic-messages", + "provider": "github-copilot", + "baseUrl": "https://api.githubcopilot.com", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 64000, + "headers": { + "User-Agent": "opencode/1.3.15" + }, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max" + } } }, "gitlab-duo": { @@ -22786,6 +23070,46 @@ "minLevel": "minimal", "maxLevel": "xhigh" } + }, + "anthropic/claude-opus-5": { + "id": "anthropic/claude-opus-5", + "name": "Anthropic Opus 5", + "api": "openai-completions", + "provider": "kilo", + "baseUrl": "https://api.kilo.ai/api/gateway", + "reasoning": false, + "input": [ + "text", + "image" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, + "contextWindow": 222222, + "maxTokens": 8888 + }, + "anthropic/claude-opus-5-fast": { + "id": "anthropic/claude-opus-5-fast", + "name": "Anthropic Opus 5 (Fast) ($$$$)", + "api": "openai-completions", + "provider": "kilo", + "baseUrl": "https://api.kilo.ai/api/gateway", + "reasoning": false, + "input": [ + "text", + "image" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, + "contextWindow": 222222, + "maxTokens": 8888 } }, "kimi-code": { @@ -61331,6 +61655,31 @@ }, "contextWindow": 131072, "maxTokens": 131072 + }, + "claude-opus-5": { + "id": "claude-opus-5", + "name": "Anthropic Opus 5", + "api": "anthropic-messages", + "provider": "opencode-zen", + "baseUrl": "https://opencode.ai/zen", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max" + } } }, "opengateway": { @@ -69992,6 +70341,56 @@ "minLevel": "minimal", "maxLevel": "high" } + }, + "anthropic/claude-opus-5": { + "id": "anthropic/claude-opus-5", + "name": "Anthropic Opus 5", + "api": "openai-completions", + "provider": "openrouter", + "baseUrl": "https://openrouter.ai/api/v1", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "high" + } + }, + "anthropic/claude-opus-5-fast": { + "id": "anthropic/claude-opus-5-fast", + "name": "Anthropic Opus 5 (Fast)", + "api": "openai-completions", + "provider": "openrouter", + "baseUrl": "https://openrouter.ai/api/v1", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 10, + "output": 50, + "cacheRead": 1, + "cacheWrite": 12.5 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "high" + } } }, "qianfan": { @@ -73609,6 +74008,57 @@ "compat": { "supportsUsageInStreaming": false } + }, + "claude-opus-5": { + "id": "claude-opus-5", + "name": "Anthropic Opus 5", + "api": "openai-completions", + "provider": "venice", + "baseUrl": "https://api.venice.ai/api/v1", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "compat": { + "supportsUsageInStreaming": false + }, + "thinking": { + "mode": "effort", + "minLevel": "minimal", + "maxLevel": "xhigh" + } + }, + "claude-opus-5-fast": { + "id": "claude-opus-5-fast", + "name": "anthropic-opus-5-fast", + "api": "openai-completions", + "provider": "venice", + "baseUrl": "https://api.venice.ai/api/v1", + "reasoning": false, + "input": [ + "text", + "image" + ], + "cost": { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + }, + "contextWindow": 1000000, + "maxTokens": 8888, + "compat": { + "supportsUsageInStreaming": false + } } }, "vercel-ai-gateway": { @@ -78853,6 +79303,56 @@ "minLevel": "minimal", "maxLevel": "xhigh" } + }, + "anthropic/claude-opus-5": { + "id": "anthropic/claude-opus-5", + "name": "Anthropic Opus 5", + "api": "anthropic-messages", + "provider": "vercel-ai-gateway", + "baseUrl": "https://ai-gateway.vercel.sh", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 5, + "output": 25, + "cacheRead": 0.5, + "cacheWrite": 6.25 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max" + } + }, + "anthropic/claude-opus-5-fast": { + "id": "anthropic/claude-opus-5-fast", + "name": "Anthropic Opus 5 (Fast)", + "api": "anthropic-messages", + "provider": "vercel-ai-gateway", + "baseUrl": "https://ai-gateway.vercel.sh", + "reasoning": true, + "input": [ + "text", + "image" + ], + "cost": { + "input": 10, + "output": 50, + "cacheRead": 1, + "cacheWrite": 12.5 + }, + "contextWindow": 1000000, + "maxTokens": 128000, + "thinking": { + "mode": "anthropic-adaptive", + "minLevel": "minimal", + "maxLevel": "max" + } } }, "xai": { @@ -84851,4 +85351,4 @@ } } } -} \ No newline at end of file +} diff --git a/packages/ai/test/claude-opus-vision.test.ts b/packages/ai/test/claude-opus-vision.test.ts index c181eb6d59..9bd88fc07a 100644 --- a/packages/ai/test/claude-opus-vision.test.ts +++ b/packages/ai/test/claude-opus-vision.test.ts @@ -1,24 +1,68 @@ import { describe, expect, it } from "bun:test"; +import { claudeOpusGeneration, VISION_CORRECTED_CLAUDE_OPUS_GENERATIONS } from "../scripts/generate-models"; import { getBundledModels, getBundledProviders } from "../src/models"; /** - * Every Claude Opus 4.8 variant is vision-capable. Some upstream catalogs omit - * image input (e.g. kilo/venice "-fast" entries); generate-models.ts corrects - * these via applyClaudeOpusVisionCorrections so capability advertising stays - * consistent across providers. + * Every reviewed Claude Opus generation is vision-capable. Some upstream + * catalogs omit image input (e.g. kilo/venice "-fast" entries); + * generate-models.ts corrects these via applyClaudeOpusVisionCorrections so + * capability advertising stays consistent across providers. */ -describe("Claude Opus 4.8 vision capability", () => { - it("advertises image input for every bundled claude-opus-4.8 variant", () => { - const offenders: string[] = []; - for (const provider of getBundledProviders()) { - for (const model of getBundledModels(provider as Parameters[0])) { - const normalizedId = model.id.toLowerCase().replace(/\./g, "-"); - if (!normalizedId.includes("claude-opus-4-8")) continue; - if (!model.input.includes("image")) { - offenders.push(`${provider}/${model.id}`); - } - } +function bundledOpusModels(): { qualifiedId: string; generation: number; hasImage: boolean }[] { + const models: { qualifiedId: string; generation: number; hasImage: boolean }[] = []; + for (const provider of getBundledProviders()) { + for (const model of getBundledModels(provider as Parameters[0])) { + const generation = claudeOpusGeneration(model.id); + if (generation === undefined) continue; + models.push({ + qualifiedId: `${provider}/${model.id}`, + generation, + hasImage: model.input.includes("image"), + }); } - expect(offenders).toEqual([]); + } + return models; +} + +describe("Claude Opus vision capability", () => { + it("parses the generation out of provider-prefixed, aliased, and date-suffixed ids", () => { + expect(claudeOpusGeneration("claude-opus-4-8")).toBe(4.8); + expect(claudeOpusGeneration("anthropic.claude-opus-4-8")).toBe(4.8); + expect(claudeOpusGeneration("us.anthropic.claude-opus-5")).toBe(5); + expect(claudeOpusGeneration("claude-opus-5-fast")).toBe(5); + expect(claudeOpusGeneration("claude-opus-45")).toBe(4.5); + expect(claudeOpusGeneration("claude-opus-4-20250514")).toBe(4); + // A future generation must resolve even when suffixed or date-qualified, + // otherwise the tripwire below would silently skip it. + expect(claudeOpusGeneration("claude-opus-6")).toBe(6); + expect(claudeOpusGeneration("claude-opus-6-fast")).toBe(6); + expect(claudeOpusGeneration("anthropic/claude-opus-6-1-fast")).toBe(6.1); + expect(claudeOpusGeneration("claude-opus-6-20270101")).toBe(6); + // A two-digit major must not be read as a compact major/minor alias. + expect(claudeOpusGeneration("claude-opus-10")).toBe(10); + expect(claudeOpusGeneration("claude-opus-10-fast")).toBe(10); + expect(claudeOpusGeneration("claude-sonnet-5")).toBeUndefined(); + }); + + for (const generation of VISION_CORRECTED_CLAUDE_OPUS_GENERATIONS) { + it(`advertises image input for every bundled claude-opus-${generation} variant`, () => { + const offenders = bundledOpusModels() + .filter(model => model.generation === generation && !model.hasImage) + .map(model => model.qualifiedId); + expect(offenders).toEqual([]); + }); + } + + // Tripwire: the allowlist is deliberately explicit rather than a + // `claude-opus-*` prefix match, so a newer bundled generation would silently + // bypass both the generator correction and the coverage above. Fail instead, + // forcing the new generation to be reviewed and declared. + it("declares the newest bundled Claude Opus generation in the correction allowlist", () => { + const models = bundledOpusModels(); + // Guards against the check going vacuous if id parsing ever drifts. + expect(models.length).toBeGreaterThan(0); + const newestDeclared = Math.max(...VISION_CORRECTED_CLAUDE_OPUS_GENERATIONS); + const undeclared = models.filter(model => model.generation > newestDeclared).map(model => model.qualifiedId); + expect(undeclared).toEqual([]); }); }); diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index 223ecb65d6..09f98270e3 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +### Changed + +- The built-in `claude-opus`, `opus-codex`, and `fable-opus-codex` presets now use `anthropic/claude-opus-5` instead of `anthropic/claude-opus-4-8`, with effort suffixes preserved; `packages/ai/src/models.json` was regenerated so `anthropic/claude-opus-5` resolves; non-opus roles (`anthropic/claude-sonnet-5` executor/planner overrides, codex and fable roles) are unchanged. ### Fixed diff --git a/packages/coding-agent/src/config/model-profiles.ts b/packages/coding-agent/src/config/model-profiles.ts index 68dda7154b..3ade8372bb 100644 --- a/packages/coding-agent/src/config/model-profiles.ts +++ b/packages/coding-agent/src/config/model-profiles.ts @@ -100,11 +100,11 @@ export const BUILTIN_MODEL_PROFILES: readonly ModelProfileDefinition[] = [ architect: "opencode-go/deepseek-v4-pro", }), profile("claude-opus", ["anthropic"], { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", executor: "anthropic/claude-sonnet-5", - planner: "anthropic/claude-opus-4-8:low", - critic: "anthropic/claude-opus-4-8:high", - architect: "anthropic/claude-opus-4-8:xhigh", + planner: "anthropic/claude-opus-5:low", + critic: "anthropic/claude-opus-5:high", + architect: "anthropic/claude-opus-5:xhigh", }), profile("claude-fable", ["anthropic"], { default: "anthropic/claude-fable-5:xhigh", @@ -271,7 +271,7 @@ export const BUILTIN_MODEL_PROFILES: readonly ModelProfileDefinition[] = [ critic: "alibaba-token-plan/qwen3.8-max-preview:xhigh", }), profile("opus-codex", ["anthropic", "openai-codex"], { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", executor: "openai-codex/gpt-5.6-terra:low", planner: "anthropic/claude-sonnet-5", critic: "openai-codex/gpt-5.6-sol:xhigh", @@ -287,8 +287,8 @@ export const BUILTIN_MODEL_PROFILES: readonly ModelProfileDefinition[] = [ profile("fable-opus-codex", ["anthropic", "openai-codex"], { default: "anthropic/claude-fable-5:high", executor: "openai-codex/gpt-5.6-terra:medium", - planner: "anthropic/claude-opus-4-8:medium", - critic: "anthropic/claude-opus-4-8:high", + planner: "anthropic/claude-opus-5:medium", + critic: "anthropic/claude-opus-5:high", architect: "openai-codex/gpt-5.6-sol:xhigh", }), ]; diff --git a/packages/coding-agent/src/internal-urls/docs-index.generated.ts b/packages/coding-agent/src/internal-urls/docs-index.generated.ts index c5a0880163..9e07c75b78 100644 --- a/packages/coding-agent/src/internal-urls/docs-index.generated.ts +++ b/packages/coding-agent/src/internal-urls/docs-index.generated.ts @@ -33,7 +33,7 @@ export const EMBEDDED_DOCS: Readonly> = { "gjc-dogfood-skill-template.md": "# GJC dogfood local skill template\n\nIssue #93 requested a gaebal-gajae/operator dogfood skill. The live issue has no comment approving a fifth bundled default workflow skill, so this stays a local template instead of changing the default workflow surface. Operators can copy it into a user or project override when they want GJC-first session guidance.\n\nThe installable skill body is everything from the first frontmatter marker down; the frontmatter must be the **first line** of the installed file or the skill scan silently skips it (the scan requires a parsed `description`). Install into the user-level scan location (`~/.gjc/agent/skills/`, not `~/.gjc/skills/`):\n\n```sh\nmkdir -p ~/.gjc/agent/skills/gjc-dogfood\nsed -n '/^---$/,$p' docs/gjc-dogfood-skill-template.md > ~/.gjc/agent/skills/gjc-dogfood/SKILL.md\n```\n\nFor a single project, install to `/.gjc/skills/gjc-dogfood/SKILL.md` with the same extraction. Do not commit that project `.gjc` copy unless the project explicitly wants a local override.\n\nFilesystem skill discovery is off by default, so enable it once. Set `skills.enabled`, then enable **only the scan that matches where you installed** — `enablePiUser` and `enablePiProject` default to `false` in `DEFAULT_SKILL_DISCOVERY_SETTINGS`, and enabling the project scan opts every future session into repo-local `.gjc/skills` discovery, so do not enable it for a user-only install:\n\n```sh\ngjc config set skills.enabled true\n\n# for the user-level install (~/.gjc/agent/skills/):\ngjc config set skills.enablePiUser true\n\n# OR, for the project-level install (/.gjc/skills/):\ngjc config set skills.enablePiProject true\n```\n\nThen verify in a new session: `/skill:gjc-dogfood` should autocomplete.\n\n---\nname: gjc-dogfood\ndescription: Use when running or reviewing work through GJC sessions, dogfooding Gajae-Code, or migrating an operator workflow from OMX to GJC.\n---\n\n# GJC Dogfood Operator Workflow\n\nUse GJC first for coding, review, planning, and follow-up sessions. Treat OMX as a fallback only when GJC is unavailable, broken, or missing a required capability.\n\n## Locate and launch GJC\n\n- Installed CLI: run `command -v gjc` and then launch with `gjc --tmux`.\n- Repository checkout: from the gajae-code repo, prefer `bun packages/coding-agent/src/cli.ts --tmux` when testing source changes before install.\n- Worktree isolation: for branch-specific work, either let GJC create a managed sibling worktree with `gjc --tmux --worktree ` or `cd ` and run `gjc --tmux` there. Do not pass filesystem paths to `--worktree`.\n- Name sessions explicitly with the project and issue, for example `gajae-code-93-dogfood-skill`, so tmux panes, logs, and exports remain traceable.\n\n## Start the session\n\n- Put git operations inside the GJC session: fetch, branch/worktree setup, focused commits, pushes, and PR creation should be visible in-session.\n- Submit the initial prompt with the issue URL, target branch, acceptance criteria, verification limits, and any existing plan/spec link.\n- Verify the prompt was accepted: the TUI should show the user prompt, an active assistant turn, or a tool/action request. If the session silently idles, resend once with a shorter prompt and capture the failure.\n- Verify working state before leaving the session unattended: confirm the target cwd/worktree, branch, and issue scope are visible in the transcript or command output.\n\n## During work\n\n- Keep session names and branch names issue-scoped.\n- Prefer GJC workflow skills only when they fit: `deep-interview` for unclear requirements, `ralplan` for planning, `ultragoal` for durable ledgers, and `team` for coordinated tmux execution.\n- Keep evidence in the session: issue reads, focused tests/checks, screenshots only when visual behavior matters, and PR URLs.\n- When GJC is weaker than OMX, finish the urgent work with the smallest safe fallback and file a gajae-code follow-up issue with the missing capability, exact command/session context, expected behavior, and evidence.\n\n## Fallback policy\n\nUse OMX or another operator path only when:\n\n- `gjc` cannot be located or launched after checking installed and repo-local commands;\n- authentication, model routing, tmux, or prompt submission is broken;\n- GJC lacks a required capability that OMX already has;\n- an urgent production/review deadline would be missed by debugging GJC first.\n\nRecord the fallback reason and create or link the gajae-code issue that would make GJC sufficient next time.\n\n## Evidence checklist\n\nReport:\n\n- project, issue, branch/worktree, and session name;\n- whether GJC was installed or repo-local;\n- prompt acceptance and working-state evidence;\n- git operations performed in-session;\n- focused verification commands and results;\n- PR/issue URLs;\n- follow-up gajae-code issues for any GJC gap or fallback.\n", "gjc-plugins.md": "# GJC Plugin Bundles\n\nGJC supports two distinct plugin families. Do not confuse them:\n\n1. **Legacy marketplace / npm plugins** (`packages/coding-agent/src/extensibility/plugins`) — installed through the existing `gjc plugin install ` marketplace/npm flows. Unchanged by this system.\n2. **GJC plugin bundles** — directories whose root contains a **`gajae-plugin.json`** manifest (`kind: \"gajae-code-plugin\"`). These *extend* existing GJC capabilities and are the subject of this document.\n\nA GJC plugin bundle may only **extend** existing skills/agents — it can never register a new top-level skill, slash-command, command, or agent. GJC exposes exactly four default workflow skills (`deep-interview`, `ralplan`, `team`, `ultragoal`) and four role agents (`executor`, `architect`, `planner`, `critic`); bundles add sub-skills/appendices/tools/hooks/MCPs to those existing parents only.\n\n## Manifest (`gajae-plugin.json`)\n\n```json\n{\n \"kind\": \"gajae-code-plugin\",\n \"name\": \"example-domain-bundle\",\n \"version\": \"1.0.0\",\n \"subskills\": [\"subskills/ralplan-design/SKILL.md\"],\n \"tools\": [\n { \"name\": \"domain_note\", \"path\": \"tools/domain-note.ts\", \"description\": \"...\" }\n ],\n \"hooks\": [\n { \"name\": \"audit-read\", \"event\": \"tool_call\", \"target\": \"read\", \"phase\": \"before\", \"path\": \"hooks/audit-read.ts\" }\n ],\n \"mcps\": [\n { \"name\": \"domain_docs\", \"transport\": \"stdio\", \"command\": \"bun\", \"args\": [\"mcp/domain-docs.ts\"], \"cwd\": \".\" }\n ],\n \"system_appendix\": [{ \"name\": \"domain-policy\", \"path\": \"prompts/system-appendix.md\" }],\n \"agent-appendix\": [{ \"agent\": \"executor\", \"name\": \"domain-executor\", \"path\": \"prompts/executor-appendix.md\" }]\n}\n```\n\n### Surfaces (the only allowed extension points)\n\n| Surface | Purpose | Additive rule |\n|---------|---------|---------------|\n| `subskills` | Inline sub-skills bound to an existing skill/agent (`binds_to`/`phase`/`activation_arg`) | Two-tier (see below) |\n| `tools` | Always-on custom tools (object entries) or legacy subskill-scoped string paths | Additive; manifest-declared name is authoritative, never overwrites an existing tool |\n| `hooks` | Constrained event hooks bound to a declared `event`/`target`/`phase` | Additive; run alongside built-ins, never replace |\n| `mcps` | MCP servers (`stdio`/`http`/`sse`) | Additive; server-name collisions are hard errors |\n| `system_appendix` | Lower-authority text appended to the default agent system prompt | Append-only, never overrides base |\n| `agent-appendix` | Lower-authority text appended to an existing role agent's prompt | Append-only per named agent |\n\n### Forbidden / unsupported keys\n\n- **Forbidden** (`forbidden_surface`): `skills`, `slash-commands`, `commands`, `agents` — bundles may not register new top-level definitions.\n- **Unsupported** (`unsupported_surface`): `mcp`, `mcpServers` (use the canonical `mcps`), and any unknown top-level key.\n\n## Installation\n\n```sh\ngjc plugin install --user # install into the user root\ngjc plugin install --project # install into the project root\n```\n\nExactly one of `--user` / `--project` is required for GJC plugin bundles (there is no default root). A source containing `gajae-plugin.json` is classified as a GJC bundle and routed to the bundle installer **before** the marketplace/npm path; non-bundle sources fall through to the legacy flow.\n\nInstall is **compile-validate-then-copy**:\n\n1. The bundle is compiled and validated **without importing any plugin code** (manifest, frontmatter, and declared files are read as bytes only).\n2. Collision and MCP security policy are enforced (the durable registry is the collision authority — never capability \"first-wins\").\n3. Only the validated, hashed files are copied into a temp sibling, then atomically renamed into place; the registry entry is written last under a per-scope lock. Nothing is mutated on failure.\n\nIdempotency: re-installing identical content is a no-op; different content requires `--force`.\n\n## Security model\n\n- **Install validation never executes plugin code.** Tool/hook names are manifest-declared; at runtime the loaded factory must return/register exactly the declared name/event or the surface is quarantined (`runtime_mismatch`).\n- **MCP policy** (install + runtime connect): HTTPS-only for `http`/`sse`; private/loopback/link-local/unique-local/multicast and the `169.254.169.254` metadata endpoint are denied across IPv4, IPv6, IPv4-mapped/compatible, zone-id and trailing-dot forms; URL credentials and CRLF headers are rejected; DNS is re-resolved before connect (rebinding defence). `stdio` servers are confined to the plugin root (allowed launchers `node`/`bun` or a root-confined executable; required bundled script argument; no eval/loader flags; no env expansion).\n- **Hooks** run through a *constrained* API: only a handler for the declared event may be registered. `registerCommand`, `sendMessage`, `appendEntry`, renderer registration, and shell `exec` are denied (`security_policy`). The broad first-party hook API is never exposed to bundle hooks.\n- **Appendices** render as lower-authority, delimited `` / `` blocks appended after the base/project prompt; size-capped (8 KiB/appendix, 32 KiB total) fail-closed; content is escaped and control-char sanitized. They can never override base/developer instructions.\n- **Hash drift**: installed files are re-verified against the registry at session start; any drift quarantines the plugin (`runtime_mismatch`).\n\n## Sub-skills: Tier-1 vs Tier-2\n\n- **Tier-1 advertisement** (metadata-only): when a parent skill/agent prompt is built, installed sub-skills bound to it are advertised as a bounded list (`plugin` / `name` / `description` / `activation_arg` / `phase`; max 12 items, 200-char descriptions, 4 KiB block, with an overflow note). No body content; rendered only in the target parent prompt, never the global public-workflow surface.\n- **Tier-2 activation** (full body): on explicit activation (e.g. `deep-interview --autoresearch`) or an agent's contextual choice, the full sub-skill body is injected as a `` block at the matching phase.\n\n## Registry, enablement, and quarantine\n\nEach scope keeps a durable `registry.json` recording per-plugin: name/version, source (`path`/`git`/`tarball` + ref/sha), manifest hash, copied files (relative path + sha256 — the uninstall ownership boundary), per-surface extension IDs, `enabled` flag, `disabledSurfaceIds`, and any `quarantine` entries.\n\nExtension IDs are stable: `tool:`, `hook::::`, `mcp:`, `system-appendix::`, `agent-appendix:::`, `subskill:::`. Disabled is user-controlled (not an error); quarantine is fail-closed and visible.\n\n## Status / scope notes\n\n- Always-on **tools**, **system appendices**, **agent appendices**, and **Tier-1 advertisement** activate at session start (additive; no-op when no bundle is installed).\n- **MCP runtime connection** and the **live hook runner** integration are gated behind the same validated registry + policy; consult the ledger/run notes for their wiring status.\n- Full enable/disable/uninstall/upgrade UX is a planned follow-up; the registry already records everything required for it (per-surface IDs + copied-file ownership).\n", "gjc-session-clawhip-routing.md": "# Human-owned GJC tmux sessions\n\nA tmux-hosted GJC TUI is a **human-only terminal surface**. It is not an external control or viewing API.\n\n## Human operator use\n\nA human operator may start an interactive TUI in a dedicated worktree for local terminal visibility:\n\n```sh\n./scripts/gjc-session/create.sh \n```\n\nThe person at that terminal interacts with the TUI directly. The helper retains durable, public owner-lifecycle receipts for local troubleshooting; it never accepts routed prompts, exposes pane output, or registers a machine observer.\n\n## External bots and machines\n\nAll external bots, machines, and automation must use a canonical external surface:\n\n- Coordinator MCP for bounded workflow control, turn status, questions, and reports.\n- ACP for an ACP client over the SDK-backed session surface.\n- The Gajae-Code SDK for authenticated lifecycle, control, and query operations.\n\nDo not inject prompts, scrape terminal output, or use tmux state as workflow evidence. Use Coordinator lifecycle events and SDK status for external decisions, notifications, and audit records.\n\n## Boundaries\n\n- Keep visible work in a dedicated worktree, never the shared canonical checkout.\n- Treat tmux existence and terminal output as human-only diagnostics.\n- Keep all bot credentials and routing configuration in the external Coordinator MCP/ACP/SDK deployment, not in the tmux helper.", - "gpt-5.6-codex-preset-benchmark.md": "# GPT-5.6 Codex preset benchmark\n\nThis report records descriptive local exact-edit evidence and the product judgments used to assign GPT-5.6 Sol, Terra, and Luna to GJC's built-in Codex-related model profiles.\n\n## Decision summary\n\nBuilt-in role assignments are product judgments. The selected TypeScript edit evidence below directly compares only bounded executor-style edits; it does not establish superiority, statistical significance, production reliability, or stability for any role.\n\n- **Eco**: `terra:low` default, `luna:low` executor, `luna:high` planner, `terra:xhigh` critic, and `terra:high` architect.\n- **Medium**: `sol:low` default, `terra:low` executor, `terra:high` planner, `sol:xhigh` critic, and `sol:high` architect.\n- **Pro**: `sol:medium` default, `terra:medium` executor, `sol:high` planner, `sol:max` critic, and `sol:xhigh` architect.\n- **Combos**: `opus-codex` uses the Medium Codex executor, critic, and architect roles, with the durable `anthropic/claude-sonnet-5` planner override; `codex-opencodego` uses Medium Codex default and architect roles; and `fable-opus-codex` uses Pro Codex executor and architect roles with `anthropic/claude-opus-4-8:medium` as planner.\n\nThe edit benchmark does not measure default-agent interpretation, orchestration, explanation, or routing, and it does not measure planner, architect, or critic work. Those non-executor assignments are product judgments, not benchmark findings.\n\n## Environment\n\n- Date: 2026-07-11\n- GJC provider: local `layofflabs` OpenAI Responses-compatible endpoint\n- Models: `gpt-5.6-luna`, `gpt-5.6-terra`, `gpt-5.6-sol`\n- Benchmark: `packages/typescript-edit-benchmark`\n- Verification: exact expected-file comparison after formatting normalization\n- Required tools: at least one `read` and one `edit` call per successful sample\n- Guided edits: disabled\n- Attempts: one per sample\n\nThe local provider recorded zero cost. The amounts below are non-billing list-price estimates calculated from the listed rates; they are not provider charges or production-cost predictions.\n\n| Model | Input / 1M | Output / 1M |\n|---|---:|---:|\n| Luna | $1.00 | $6.00 |\n| Terra | $2.50 | $15.00 |\n| Sol | $5.00 | $30.00 |\n\n## Initial broad sample\n\nThe first pass used eight mutation tasks with one run per task:\n\n- multi-location identifier replacement\n- call-argument swap\n- early-return removal\n- `if`/`else` structural swap\n- named-import swap\n- duplicate-line disambiguation\n- off-by-one literal correction\n- optional-chain removal\n\n| Setup | Tasks passed | Avg time/run | Input tokens | Output tokens | Est. cost |\n|---|---:|---:|---:|---:|---:|\n| Luna high | 6/8 | 54.8s | 2.86M | 10.8K | $2.92 |\n| Luna xhigh | 7/8 | 31.2s | 784K | 6.6K | $0.82 |\n| Terra high | 7/8 | 51.1s | 1.13M | 5.9K | $2.92 |\n| Terra xhigh | 8/8 | 50.9s | 820K | 5.9K | $2.14 |\n| Sol medium | 6/8 | 30.1s | 376K | 4.3K | $2.01 |\n\nIn this eight-task, one-attempt-per-task sample, Terra xhigh recorded 8/8 verified edits. Luna xhigh recorded 7/8; one run per task does not establish stability.\n\n## Repeated selected-task sample\n\nThe selected pass ran four discriminating TypeScript edit tasks three times each, scheduling 12 samples per setup:\n\n1. Remove the intended early return from a file containing several similar returns.\n2. Swap the intended `if`/`else` branches without changing nearby equivalent logic.\n3. Correct one specific off-by-one value among several plausible candidates.\n4. Remove the intended optional chain without modifying similar occurrences.\n\nThe confirmation command shape was:\n\n```sh\nbun --cwd=packages/typescript-edit-benchmark run start \\\n --model \"layofflabs/\" \\\n --thinking \"\" \\\n --runs 3 \\\n --task-concurrency 2 \\\n --timeout 180000 \\\n --max-turns 40 \\\n --tasks \"structural-remove-early-return-003,structural-swap-if-else-004,literal-off-by-one-003,access-remove-optional-chain-004\" \\\n --require-read-tool-call \\\n --require-edit-tool-call \\\n --format json\n```\n\n| Setup | Verified edits / recorded runs | Rate | Avg time | Input tokens | Output tokens | Est. list-price cost | Est. cost / verified edit |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| Luna high | 8/12 | 66.7% | 75.2s | 3.61M | 18.9K | $3.73 | $0.47 |\n| Luna xhigh | 9/12 | 75.0% | 80.5s | 6.60M | 25.0K | $6.75 | $0.75 |\n| Terra high | 6/11 | 54.5% | 58.9s | 572K | 10.0K | $1.58 | $0.26 |\n| Terra xhigh | 9/12 | 75.0% | 57.3s | 1.86M | 14.2K | $4.86 | $0.54 |\n| Sol medium | 4/12 | 33.3% | 46.3s | 558K | 10.1K | $3.09 | $0.77 |\n\nTerra high had one transport/ghost failure, so it has 11 recorded runs rather than 12 scheduled samples; its rate and cost per verified edit use those recorded results.\n\n## Findings\n\n### Terra xhigh's selected-task executor result\n\nAcross these four selected TypeScript edit tasks under the documented local setup, Terra xhigh and Luna xhigh each recorded 9/12 verified edits. Terra xhigh's reported totals were 72% fewer input tokens, 43% fewer output tokens, 28% less estimated list-price cost, and 29% less time than Luna xhigh. These descriptive results inform, but do not prove, the Terra xhigh executor assignment.\n\n### Luna remains useful, but not as the premium executor\n\nLuna xhigh recorded 7/8 in the broad sample and 9/12 in the selected-task sample. Luna high remains the Eco executor as a product judgment for that preset's lower-priced-family-member trade-off; these local runs do not establish a capability ceiling or production behavior.\n\n### Terra high's product assignment\n\nTerra high recorded 6/11 verified edits after one transport/ghost failure in the selected-task sample. Its planning and lower-stakes critic assignments are product judgments; this edit benchmark does not measure those roles.\n\n### Sol medium's product assignment\n\nSol medium recorded 4/12 verified edits in the selected-task sample and was faster with fewer reported input tokens than the other listed xhigh setups. Its `codex-medium` default-agent assignment and the Sol-family architecture assignments are product judgments because the benchmark does not measure those broader roles.\n\n### Higher effort is not automatically cheaper\n\nThe selected-task data show that Luna xhigh used more reported tokens than Luna high in this local setup. They do not establish a general cost rule for thinking effort; effort selection remains a product decision informed by model tier and role shape.\n\n## Resulting built-in profiles\n\n| Profile | Default | Executor | Planner | Critic | Architect |\n|---|---|---|---|---|---|\n| `codex-eco` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-luna:low` | `openai-codex/gpt-5.6-luna:high` | `openai-codex/gpt-5.6-terra:xhigh` | `openai-codex/gpt-5.6-terra:high` |\n| `codex-medium` | `openai-codex/gpt-5.6-sol:low` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-terra:high` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` |\n| `codex-pro` | `openai-codex/gpt-5.6-sol:medium` | `openai-codex/gpt-5.6-terra:medium` | `openai-codex/gpt-5.6-sol:high` | `openai-codex/gpt-5.6-sol:max` | `openai-codex/gpt-5.6-sol:xhigh` |\n| `opus-codex` | `anthropic/claude-opus-4-8:xhigh` | `openai-codex/gpt-5.6-terra:low` | `anthropic/claude-sonnet-5` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` |\n| `codex-opencodego` | `openai-codex/gpt-5.6-sol:low` | `opencode-go/deepseek-v4-pro` | `opencode-go/kimi-k2.6` | `opencode-go/mimo-v2.5-pro` | `openai-codex/gpt-5.6-sol:high` |\n| `fable-opus-codex` | `anthropic/claude-fable-5:high` | `openai-codex/gpt-5.6-terra:medium` | `anthropic/claude-opus-4-8:medium` | `anthropic/claude-opus-4-8:high` | `openai-codex/gpt-5.6-sol:xhigh` |\n\n## Limitations\n\n- The benchmark measures four selected precise TypeScript source mutations in the repeated sample, not full-session planning, architecture, criticism, or default-agent quality.\n- The corpus is small and intentionally adversarial; the results are descriptive, not statistically significant or a proof of general superiority, production reliability, or stability.\n- Samples used a local OpenAI-compatible provider rather than OpenAI's production endpoint.\n- Terra high has 11 recorded runs because one of 12 scheduled samples ended in a transport/ghost failure.\n- Token accounting reflects the local transport and benchmark context construction. The provider recorded zero cost; displayed costs are rounded list-price estimates, not billing predictions.\n- Model behavior can change as provider snapshots are updated.\n\nThe raw JSON reports and conversation dumps were generated under `runs/gpt-5.6-local-2026-07-11/` and `runs/gpt-5.6-confirmation-2026-07-11/`, but are not committed. The committed tables support the displayed denominators and rounded comparisons, not reconstruction of unrounded token totals or list-price estimates.\n", + "gpt-5.6-codex-preset-benchmark.md": "# GPT-5.6 Codex preset benchmark\n\nThis report records descriptive local exact-edit evidence and the product judgments used to assign GPT-5.6 Sol, Terra, and Luna to GJC's built-in Codex-related model profiles.\n\n## Decision summary\n\nBuilt-in role assignments are product judgments. The selected TypeScript edit evidence below directly compares only bounded executor-style edits; it does not establish superiority, statistical significance, production reliability, or stability for any role.\n\n- **Eco**: `terra:low` default, `luna:low` executor, `luna:high` planner, `terra:xhigh` critic, and `terra:high` architect.\n- **Medium**: `sol:low` default, `terra:low` executor, `terra:high` planner, `sol:xhigh` critic, and `sol:high` architect.\n- **Pro**: `sol:medium` default, `terra:medium` executor, `sol:high` planner, `sol:max` critic, and `sol:xhigh` architect.\n- **Combos**: `opus-codex` uses the Medium Codex executor, critic, and architect roles, with the durable `anthropic/claude-sonnet-5` planner override; `codex-opencodego` uses Medium Codex default and architect roles; and `fable-opus-codex` uses Pro Codex executor and architect roles with `anthropic/claude-opus-5:medium` as planner.\n\nThe edit benchmark does not measure default-agent interpretation, orchestration, explanation, or routing, and it does not measure planner, architect, or critic work. Those non-executor assignments are product judgments, not benchmark findings.\n\n## Environment\n\n- Date: 2026-07-11\n- GJC provider: local `layofflabs` OpenAI Responses-compatible endpoint\n- Models: `gpt-5.6-luna`, `gpt-5.6-terra`, `gpt-5.6-sol`\n- Benchmark: `packages/typescript-edit-benchmark`\n- Verification: exact expected-file comparison after formatting normalization\n- Required tools: at least one `read` and one `edit` call per successful sample\n- Guided edits: disabled\n- Attempts: one per sample\n\nThe local provider recorded zero cost. The amounts below are non-billing list-price estimates calculated from the listed rates; they are not provider charges or production-cost predictions.\n\n| Model | Input / 1M | Output / 1M |\n|---|---:|---:|\n| Luna | $1.00 | $6.00 |\n| Terra | $2.50 | $15.00 |\n| Sol | $5.00 | $30.00 |\n\n## Initial broad sample\n\nThe first pass used eight mutation tasks with one run per task:\n\n- multi-location identifier replacement\n- call-argument swap\n- early-return removal\n- `if`/`else` structural swap\n- named-import swap\n- duplicate-line disambiguation\n- off-by-one literal correction\n- optional-chain removal\n\n| Setup | Tasks passed | Avg time/run | Input tokens | Output tokens | Est. cost |\n|---|---:|---:|---:|---:|---:|\n| Luna high | 6/8 | 54.8s | 2.86M | 10.8K | $2.92 |\n| Luna xhigh | 7/8 | 31.2s | 784K | 6.6K | $0.82 |\n| Terra high | 7/8 | 51.1s | 1.13M | 5.9K | $2.92 |\n| Terra xhigh | 8/8 | 50.9s | 820K | 5.9K | $2.14 |\n| Sol medium | 6/8 | 30.1s | 376K | 4.3K | $2.01 |\n\nIn this eight-task, one-attempt-per-task sample, Terra xhigh recorded 8/8 verified edits. Luna xhigh recorded 7/8; one run per task does not establish stability.\n\n## Repeated selected-task sample\n\nThe selected pass ran four discriminating TypeScript edit tasks three times each, scheduling 12 samples per setup:\n\n1. Remove the intended early return from a file containing several similar returns.\n2. Swap the intended `if`/`else` branches without changing nearby equivalent logic.\n3. Correct one specific off-by-one value among several plausible candidates.\n4. Remove the intended optional chain without modifying similar occurrences.\n\nThe confirmation command shape was:\n\n```sh\nbun --cwd=packages/typescript-edit-benchmark run start \\\n --model \"layofflabs/\" \\\n --thinking \"\" \\\n --runs 3 \\\n --task-concurrency 2 \\\n --timeout 180000 \\\n --max-turns 40 \\\n --tasks \"structural-remove-early-return-003,structural-swap-if-else-004,literal-off-by-one-003,access-remove-optional-chain-004\" \\\n --require-read-tool-call \\\n --require-edit-tool-call \\\n --format json\n```\n\n| Setup | Verified edits / recorded runs | Rate | Avg time | Input tokens | Output tokens | Est. list-price cost | Est. cost / verified edit |\n|---|---:|---:|---:|---:|---:|---:|---:|\n| Luna high | 8/12 | 66.7% | 75.2s | 3.61M | 18.9K | $3.73 | $0.47 |\n| Luna xhigh | 9/12 | 75.0% | 80.5s | 6.60M | 25.0K | $6.75 | $0.75 |\n| Terra high | 6/11 | 54.5% | 58.9s | 572K | 10.0K | $1.58 | $0.26 |\n| Terra xhigh | 9/12 | 75.0% | 57.3s | 1.86M | 14.2K | $4.86 | $0.54 |\n| Sol medium | 4/12 | 33.3% | 46.3s | 558K | 10.1K | $3.09 | $0.77 |\n\nTerra high had one transport/ghost failure, so it has 11 recorded runs rather than 12 scheduled samples; its rate and cost per verified edit use those recorded results.\n\n## Findings\n\n### Terra xhigh's selected-task executor result\n\nAcross these four selected TypeScript edit tasks under the documented local setup, Terra xhigh and Luna xhigh each recorded 9/12 verified edits. Terra xhigh's reported totals were 72% fewer input tokens, 43% fewer output tokens, 28% less estimated list-price cost, and 29% less time than Luna xhigh. These descriptive results inform, but do not prove, the Terra xhigh executor assignment.\n\n### Luna remains useful, but not as the premium executor\n\nLuna xhigh recorded 7/8 in the broad sample and 9/12 in the selected-task sample. Luna high remains the Eco executor as a product judgment for that preset's lower-priced-family-member trade-off; these local runs do not establish a capability ceiling or production behavior.\n\n### Terra high's product assignment\n\nTerra high recorded 6/11 verified edits after one transport/ghost failure in the selected-task sample. Its planning and lower-stakes critic assignments are product judgments; this edit benchmark does not measure those roles.\n\n### Sol medium's product assignment\n\nSol medium recorded 4/12 verified edits in the selected-task sample and was faster with fewer reported input tokens than the other listed xhigh setups. Its `codex-medium` default-agent assignment and the Sol-family architecture assignments are product judgments because the benchmark does not measure those broader roles.\n\n### Higher effort is not automatically cheaper\n\nThe selected-task data show that Luna xhigh used more reported tokens than Luna high in this local setup. They do not establish a general cost rule for thinking effort; effort selection remains a product decision informed by model tier and role shape.\n\n## Resulting built-in profiles\n\n| Profile | Default | Executor | Planner | Critic | Architect |\n|---|---|---|---|---|---|\n| `codex-eco` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-luna:low` | `openai-codex/gpt-5.6-luna:high` | `openai-codex/gpt-5.6-terra:xhigh` | `openai-codex/gpt-5.6-terra:high` |\n| `codex-medium` | `openai-codex/gpt-5.6-sol:low` | `openai-codex/gpt-5.6-terra:low` | `openai-codex/gpt-5.6-terra:high` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` |\n| `codex-pro` | `openai-codex/gpt-5.6-sol:medium` | `openai-codex/gpt-5.6-terra:medium` | `openai-codex/gpt-5.6-sol:high` | `openai-codex/gpt-5.6-sol:max` | `openai-codex/gpt-5.6-sol:xhigh` |\n| `opus-codex` | `anthropic/claude-opus-5:xhigh` | `openai-codex/gpt-5.6-terra:low` | `anthropic/claude-sonnet-5` | `openai-codex/gpt-5.6-sol:xhigh` | `openai-codex/gpt-5.6-sol:high` |\n| `codex-opencodego` | `openai-codex/gpt-5.6-sol:low` | `opencode-go/deepseek-v4-pro` | `opencode-go/kimi-k2.6` | `opencode-go/mimo-v2.5-pro` | `openai-codex/gpt-5.6-sol:high` |\n| `fable-opus-codex` | `anthropic/claude-fable-5:high` | `openai-codex/gpt-5.6-terra:medium` | `anthropic/claude-opus-5:medium` | `anthropic/claude-opus-5:high` | `openai-codex/gpt-5.6-sol:xhigh` |\n\n## Limitations\n\n- The benchmark measures four selected precise TypeScript source mutations in the repeated sample, not full-session planning, architecture, criticism, or default-agent quality.\n- The corpus is small and intentionally adversarial; the results are descriptive, not statistically significant or a proof of general superiority, production reliability, or stability.\n- Samples used a local OpenAI-compatible provider rather than OpenAI's production endpoint.\n- Terra high has 11 recorded runs because one of 12 scheduled samples ended in a transport/ghost failure.\n- Token accounting reflects the local transport and benchmark context construction. The provider recorded zero cost; displayed costs are rounded list-price estimates, not billing predictions.\n- Model behavior can change as provider snapshots are updated.\n\nThe raw JSON reports and conversation dumps were generated under `runs/gpt-5.6-local-2026-07-11/` and `runs/gpt-5.6-confirmation-2026-07-11/`, but are not committed. The committed tables support the displayed denominators and rounded comparisons, not reconstruction of unrounded token totals or list-price estimates.\n", "grok-build-provider-design.md": "# Grok Build provider design\n\n## Status\n\nProposal for maintainer design review. This document intentionally does not add a bundled provider implementation. It records the product/API decisions that must be accepted before any Grok Build implementation PR should land.\n\nThis is not an authorization claim for xAI endpoints, not a final naming decision, not approval for a bundled-loading exception, and not trademark/display-name approval. Those items require explicit owner sign-off before implementation.\n\n## Required owner sign-off gates\n\nImplementation should remain blocked until the owner signs off on these gates:\n\n1. **Authorized use / ToS** — confirm that GJC may use `cli-chat-proxy.grok.com` and the xAI CLI OAuth public client from a third-party tool. A public OAuth client id is not proof that this use is authorized.\n2. **Bundled-loading trust boundary** — confirm whether a source-controlled bundled provider may load even when ordinary user extension discovery is disabled.\n3. **Public selector naming** — choose the stable provider selector prefix: `grok-cli`, `grok-build`, or another owner-selected id.\n4. **Trademark/display-name** — confirm whether GJC may present the provider/profile using `Grok Build` or should use a more neutral owner-approved label.\n\nIf gate 1 is not accepted, the Grok Build provider implementation should not ship against `cli-chat-proxy.grok.com`. The fallback direction would be a documented user-supplied xAI/API-key provider or a different officially authorized integration path.\n\n## Problem\n\nGJC can load third-party extensions, but the first-run interactive path needs a maintainer-owned decision before a bundled Grok Build provider can be accepted. The desired product flow is:\n\n```text\ngjc -> /login -> OAuth -> Grok Build -> browser xAI login -> /model -> /grok-composer-2.5-fast\n```\n\nThe previously proposed implementation touched bundled extension loading, OAuth registration, model profiles, vendor code, usage reporting, and tests in one PR. That is too much surface for review without first agreeing on the provider contract and the owner sign-off gates above.\n\n## Goals\n\n- Keep Grok Build, if accepted, as a bundled provider extension rather than a workflow skill.\n- Preserve the existing four bundled workflow skills and four role agents.\n- Define the `/login` OAuth contract for an owner-approved display name, with `Grok Build` only as a candidate label.\n- Define the `/model` contract for `grok-composer-2.5-fast` without committing to the final selector prefix before owner sign-off.\n- Define the guardrails for any bundled provider that loads while ordinary extension discovery is disabled.\n- Keep credentials in the existing auth storage path; no tokens or user env values are checked into the repo.\n- Keep implementation PRs small enough for independent review, rejection, or rollback.\n\n## Non-goals\n\n- No new workflow command or `/skill` surface.\n- No automatic installation from npm or remote code at runtime.\n- No direct `packages/ai/src/models.json` edits.\n- No broad model-profile reshuffle.\n- No provider-specific secrets in source.\n- No claim that xAI has authorized this endpoint/client usage without owner review.\n\n## Candidate provider contract\n\nThese are candidate values for owner review, not final commitments:\n\n| Field | Candidate value | Decision status | Notes |\n| --- | --- | --- | --- |\n| Public provider id | `grok-cli` or `grok-build` | **Owner decision required** | See naming section below. |\n| Display name | `Grok Build` or owner-selected label | **Owner decision required** | Name shown in `/login` and UI surfaces; see trademark/display-name section below. |\n| Default model id | `grok-composer-2.5-fast` | Proposed | Full selector depends on final provider id. |\n| Secondary model id | `grok-build` | Proposed | Candidate for executor/architect roles if a profile is accepted. |\n| Base URL | `https://cli-chat-proxy.grok.com/v1` | **Authorized-use sign-off required** | Undocumented/private-looking endpoint; do not ship without owner approval. |\n| OAuth issuer | `https://auth.x.ai` | **Authorized-use sign-off required** | OIDC discovery must validate xAI-owned HTTPS endpoints. |\n| OAuth callback | loopback `127.0.0.1` | Proposed | Uses PKCE + state validation. |\n| API adapter | `grok-cli-responses` | Proposed internal name | Provider-specific stream adapter; not a new generic API shape. |\n| Env bypass | `GROK_CLI_OAUTH_TOKEN` | Optional follow-up | Local bypass only; no refresh or discovery guarantees. |\n\n## Authorized-use and ToS caveat\n\n`cli-chat-proxy.grok.com` and the xAI CLI OAuth public client appear to be designed for xAI/Grok CLI traffic. Reusing them from GJC may be technically possible but still unauthorized or contrary to xAI terms.\n\nBefore implementation, the owner should explicitly decide one of:\n\n- **Accept** — proceed with this integration after reviewing the legal/product risk.\n- **Defer** — keep this design document only; no code ships until authorization is clarified.\n- **Reject** — do not integrate against `cli-chat-proxy.grok.com`; use only an official public API path.\n\nImplementation PRs must not describe the public client id as a secret, but they also must not present it as authorization. Tests should avoid real tokens and should not require an xAI account.\n\n## Trademark/display-name caveat\n\n`Grok` and `xAI` are third-party marks. `Grok Build` may also imply an official xAI/Grok product relationship even when the integration is third-party. Before implementation, the owner should explicitly choose one of:\n\n- **Use `Grok Build`** — acceptable as the user-facing provider/profile label after trademark/product-risk review.\n- **Use a neutral label** — for example `xAI Grok`, `Grok OAuth`, or another owner-selected name that avoids implying official endorsement.\n- **Avoid built-in branding** — keep any Grok-specific naming only in user-provided configuration until authorization/branding is clarified.\n\nImplementation PRs should avoid lock-in language such as \"official\" unless there is explicit authorization. UI labels, profile names, docs, tests, and screenshots must all use the owner-approved label consistently.\n\n## OAuth behavior\n\nIf authorized-use is accepted, the OAuth implementation should use the existing custom OAuth provider path:\n\n1. The chosen provider id registers an OAuth provider using the owner-approved display name.\n2. `/login` calls the existing auth storage login path for that provider.\n3. The provider opens an xAI authorization URL using OIDC discovery, PKCE, `state`, and a loopback callback.\n4. The callback exchanges the authorization code for access and refresh tokens.\n5. Credentials are stored by the existing auth storage code path.\n6. Refresh uses the stored refresh token and validates the token endpoint origin.\n\nSecurity constraints:\n\n- OIDC `authorization_endpoint` and `token_endpoint` must be HTTPS and under owner-approved xAI hosts.\n- The callback server binds to loopback by default.\n- The callback must reject state mismatches.\n- Access and refresh tokens must not be logged, rendered, committed, or included in tests.\n- Error messages may include status and provider error text, but not credential values.\n- Env overrides for base URL, scope, callback host, or client id must be treated as local developer/debug escape hatches, not default product behavior.\n\n## Bundled-loading trust boundary\n\nA bundled provider is different from ordinary user extension discovery, but loading it while `disableExtensionDiscovery: true` still expands the bootstrap trust boundary. Owner sign-off is required before implementation.\n\nMinimum guardrails if accepted:\n\n- Load only source-controlled, maintainer-reviewed bundled provider paths.\n- Use a static allowlist or exported enumerator; never scan arbitrary user directories for this path.\n- Do not install, fetch, or resolve remote package code at runtime.\n- Keep ordinary user extension discovery disabled when `disableExtensionDiscovery: true`; the exception is only for bundled provider defaults.\n- Add tests proving bundled providers load before model selection and caller-supplied `additionalExtensionPaths` still coexist.\n- Keep this bootstrap change separate from the Grok vendor implementation so it can be reviewed independently.\n\nAlternatives the owner may choose:\n\n- Do not load bundled providers when extension discovery is disabled; require explicit setup/defaults install.\n- Gate bundled provider loading behind a setting or compile-time default.\n- Allow bundled loading only in packaged builds, not arbitrary source checkouts.\n\n## Provider selector naming\n\nThe selector prefix is a stable user-facing contract and must be chosen before implementation.\n\n| Option | Example selector | Pros | Cons |\n| --- | --- | --- | --- |\n| `grok-cli` | `grok-cli/grok-composer-2.5-fast` | Matches the upstream CLI/proxy lineage and existing prototype. | User-facing name is less aligned with `Grok Build`; may expose implementation detail. |\n| `grok-build` | `grok-build/grok-composer-2.5-fast` | Matches UI label and requested product wording. | Diverges from existing prototype and env names; migration needed if prototypes used `grok-cli`. |\n| Owner-selected third id | `/grok-composer-2.5-fast` | Lets maintainers align with broader provider taxonomy. | Requires updating all docs/tests before implementation. |\n\nUntil this is decided, implementation docs and PRs should use `` when describing the public selector. Internal adapter names may still use `grok-cli-responses` if maintainers accept that as an implementation detail.\n\n## Model/profile behavior\n\nModel registration should be provider-owned. If accepted, the provider should register at least:\n\n- `grok-composer-2.5-fast`\n- `grok-build`\n\nA built-in profile is optional and should be reviewed separately. If accepted, a candidate profile is:\n\n```text\ngrok-pro.default -> /grok-composer-2.5-fast\ngrok-pro.planner -> /grok-composer-2.5-fast\ngrok-pro.critic -> /grok-composer-2.5-fast\ngrok-pro.executor -> /grok-build\ngrok-pro.architect -> /grok-build\n```\n\nIf maintainers prefer not to add a built-in profile, the provider can still satisfy the core `/login` and `/model` flow through direct model selection.\n\n## Usage reporting behavior\n\nUsage reporting should be an optional follow-up after login/model support lands:\n\n- Provider id: the owner-selected ``.\n- Fetches usage with the effective OAuth access token.\n- Returns `null` when no token is available.\n- Does not require the usage provider for chat/model selection to work.\n- Should be skipped entirely if the authorized-use gate is not accepted.\n\n## Staged PR plan\n\n### PR 1: this design document\n\nPurpose: agree on caveats, owner sign-off gates, provider id, OAuth contract, bundled-loading trust boundary, model selector, security boundaries, and implementation split.\n\n### PR 2: bundled provider bootstrap contract\n\nSmall core change only, after owner sign-off on the bundled-loading gate:\n\n- Add a maintainer-owned way to enumerate bundled provider extension paths.\n- Load those paths during session/bootstrap only under the accepted guardrails.\n- Add tests proving bundled providers and caller-supplied extension paths coexist.\n\nNo Grok vendor implementation in this PR.\n\n### PR 3: Grok Build provider extension\n\nProvider implementation only, after owner sign-off on authorized use, public selector naming, and trademark/display-name:\n\n- Add bundled Grok Build provider source.\n- Register the chosen provider id, OAuth provider, and models.\n- Include sanitize and provider-specific stream handling.\n- Test `/login` provider registration and `grok-composer-2.5-fast` model availability.\n\n### PR 4: profile and model defaults\n\nOptional product-surface PR:\n\n- Add `grok-pro` only if maintainers accept a built-in profile.\n- Add model profile catalog tests.\n\n### PR 5: usage reporting\n\nOptional observability PR:\n\n- Add usage provider for the owner-selected provider id.\n- Add focused usage tests.\n\n## Acceptance criteria for the implementation series\n\n- Owner sign-off is recorded for authorized use, bundled loading, selector naming, and trademark/display-name before implementation lands.\n- Fresh checkout test proves `createAgentSession` registers the bundled provider under the accepted bootstrap rules.\n- `/login` includes the owner-approved display name for the owner-selected provider id.\n- `/model` includes `/grok-composer-2.5-fast`.\n- A real OAuth URL redirects to the owner-approved xAI account login page.\n- Third-party extension paths still load alongside bundled providers when configured.\n- Token values never appear in tests, logs, checked-in docs, or git history.\n\n## Open maintainer decisions\n\n- Is using `cli-chat-proxy.grok.com` plus the xAI CLI OAuth client from GJC authorized and acceptable for this project?\n- Should bundled provider defaults load while `disableExtensionDiscovery: true`, and under which guardrails?\n- Should the final public provider id be `grok-cli`, `grok-build`, or another id?\n- May GJC use `Grok Build` as the display/profile name, or should the integration use a neutral owner-selected label?\n- Should `grok-pro` be a built-in profile or documented as a user profile?\n- Should usage reporting be included in the initial provider PR or kept as a separate follow-up?", "handoff-generation-pipeline.md": "# `/handoff` generation pipeline\n\nThis document describes how the coding-agent implements `/handoff`: trigger path, oneshot generation, session switch, context reinjection, persistence, and UI behavior.\n\n## Scope\n\nCovers:\n\n- Interactive `/handoff` command dispatch\n- `AgentSession.handoff()` lifecycle and state transitions\n- `generateHandoff(...)` request shape\n- How old/new sessions persist handoff data differently\n- UI behavior for success, cancel, and failure\n\nDoes not cover:\n\n- Generic tree navigation/branch internals\n- Non-handoff session commands (`/new`, `/fork`, `/resume`)\n\n## Implementation files\n\n- [`../src/modes/controllers/input-controller.ts`](../packages/coding-agent/src/modes/controllers/input-controller.ts)\n- [`../src/modes/controllers/command-controller.ts`](../packages/coding-agent/src/modes/controllers/command-controller.ts)\n- [`../src/session/agent-session.ts`](../packages/coding-agent/src/session/agent-session.ts)\n- [`packages/agent/src/compaction/compaction.ts`](../packages/agent/src/compaction/compaction.ts)\n- [`../src/session/session-manager.ts`](../packages/coding-agent/src/session/session-manager.ts)\n- [`../src/extensibility/slash-commands.ts`](../packages/coding-agent/src/extensibility/slash-commands.ts)\n\n## Trigger path\n\n1. `/handoff` is declared in builtin slash command metadata (`slash-commands.ts`) with optional inline hint: `[focus instructions]`.\n2. In interactive input handling (`InputController`), submit text matching `/handoff` or `/handoff ...` is intercepted before normal prompt submission.\n3. The editor is cleared and `handleHandoffCommand(customInstructions?)` is called.\n4. `CommandController.handleHandoffCommand` performs a preflight guard using current entries:\n - Counts `type === \"message\"` entries.\n - If `< 2`, it warns: `Nothing to hand off (no messages yet)` and returns.\n\nThe same minimum-content guard exists again inside `AgentSession.handoff()` and throws if violated. This duplicates safety at both UI and session layers.\n\n## End-to-end lifecycle\n\n### 1) Start handoff generation\n\n`AgentSession.handoff(customInstructions?)`:\n\n- Reads current branch entries (`sessionManager.getBranch()`).\n- Validates minimum message count (`>= 2`).\n- Creates `#handoffAbortController` and links any caller-provided abort signal to it.\n- Resolves the current model API key through `ModelRegistry`.\n- Calls `generateHandoff(...)` with:\n - live agent messages (`agent.state.messages`),\n - the current model and API key,\n - the base system prompt (`#baseSystemPrompt`),\n - the live tool array (`agent.state.tools`),\n - optional focus instructions,\n - coding-agent message conversion (`convertToLlm`),\n - provider metadata and `initiatorOverride: \"agent\"`.\n\n`generateHandoff(...)` lives in `packages/agent/src/compaction/compaction.ts` next to summarization. It renders `packages/agent/src/compaction/prompts/handoff-document.md` via `renderHandoffPrompt(...)` with optional `additionalFocus`.\n\n### 2) Generate and capture output\n\n`generateHandoff(...)` converts the existing `AgentMessage[]` history to real LLM `Message[]` history, then appends one trailing agent-attributed `user` message containing the rendered handoff prompt.\n\nThe request uses `completeSimple(...)` directly:\n\n```ts\nawait completeSimple(\n model,\n {\n systemPrompt,\n messages: requestMessages,\n tools,\n },\n {\n apiKey,\n signal,\n reasoning: Effort.High,\n toolChoice: \"none\",\n initiatorOverride,\n metadata,\n },\n);\n```\n\nImportant generation properties:\n\n- The request preserves the live provider cache prefix by reusing the same system prompt, tool definitions, and real message history shape as the active agent.\n- The handoff instruction is a trailing `user` message, not a developer message, so the cached prefix remains aligned with the prior turn.\n- `toolChoice: \"none\"` prevents intentional tool dispatch.\n- The returned assistant content is filtered to text blocks and joined with `\\n`; stray tool-call blocks are ignored if a provider does not honor `toolChoice: \"none\"`.\n- `stopReason === \"error\"` throws a generation error.\n\nNo agent-loop events are used for capture. The handoff path no longer waits for `agent_end` and no longer scans the latest assistant message.\n\n### 3) Cancellation checks\n\nCancellation throws `Error(\"Handoff cancelled\")`; a completed generation with no text returns `undefined`.\n\n- caller signal aborts `#handoffAbortController`\n- `completeSimple(...)` receives the abort signal\n- aborted handoff signal or provider `AbortError` is normalized to `Error(\"Handoff cancelled\")`\n- empty generated text returns `undefined`\n\n`AgentSession.handoff()` always clears `#handoffAbortController` in `finally`.\n\n### 4) New session creation\n\nIf text was generated and not aborted:\n\n1. Flush current session writer (`sessionManager.flush()`).\n2. Cancel session-owned async jobs.\n3. Start a brand-new session with `parentSession` pointing at the previous session file when one exists.\n4. Reset in-memory agent state (`agent.reset()`).\n5. Rebind `agent.sessionId` to the new session id.\n6. Rekey/reset hindsight state for the new session.\n7. Clear queued context arrays (`#steeringMessages`, `#followUpMessages`, `#pendingNextTurnMessages`) and any scheduled hidden next-turn generation.\n8. Reset todo reminder counter.\n\n### 5) Handoff-context injection\n\nThe generated handoff document is wrapped by coding-agent session glue and appended to the new session as a `custom_message` entry:\n\n```text\n\n...handoff text...\n\n\nThe above is a handoff document from a previous session. Use this context to continue the work seamlessly.\n```\n\nInsertion call:\n\n```ts\nthis.sessionManager.appendCustomMessageEntry(\"handoff\", handoffContent, true, undefined, \"agent\");\n```\n\nSemantics:\n\n- `customType`: `\"handoff\"`\n- `display`: `true` (visible in TUI rebuild)\n- attribution: `\"agent\"`\n- Entry type: `custom_message` (participates in LLM context)\n\n### 6) Rebuild active agent context\n\nAfter injection:\n\n1. `buildDisplaySessionContext()` resolves message list for current leaf.\n2. `agent.replaceMessages(sessionContext.messages)` makes the injected handoff message active context.\n3. Todo phases are synchronized from the new branch.\n4. Method returns `{ document: handoffText, savedPath? }`.\n\nAt this point, the active LLM context in the new session contains the injected handoff message, not the old transcript.\n\n## Persistence model: old session vs new session\n\n### Old session\n\nHandoff generation is a oneshot request, not a visible agent turn. The generated handoff text is not appended to the old session as an assistant message.\n\nResult: the original session keeps its prior transcript unchanged except for data already persisted before handoff began.\n\n### New session\n\nAfter session reset, handoff is persisted as `custom_message` with `customType: \"handoff\"`.\n\n`buildSessionContext()` converts this entry into a runtime custom/user-context message via `createCustomMessage(...)`, so it is included in future prompts from the new session.\n\nAuto-triggered handoffs can additionally save the handoff document as a session artifact when `compaction.handoffSaveToDisk` is enabled; `handoff()` returns its resolvable `artifact://` URI as `savedPath`. Manual `/handoff` does not save an artifact.\n\n## Controller/UI behavior\n\n`CommandController.handleHandoffCommand` behavior:\n\n- Shows a status loader: `Generating handoff… (esc to cancel)`.\n- Calls `await session.handoff(customInstructions)`.\n- If result is `undefined`: `showError(\"Handoff cancelled\")`.\n- On success:\n - `rebuildChatFromMessages()` (loads new session context, including injected handoff)\n - invalidates status line and editor top border\n - reloads todos\n - appends success chat line: `New session started with handoff context`\n- On exception:\n - if message is `\"Handoff cancelled\"` or error name is `AbortError`: `showError(\"Handoff cancelled\")`\n - otherwise: `showError(\"Handoff failed: \")`\n- Stops the loader, restores the previous Escape handler, and requests render at end.\n\nManual `/handoff` no longer streams the generated document into chat. A cancellable loader remains visible while the oneshot request runs, and the chat is rebuilt after generation completes.\n\n## Cancellation semantics\n\n### Session-level cancellation primitive\n\n`AgentSession` exposes:\n\n- `abortHandoff()` → aborts `#handoffAbortController`\n- `isGeneratingHandoff` → true while controller exists\n\nWhen this abort path is used, the abort signal is passed to `completeSimple(...)`; `handoff()` normalizes the cancellation to `Error(\"Handoff cancelled\")`, and command controller maps it to cancellation UI.\n\n### Interactive `/handoff` path\n\nThe command controller installs a temporary Escape handler for `/handoff` while the loader is visible. Pressing Escape calls `session.abortHandoff()`, which aborts the `completeSimple(...)` request through `#handoffAbortController`.\n\n## Aborted vs failed handoff\n\nCurrent UI classification:\n\n- **Aborted/cancelled**\n - `abortHandoff()` path triggers `\"Handoff cancelled\"`, or\n - thrown `AbortError`\n - UI shows `Handoff cancelled`\n- **Failed**\n - any other thrown error from `handoff()` / `generateHandoff()` / provider request path\n - UI shows `Handoff failed: ...`\n\nAdditional nuance: if generation completes but no text is returned, `handoff()` returns `undefined` and controller currently reports **cancelled**, not **failed**.\n\n## Short-session and minimum-content guardrails\n\nTwo guards prevent low-signal handoffs:\n\n- UI layer (`handleHandoffCommand`): warns and returns early for `< 2` message entries\n- Session layer (`handoff()`): throws the same condition as an error\n\nThis avoids creating a new session with empty/near-empty handoff context.\n\n## Concurrency: the shared session-transition lease\n\n`handoff()` does not run concurrently with any other session-identity transition.\nA single synchronously-acquired lease (`#beginSessionTransition` / `#endSessionTransition`)\nserializes every operation that replaces or rewrites session identity/history:\n\n- `handoff()`\n- `compact()`\n- `newSession()` / `switchSession()` / `branch()` / `clearContext()`\n- `fork()`\n- `navigateTree()`\n\nEach of these acquires the lease at its entry (before its first `await`) and releases\nit in its `finally`. Because acquisition is synchronous and up front, exclusion is\n**symmetric**: whichever transition starts first owns the lease, and any peer that\nstarts while it is held is rejected with an `Error` carrying `code: \"busy\"` and a\nmessage of the form `Cannot start while a transition is in progress.`\nThe rejection happens at the peer's own lease-acquisition point, i.e. **before any\nsession mutation**, so a losing transition never partially mutates the session.\n\nAuto-triggered handoff acquires the lease through `handoff()` itself; the maintenance\norchestrator does not hold the lease, so an auto-handoff running inside post-turn\nmaintenance does not self-deadlock even while auto-compaction owns its own abort\ncontroller.\n\nThis lease is distinct from the turn-start guard (`#assertNoHandoffTransition`), which\nfences external turn starters (prompt / steer / follow-up / continuation) for the whole\nhandoff transition and rejects them with `Cannot start a turn while a handoff is in progress.`\n\n## State transition summary\n\nHigh-level state flow:\n\n1. Interactive slash command intercepted.\n2. Preflight message-count guard.\n3. `#handoffAbortController` created (`isGeneratingHandoff = true`).\n4. `generateHandoff(...)` issues one `completeSimple(...)` request with live system prompt, tools, message history, and trailing handoff prompt.\n5. Assistant response text blocks are joined; tool-call blocks are discarded.\n6. If missing text → return `undefined`; if aborted → cancellation error path.\n7. If present:\n - flush old session\n - cancel async jobs\n - create new empty session with previous session as parent\n - reset runtime queues/counters\n - append `custom_message(handoff)`\n - optionally save an auto-triggered handoff document under the session artifacts directory when `compaction.handoffSaveToDisk` is enabled\n8. Controller rebuilds chat UI and announces success.\n9. `#handoffAbortController` cleared (`isGeneratingHandoff = false`).\n\n## Known assumptions and limitations\n\n- No structural validation checks that generated markdown follows the requested section format.\n- Missing generated text is reported as cancellation in controller UX.\n- Manual handoff has no streaming visibility; a cancellable loader is shown until the UI updates after generation completes.\n- Auto-triggered handoffs can save the handoff document as a session artifact (`artifact://`) when `compaction.handoffSaveToDisk` is enabled; save failure is logged and does not fail the handoff.\n", "hermes-mcp-bridge.md": "# Coordinator MCP bridge\n\nGJC exposes a native outward MCP bridge for external coordinators:\n\n```bash\ngjc mcp-serve coordinator\n```\n\n`gjc mcp-serve hermes` is accepted as a compatibility alias for the same coordinator bridge.\n\nThe bridge is intentionally separate from GJC's client-side MCP runtime. It lets an external coordinator discover and control SDK-backed sessions, queue bounded follow-up prompts, read status/artifacts, handle structured questions, and write coordination reports without scraping terminal scrollback.\n\n## Core contract and adapters\n\nThe coordinator bridge is intentionally a core contract with multiple adapters, not an MCP-only or Hermes-only product direction. Hermes is one compatibility preset, not a privileged integration mode:\n\n- `packages/coding-agent/src/coordinator/contract.ts` owns transport-neutral server metadata and tool names.\n- `gjc mcp-serve coordinator` is the outward MCP adapter for external agents.\n- `gjc coordinator` is the read-only CLI/debug adapter for humans and scripts that need to inspect the same contract without starting MCP transport.\n- `gjc setup hermes` is the compatibility setup adapter that renders coordinator config and operator guidance.\n\nFuture session, turn, question, artifact, and report behavior should move toward shared coordinator core services that both MCP and CLI adapters call instead of duplicating transport-specific logic.\n\n## Coordinator setup adapter\n\nUse `gjc setup hermes` to render or install a portable MCP setup package for any controller that accepts Hermes-compatible MCP config:\n\n```bash\ngjc setup hermes --root /path/to/repo --profile my-bot --repo gajae-code\n```\n\nThe default mode is render-only and writes no files. To install into a Hermes profile:\n\n```bash\ngjc setup hermes \\\n --root /path/to/repo \\\n --profile my-bot \\\n --repo gajae-code \\\n --mutation sessions,questions,reports \\\n --profile-dir /path/to/hermes/profile \\\n --install\n```\n\nThe generated setup is model-agnostic and worktree-isolated. By default it renders `GJC_COORDINATOR_MCP_SESSION_COMMAND` as `gjc --worktree`, which is a typed selector for SDK lifecycle creation—not a shell command the bridge runs. Spawned sessions launch inside a GJC-managed sibling worktree while GJC retains the source repository as project identity. Users who need a stable named branch can set `--worktree-name`:\n\n```bash\ngjc setup hermes \\\n --root /path/to/repo \\\n --worktree-name hermes-gajae-code\n```\n\nThe runtime accepts only the literal selectors `gjc` and `gjc --worktree [name]`. It rejects local wrappers, shell syntax, tmux flags, and model/provider flags before creating a session. Existing setup configs that contain a legacy explicit `--session-command` must be changed to one of those selectors; provider and model resolution remains normal GJC configuration, not coordinator command injection.\n\nRun a non-mutating setup smoke check with:\n\n```bash\ngjc setup hermes --root /path/to/repo --smoke\n```\n\nSmoke verifies the MCP server/tool contract. It does not call a downstream LLM and does not validate provider credentials.\n\n\n## Safety model\n\nThe bridge is read-only and fail-closed by default.\n\nRequired root allowlist:\n\n```bash\nexport GJC_COORDINATOR_MCP_WORKDIR_ROOTS=\"/path/to/repo:/path/to/worktrees\"\n```\n\nMutating tools require both startup opt-in and per-call consent:\n\n```bash\nexport GJC_COORDINATOR_MCP_MUTATIONS=\"sessions,questions,reports\"\n```\n\nEvery mutating MCP call that requires a caller key must include `allow_mutation: true` and the required caller-provided `idempotency_key`. The bridge durably binds the key to the tool and canonical arguments, serializes concurrent duplicates, replays the original bounded public response, and rejects reuse with different arguments as `idempotency_conflict`.\n\n`gjc_coordinator_start_session` uses SDK lifecycle control with the configured typed GJC selector. `gjc setup hermes` writes `gjc --worktree` by default:\n\n```bash\nexport GJC_COORDINATOR_MCP_SESSION_COMMAND=\"gjc --worktree\"\n```\n\nThe only supported values are `gjc` and `gjc --worktree [name]`; this variable is never evaluated as a shell command. The coordinator binds registration, reuse, and control to the broker's exact canonical workspace and endpoint generation, then discovers the generation-bound SDK endpoint internally. Endpoint credentials are never persisted in coordinator records or returned by coordinator tools. `gjc_coordinator_read_coordination_status` returns a canonical polling snapshot for public session, state, turn, question, report, and bounded event data. Tmux identifiers, when supplied while registering an existing session, are advisory process metadata only; they do not provide control authority, machine viewing, startup, prompt injection, or determine turn completion.\n\nFor resume safety, prefer the generated GJC-native worktree selector over creating a git worktree in Hermes itself. GJC's launch path records the original repo as the project identity while running in the worktree, so session listing/resume can still group the session under the source project. If Hermes creates and later deletes an unmanaged worktree, a saved session may still exist but its cwd can be gone.\n\nArtifact reads are canonicalized, symlink escapes are rejected, and returned content is byte-capped by `GJC_COORDINATOR_MCP_ARTIFACT_BYTE_CAP`.\n\n`gjc setup hermes` renders `GJC_COORDINATOR_MCP_WORKDIR_ROOTS` with the host platform path delimiter (`:` on POSIX, `;` on Windows). Manual configs should prefer the same encoding.\n\n## Optional namespace\n\nUse namespace variables to prevent cross-profile or cross-repo enumeration:\n\n```bash\nexport GJC_COORDINATOR_MCP_PROFILE=\"team-a\"\nexport GJC_COORDINATOR_MCP_REPO=\"gajae-code\"\n```\n\nMissing namespace never widens into global session enumeration.\n\n## Tool surface\n\nRead tools:\n\n- `gjc_coordinator_list_sessions`\n- `gjc_coordinator_read_status`\n- `gjc_coordinator_read_tail`\n- `gjc_coordinator_list_questions`\n- `gjc_coordinator_list_artifacts`\n- `gjc_coordinator_read_artifact`\n- `gjc_coordinator_read_coordination_status`\n- `gjc_coordinator_read_turn`\n- `gjc_coordinator_await_turn`\n- `gjc_coordinator_watch_events`\n\n\nMutating tools:\n\n- `gjc_coordinator_start_session`\n- `gjc_coordinator_register_session`\n- `gjc_coordinator_send_prompt`\n- `gjc_coordinator_submit_question_answer`\n- `gjc_coordinator_report_status`\n- `gjc_delegate_plan`\n- `gjc_delegate_execute`\n- `gjc_delegate_team`\n\nThe `gjc_delegate_*` tools are high-level, session-level delegation: each starts (or reuses) an SDK-discovered session and sends one workflow-tagged turn for `/skill:ralplan`, `/skill:ultragoal`, or `/skill:team`, returning a durable `turn_id`, status, and artifact references. They use the same `sessions` mutation class and fail-closed workdir gating as `gjc_coordinator_start_session`, and emit a `delegation.started` event. Pass `await_completion: true` to use the durable bounded await/report path; `timeout_ms` and `poll_interval_ms` apply to that completion payload. Without it, the tool returns immediately after SDK acknowledgement. Pass `cwd` and `task`; set `allow_mutation: true` and a caller-provided `idempotency_key` only with startup mutation opt-in plus per-call consent. Optionally pass `mpreset` (same semantics as `gjc --mpreset `) to `gjc_coordinator_start_session` or a delegate tool to authoritatively activate a GJC model profile when starting a fresh session — it is resolved through the merged built-in/custom profile registry, applied from the first turn, and surfaced in status; unknown names are rejected with the available-profile listing, and reusing a session with a conflicting `mpreset` fails with `mpreset_conflict`. This is distinct from the advisory `model` prompt hint. Prefer these over manual `start_session` + `send_prompt` when delegating a whole workflow.\n\n`gjc_coordinator_register_session` registers an existing SDK-discoverable GJC session for coordinator control. It validates the workdir allowlist and session id, then verifies the broker's exact canonical workspace and endpoint generation before writing a credential-free session record. Optional tmux identifiers are retained only as advisory process metadata and are never machine-read.\n## Turn orchestration flow\n\nExternal coordinators should treat turns, not terminal scrollback, as the unit of work:\n\n1. Call `gjc_coordinator_start_session` with `allow_mutation: true` and `idempotency_key`.\n2. Call `gjc_coordinator_send_prompt` with `allow_mutation: true` and `idempotency_key`.\n3. Store the returned `turn_id`.\n4. Poll `gjc_coordinator_read_turn`, or call bounded `gjc_coordinator_await_turn`, until the turn is terminal.\n5. Pull `gjc_coordinator_list_questions` with the required `session_id`; it reconciles pending `workflow.gates.list` rows and returns bounded questions, diagnostics, and reconciliation state. Submit each pending row with `gjc_coordinator_submit_question_answer`.\n\n6. Use `gjc_coordinator_report_status` with `session_id` and `turn_id` to write explicit completion/failure evidence.\n Use `status: \"cancelled\"` for coordinator-policy cancellation, and `status: \"failed\"` plus `blocker` for provider/tool/task failures.\n\n`gjc_coordinator_send_prompt` returns versioned top-level routing fields that exactly mirror its nested durable `turn`: `status`, `queued`, and `delivered` equal `turn.status`, `turn.delivery.queued`, and `turn.delivery.delivered`; `active_turn_id` is the new turn id unless this response queued a follow-up, in which case it is the existing active turn id.\n\n```json\n{\n \"ok\": true,\n \"session_id\": \"gjc-coordinator-demo\",\n \"turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"active_turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"status\": \"active\",\n \"queued\": false,\n \"delivered\": true\n}\n```\n\nA session may have only one active turn by default. A second prompt is rejected with `active_turn_exists` unless the caller explicitly passes `queue: true` or `force: true`. Queued turns are durable and the next queued turn is promoted when the active turn reaches a terminal `gjc_coordinator_report_status`. Force supersedes the previous active turn and audits that state in the turn journal.\nCoordinator cancellation is recorded through `gjc_coordinator_report_status` with terminal `status: \"cancelled\"`; this updates durable turn state but does not control any process. If the correct policy is replacement work rather than cancellation, send the replacement prompt with `force: true` so the previous active turn is superseded and audited.\n\n`gjc_coordinator_read_turn` returns the authoritative durable turn and SDK-only advisory status. For the latest assistant output, use `gjc_coordinator_read_tail`; it queries `session.last_assistant` through the session SDK and returns only the requested bounded line suffix, never terminal output.\n\n```json\n{\n \"ok\": true,\n \"turn\": {\n \"schema_version\": 1,\n \"turn_id\": \"turn-00000000-0000-0000-0000-000000000000\",\n \"session_id\": \"gjc-coordinator-demo\",\n \"status\": \"completed\",\n \"final_response\": {\n \"text\": \"Done\",\n \"format\": \"markdown\",\n \"source\": \"report_status\",\n \"artifact_path\": null,\n \"truncated\": false\n },\n \"evidence\": [{ \"path\": \"artifact.txt\" }],\n \"error\": null\n },\n \"advisory_status\": {\n \"authority\": \"sdk\",\n \"live\": true,\n \"is_streaming\": false\n }\n}\n```\n\nThe coordinator MCP bridge is currently a durable polling/await surface. It does not expose a push subscription stream; external coordinators should poll `gjc_coordinator_read_coordination_status`, `gjc_coordinator_read_turn`, or bounded `gjc_coordinator_await_turn` instead of waiting for server-sent push events.\n\nExternal `session_id`, `turn_id`, and `question_id` values are validated before path use, and loaded records must match the requested session/turn owner.\n\n### Coordinator question pull loop\n\n`gjc_coordinator_list_questions` requires `session_id` and reconciles the session's pending `workflow.gates.list` rows on every call. Its bounded response contains public `questions`, `diagnostics`, and `reconciliation`; `status: \"pending\"` selects pending rows, while `status: \"open\"` remains a compatibility alias. More than one pending question may be returned. Public rows expose only the safe question shape, public option ids, and a fresh `answer_binding` for each pending row—never raw/private gate payloads or values.\n\n`gjc_coordinator_submit_question_answer` requires `session_id`, `turn_id`, `question_id`, `answer_binding`, `answer`, `idempotency_key`, and `allow_mutation: true`. Copy the identifiers and binding from the pending row and use the advertised answer shape. The bridge re-reconciles and revalidates ownership, pending state, and the binding before calling `workflow.gate_answer`; it never invokes generic `ask.answer`. An incomplete snapshot fails as `terminal_uncertain`; stale, terminal, missing, or ownership-mismatched rows are non-answerable. Restart can remint or quarantine gates, so re-list instead of reusing old rows. Identical idempotent replay returns the original accepted result; the same key with different arguments fails `idempotency_conflict`.\n\nThis pull-loop contract is independent of #2549/#2551 and unattended plain-CLI handling.\n\n## Coordinator event journal\n\nThe bridge persists a restart-safe event journal under the configured coordinator state namespace, for example:\n\n```text\n$GJC_COORDINATOR_MCP_STATE_ROOT///events/event-journal.jsonl\n```\n\nEach event is a bounded JSONL record with `schema_version`, monotonic namespace-local `seq`, stable `id`, `timestamp`, canonical `kind`, optional `session_id`/`turn_id`/`question_id`/`report_id`, short `summary`, optional `payload_ref`, and bounded scalar `metadata`. Full prompts, reports, final responses, and artifacts stay in their existing turn/report/artifact read paths; event records only point at them.\n\n`gjc_coordinator_watch_events` is a bounded long-poll MCP tool, not an unbounded stream. Inputs are `after_seq` (default `0`), optional `session_id`, optional `event_types`, `timeout_ms` capped at 30000, and `limit` capped at 100. If matching events already exist after `after_seq`, it returns immediately. Otherwise it waits for the event journal to change or for timeout. The response includes `events`, `latest_seq`, `timed_out`, and `transport: { \"mcp\": \"long_poll\", \"push_subscriptions\": false }`, so coordinators can persist `latest_seq` and resume safely after restart.\n\n`gjc_coordinator_read_coordination_status` keeps its existing report fields and now also includes `latest_event_seq` plus recent event summaries for snapshot-style consumers.\n\n## Generic controller config snippet\n\n```json\n{\n \"mcp_servers\": {\n \"gjc_coordinator\": {\n \"command\": \"gjc\",\n \"args\": [\"mcp-serve\", \"coordinator\"],\n \"env\": {\n \"GJC_COORDINATOR_MCP_WORKDIR_ROOTS\": \"/path/to/repo\",\n \"GJC_COORDINATOR_MCP_PROFILE\": \"team-a\",\n \"GJC_COORDINATOR_MCP_REPO\": \"project\",\n \"GJC_COORDINATOR_MCP_SESSION_COMMAND\": \"gjc --worktree\"\n },\n \"enabled\": true\n }\n }\n}\n```\n\n## Smoke check\n\n```bash\ngjc mcp-serve coordinator --check --json\n```\n\nExpected result includes `ok: true`, server name `gjc-coordinator-mcp`, and the GJC-named tool list. The JSON check is discovery-only and non-mutating: it retains those legacy fields and adds `catalog: { \"ready\": true, \"reason\": null }` and `broker`. `broker.discovery_status` is `ready`, `unavailable`, or `error`, with reason `null`, `absent_or_invalid`, `unsupported_state_version`, `discovery_access_denied`, or `discovery_read_failed`. `broker.operational_ready` is always `null`; the check does not connect, ensure/bootstrap, write, repair, or delete. `bootstrap_supported` is `true` and `bootstrap_attempted` is `false`. It does not expose broker authority, path, endpoint, process metadata, token, or raw error details. `gjc mcp-serve hermes --check --json` returns the identical coordinator check payload; its human output remains the server/tools summary.\n", @@ -41,8 +41,8 @@ export const EMBEDDED_DOCS: Readonly> = { "keybindings.md": "# Keybindings\n\nRun `/hotkeys` inside an `gjc` session to see the active chords for your current build. The list reflects any remaps loaded from disk and any bindings added by extensions.\n\n## Customize keybindings\n\nUser remaps live in `~/.gjc/agent/keybindings.json`. The file is a JSON object whose keys are keybinding action IDs and whose values are either one chord string or an array of chord strings. It is not read from `~/.gjc/agent/config.yml`, and there is no nested `keybindings` object.\n\n```json\n{\n \"app.commandPalette.open\": \"ctrl+p\",\n \"app.model.cycleForward\": \"alt+n\",\n \"app.model.selectTemporary\": \"alt+p\",\n \"app.plan.toggle\": \"alt+shift+p\"\n}\n```\n\nChord names are case-insensitive. New configuration should use canonical textual IDs rather than matching the labels shown in the UI.\nConfiguration uses portable canonical key IDs, not the labels printed by a particular host: use `ctrl`, `alt`, `shift`, and `super` with a key name, for example `ctrl+p`, `alt+enter`, `shift+tab`, and `super+c`. Matching is case-insensitive, but new configuration should use this canonical textual form so the same file remains portable.\n\nRuntime UI labels are platform-native. On macOS, `Ctrl`, `Alt`, `Shift`, and `Super` display as `⌃`, `⌥`, `⇧`, and `⌘`; MacBook keycaps such as Return, Escape, Tab, Delete, and the arrow keys display as `↩`, `⎋`, `⇥`, `⌫`/`⌦`, and arrows. These glyphs are display labels only: configure `super+c`, not `⌘C`, and `alt+enter`, not `⌥↩`.\nStatic onboarding and generated reference material describe shipped defaults and must stay host-independent. The active runtime surface is authoritative for effective bindings after user remaps and extensions load: use `/hotkeys` to see those bindings on the current platform.\n\nSet an action to an empty array to disable it:\n\n```json\n{\n \"app.stt.toggle\": []\n}\n```\n\n## Common action IDs\n\n| Action ID | Default | Meaning |\n| --- | --- | --- |\n| `app.commandPalette.open` | `ctrl+p` | Open the command palette |\n| `app.model.cycleForward` | `alt+n` | Cycle role models forward |\n| `app.model.cycleBackward` | `alt+shift+n` | Cycle role models backward |\n| `app.model.selectTemporary` | `alt+p` | Pick a model temporarily for this session |\n| `app.model.select` | `ctrl+l` | Open the model selector and set roles |\n| `app.plan.toggle` | `alt+shift+p` | Toggle plan mode |\n| `app.history.search` | `ctrl+r` | Search prompt history |\n| `app.tools.expand` | `ctrl+o` | Toggle tool-output expansion |\n| `app.thinking.toggle` | `ctrl+t` | Toggle thinking-block visibility |\n| `app.thinking.cycle` | `shift+tab` | Cycle thinking level |\n| `app.editor.external` | `ctrl+g` | Edit the draft in `$VISUAL` / `$EDITOR` |\n| `app.message.followUp` | _(none)_ | Optional remap for a follow-up message; `ctrl+enter` is reserved for editor newline |\n| `app.message.queue` | `alt+enter` (`alt+q` on darwin/win32) | Explicitly queue a message for the next turn |\n| `app.message.dequeue` | `alt+up` | Dequeue a queued message back into the editor |\n\n| `app.clipboard.copyLine` | `alt+shift+l` | Copy the current line |\n| `app.clipboard.copyPrompt` | `alt+shift+c` | Copy the whole prompt |\n| `app.stt.toggle` | `alt+h` | Toggle speech-to-text recording |\n| `app.irc.sidebar.toggle` | `alt+i` | Toggle IRC sidebar |\n\nOlder unqualified action names are migrated when `keybindings.json` is loaded, but new docs and new configs should use the namespaced action IDs above.\n\nOn macOS and native Windows terminals, GJC defaults `app.message.queue` to `Alt+Q`; Windows Terminal and PowerShell commonly reserve `Alt+Enter` for fullscreen before GJC can receive it. Users who prefer another chord can remap `app.message.queue` in `~/.gjc/agent/keybindings.json`.\n\nIn the main GJC composer, plain `PageUp` / `PageDown` page the visible transcript viewport instead of browsing prompt history; use `Up` / `Down` or `Ctrl+R` for prompt history. Autocomplete and selector surfaces still use `PageUp` / `PageDown` for list paging while they have focus.\n\n## Auditing default-key collisions\n\nSome default chords are intentionally reused across different UI contexts, where the focused component disambiguates them at dispatch time. For example `Enter` maps to both input submit and selection confirm, and `Ctrl+C` maps to both input copy and selection cancel. These are not conflicts — only one context is active at a time.\n\nTo audit the registry for keys whose default binding is claimed by more than one action, use `detectDefaultKeyCollisions(definitions)` from `@gajae-code/tui/keybindings`. It returns one entry per colliding key with the list of claiming action IDs, which is useful when adding new defaults or reviewing the surface. User-remap conflicts (multiple actions bound to the same chord in `keybindings.json`) continue to be reported separately by `KeybindingsManager.getConflicts()`.\n\nTwo audit clarifications for the current surface:\n\n- `app.clipboard.copyLine` is registry-backed and dispatched through the input controller's custom key handlers, not hardcoded.\n- `tui.input.copy` is declared in the registry but is not currently dispatched by `Editor.handleInput`.\n\nThe editor's configurable action defaults (including the platform-aware `app.clipboard.pasteImage` default) are derived directly from the central `KEYBINDINGS` registry, so there is a single source of truth for those defaults.\n\n## Current surface audit\n\nAuthoritative inventory of the keybinding registry, one row per action. Generated from `TUI_KEYBINDINGS` (`packages/tui/src/keybindings.ts`) and `KEYBINDINGS` (`packages/coding-agent/src/config/keybindings.ts`). Every action ID below is remappable via `~/.gjc/agent/keybindings.json` unless noted. A drift test (`packages/coding-agent/test/keybindings-audit.test.ts`) asserts every registry action ID appears in this table.\n\n### Editor context (`tui.editor.*`)\n\n| Action ID | Default | Notes |\n| --- | --- | --- |\n| `tui.editor.cursorUp` | `up` | |\n| `tui.editor.cursorDown` | `down` | |\n| `tui.editor.cursorLeft` | `left`, `ctrl+b` | `ctrl+b` also `app.tool.backgroundFold` (other context) |\n| `tui.editor.cursorRight` | `right`, `ctrl+f` | |\n| `tui.editor.cursorWordLeft` | `alt+left`, `ctrl+left`, `alt+b` | `ctrl+left` also `app.tree.foldOrUp` |\n| `tui.editor.cursorWordRight` | `alt+right`, `ctrl+right`, `alt+f` | `ctrl+right` also `app.tree.unfoldOrDown` |\n| `tui.editor.cursorLineStart` | `home`, `ctrl+a` | |\n| `tui.editor.cursorLineEnd` | `end`, `ctrl+e` | |\n| `tui.editor.jumpForward` | `ctrl+]` | |\n| `tui.editor.jumpBackward` | `ctrl+alt+]` | |\n| `tui.editor.pageUp` | `pageUp` | |\n| `tui.editor.pageDown` | `pageDown` | |\n| `tui.editor.deleteCharBackward` | `backspace` | |\n| `tui.editor.deleteCharForward` | `delete`, `ctrl+d` | `ctrl+d` also `app.exit` / `app.session.delete` |\n| `tui.editor.deleteWordBackward` | `ctrl+w`, `alt+backspace`, `ctrl+backspace` | |\n| `tui.editor.deleteWordForward` | `alt+delete`, `alt+d` | |\n| `tui.editor.deleteToLineStart` | `ctrl+u` | |\n| `tui.editor.deleteToLineEnd` | `ctrl+k` | |\n| `tui.editor.yank` | `ctrl+y` | |\n| `tui.editor.yankPop` | `alt+y` | |\n| `tui.editor.undo` | `ctrl+-`, `ctrl+_` | |\n\n### Input context (`tui.input.*`)\n\n| Action ID | Default | Notes |\n| --- | --- | --- |\n| `tui.input.newLine` | `Shift+Enter` | `Ctrl+Enter` and `Ctrl+Shift+Enter` are also accepted by the editor when the terminal encodes them distinctly |\n\n| `tui.input.submit` | `enter` | also `tui.select.confirm` (other context) |\n| `tui.input.tab` | `tab` | |\n| `tui.input.copy` | `ctrl+c` | declared but not dispatched by `Editor.handleInput` |\n\n### Selection context (`tui.select.*`)\n\n| Action ID | Default | Notes |\n| --- | --- | --- |\n| `tui.select.up` | `up` | |\n| `tui.select.down` | `down` | |\n| `tui.select.pageUp` | `pageUp` | |\n| `tui.select.pageDown` | `pageDown` | |\n| `tui.select.confirm` | `enter` | |\n| `tui.select.cancel` | `escape`, `ctrl+c` | `escape` also `app.interrupt` |\n\n### Application context (`app.*`)\n\n| Action ID | Default | Domains |\n| --- | --- | --- |\n| `app.interrupt` | escape | global |\n| `app.clear` | ctrl+c | global |\n| `app.exit` | ctrl+d | global |\n| `app.suspend` | ctrl+z | global |\n| `app.thinking.cycle` | shift+tab | composer |\n| `app.thinking.toggle` | ctrl+t | composer |\n| `app.commandPalette.open` | ctrl+p | composer |\n| `app.model.cycleForward` | alt+n | composer |\n| `app.model.cycleBackward` | alt+shift+n | composer |\n| `app.model.select` | ctrl+l | composer |\n| `app.model.selectTemporary` | alt+p | composer |\n| `app.tools.expand` | ctrl+o | composer |\n| `app.tool.backgroundFold` | ctrl+b | composer |\n| `app.editor.external` | ctrl+g | composer |\n| `app.message.followUp` | _(none)_ | composer |\n| `app.message.queue` | alt+q (darwin/win32) / alt+enter (linux) | composer |\n| `app.message.dequeue` | alt+up, alt+down | composer |\n| `app.clipboard.pasteImage` | ctrl+v (darwin/linux) / alt+v (win32) | composer |\n| `app.clipboard.copyLine` | alt+shift+l | composer |\n| `app.clipboard.copyPrompt` | alt+shift+c | composer |\n| `app.session.new` | ctrl+n | composer |\n| `app.session.tree` | _(none)_ | composer |\n| `app.session.fork` | _(none)_ | composer |\n| `app.session.resume` | _(none)_ | composer |\n| `app.session.observe` | ctrl+s | composer |\n| `app.session.dashboard` | _(none)_ | composer |\n| `app.jobs.open` | alt+j | composer |\n| `app.session.togglePath` | ctrl+p | selector |\n| `app.session.toggleSort` | ctrl+s | selector |\n| `app.session.rename` | ctrl+r | selector |\n| `app.session.delete` | ctrl+d | selector |\n| `app.session.deleteNoninvasive` | ctrl+backspace | selector |\n| `app.tree.foldOrUp` | ctrl+left, alt+left | selector |\n| `app.tree.unfoldOrDown` | ctrl+right, alt+right | selector |\n| `app.plan.toggle` | alt+shift+p | composer |\n| `app.history.search` | ctrl+r | composer |\n| `app.stt.toggle` | alt+h | composer |\n| `app.irc.sidebar.toggle` | alt+i | composer |\n| `app.transcript.browse` | _(none)_ | composer |\n| `app.transcript.prevTurn` | _(none)_ | composer |\n| `app.transcript.nextTurn` | _(none)_ | composer |\n| `app.mode.cycle` | _(none)_ | composer |\n| `app.tasks.toggle` | alt+t | composer |\n| `app.queue.togglePane` | _(none)_ | composer |\n| `app.message.sendNow` | _(none)_ | composer |\n\n### Global engine context (`tui.global.*`)\n\n| Action ID | Default | Notes |\n| --- | --- | --- |\n| `tui.global.debug` | `shift+ctrl+d` | Toggle debug overlay; resolved through the registry in `tui.ts` |\n\nCross-context default reuse (`ctrl+s`, `ctrl+r`, `ctrl+d`, `ctrl+b`, `ctrl+left`/`ctrl+right`, `enter`, `escape`, `ctrl+c`) is intentional: each pair is active in a different focused context and is disambiguated at dispatch time. Use `detectDefaultKeyCollisions()` (above) to re-derive this list from the registry.\n\n### Not yet registry-managed\n\nA few contexts still match chords directly instead of resolving through the registry, and are tracked for a later phase:\n\n- Tree selector (`tree-selector.ts`): up/down/left/right/enter, `ctrl+c`, filter cycling (`ctrl+o` / `ctrl+shift+o`), filter modes (`alt+d/t/u/l/a`), label edit (`shift+l`).\n- Parts of the model selector.\n", "lsp-config.md": "# LSP configuration in GJC\n\nThis guide explains how to configure language servers for the GJC coding agent.\n\nSource of truth in code:\n\n- Server config type: `packages/coding-agent/src/lsp/types.ts` (`ServerConfig`)\n- Config loader: `packages/coding-agent/src/lsp/config.ts`\n- Built-in server definitions: `packages/coding-agent/src/lsp/defaults.json`\n\n## Auto-detection\n\nWhen no LSP config file is present, GJC auto-detects servers by intersecting two conditions:\n\n1. The project directory contains at least one of the server's `rootMarkers`.\n2. The server binary is a trusted external executable. Project-local binaries, including paths reached through symlinks, are rejected.\n\nNo configuration is required for common setups. The built-in server list covers most popular languages; see [`defaults.json`](../packages/coding-agent/src/lsp/defaults.json) for the full set.\n\n## Config file locations\n\nGJC merges LSP config from multiple files, lowest to highest priority:\n\n| Priority | Location |\n|----------|----------|\n| 5 (lowest) | `~/lsp.json`, `~/.lsp.json`, `~/lsp.yaml`, `~/.lsp.yaml` |\n| 4 | Preloaded trusted external plugin LSP config outside the project (internal loader support; no current CLI/startup producer) |\n| 3 | `~/.gjc/agent/lsp.json`, `~/.gjc/agent/lsp.yaml`, `~/.gemini/lsp.*` |\n| 2 | `/.gjc/lsp.json`, `/.gjc/lsp.yaml`, `/.gemini/lsp.*` |\n| 1 (highest) | `/lsp.json`, `/.lsp.json`, `/lsp.yaml` |\n\nEach location accepts both `.json` and `.yaml` / `.yml` variants, as well as hidden-file versions (`.lsp.json`, `.lsp.yaml`). Configuration is merged in order, but project-controlled files can only control declarative server matching, activation, and capabilities. They cannot define or override a server's `command`, `args`, executable, client factory, `initOptions` / `initializationOptions`, or `settings`; opaque options that can instruct a trusted server belong to trusted user configuration.\n\nThe recommended trusted user configuration is `~/.gjc/agent/lsp.json` (or YAML equivalent). Legacy user-wide `~/.gemini/lsp.*` and home-root `~/lsp.*` / `~/.lsp.*` files are also outside the project and may define launch settings and opaque server options, including custom servers. Project files may refine declarative matching and activation fields of built-in or user-defined servers.\n\n**Recommended locations:**\n\n- Trusted user launch settings, `initOptions`, and `settings` → `~/.gjc/agent/lsp.json`\n- Project-specific matching and activation → `/.gjc/lsp.json`\n\n> **Note:** The presence of any LSP config file disables auto-detection. When at least one file is found, GJC skips the binary-scan phase and loads matching, available, non-disabled servers using trusted launch definitions.\n\n## File shape\n\nBoth JSON and YAML are accepted. The top-level object can use either a `servers` wrapper key or a flat map directly:\n\n```json\n{\n \"servers\": {\n \"server-name\": { ... }\n },\n \"idleTimeoutMs\": 300000\n}\n```\n\nor (flat, without the `servers` wrapper):\n\n```json\n{\n \"server-name\": { ... },\n \"idleTimeoutMs\": 300000\n}\n```\n\nTop-level keys:\n\n- `servers` — map of server name to `ServerConfig` (optional wrapper; flat form is equivalent)\n- `idleTimeoutMs` — shut down idle language servers after this many milliseconds; disabled by default\n\n## ServerConfig fields\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `command` | `string` | trusted user config only | Server executable name or absolute path; project configuration cannot set or override it |\n| `args` | `string[]` | no | Launch arguments; trusted user config only |\n| `fileTypes` | `string[]` | yes | File extensions this server handles, e.g. `[\".ts\", \".tsx\"]` |\n| `rootMarkers` | `string[]` | yes | Files/dirs that indicate a project root; glob patterns (e.g. `*.cabal`) are supported |\n| `initOptions` | `object` | trusted user config only | Sent as `initializationOptions` during LSP handshake |\n| `settings` | `object` | trusted user config only | Workspace settings pushed via `workspace/didChangeConfiguration` |\n| `disabled` | `boolean` | no | Set to `true` to disable this server entirely |\n| `warmupTimeoutMs` | `number` | no | Startup timeout in ms for this server (overrides the global default) |\n| `isLinter` | `boolean` | no | Mark server as linter/formatter only; excluded from type-intelligence operations (hover, go-to-definition, etc.) |\n| `capabilities` | `object` | no | Opt-in server-specific features; see [Capabilities](#capabilities) |\n\n`resolvedCommand` is populated automatically at runtime — do not set it manually.\n\n### Capabilities\n\nThe `capabilities` object enables optional server-specific features that GJC supports on a per-server basis:\n\n```json\n{\n \"capabilities\": {\n \"flycheck\": true,\n \"ssr\": true,\n \"expandMacro\": true,\n \"runnables\": true,\n \"relatedTests\": true\n }\n}\n```\n\nAll fields are boolean and optional. They are currently used by `rust-analyzer`.\n\n## Common recipes\n\n### Override a built-in server's settings from trusted user configuration\n\nOpaque server settings may contain process-affecting instructions, so place these partial overrides in trusted user configuration such as `~/.gjc/agent/lsp.json`:\n\n```json\n{\n \"servers\": {\n \"typescript-language-server\": {\n \"settings\": {\n \"typescript\": {\n \"preferences\": {\n \"quoteStyle\": \"single\"\n }\n }\n }\n }\n }\n}\n```\n\n```yaml\nservers:\n gopls:\n settings:\n gopls:\n gofumpt: false\n staticcheck: false\n```\n\n### Disable a built-in server\n\n```json\n{\n \"servers\": {\n \"eslint\": {\n \"disabled\": true\n }\n }\n}\n```\n\n### Register a custom server\n\nRegister custom servers in the canonical trusted user configuration, `~/.gjc/agent/lsp.json`. New servers require `command`, `fileTypes`, and `rootMarkers`; `args` is optional. Project configuration cannot register a launch definition or override a server's command, arguments, executable, or client factory.\n\n```json\n{\n \"servers\": {\n \"my-lsp\": {\n \"command\": \"my-lsp-server\",\n \"args\": [\"--stdio\"],\n \"fileTypes\": [\".xyz\"],\n \"rootMarkers\": [\".xyz-project\", \".git\"]\n }\n }\n}\n```\n\n### Set a global idle timeout\n\nShut down language servers that have been inactive for more than five minutes:\n\n```json\n{\n \"idleTimeoutMs\": 300000\n}\n```\n\n### Disable a server for one project, keep it globally\n\nPlace the override in `/.gjc/lsp.json`:\n\n```json\n{\n \"servers\": {\n \"pylsp\": {\n \"disabled\": true\n }\n }\n}\n```\n\nThe user-level config in `~/.gjc/agent/lsp.json` is unaffected; pylsp is only suppressed in this project.\n\nWhen multiple built-in primary servers support the same file, a default server can list lower-precedence servers in `supersedes`. For example, `csharp-ls` supersedes `omnisharp` only when both C# servers are installed and detected; if `csharp-ls` is unavailable, `omnisharp` remains the fallback.\n\n## lspmux\n\n`GJC_DISABLE_LSPMUX=1` is the canonical opt-out. `PI_DISABLE_LSPMUX=1` is a supported compatibility alias. A truthy value for either variable disables lspmux probing and wrapping.\n\n## Built-in server list\n\nThe following servers ship in `defaults.json` and are eligible for auto-detection:\n\n| Server key | Language(s) | Binary |\n|---|---|---|\n| `rust-analyzer` | Rust | `rust-analyzer` |\n| `clangd` | C, C++, ObjC | `clangd` |\n| `zls` | Zig | `zls` |\n| `gopls` | Go | `gopls` |\n| `typescript-language-server` | TypeScript, JavaScript | `typescript-language-server` |\n| `denols` | TypeScript, JavaScript (Deno) | `deno` |\n| `biome` | TS/JS/JSON (linter) | `biome` |\n| `eslint` | TS/JS/Vue/Svelte (linter) | `vscode-eslint-language-server` |\n| `vscode-html-language-server` | HTML | `vscode-html-language-server` |\n| `vscode-css-language-server` | CSS, SCSS, Less | `vscode-css-language-server` |\n| `vscode-json-language-server` | JSON | `vscode-json-language-server` |\n| `tailwindcss` | HTML, CSS, TS/JS | `tailwindcss-language-server` |\n| `svelte` | Svelte | `svelteserver` |\n| `vue-language-server` | Vue | `vue-language-server` |\n| `astro` | Astro | `astro-ls` |\n| `pyright` | Python | `pyright-langserver` |\n| `basedpyright` | Python | `basedpyright-langserver` |\n| `pylsp` | Python | `pylsp` |\n| `ruff` | Python (linter) | `ruff` |\n| `jdtls` | Java | `jdtls` |\n| `kotlin-lsp` | Kotlin | `kotlin-lsp` |\n| `metals` | Scala | `metals` |\n| `hls` | Haskell | `haskell-language-server-wrapper` |\n| `ocamllsp` | OCaml | `ocamllsp` |\n| `elixirls` | Elixir | `elixir-ls` |\n| `erlangls` | Erlang | `erlang_ls` |\n| `gleam` | Gleam | `gleam` |\n| `solargraph` | Ruby | `solargraph` |\n| `ruby-lsp` | Ruby | `ruby-lsp` |\n| `rubocop` | Ruby (linter) | `rubocop` |\n| `bashls` | Bash, Zsh | `bash-language-server` |\n| `lua-language-server` | Lua | `lua-language-server` |\n| `intelephense` | PHP | `intelephense` |\n| `phpactor` | PHP | `phpactor` |\n| `csharp-ls` | C# | `csharp-ls` |\n| `omnisharp` | C# | `omnisharp` |\n| `yamlls` | YAML | `yaml-language-server` |\n| `terraformls` | Terraform | `terraform-ls` |\n| `dockerls` | Dockerfile | `docker-langserver` |\n| `helm-ls` | Helm | `helm_ls` |\n| `nixd` | Nix | `nixd` |\n| `nil` | Nix | `nil` |\n| `ols` | Odin | `ols` |\n| `dartls` | Dart | `dart` |\n| `marksman` | Markdown | `marksman` |\n| `texlab` | LaTeX | `texlab` |\n| `graphql` | GraphQL | `graphql-lsp` |\n| `prismals` | Prisma | `prisma-language-server` |\n| `vimls` | Vim script | `vim-language-server` |\n| `emmet-language-server` | HTML, CSS, JSX | `emmet-language-server` |\n| `sourcekit-lsp` | Swift | `sourcekit-lsp` |\n| `swiftlint` | Swift (linter) | `swiftlint` |\n| `tlaplus` | TLA+ | `tlapm_lsp` |\n", "memory.md": "# Autonomous Memory\n\nWhen enabled, the agent automatically extracts durable knowledge from past sessions and injects a compact summary into each new session. Over time it builds a project-scoped memory store — technical decisions, recurring workflows, pitfalls — that carries forward without manual effort.\n\nDisabled by default. Enable via `/settings` or `config.yml`:\n\n```yaml\nmemories:\n enabled: true\n```\n\n## Usage\n\n### What gets injected\n\nAt session start, if a memory summary exists for the current project, it is injected into the system prompt as a **Memory Guidance** block. The agent is instructed to:\n\n- Treat memory as heuristic context — useful for process and prior decisions, not authoritative on current repo state.\n- Pair memory-influenced decisions with current-repo evidence before acting.\n- Prefer repo state and user instruction when they conflict with memory; treat conflicting memory as stale.\n\n### Memory artifacts\n\nGenerated local-memory artifacts are private runtime state, not a public tool or URI surface. They may be summarized into the system prompt when local memory is enabled, but users and model-facing tool docs should not rely on direct `memory://` reads. The legacy internal `memory://` resolver remains only for compatibility with existing persisted guidance and is not part of the public coding harness contract; remove it after legacy local-memory prompts no longer reference it.\n### `/memory` slash command\n\n| Subcommand | Effect |\n| --------------------- | ---------------------------------------------- |\n| `view` | Show the current memory injection payload |\n| `clear` / `reset` | Delete all memory data and generated artifacts |\n| `enqueue` / `rebuild` | Force consolidation to run at next startup |\n\n## How it works\n\nMemories are built by a background pipeline that runs at startup or when manually triggered via slash command.\n\n**Phase 1 — per-session extraction:** For each past session that has changed since it was last processed, a model reads the session history and extracts durable signal: technical decisions, constraints, resolved failures, recurring workflows. Sessions that are too recent, too old, or currently active are skipped. Each extraction produces a raw memory block and a short synopsis for that session.\n\n**Phase 2 — consolidation:** After extraction, a second model pass reads all per-session extractions and produces three outputs written to disk:\n\n- `MEMORY.md` — a curated long-term memory document\n- `memory_summary.md` — the compact text injected at session start\n- `skills/` — reusable procedural playbooks, each in its own subdirectory\n\nPhase 2 uses a lease to prevent double-running when multiple processes start simultaneously. Stale skill directories from prior runs are pruned automatically.\n\nAll output is scanned for secrets before being written to disk.\n\n### Extraction behavior\n\nMemory extraction and consolidation behavior is driven by static prompt files in `packages/coding-agent/src/prompts/memories/`.\n\n| File | Purpose | Variables |\n| --------------------- | ------------------------------------------- | ------------------------------------------- |\n| `stage_one_system.md` | System prompt for per-session extraction | — |\n| `stage_one_input.md` | User-turn template wrapping session content | `{{thread_id}}`, `{{response_items_json}}` |\n| `consolidation.md` | Prompt for cross-session consolidation | `{{raw_memories}}`, `{{rollout_summaries}}` |\n| `read_path.md` | Memory guidance injected into live sessions | `{{memory_summary}}` |\n\n### Model selection\n\nMemory piggybacks on the model role system.\n\n| Phase | Role | Purpose |\n| ----------------------- | ------------------------------------------------------------------- | -------------------------------- |\n| Phase 1 (extraction) | `default` | Per-session knowledge extraction |\n| Phase 2 (consolidation) | `smol` (falls back to `default`, then current/first registry model) | Cross-session synthesis |\n\nIf the requested memory role is not configured, memory model resolution falls back to the `default` role, then the active session model, then the first model in the registry.\n\n## Configuration\n\n| Setting | Default | Description |\n| ------------------------------------- | ------- | --------------------------------------------------------- |\n| `memories.enabled` | `false` | Master switch |\n| `memories.maxRolloutAgeDays` | `30` | Sessions older than this are not processed |\n| `memories.minRolloutIdleHours` | `12` | Sessions active more recently than this are skipped |\n| `memories.maxRolloutsPerStartup` | `64` | Cap on sessions processed in a single startup |\n| `memories.summaryInjectionTokenLimit` | `5000` | Max tokens of the summary injected into the system prompt |\n\nAdditional tuning knobs (concurrency, lease durations, token budgets) are available in config for advanced use.\n\n## Key files\n\n- `packages/coding-agent/src/memories/index.ts` — pipeline orchestration, injection, slash command handling\n- `packages/coding-agent/src/memories/storage.ts` — SQLite-backed job queue and thread registry\n- `packages/coding-agent/src/prompts/memories/` — memory prompt templates\n- `packages/coding-agent/src/internal-urls/memory-protocol.ts` — legacy non-public `memory://` compatibility handler\n", - "models.md": "# Model and Provider Configuration (`models.yml`)\n\nThis document describes how the coding-agent currently loads models, applies overrides, resolves credentials, and chooses models at runtime.\n\n## What controls model behavior\n\nPrimary implementation files:\n\n- `src/config/model-registry.ts` — loads built-in + custom models, provider overrides, runtime discovery, auth integration\n- `src/config/model-resolver.ts` — parses model patterns and selects models for the default and agent roles\n- `src/config/settings-schema.ts` — model-related settings (`modelRoles`, provider transport preferences)\n- `src/session/auth-storage.ts` — API key + OAuth resolution order\n- `packages/ai/src/models.ts` and `packages/ai/src/types.ts` — built-in providers/models and `Model`/`compat` types\n\n## Config file location and legacy behavior\n\nDefault config path:\n\n- `~/.gjc/agent/models.yml`\n\nLegacy behavior still present:\n\n- If `models.yml` is missing and `models.json` exists at the same location, it is migrated to `models.yml`.\n- Explicit `.json` / `.jsonc` config paths are still supported when passed programmatically to `ModelRegistry`.\n\n## `models.yml` shape\n\n```yaml\nproviders:\n :\n # provider-level config\nequivalence:\n overrides:\n /: \n exclude:\n - /\n```\n\n`provider-id` is the canonical provider key used across selection and auth lookup.\n\n`equivalence` is optional and configures canonical model grouping on top of concrete provider models:\n\n- `overrides` maps an exact concrete selector (`provider/modelId`) to an official upstream canonical id\n- `exclude` opts a concrete selector out of canonical grouping\n\n## Provider-level fields\n\n```yaml\nproviders:\n my-provider:\n baseUrl: https://api.example.com/v1\n apiKey: MY_PROVIDER_API_KEY\n api: openai-completions\n headers:\n X-Team: platform\n authHeader: true\n auth: apiKey\n disableStrictTools: false # set true for Anthropic-compatible endpoints that reject the strict field\n cacheRetention: short # none | short | long; model entries and modelOverrides can override this\n discovery:\n type: ollama\n modelOverrides:\n some-model-id:\n name: Renamed model\n cacheRetention: long\n models:\n - id: some-model-id\n name: Some Model\n api: openai-completions\n reasoning: false\n input: [text]\n cost:\n input: 0\n output: 0\n cacheRead: 0\n cacheWrite: 0\n contextWindow: 128000\n maxTokens: 16384\n headers:\n X-Model: value\n cacheRetention: none\n thinking:\n minLevel: low\n maxLevel: xhigh\n mode: effort\n defaultLevel: high\n levels: [low, medium, high, xhigh]\n compat:\n supportsStore: true\n supportsDeveloperRole: true\n supportsReasoningEffort: true\n maxTokensField: max_completion_tokens\n openRouterRouting:\n only: [anthropic]\n vercelGatewayRouting:\n order: [anthropic, openai]\n extraBody:\n gateway: m1-01\n controller: mlx\nmodelBindings:\n modelRoles:\n default: my-provider/some-model-id:high\n agentModelOverrides:\n executor: my-provider/some-model-id\n```\n\n### Allowed provider/model `api` values\n\n- `openai-completions`\n- `openai-responses`\n- `openai-codex-responses`\n- `azure-openai-responses`\n- `bedrock-converse-stream`\n- `anthropic-messages`\n- `google-generative-ai`\n- `google-vertex`\n- `google-gemini-cli`\n- `ollama-chat`\n- `cursor-agent`\n\n\n### First-class DeepInfra, Azure OpenAI, and Amazon Bedrock examples\n\nAzure OpenAI uses canonical OpenAI model IDs in GJC and resolves those IDs to Azure deployment names at request time. Set `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` to avoid assuming model id equals deployment name:\n\n```yaml\nproviders:\n azure-openai:\n baseUrl: https://my-resource.openai.azure.com/openai/v1\n apiKeyEnv: AZURE_OPENAI_API_KEY\n api: azure-openai-responses\n models:\n - id: gpt-4.1\n - id: o3\n```\n\n```sh\nexport AZURE_OPENAI_DEPLOYMENT_NAME_MAP='gpt-4.1=gpt-41-prod,o3=o3-reasoning-prod'\n```\n\nDeepInfra is available as the first-class `deepinfra` provider. It uses DeepInfra's OpenAI-compatible Chat Completions endpoint and reads `DEEPINFRA_API_KEY` when no explicit config key is provided. Set `serviceTier: priority` in GJC config or use the runtime service-tier controls to send DeepInfra's `service_tier: \"priority\"` request field for supported models:\n\n```yaml\nproviders:\n deepinfra:\n baseUrl: https://api.deepinfra.com/v1/openai\n apiKeyEnv: DEEPINFRA_API_KEY\n api: openai-completions\n models:\n - id: deepseek-ai/DeepSeek-V3.2\n```\n\nAmazon Bedrock uses the native `bedrock-converse-stream` transport and AWS credential chain auth. Do not put AWS access keys in `models.yml`; configure `AWS_REGION` / `AWS_PROFILE` or standard static AWS credential environment variables instead:\n\n```yaml\nproviders:\n amazon-bedrock:\n baseUrl: https://bedrock-runtime.us-east-1.amazonaws.com\n api: bedrock-converse-stream\n models:\n - id: us.anthropic.claude-opus-4-6-v1\n - id: anthropic.claude-3-5-sonnet-20241022-v2:0\n```\n\n### MiniMax and GLM custom provider examples\n\nFor common MiniMax and GLM/zAI setup, prefer the provider presets so the OpenAI-compatible API, base URL, env var, model id, and compatibility flags are written together:\n\n```sh\ngjc setup provider --preset minimax\ngjc setup provider --preset minimax-cn\ngjc setup provider --preset glm\ngjc setup provider --preset alibaba-token-plan\n```\n\nThe same presets are available inside the TUI:\n\n```text\n/provider add --preset minimax\n/provider add --preset glm\n/provider add zai\n/provider add --preset alibaba-token-plan\n```\n\nPresets only write `models.yml` entries that reference documented environment variable names (`MINIMAX_CODE_API_KEY`, `MINIMAX_CODE_CN_API_KEY`, `ZAI_API_KEY`, or `ALIBABA_TOKEN_PLAN_API_KEY`); they do not store or validate real credentials. The GLM preset aliases (`glm`, `zai`, `z-ai`) write an OpenAI-compatible custom provider named `glm-proxy` and do not replace the first-class `zai` provider. The Alibaba Token Plan preset (aliases: alibaba, token-plan) writes an OpenAI-compatible custom provider named alibaba-token-plan with per-model API routing (qwen3.8-max-preview uses openai-responses; glm-5.2 and deepseek-v4-pro use openai-completions).\n\n## Model profiles (`--mpreset`)\n\nModel profiles are optional top-level `profiles:` entries in `~/.gjc/agent/models.yml`. A profile can require provider credentials before activation and can map one or more model roles; omitted roles inherit from the active defaults.\n\n> See also: [Cross-vendor role-based profiles](./multi-vendor-profiles.md) — a curated multi-vendor `profiles:` recipe and verified selector notes that build on the mechanism described here.\n\n```yaml\nprofiles:\n team-standard:\n required_providers: [openai, anthropic]\n model_mapping:\n default: openai/gpt-5.2\n executor: anthropic/claude-sonnet-5:medium\n architect: openai/o3:high\n planner: openai/o3:high\n critic: openai/o3:high\n```\n\n`model_mapping` keys are role names (`default`, `executor`, `architect`, `planner`, `critic`). Every role accepts either one `provider/modelId[:effort]` selector or a non-empty ordered array of selectors; the first entry is primary and later entries are fallback candidates. `required_providers` is the aggregate set of providers required across the profile's mapped roles.\n\n### Fallback chains\n\nPreset `model_mapping` roles, top-level `modelRoles`, and `task.agentModelOverrides` all accept `string | string[]`. Keep one selector per line when a chain needs to be readable:\n\n```yaml\nprofiles:\n reliable:\n required_providers: [anthropic, openai]\n model_mapping:\n default: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\nmodelBindings:\n modelRoles:\n default: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\n agentModelOverrides:\n executor: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\n```\n\nResolution-time skips for unavailable, unauthenticated, or unknown entries cost zero attempts and advance immediately. Only request-time retryable failures (such as 429, quota, authentication, or 5xx failures) consume an entry's `fallback.maxAttempts` total attempts (default: `3`). The active default fallback remains sticky for the session; role-override fallback state is fresh for each subagent call. The active model is shown consistently in status and `/model`.\n\nManaged fallback attempts buffer provisional streamed output until an attempt is accepted, so output can appear later than it does for a one-model stream. Current Cursor-agent transports are fail-closed unavailable in retryable fallback chains: resolution rejects them with `Cursor model requires provider-side tool execution and cannot be used in a retryable fallback chain` because they do not provide a client-side tool-call mode.\n\nCancellation discards provisional output and emits exactly one cancelled `agent_end`; RPC, ACP, and the TUI therefore settle once. On load, the source-aware one-shot migration reads legacy `retry.fallbackChains`, prepends the effective role chain, and writes the ordered, deduplicated result to the corresponding role array; the legacy key is then ignored.\n\nBuilt-in profiles are grouped by provider mix and tier:\n\n- `codex-{eco,medium,pro}` — GPT-5.6 Sol/Terra/Luna role mixes tuned by tier and reasoning effort\n- `opencodego` — single OpenCode Go preset (Kimi default, DeepSeek executor/architect, Qwen planner, MiMo critic)\n- `claude-opus` — Anthropic OAuth preset centered on `claude-opus-4-8`\n- Single-provider tiers: `glm-{eco,medium,pro}`, `kimi-coding-plan-{eco,medium,pro}`, `mimo-{eco,medium,pro}`, `grok-{eco,medium,pro}`, `cursor-{eco,medium,pro}`, `minimax-{eco,medium,pro}`\n- Combos: `opus-codex`, `codex-opencodego`, and `fable-opus-codex`\n\nThe `eco`, `medium`, and `pro` Codex profile mappings are current product judgments: Eco assigns Terra low/Luna low/Luna high/Terra xhigh/Terra high to default/executor/planner/critic/architect; Medium assigns Sol low/Terra low/Terra high/Sol xhigh/Sol high; and Pro assigns Sol medium/Terra medium/Sol high/Sol max/Sol xhigh. `opus-codex` retains the Medium Codex executor, critic, and architect roles but uses `anthropic/claude-sonnet-5` for planner; `codex-opencodego` retains the Medium Codex default and architect roles; and `fable-opus-codex` uses the Pro Codex executor and architect roles with `anthropic/claude-opus-4-8:medium` for planner. The descriptive repeated local exact-edit evidence informs only selected executor-style TypeScript tasks; it does not evaluate or prove default, planner, architect, or critic performance. See [GPT-5.6 Codex preset benchmark](./gpt-5.6-codex-preset-benchmark.md). Effort suffixes are clamped to each model's supported thinking range at preview and activation time. Single-provider tiers pin each provider's current flagship (`zai/glm-5.2`, `kimi-code/kimi-k2.7-code`, `xiaomi/mimo-v2.5-pro`, `xai/grok-4.3`, `cursor/composer-1.5`, `minimax-code/minimax-m3`). User-defined profiles override built-ins by exact profile name.\n\n\nUse `gjc --mpreset ` to activate a profile for the current session only. Activation hard-blocks when any provider listed in `required_providers` lacks credentials. Add `--default` to persist the selected profile as `modelProfile.default` in `config.yml`, so it applies at startup:\n\n```sh\ngjc --mpreset codex-medium\ngjc --mpreset opencodego --default\n```\n\nThe `/model` command opens to a preset landing view: presets are grouped by provider with live auth marks (✓/✗), highlighting a group expands its tiers, and selecting a tier shows the full role→model preview before applying for the session or as default. Typing jumps straight to model search, and `Browse all models` opens the classic tabbed model selector. In `/login`, `Add custom provider` is the first option for configuring credentials needed by custom or profile-required providers; after a successful provider login, the matching preset is recommended automatically.\n\nMiniMax's OpenAI-compatible endpoint rejects multiple system messages and emits thinking in `reasoning_content`, so pin the public-safe compatibility fields when hand-authoring a custom provider:\n\n```yaml\nproviders:\n minimax-custom:\n baseUrl: https://api.minimax.io/v1\n apiKeyEnv: MINIMAX_API_KEY\n api: openai-completions\n compat:\n supportsStore: false\n supportsDeveloperRole: false\n supportsReasoningEffort: false\n reasoningContentField: reasoning_content\n models:\n - id: MiniMax-M2.5\n```\n\nGLM via z.ai is available as the first-class `zai` provider. For a private GLM-compatible proxy, keep secrets in an env var and disable OpenAI-only request fields as needed:\n\n```yaml\nproviders:\n glm-proxy:\n baseUrl: https://api.z.ai/api/paas/v4\n apiKeyEnv: ZAI_API_KEY\n api: openai-completions\n compat:\n supportsDeveloperRole: false\n supportsReasoningEffort: false\n models:\n - id: glm-4.6\n```\n### Allowed auth/discovery values\n\n- `auth`: `apiKey` (default), `none`, or `oauth`; for `models.yml` custom models, `oauth` is accepted by schema but does not waive the `apiKey` requirement\n- `models.yml` is strict: unknown provider/model keys fail validation before provider dispatch, so stale keys such as `requestTransform` or `wireModelId` only work where this document lists them.\n- `discovery.type`: `ollama`, `llama.cpp`, `lm-studio`, or `openai-models-list`\n- `cacheRetention`: `none`, `short`, or `long`; request-time options win over model/modelOverride values, then provider values, then `GJC_CACHE_RETENTION`, then the runtime default. The runtime default is `short` for most providers, but the Anthropic provider defaults to `long` (`ttl: \"1h\"`) because the ~5m default is too fragile for long-running subagent workflows. The 1h marker is only emitted on the canonical Anthropic API (`api.anthropic.com`) for models advertising `supportsLongCacheRetention`; proxies, gateways, and incapable models fall back to the default ephemeral (~5m) breakpoint. For OpenAI Responses, this controls `prompt_cache_retention` only; it does not disable `prompt_cache_key` when a stable session id exists.\n\n## OpenAI-compatible proxy configuration\n\nOpenAI-compatible proxy providers should use schema-supported provider keys first:\n\n```yaml\nproviders:\n proxy-provider:\n baseUrl: https://api.proxy.example/v1\n apiKeyEnv: PROXY_API_KEY\n api: openai-completions\n auth: apiKey\n headers:\n User-Agent: curl/8.7.1\n models:\n - id: local-gpt\n name: Local GPT\n reasoning: true\n input: [text]\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }\n contextWindow: 400000\n maxTokens: 128000\n```\n\nUse provider-level `headers` for proxy-required headers. Keep the provider `api` set to `openai-completions` when the proxy exposes Chat Completions-compatible `/v1/chat/completions` semantics. `auth: apiKey` sends the resolved token as bearer auth; use `auth: none` only for trusted local/no-auth endpoints.\n\n`input` is the model modality list GJC uses to decide whether image content is forwarded. When a custom model omits `input`, GJC defaults to `[text]` (unless a bundled model with the same id contributes a reference). Vision-capable upstream models therefore need an explicit `input: [text, image]`; otherwise `read`/tool images are stripped before the request and replaced with `[image omitted: model does not support vision]`, even if the remote model can see images.\n\n```yaml\nproviders:\n ali:\n baseUrl: https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\n apiKeyEnv: ALI_API_KEY\n api: openai-completions\n auth: apiKey\n models:\n # id-only → text-only; images will be omitted\n - id: some-text-model\n # vision-capable hosted model must declare image input\n - id: qwen3.8-max-preview\n name: Qwen3.8 Max Preview\n reasoning: true\n input: [text, image]\n```\n\n`requestTransform` and `wireModelId` remain supported for request-body shaping, but they are not needed for ordinary OpenAI-compatible proxies whose local model id is already the upstream wire id. Unknown config keys fail validation before a provider request is sent.\n\nWhen request shaping is needed:\n\n- `requestTransform.profile: openai-proxy` strips OpenAI SDK/Stainless telemetry and beta headers at final fetch time and sets a generic GJC user agent.\n- `stripHeaders` replaces the preset strip list when provided.\n- `setHeaders` is applied after stripping; use `null` to remove a header.\n- `extraBody` is shallow-merged into the JSON request body after provider compatibility fields; core transport keys such as `model`, `messages`/`input`, `stream`, `tools`, and `tool_choice` are protected and ignored.\n- Model-level `requestTransform` overrides provider-level fields and shallow-merges `setHeaders`/`extraBody`.\n- `wireModelId` changes only the upstream request body model id; local selection still uses `provider/id`.\n\n### Layofflabs-style proxy example\n\n```yaml\nproviders:\n layofflabs:\n baseUrl: https://api.layofflabs.com/v1\n apiKeyEnv: OPENAI_API_KEY\n api: openai-completions\n auth: apiKey\n headers:\n User-Agent: curl/8.7.1\n models:\n - id: gpt-5.5\n name: GPT 5.5 via Layofflabs\n reasoning: true\n thinking:\n minLevel: low\n maxLevel: xhigh\n mode: effort\n defaultLevel: high\n levels: [low, medium, high, xhigh]\n input: [text]\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }\n contextWindow: 400000\n maxTokens: 128000\n\nmodelBindings:\n modelRoles:\n default: layofflabs/gpt-5.5:high\n agentModelOverrides:\n executor: layofflabs/gpt-5.5:high\n```\n\n## Validation rules (current)\n\n### Full custom provider (`models` is non-empty)\n\nRequired:\n\n- `baseUrl`\n- `apiKey` unless `auth: none`\n- `api` at provider level or each model\n\n### Override-only provider (`models` missing or empty)\n\nMust define at least one of:\n\n- `baseUrl`\n- `headers`\n- `compat`\n- `requestTransform`\n- `disableStrictTools`\n- `modelOverrides`\n- `discovery`\n\n### Discovery\n\n- `discovery` requires provider-level `api`.\n\n### Model value checks\n\n- `id` required\n- `contextWindow` and `maxTokens` must be positive if provided\n- unknown provider, model, override, and request-transform keys fail schema validation; remove stale keys instead of relying on them being ignored.\n\n## Merge and override order\n\nModelRegistry pipeline (on refresh):\n\n1. Load built-in providers/models from `@gajae-code/ai`.\n2. Load `models.yml` custom config.\n3. Apply provider overrides (`baseUrl`, `headers`, `requestTransform`, `disableStrictTools`, `cacheRetention`) to built-in models.\n4. Apply `modelOverrides` (per provider + model id).\n5. Merge custom `models`:\n - same `provider + id` replaces existing\n - otherwise append\n6. Load cached/runtime-discovered models (Ollama, llama.cpp, LM Studio, plus built-in provider managers), then re-apply model overrides.\n\n### Provider-model cache and static fingerprint\n\nCached per-provider model lists are persisted in the model-cache SQLite\ndatabase (schema v3) with a `static_fingerprint` column that hashes the\nstatic catalog slice merged into the row. When `resolveProviderModels`\nskips the network fetch and the fingerprint of the in-memory static\ncatalog matches the cached one, the cached rows are returned verbatim —\nthe static + dynamic merge is bypassed entirely. The fingerprint is\nmemoized per process via a WeakMap keyed by the static-models array\nreference, so repeated cold-start calls do not re-hash.\n\n## Canonical model equivalence and coalescing\n\nThe registry keeps every concrete provider model and then builds a canonical layer above them.\n\nCanonical ids are official upstream ids only, for example:\n\n- `anthropic-model-opus-4-6`\n- `anthropic-model-haiku-4-5`\n- `gpt-5.3-openai-code`\n\n### `models.yml` equivalence config\n\nExample:\n\n```yaml\nproviders:\n zenmux:\n baseUrl: https://api.zenmux.example/v1\n apiKey: ZENMUX_API_KEY\n api: openai-codex-responses\n models:\n - id: openai-code\n name: Zenmux OpenAI code\n reasoning: true\n input: [text]\n cost:\n input: 0\n output: 0\n cacheRead: 0\n cacheWrite: 0\n contextWindow: 200000\n maxTokens: 32768\n\nequivalence:\n overrides:\n zenmux/openai-code: gpt-5.3-openai-code\n p-openai-code/openai-code: gpt-5.3-openai-code\n exclude:\n - demo/openai-code-preview\n```\n\nBuild order for canonical grouping:\n\n1. exact user override from `equivalence.overrides`\n2. bundled official-id matches from built-in model metadata\n3. conservative heuristic normalization for gateway/provider variants\n4. fallback to the concrete model's own id\n\nCurrent heuristics are intentionally narrow:\n\n- embedded upstream prefixes can be stripped when present, for example `anthropic/...` or `openai/...`\n- dotted and dashed version variants can normalize only when they map to an existing official id, for example `4.6 -> 4-6`\n- ambiguous families or versions are not merged without a bundled match or explicit override\n\n### Canonical resolution behavior\n\nWhen multiple concrete variants share a canonical id, resolution uses:\n\n1. availability and auth\n2. `config.yml` `modelProviderOrder`\n3. the lowest combined `cost.input + cost.cacheRead`\n4. existing registry/provider order if the earlier ranks tie\n\nDisabled or unauthenticated providers are skipped. A session that resolves a canonical selector keeps its concrete variant across discovery refreshes; it changes only after an explicit concrete selection or when that variant is no longer available.\n\nSession state and transcripts continue to record the concrete provider/model that actually executed the turn.\n\nProvider defaults vs per-model overrides:\n\n- Provider `headers` are baseline.\n- Model `headers` override provider header keys.\n- `modelOverrides` can override model metadata (`name`, `reasoning`, `input`, `cost`, `contextWindow`, `maxTokens`, `headers`, `compat`, `contextPromotionTarget`).\n- `compat` is deep-merged for nested routing blocks (`openRouterRouting`, `vercelGatewayRouting`, `extraBody`).\n\n## Runtime discovery integration\n\n### Implicit Ollama discovery\n\nIf `ollama` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `ollama`\n- api: `openai-responses`\n- base URL: `OLLAMA_BASE_URL` or `http://127.0.0.1:11434`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery calls Ollama endpoints and normalizes discovered OpenAI-compatible models to `openai-responses`.\n\n### Implicit llama.cpp discovery\n\nIf `llama.cpp` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `llama.cpp`\n- api: `openai-responses`\n- base URL: `LLAMA_CPP_BASE_URL` or `http://127.0.0.1:8080`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery calls llama.cpp model endpoints and synthesizes model entries with local defaults.\n\n### Implicit LM Studio discovery\n\nIf `lm-studio` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `lm-studio`\n- api: `openai-completions`\n- base URL: `LM_STUDIO_BASE_URL` or `http://127.0.0.1:1234/v1`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery fetches models (`GET /models`) and synthesizes model entries with local defaults.\n\n### Explicit provider discovery\n\nYou can configure discovery yourself:\n\n```yaml\nproviders:\n ollama:\n baseUrl: http://127.0.0.1:11434\n api: openai-responses\n auth: none\n discovery:\n type: ollama\n\n llama.cpp:\n baseUrl: http://127.0.0.1:8080\n api: openai-responses\n auth: none\n discovery:\n type: llama.cpp\n```\n\n### Extension provider registration\n\nExtensions can register providers at runtime (`pi.registerProvider(...)`), including:\n\n- model replacement/append for a provider\n- custom stream handler registration for new API IDs\n- custom OAuth provider registration\n\n## Auth and API key resolution order\n\nWhen requesting a key for a provider, effective order is:\n\n1. Runtime override (CLI `--api-key`)\n2. Stored API key credential in `agent.db`\n3. Stored OAuth credential in `agent.db` (with refresh)\n4. Environment variable mapping (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.)\n5. ModelRegistry fallback resolver (provider `apiKey` from `models.yml`, env-name-or-literal semantics)\n\n`models.yml` `apiKey` behavior:\n\n- Value is first treated as an environment variable name.\n- If no env var exists, the literal string is used as the token.\n\nIf `authHeader: true` and provider `apiKey` is set, models get:\n\n- `Authorization: Bearer ` header injected.\n\nKeyless providers:\n\n- Providers marked `auth: none` are treated as available without credentials.\n- `getApiKey*` returns `kNoAuth` for them.\n\n### Broker mode\n\nWhen `GJC_AUTH_BROKER_URL` (or `auth.broker.url`) is set, the local SQLite credential store is replaced by `RemoteAuthCredentialStore`. Layers 2 and 3 above (stored API key / OAuth in `agent.db`) are served from a broker-supplied snapshot whose `refresh` tokens are redacted; expiry triggers `POST /v1/credential/:id/refresh` on the broker rather than a local refresh.\n\n`AuthStorage.setConfigApiKey` lets a `models.yml` `apiKey` win over a broker-resolved OAuth token without overriding a runtime `--api-key`. See [`auth-broker-gateway.md`](./auth-broker-gateway.md) for the full broker / gateway design and env surface (`GJC_AUTH_BROKER_URL`, `GJC_AUTH_BROKER_TOKEN`, `auth.broker.url`, `auth.broker.token`).\n\n## Model availability vs all models\n\n- `getAll()` returns the loaded model registry (built-in + merged custom + discovered).\n- `getAvailable()` filters to models that are keyless or have resolvable auth.\n\nSo a model can exist in registry but not be selectable until auth is available.\n\n## Runtime model resolution\n\n### CLI and pattern parsing\n\n`model-resolver.ts` supports:\n\n- exact `provider/modelId`\n- exact canonical model id\n- exact model id (provider inferred)\n- fuzzy/substring matching\n- glob scope patterns in `--models` (e.g. `openai/*`, `*sonnet*`)\n- optional `:thinkingLevel` suffix (`off|minimal|low|medium|high|xhigh`)\n\n`--provider` is legacy; `--model` is preferred.\n\nResolution precedence for exact selectors:\n\n1. exact `provider/modelId` bypasses coalescing\n2. exact canonical id resolves through the canonical index\n3. exact bare concrete id still works\n4. fuzzy and glob matching run after the exact paths\n\nThinking suffixes are split once from the final `:` only after the complete selector does not resolve. This preserves concrete OpenRouter route IDs such as `openrouter/z-ai/glm-4.7:nitro`; `:high` can follow that route suffix. Multiple suffixes are not recursively consumed. A complete `provider/modelId` selector is exact-only: it never falls back to fuzzy, substring, glob, or another provider when that concrete selector is absent. Exact-case provider/model entries resolve deterministically for custom replacement semantics; a case-insensitive selector that remains ambiguous does not guess.\n\n### Initial model selection priority\n\n`findInitialModel(...)` uses this order:\n\n1. explicit CLI provider+model\n2. first scoped model (if not resuming)\n3. saved default provider/model\n4. known provider defaults (e.g. OpenAI/Anthropic/etc.) among available models\n5. first available model\n\n### Role aliases and settings\n\nSupported model roles:\n\n- `default` plus the agent assignment targets `executor`, `architect`, `planner`, `critic`\n\nRole aliases like `pi/default` expand through `settings.modelRoles`. Each role value can also append a thinking selector such as `:minimal`, `:low`, `:medium`, or `:high`.\n\nIf a role points at another role, the target model still inherits normally and any explicit suffix on the referring role wins for that role-specific use.\n\nRelated settings:\n\n- `modelRoles` (record)\n- `enabledModels` (scoped pattern list)\n- `modelProviderOrder` (global canonical-provider precedence)\n- `providers.kimiApiFormat` (`openai` or `anthropic` request format)\n- `providers.openaiWebsockets` (`auto|off|on` websocket preference for OpenAI code provider transport)\n\n`modelRoles` may store either:\n\n- `provider/modelId` to pin a concrete provider variant\n- a canonical id such as `gpt-5.3-openai-code` to allow provider coalescing\n\nFor `enabledModels` and CLI `--models`:\n\n- exact canonical ids expand to all concrete variants in that canonical group\n- explicit `provider/modelId` entries stay exact\n- globs and fuzzy matches still operate on concrete models\n\nGlobal `enabledModels` and `disabledProviders` entries may also be scoped to a path prefix:\n\n```yaml\nenabledModels:\n - anthropic-model-sonnet-4-5\n - path: ~/work\n models:\n - anthropic/anthropic-model-opus-4-5\ndisabledProviders:\n - ollama\n - path: ~/private\n providers:\n - anthropic\n```\n\nString entries apply everywhere. Scoped entries apply when the current working directory is the configured path or one of its subdirectories. Use `path`, `paths`, `pathPrefix`, or `pathPrefixes`; use `models` for `enabledModels`, `providers` for `disabledProviders`, or `values` for either.\n\n## `/model` and `--list-models`\n\nBoth surfaces keep provider-prefixed models visible and selectable.\n\nThey now also expose canonical/coalesced models:\n\n- `/model` includes a canonical view alongside provider tabs\n- `--list-models` prints a canonical section plus the concrete provider rows\n\nSelecting a canonical entry stores the canonical selector. Selecting a provider row stores the explicit `provider/modelId`.\n\n## Context promotion (model-level fallback chains)\n\nContext promotion is an overflow recovery mechanism for small-context variants (for example `*-spark`) that automatically promotes to a larger-context sibling when the API rejects a request with a context length error. It is **off by default** (`contextPromotion.enabled` is `false`); opt in to enable it.\n\n### Trigger and order\n\nWhen a turn fails with a context overflow error (e.g. `context_length_exceeded`), `AgentSession` attempts promotion **before** falling back to compaction:\n\n1. If `contextPromotion.enabled` is true, resolve a promotion target (see below).\n2. If a target is found, switch to it and retry the request — no compaction needed.\n3. If no target is available, fall through to auto-compaction on the current model.\n\n### Target selection\n\nSelection is model-driven, not role-driven:\n\n1. `currentModel.contextPromotionTarget` (if configured)\n2. smallest larger-context model on the same provider + API\n\nCandidates are ignored unless credentials resolve (`ModelRegistry.getApiKey(...)`).\n\n### OpenAI code provider websocket handoff\n\nIf switching from/to `openai-codex-responses`, session provider state key `openai-codex-responses` is closed before model switch. This drops websocket transport state so the next turn starts clean on the promoted model.\n\n### Persistence behavior\n\nPromotion uses temporary switching (`setModelTemporary`):\n\n- recorded as a temporary `model_change` in session history\n- does not rewrite saved role mapping\n\n### Configuring explicit fallback chains\n\nConfigure fallback directly in model metadata via `contextPromotionTarget`.\n\n`contextPromotionTarget` accepts either:\n\n- `provider/model-id` (explicit)\n- `model-id` (resolved within current provider)\n\nExample (`models.yml`) for Spark -> non-Spark on the same provider:\n\n```yaml\nproviders:\n openai-code:\n modelOverrides:\n gpt-5.3-openai-code-spark:\n contextPromotionTarget: openai-code/gpt-5.3-openai-code\n```\n\nThe built-in model generator also assigns this automatically for `*-spark` models when a same-provider base model exists.\n\n## Compatibility and routing fields\n\nThe `compat` block on a provider or model overrides the URL-based auto-detection in `packages/ai/src/providers/openai-completions-compat.ts`. It is validated by `OpenAICompatSchema` in `packages/coding-agent/src/config/model-registry.ts` and consumed by every `openai-completions` transport (`packages/ai/src/providers/openai-completions.ts`). The canonical type is `OpenAICompat` in `packages/ai/src/types.ts`.\n\n`models.yml` accepts the following keys (all optional; unset falls back to URL detection):\n\nRequest shaping:\n\n- `supportsStore` — emit `store: false` on requests. Default: auto (off for non-standard endpoints).\n- `supportsDeveloperRole` — use the `developer` system role for reasoning models instead of `system`. Default: auto.\n- `sendSessionHeaders` — forward the agent session id as `session_id` and `x-session-id` request headers so OpenAI-compatible relays/proxies can do session-affinity routing and reuse a server-side prompt cache. Default: `false`. Caller-set `headers`/`requestTransform` values are never overwritten.\n- `supportsUsageInStreaming` — send `stream_options: { include_usage: true }` to receive token usage on streaming responses. Default: `true`.\n- `maxTokensField` — `\"max_completion_tokens\"` or `\"max_tokens\"`. Default: auto.\n- `supportsToolChoice` — emit the `tool_choice` parameter when the caller forces a specific tool. Default: `true`. Set `false` for endpoints that 400 on `tool_choice` (e.g. DeepSeek when reasoning is on).\n- `disableReasoningOnForcedToolChoice` — drop `reasoning_effort` / OpenRouter `reasoning` whenever `tool_choice` forces a call. Default: auto (Kimi/Anthropic-fronted endpoints).\n- `extraBody` — extra top-level fields merged into every request body (gateway hints, controller selectors, etc.).\n\nReasoning / thinking:\n\n- `supportsReasoningEffort` — accept `reasoning_effort`. Default: auto (off for Grok and zAI).\n- `reasoningEffortMap` — partial map from internal effort levels (`minimal|low|medium|high|xhigh`) to provider-specific strings (e.g. DeepSeek maps `xhigh -> \"max\"`).\n- `thinkingFormat` — request shape for thinking: `\"openai\"` (`reasoning_effort`), `\"openrouter\"` (`reasoning: { effort }`), `\"zai\"` (`thinking: { type: \"enabled\" }`), `\"qwen\"` (top-level `enable_thinking`), or `\"qwen-chat-template\"` (`chat_template_kwargs.enable_thinking`). Default: `\"openai\"`.\n- `reasoningContentField` — assistant field carrying chain-of-thought: `\"reasoning_content\"`, `\"reasoning\"`, or `\"reasoning_text\"`. Default: auto.\n- `requiresReasoningContentForToolCalls` — assistant tool-call turns must round-trip the reasoning field (DeepSeek-R1, Kimi, OpenRouter when reasoning is on). Default: `false`.\n- `requiresAssistantContentForToolCalls` — assistant tool-call turns must include non-empty text content (Kimi). Default: `false`.\n\nTool / message normalization:\n\n- `requiresToolResultName` — tool-result messages need a `name` field (Mistral). Default: auto.\n- `requiresAssistantAfterToolResult` — a user message after a tool result needs an assistant turn in between. Default: auto.\n- `requiresThinkingAsText` — convert thinking blocks to text wrapped in `` delimiters (Mistral). Default: auto.\n- `requiresMistralToolIds` — normalize tool-call ids to exactly 9 alphanumeric chars. Default: auto.\n- `supportsStrictMode` — accept the per-tool `strict` field on tool schemas. Default: conservative auto-detect per provider/baseUrl.\n- `toolStrictMode` — `\"all_strict\"` forces strict on every tool, `\"none\"` forces it off; unset keeps the existing per-tool mixed behavior.\n\nGateway routing (only applied when `baseUrl` matches the gateway):\n\n- `openRouterRouting.only` / `openRouterRouting.order` — provider routing on `openrouter.ai` (see ).\n- `vercelGatewayRouting.only` / `vercelGatewayRouting.order` — provider routing on `ai-gateway.vercel.sh` (see ).\n\nProvider-level `compat` is the baseline; per-model `compat` is deep-merged on top, with `openRouterRouting`, `vercelGatewayRouting`, and `extraBody` merged as nested objects.\n\n### Anthropic compatibility (`anthropic-messages`)\n\nFor `anthropic-messages` models the runtime uses a separate `AnthropicCompat` shape (`packages/ai/src/types.ts`). The `models.yml` schema currently exposes only the strict-tools opt-out as a top-level provider field (see below); the remaining Anthropic-side knobs (`disableAdaptiveThinking`, `supportsEagerToolInputStreaming`, `supportsLongCacheRetention`) are set by built-in catalog metadata and are not user-configurable from `models.yml`.\n\n### Strict tool schemas (`disableStrictTools`)\n\nAnthropic's API supports a `strict` field on tool definitions that forces the model to always follow the provided schema exactly. This is enabled by default for all `anthropic-messages` providers because it guarantees schema conformance in agentic systems.\n\nThird-party providers that front the Anthropic API (AWS Bedrock, Azure, self-hosted proxies) do not always implement this field and will reject requests that include it. Set `disableStrictTools: true` at the provider level to opt out:\n\n```yaml\nproviders:\n bedrock-anthropic:\n baseUrl: https://bedrock-runtime.us-east-1.amazonaws.com/anthropic\n apiKey: AWS_BEARER_TOKEN\n api: anthropic-messages\n disableStrictTools: true\n models:\n - id: anthropic-model-sonnet-4-20250514\n name: Anthropic model Sonnet 4 (Bedrock)\n input: [text, image]\n contextWindow: 200000\n maxTokens: 16384\n cost:\n input: 3.00\n output: 15.00\n cacheRead: 0.30\n cacheWrite: 3.75\n```\n\n`disableStrictTools` is a provider-level flag that applies to all models in the provider.\n\nTool schemas going on the wire are normalized by the unified flow in\n`packages/ai/src/utils/schema/normalize.ts` (Google/CCA/MCP dispatchers\nplus the OpenAI strict-mode sanitize+enforce pipeline). See\n[`ai-schema-normalize.md`](./ai-schema-normalize.md) for the strict-mode\nedge cases (local `$ref` inlining, single-item `allOf` collapse,\n`anyOf`-wrapper description hoist, enum/const primitive-type inference)\nand the per-provider dispatcher mapping.\n## Practical examples\n\n### Local OpenAI-compatible endpoint (no auth)\n\n```yaml\nproviders:\n local-openai:\n baseUrl: http://127.0.0.1:8000/v1\n auth: none\n api: openai-completions\n models:\n - id: Qwen/Qwen2.5-Coder-32B-Instruct\n name: Qwen 2.5 Coder 32B (local)\n```\n\n### Hosted proxy with env-based key\n\n```yaml\nproviders:\n anthropic-proxy:\n baseUrl: https://proxy.example.com/anthropic\n apiKey: ANTHROPIC_PROXY_API_KEY\n api: anthropic-messages\n authHeader: true\n disableStrictTools: true # if the proxy doesn't support strict tool schemas\n models:\n - id: anthropic-model-sonnet-4-20250514\n name: Anthropic model Sonnet 4 (Proxy)\n reasoning: true\n input: [text, image]\n```\n\n### Override built-in provider route + model metadata\n\n```yaml\nproviders:\n openrouter:\n baseUrl: https://my-proxy.example.com/v1\n headers:\n X-Team: platform\n modelOverrides:\n anthropic/anthropic-model-sonnet-4:\n name: Sonnet 4 (Corp)\n compat:\n openRouterRouting:\n only: [anthropic]\n```\n\n## Legacy consumer caveat\n\nMost model configuration now flows through `models.yml` via `ModelRegistry`. Explicit `.json` / `.jsonc` paths remain supported only when passed programmatically to `ModelRegistry`; the default user config is `~/.gjc/agent/models.yml`.\n\n## Failure mode\n\nIf `models.yml` fails schema or validation checks:\n\n- registry keeps operating with built-in models\n- error is exposed via `ModelRegistry.getError()` and surfaced in UI/notifications\n", - "multi-vendor-profiles.md": "# Choosing models in GJC: role-based profiles\n\nA practical guide to picking models for GJC's roles, for every subscription situation — one vendor, two vendors, or the full multi-vendor set. It adds curated cross-vendor `profiles:` for `~/.gjc/agent/models.yml` and verified selector notes on top of the mechanism in [Model profiles](./models.md#model-profiles---mpreset). Everything here is **user config**; it complements the built-in `--mpreset` presets and overrides a built-in only when it shares its exact name.\n\n> Selectors, prices, and \"axis leaders\" are catalog- and time-sensitive (observed 2026-06 on the current bundled catalog). Re-verify any selector with `gjc -p --no-session --no-tools --model \"Reply OK\"`.\n\n## The five roles\n\n`default` runs the main loop and most turns; `executor` / `architect` / `planner` / `critic` are the four bundled task agents, delegated only when the work calls for it.\n\n| Role | What it optimizes for |\n| --- | --- |\n| `default` | tool-calling reliability + honesty (it routes — its quality bounds the whole system) |\n| `executor` | real coding (SWE-bench Verified) |\n| `planner` | reasoning + sequencing (GPQA / ARC-AGI-2) |\n| `architect` | large-context + multimodal review |\n| `critic` | independent adversarial review (different family from what it reviews) |\n\n## Pick by what you subscribe to\n\n| You have | Use |\n| --- | --- |\n| **One vendor** | the built-in preset for that vendor — `claude-opus` (Anthropic), `codex-{eco,medium,pro}` (OpenAI/Codex), `opencodego` (OpenCode Go), or a single-vendor flagship tier (`zai/glm-5.2`, `kimi-code/...`, `xiaomi/...`, `xai/grok-4.3`, `minimax-code/...`). These already map all five roles inside one vendor. |\n| **Claude + Codex** | the built-in `opus-codex` (Claude main loop + Codex support roles). |\n| **Three or more / all five** | the cross-vendor profiles below — each role on its axis leader, `critic` kept cross-family. |\n\nThe single guiding rule across all of these: **keep `default` on the strongest router you have** (Anthropic Opus when available). A weak `default` caps quality regardless of the delegated models.\n\n## Cross-vendor profiles (3+ vendors)\n\nNo single vendor leads every axis, so these put each role on its axis leader and keep `critic` on a different family from the `executor` it reviews.\n\n```yaml\nprofiles:\n\n daily: # everyday balance\n required_providers: [anthropic, openai-codex, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-4-8:medium\n executor: openai-codex/gpt-5.4:high\n planner: google-antigravity/gemini-3.1-pro-low:high\n architect: google-antigravity/gemini-3.1-pro-low:high\n critic: xai/grok-4.3:medium\n\n ultimate: # cost-no-object, best per role\n required_providers: [anthropic, openai-codex, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-4-8:high\n executor: anthropic/claude-opus-4-8:max\n planner: openai-codex/gpt-5.5:xhigh\n architect: google-antigravity/gemini-3.1-pro-low:high\n critic: xai/grok-4.3:high\n\n eco: # cheapest delegated work; main loop stays on Opus\n required_providers: [anthropic, opencode-go, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-4-8:low\n executor: opencode-go/deepseek-v4-flash\n planner: xai/grok-4-1-fast:high\n architect: google-antigravity/gemini-3.1-pro-low\n critic: google-antigravity/gemini-3.5-flash\n\n monorepo: # huge codebases (openai-codex excluded: 272k context cap)\n required_providers: [anthropic, google-antigravity, opencode-go]\n model_mapping:\n default: anthropic/claude-opus-4-8:medium\n executor: anthropic/claude-opus-4-8:high\n planner: google-antigravity/gemini-3.1-pro-low:high\n architect: anthropic/claude-opus-4-8:high\n critic: opencode-go/glm-5.2\n\n reviewer: # review/audit stance — the author-mode role split, inverted\n required_providers: [anthropic, openai-codex, google-antigravity]\n model_mapping:\n default: anthropic/claude-opus-4-8:high # aggregator restraint: preserve raw reviewer verdicts\n executor: openai-codex/gpt-5.5:high # support — repro PoCs, failing tests, harnesses\n planner: google-antigravity/gemini-3.1-pro-low:high # review checklists / audit scoping\n architect: anthropic/claude-opus-4-8:high # lead 1 — primary code-review judge (effective long-context)\n critic: openai-codex/gpt-5.5:high # lead 2 — merge gate, cross-family vs Claude-authored code\n```\n\n## Reviewer stance and the external review gate\n\nThe profiles above assume an **authoring** stance: `executor` is the lead and `architect`/`critic` verify its work. In a session whose primary job is reviewing or auditing (not writing) code, the roles invert — `architect`/`critic` become the leads and `executor` is support (reproduction PoCs, failing tests). The `reviewer` profile encodes that inversion, with one generalized provenance rule: **the reviewing model family must differ from the family that authored the code under review**, not merely from the session's own executor.\n\nA verified use is the cross-session final review gate: the authoring session launches a fresh, stateless reviewer sub-session so the finished diff is judged without the authoring context:\n\n```sh\n# the one-shot gate needs only a cross-family --model; add --mpreset reviewer as an\n# optional enhancement AFTER installing this profile in ~/.gjc/agent/models.yml:\ngjc -p --no-session --model openai-codex/gpt-5.5:xhigh --tools read,search,find \"\"\n```\n\nThe `--tools` allowlist is part of the contract: it enforces the reviewer's read-only boundary for the built-in tool surface instead of trusting the prompt (the runtime still injects the session `goal` tool unless `goal.enabled` is off — disabling it for the reviewer invocation is **mandatory**, via a dedicated gate directory outside the repo so the reviewed checkout stays clean, see the template — plus `generate_image` when an image credential exists). In this one-shot form the session's `default` model authors the verdict — a tool-restricted print session cannot delegate to the profile's `critic`/`architect` roles — so the explicit cross-family `--model` carries provenance, and the `reviewer` profile itself serves the interactive review-session case (activate it with `--mpreset reviewer` only after copying it into `models.yml`; otherwise activation fails with an unknown-profile error). Profile names in this document live in the user namespace — a user profile overrides a builtin preset only on an exact name match, and a future builtin with the same name would be silently shadowed by your copy.\n\nSee [Extragoal local skill template](./extragoal-skill-template.md) for the full gate workflow (verdict contract, findings triage, bounded re-sign loop, secret-scan and injection guards) built on this recipe.\n\n## Model cheatsheet (by need)\n\nCurrent axis leaders and the cheaper second option, with metered price ($/1M in/out; Gemini via Antigravity runs on the Google AI subscription):\n\n| Need | First pick | Cheaper option |\n| --- | --- | --- |\n| Router / tool-calling (`default`) | `anthropic/claude-opus-4-8` (5/25) | `anthropic/claude-sonnet-5` (3/15) |\n| Coding (`executor`) | `anthropic/claude-opus-4-8` — SWE-bench Verified ~88.6 (5/25) | `openai-codex/gpt-5.4` (2.5/15) · `opencode-go/deepseek-v4-flash` (0.14/0.28) |\n| Reasoning (`planner`) | `openai-codex/gpt-5.5` (ARC-AGI-2) / `google-antigravity/gemini-3.1-pro-low:high` (GPQA) | `xai/grok-4-1-fast` (0.2/0.5) |\n| Large context (`architect`) | `anthropic/claude-opus-4-8` (effective long-context) | `xai/grok-4-fast` (2M nominal, 0.2/0.5) |\n| Multimodal review (`architect`) | `google-antigravity/gemini-3.1-pro-low:high` | `google-antigravity/gemini-3.5-flash` |\n| Independent critic | `xai/grok-4.3` (1.25/2.5) | `opencode-go/glm-5.2` · `google-antigravity/gemini-3.5-flash` |\n\nOn standard tasks, all current frontier models in the catalog are accurate; **pick by cost, latency, and role fit, not by raw accuracy on easy prompts.** As an indicative GJC-routed latency reference (`gjc -p`, identical coding + reasoning prompts, all correct): `grok-4.3` and `glm-5.2` ≈ 2–3s, `deepseek-v4-pro` ≈ 3–4s, `claude-opus-4-8` / `gpt-5.5` ≈ 4–7s, `gemini-3.1-pro-low:high` ≈ 7s.\n\n## Verified selector notes (current catalog)\n\nObserved via live `gjc -p` calls; useful when wiring the profiles above:\n\n- **Antigravity Gemini, high reasoning** → use `google-antigravity/gemini-3.1-pro-low:high`. The id `gemini-3.1-pro-high` returns HTTP 400 (no matching backend model); `thinkingLevel` is a per-request parameter, so raising it on `gemini-3.1-pro-low` invokes the model's native high-reasoning mode rather than a degraded one.\n- **openai-codex on a ChatGPT account** serves base GPT only (`gpt-5.5`, `gpt-5.4`). Standalone `-codex` variants (`gpt-5.3-codex`, `gpt-5.2-codex`, `gpt-5.1-codex-max` / `-mini`) return `not supported when using Codex with a ChatGPT account`.\n- **Single-message input limit is separate from the context window.** `claude-opus-4-8` runs with a 1M window via multi-turn accumulation, but a single `@file` message above ~400k tokens returns 400 on `anthropic` / `google-antigravity`; `xai` / `opencode-go` accept larger single messages. Chunk very large inputs across turns instead of pasting one block.\n- **Some selectors come from a provider's live catalog, not the bundled snapshot.** `opencode-go/glm-5.2` and `google-antigravity/gemini-3.5-flash` resolved in `gjc -p` tests but are **not** in `packages/ai/src/models.json`; they appear only after the provider's online model discovery has populated the registry. `required_providers` verifies credentials at activation — it does **not** guarantee fresh, non-stale discovery — so activation can still fail with `selector did not resolve` until discovery runs (re-login or retry to refresh). If you hit that, substitute a bundled id: `opencode-go/deepseek-v4-pro` for the critic, or `zai/glm-5.2` (add `zai` to `required_providers`) for GLM 5.2.\n\n## Activation\n\n```bash\ngjc --mpreset daily # this session only\ngjc --mpreset ultimate --default # persist as the startup default (config.yml)\n```\n\nActivation hard-blocks when any provider in `required_providers` lacks credentials, so log in first: `/login anthropic`, `/login openai-codex`, `/login google-antigravity`, `/login xai` (and `opencode-go` via `OPENCODE_API_KEY`).\n", + "models.md": "# Model and Provider Configuration (`models.yml`)\n\nThis document describes how the coding-agent currently loads models, applies overrides, resolves credentials, and chooses models at runtime.\n\n## What controls model behavior\n\nPrimary implementation files:\n\n- `src/config/model-registry.ts` — loads built-in + custom models, provider overrides, runtime discovery, auth integration\n- `src/config/model-resolver.ts` — parses model patterns and selects models for the default and agent roles\n- `src/config/settings-schema.ts` — model-related settings (`modelRoles`, provider transport preferences)\n- `src/session/auth-storage.ts` — API key + OAuth resolution order\n- `packages/ai/src/models.ts` and `packages/ai/src/types.ts` — built-in providers/models and `Model`/`compat` types\n\n## Config file location and legacy behavior\n\nDefault config path:\n\n- `~/.gjc/agent/models.yml`\n\nLegacy behavior still present:\n\n- If `models.yml` is missing and `models.json` exists at the same location, it is migrated to `models.yml`.\n- Explicit `.json` / `.jsonc` config paths are still supported when passed programmatically to `ModelRegistry`.\n\n## `models.yml` shape\n\n```yaml\nproviders:\n :\n # provider-level config\nequivalence:\n overrides:\n /: \n exclude:\n - /\n```\n\n`provider-id` is the canonical provider key used across selection and auth lookup.\n\n`equivalence` is optional and configures canonical model grouping on top of concrete provider models:\n\n- `overrides` maps an exact concrete selector (`provider/modelId`) to an official upstream canonical id\n- `exclude` opts a concrete selector out of canonical grouping\n\n## Provider-level fields\n\n```yaml\nproviders:\n my-provider:\n baseUrl: https://api.example.com/v1\n apiKey: MY_PROVIDER_API_KEY\n api: openai-completions\n headers:\n X-Team: platform\n authHeader: true\n auth: apiKey\n disableStrictTools: false # set true for Anthropic-compatible endpoints that reject the strict field\n cacheRetention: short # none | short | long; model entries and modelOverrides can override this\n discovery:\n type: ollama\n modelOverrides:\n some-model-id:\n name: Renamed model\n cacheRetention: long\n models:\n - id: some-model-id\n name: Some Model\n api: openai-completions\n reasoning: false\n input: [text]\n cost:\n input: 0\n output: 0\n cacheRead: 0\n cacheWrite: 0\n contextWindow: 128000\n maxTokens: 16384\n headers:\n X-Model: value\n cacheRetention: none\n thinking:\n minLevel: low\n maxLevel: xhigh\n mode: effort\n defaultLevel: high\n levels: [low, medium, high, xhigh]\n compat:\n supportsStore: true\n supportsDeveloperRole: true\n supportsReasoningEffort: true\n maxTokensField: max_completion_tokens\n openRouterRouting:\n only: [anthropic]\n vercelGatewayRouting:\n order: [anthropic, openai]\n extraBody:\n gateway: m1-01\n controller: mlx\nmodelBindings:\n modelRoles:\n default: my-provider/some-model-id:high\n agentModelOverrides:\n executor: my-provider/some-model-id\n```\n\n### Allowed provider/model `api` values\n\n- `openai-completions`\n- `openai-responses`\n- `openai-codex-responses`\n- `azure-openai-responses`\n- `bedrock-converse-stream`\n- `anthropic-messages`\n- `google-generative-ai`\n- `google-vertex`\n- `google-gemini-cli`\n- `ollama-chat`\n- `cursor-agent`\n\n\n### First-class DeepInfra, Azure OpenAI, and Amazon Bedrock examples\n\nAzure OpenAI uses canonical OpenAI model IDs in GJC and resolves those IDs to Azure deployment names at request time. Set `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` to avoid assuming model id equals deployment name:\n\n```yaml\nproviders:\n azure-openai:\n baseUrl: https://my-resource.openai.azure.com/openai/v1\n apiKeyEnv: AZURE_OPENAI_API_KEY\n api: azure-openai-responses\n models:\n - id: gpt-4.1\n - id: o3\n```\n\n```sh\nexport AZURE_OPENAI_DEPLOYMENT_NAME_MAP='gpt-4.1=gpt-41-prod,o3=o3-reasoning-prod'\n```\n\nDeepInfra is available as the first-class `deepinfra` provider. It uses DeepInfra's OpenAI-compatible Chat Completions endpoint and reads `DEEPINFRA_API_KEY` when no explicit config key is provided. Set `serviceTier: priority` in GJC config or use the runtime service-tier controls to send DeepInfra's `service_tier: \"priority\"` request field for supported models:\n\n```yaml\nproviders:\n deepinfra:\n baseUrl: https://api.deepinfra.com/v1/openai\n apiKeyEnv: DEEPINFRA_API_KEY\n api: openai-completions\n models:\n - id: deepseek-ai/DeepSeek-V3.2\n```\n\nAmazon Bedrock uses the native `bedrock-converse-stream` transport and AWS credential chain auth. Do not put AWS access keys in `models.yml`; configure `AWS_REGION` / `AWS_PROFILE` or standard static AWS credential environment variables instead:\n\n```yaml\nproviders:\n amazon-bedrock:\n baseUrl: https://bedrock-runtime.us-east-1.amazonaws.com\n api: bedrock-converse-stream\n models:\n - id: us.anthropic.claude-opus-4-6-v1\n - id: anthropic.claude-3-5-sonnet-20241022-v2:0\n```\n\n### MiniMax and GLM custom provider examples\n\nFor common MiniMax and GLM/zAI setup, prefer the provider presets so the OpenAI-compatible API, base URL, env var, model id, and compatibility flags are written together:\n\n```sh\ngjc setup provider --preset minimax\ngjc setup provider --preset minimax-cn\ngjc setup provider --preset glm\ngjc setup provider --preset alibaba-token-plan\n```\n\nThe same presets are available inside the TUI:\n\n```text\n/provider add --preset minimax\n/provider add --preset glm\n/provider add zai\n/provider add --preset alibaba-token-plan\n```\n\nPresets only write `models.yml` entries that reference documented environment variable names (`MINIMAX_CODE_API_KEY`, `MINIMAX_CODE_CN_API_KEY`, `ZAI_API_KEY`, or `ALIBABA_TOKEN_PLAN_API_KEY`); they do not store or validate real credentials. The GLM preset aliases (`glm`, `zai`, `z-ai`) write an OpenAI-compatible custom provider named `glm-proxy` and do not replace the first-class `zai` provider. The Alibaba Token Plan preset (aliases: alibaba, token-plan) writes an OpenAI-compatible custom provider named alibaba-token-plan with per-model API routing (qwen3.8-max-preview uses openai-responses; glm-5.2 and deepseek-v4-pro use openai-completions).\n\n## Model profiles (`--mpreset`)\n\nModel profiles are optional top-level `profiles:` entries in `~/.gjc/agent/models.yml`. A profile can require provider credentials before activation and can map one or more model roles; omitted roles inherit from the active defaults.\n\n> See also: [Cross-vendor role-based profiles](./multi-vendor-profiles.md) — a curated multi-vendor `profiles:` recipe and verified selector notes that build on the mechanism described here.\n\n```yaml\nprofiles:\n team-standard:\n required_providers: [openai, anthropic]\n model_mapping:\n default: openai/gpt-5.2\n executor: anthropic/claude-sonnet-5:medium\n architect: openai/o3:high\n planner: openai/o3:high\n critic: openai/o3:high\n```\n\n`model_mapping` keys are role names (`default`, `executor`, `architect`, `planner`, `critic`). Every role accepts either one `provider/modelId[:effort]` selector or a non-empty ordered array of selectors; the first entry is primary and later entries are fallback candidates. `required_providers` is the aggregate set of providers required across the profile's mapped roles.\n\n### Fallback chains\n\nPreset `model_mapping` roles, top-level `modelRoles`, and `task.agentModelOverrides` all accept `string | string[]`. Keep one selector per line when a chain needs to be readable:\n\n```yaml\nprofiles:\n reliable:\n required_providers: [anthropic, openai]\n model_mapping:\n default: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\nmodelBindings:\n modelRoles:\n default: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\n agentModelOverrides:\n executor: [anthropic/claude-sonnet-4-5, openai/gpt-4o-mini]\n```\n\nResolution-time skips for unavailable, unauthenticated, or unknown entries cost zero attempts and advance immediately. Only request-time retryable failures (such as 429, quota, authentication, or 5xx failures) consume an entry's `fallback.maxAttempts` total attempts (default: `3`). The active default fallback remains sticky for the session; role-override fallback state is fresh for each subagent call. The active model is shown consistently in status and `/model`.\n\nManaged fallback attempts buffer provisional streamed output until an attempt is accepted, so output can appear later than it does for a one-model stream. Current Cursor-agent transports are fail-closed unavailable in retryable fallback chains: resolution rejects them with `Cursor model requires provider-side tool execution and cannot be used in a retryable fallback chain` because they do not provide a client-side tool-call mode.\n\nCancellation discards provisional output and emits exactly one cancelled `agent_end`; RPC, ACP, and the TUI therefore settle once. On load, the source-aware one-shot migration reads legacy `retry.fallbackChains`, prepends the effective role chain, and writes the ordered, deduplicated result to the corresponding role array; the legacy key is then ignored.\n\nBuilt-in profiles are grouped by provider mix and tier:\n\n- `codex-{eco,medium,pro}` — GPT-5.6 Sol/Terra/Luna role mixes tuned by tier and reasoning effort\n- `opencodego` — single OpenCode Go preset (Kimi default, DeepSeek executor/architect, Qwen planner, MiMo critic)\n- `claude-opus` — Anthropic OAuth preset centered on `claude-opus-5`\n- Single-provider tiers: `glm-{eco,medium,pro}`, `kimi-coding-plan-{eco,medium,pro}`, `mimo-{eco,medium,pro}`, `grok-{eco,medium,pro}`, `cursor-{eco,medium,pro}`, `minimax-{eco,medium,pro}`\n- Combos: `opus-codex`, `codex-opencodego`, and `fable-opus-codex`\n\nThe `eco`, `medium`, and `pro` Codex profile mappings are current product judgments: Eco assigns Terra low/Luna low/Luna high/Terra xhigh/Terra high to default/executor/planner/critic/architect; Medium assigns Sol low/Terra low/Terra high/Sol xhigh/Sol high; and Pro assigns Sol medium/Terra medium/Sol high/Sol max/Sol xhigh. `opus-codex` retains the Medium Codex executor, critic, and architect roles but uses `anthropic/claude-sonnet-5` for planner; `codex-opencodego` retains the Medium Codex default and architect roles; and `fable-opus-codex` uses the Pro Codex executor and architect roles with `anthropic/claude-opus-5:medium` for planner. The descriptive repeated local exact-edit evidence informs only selected executor-style TypeScript tasks; it does not evaluate or prove default, planner, architect, or critic performance. See [GPT-5.6 Codex preset benchmark](./gpt-5.6-codex-preset-benchmark.md). Effort suffixes are clamped to each model's supported thinking range at preview and activation time. Single-provider tiers pin each provider's current flagship (`zai/glm-5.2`, `kimi-code/kimi-k2.7-code`, `xiaomi/mimo-v2.5-pro`, `xai/grok-4.3`, `cursor/composer-1.5`, `minimax-code/minimax-m3`). User-defined profiles override built-ins by exact profile name.\n\n\nUse `gjc --mpreset ` to activate a profile for the current session only. Activation hard-blocks when any provider listed in `required_providers` lacks credentials. Add `--default` to persist the selected profile as `modelProfile.default` in `config.yml`, so it applies at startup:\n\n```sh\ngjc --mpreset codex-medium\ngjc --mpreset opencodego --default\n```\n\nThe `/model` command opens to a preset landing view: presets are grouped by provider with live auth marks (✓/✗), highlighting a group expands its tiers, and selecting a tier shows the full role→model preview before applying for the session or as default. Typing jumps straight to model search, and `Browse all models` opens the classic tabbed model selector. In `/login`, `Add custom provider` is the first option for configuring credentials needed by custom or profile-required providers; after a successful provider login, the matching preset is recommended automatically.\n\nMiniMax's OpenAI-compatible endpoint rejects multiple system messages and emits thinking in `reasoning_content`, so pin the public-safe compatibility fields when hand-authoring a custom provider:\n\n```yaml\nproviders:\n minimax-custom:\n baseUrl: https://api.minimax.io/v1\n apiKeyEnv: MINIMAX_API_KEY\n api: openai-completions\n compat:\n supportsStore: false\n supportsDeveloperRole: false\n supportsReasoningEffort: false\n reasoningContentField: reasoning_content\n models:\n - id: MiniMax-M2.5\n```\n\nGLM via z.ai is available as the first-class `zai` provider. For a private GLM-compatible proxy, keep secrets in an env var and disable OpenAI-only request fields as needed:\n\n```yaml\nproviders:\n glm-proxy:\n baseUrl: https://api.z.ai/api/paas/v4\n apiKeyEnv: ZAI_API_KEY\n api: openai-completions\n compat:\n supportsDeveloperRole: false\n supportsReasoningEffort: false\n models:\n - id: glm-4.6\n```\n### Allowed auth/discovery values\n\n- `auth`: `apiKey` (default), `none`, or `oauth`; for `models.yml` custom models, `oauth` is accepted by schema but does not waive the `apiKey` requirement\n- `models.yml` is strict: unknown provider/model keys fail validation before provider dispatch, so stale keys such as `requestTransform` or `wireModelId` only work where this document lists them.\n- `discovery.type`: `ollama`, `llama.cpp`, `lm-studio`, or `openai-models-list`\n- `cacheRetention`: `none`, `short`, or `long`; request-time options win over model/modelOverride values, then provider values, then `GJC_CACHE_RETENTION`, then the runtime default. The runtime default is `short` for most providers, but the Anthropic provider defaults to `long` (`ttl: \"1h\"`) because the ~5m default is too fragile for long-running subagent workflows. The 1h marker is only emitted on the canonical Anthropic API (`api.anthropic.com`) for models advertising `supportsLongCacheRetention`; proxies, gateways, and incapable models fall back to the default ephemeral (~5m) breakpoint. For OpenAI Responses, this controls `prompt_cache_retention` only; it does not disable `prompt_cache_key` when a stable session id exists.\n\n## OpenAI-compatible proxy configuration\n\nOpenAI-compatible proxy providers should use schema-supported provider keys first:\n\n```yaml\nproviders:\n proxy-provider:\n baseUrl: https://api.proxy.example/v1\n apiKeyEnv: PROXY_API_KEY\n api: openai-completions\n auth: apiKey\n headers:\n User-Agent: curl/8.7.1\n models:\n - id: local-gpt\n name: Local GPT\n reasoning: true\n input: [text]\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }\n contextWindow: 400000\n maxTokens: 128000\n```\n\nUse provider-level `headers` for proxy-required headers. Keep the provider `api` set to `openai-completions` when the proxy exposes Chat Completions-compatible `/v1/chat/completions` semantics. `auth: apiKey` sends the resolved token as bearer auth; use `auth: none` only for trusted local/no-auth endpoints.\n\n`input` is the model modality list GJC uses to decide whether image content is forwarded. When a custom model omits `input`, GJC defaults to `[text]` (unless a bundled model with the same id contributes a reference). Vision-capable upstream models therefore need an explicit `input: [text, image]`; otherwise `read`/tool images are stripped before the request and replaced with `[image omitted: model does not support vision]`, even if the remote model can see images.\n\n```yaml\nproviders:\n ali:\n baseUrl: https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\n apiKeyEnv: ALI_API_KEY\n api: openai-completions\n auth: apiKey\n models:\n # id-only → text-only; images will be omitted\n - id: some-text-model\n # vision-capable hosted model must declare image input\n - id: qwen3.8-max-preview\n name: Qwen3.8 Max Preview\n reasoning: true\n input: [text, image]\n```\n\n`requestTransform` and `wireModelId` remain supported for request-body shaping, but they are not needed for ordinary OpenAI-compatible proxies whose local model id is already the upstream wire id. Unknown config keys fail validation before a provider request is sent.\n\nWhen request shaping is needed:\n\n- `requestTransform.profile: openai-proxy` strips OpenAI SDK/Stainless telemetry and beta headers at final fetch time and sets a generic GJC user agent.\n- `stripHeaders` replaces the preset strip list when provided.\n- `setHeaders` is applied after stripping; use `null` to remove a header.\n- `extraBody` is shallow-merged into the JSON request body after provider compatibility fields; core transport keys such as `model`, `messages`/`input`, `stream`, `tools`, and `tool_choice` are protected and ignored.\n- Model-level `requestTransform` overrides provider-level fields and shallow-merges `setHeaders`/`extraBody`.\n- `wireModelId` changes only the upstream request body model id; local selection still uses `provider/id`.\n\n### Layofflabs-style proxy example\n\n```yaml\nproviders:\n layofflabs:\n baseUrl: https://api.layofflabs.com/v1\n apiKeyEnv: OPENAI_API_KEY\n api: openai-completions\n auth: apiKey\n headers:\n User-Agent: curl/8.7.1\n models:\n - id: gpt-5.5\n name: GPT 5.5 via Layofflabs\n reasoning: true\n thinking:\n minLevel: low\n maxLevel: xhigh\n mode: effort\n defaultLevel: high\n levels: [low, medium, high, xhigh]\n input: [text]\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }\n contextWindow: 400000\n maxTokens: 128000\n\nmodelBindings:\n modelRoles:\n default: layofflabs/gpt-5.5:high\n agentModelOverrides:\n executor: layofflabs/gpt-5.5:high\n```\n\n## Validation rules (current)\n\n### Full custom provider (`models` is non-empty)\n\nRequired:\n\n- `baseUrl`\n- `apiKey` unless `auth: none`\n- `api` at provider level or each model\n\n### Override-only provider (`models` missing or empty)\n\nMust define at least one of:\n\n- `baseUrl`\n- `headers`\n- `compat`\n- `requestTransform`\n- `disableStrictTools`\n- `modelOverrides`\n- `discovery`\n\n### Discovery\n\n- `discovery` requires provider-level `api`.\n\n### Model value checks\n\n- `id` required\n- `contextWindow` and `maxTokens` must be positive if provided\n- unknown provider, model, override, and request-transform keys fail schema validation; remove stale keys instead of relying on them being ignored.\n\n## Merge and override order\n\nModelRegistry pipeline (on refresh):\n\n1. Load built-in providers/models from `@gajae-code/ai`.\n2. Load `models.yml` custom config.\n3. Apply provider overrides (`baseUrl`, `headers`, `requestTransform`, `disableStrictTools`, `cacheRetention`) to built-in models.\n4. Apply `modelOverrides` (per provider + model id).\n5. Merge custom `models`:\n - same `provider + id` replaces existing\n - otherwise append\n6. Load cached/runtime-discovered models (Ollama, llama.cpp, LM Studio, plus built-in provider managers), then re-apply model overrides.\n\n### Provider-model cache and static fingerprint\n\nCached per-provider model lists are persisted in the model-cache SQLite\ndatabase (schema v3) with a `static_fingerprint` column that hashes the\nstatic catalog slice merged into the row. When `resolveProviderModels`\nskips the network fetch and the fingerprint of the in-memory static\ncatalog matches the cached one, the cached rows are returned verbatim —\nthe static + dynamic merge is bypassed entirely. The fingerprint is\nmemoized per process via a WeakMap keyed by the static-models array\nreference, so repeated cold-start calls do not re-hash.\n\n## Canonical model equivalence and coalescing\n\nThe registry keeps every concrete provider model and then builds a canonical layer above them.\n\nCanonical ids are official upstream ids only, for example:\n\n- `anthropic-model-opus-4-6`\n- `anthropic-model-haiku-4-5`\n- `gpt-5.3-openai-code`\n\n### `models.yml` equivalence config\n\nExample:\n\n```yaml\nproviders:\n zenmux:\n baseUrl: https://api.zenmux.example/v1\n apiKey: ZENMUX_API_KEY\n api: openai-codex-responses\n models:\n - id: openai-code\n name: Zenmux OpenAI code\n reasoning: true\n input: [text]\n cost:\n input: 0\n output: 0\n cacheRead: 0\n cacheWrite: 0\n contextWindow: 200000\n maxTokens: 32768\n\nequivalence:\n overrides:\n zenmux/openai-code: gpt-5.3-openai-code\n p-openai-code/openai-code: gpt-5.3-openai-code\n exclude:\n - demo/openai-code-preview\n```\n\nBuild order for canonical grouping:\n\n1. exact user override from `equivalence.overrides`\n2. bundled official-id matches from built-in model metadata\n3. conservative heuristic normalization for gateway/provider variants\n4. fallback to the concrete model's own id\n\nCurrent heuristics are intentionally narrow:\n\n- embedded upstream prefixes can be stripped when present, for example `anthropic/...` or `openai/...`\n- dotted and dashed version variants can normalize only when they map to an existing official id, for example `4.6 -> 4-6`\n- ambiguous families or versions are not merged without a bundled match or explicit override\n\n### Canonical resolution behavior\n\nWhen multiple concrete variants share a canonical id, resolution uses:\n\n1. availability and auth\n2. `config.yml` `modelProviderOrder`\n3. the lowest combined `cost.input + cost.cacheRead`\n4. existing registry/provider order if the earlier ranks tie\n\nDisabled or unauthenticated providers are skipped. A session that resolves a canonical selector keeps its concrete variant across discovery refreshes; it changes only after an explicit concrete selection or when that variant is no longer available.\n\nSession state and transcripts continue to record the concrete provider/model that actually executed the turn.\n\nProvider defaults vs per-model overrides:\n\n- Provider `headers` are baseline.\n- Model `headers` override provider header keys.\n- `modelOverrides` can override model metadata (`name`, `reasoning`, `input`, `cost`, `contextWindow`, `maxTokens`, `headers`, `compat`, `contextPromotionTarget`).\n- `compat` is deep-merged for nested routing blocks (`openRouterRouting`, `vercelGatewayRouting`, `extraBody`).\n\n## Runtime discovery integration\n\n### Implicit Ollama discovery\n\nIf `ollama` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `ollama`\n- api: `openai-responses`\n- base URL: `OLLAMA_BASE_URL` or `http://127.0.0.1:11434`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery calls Ollama endpoints and normalizes discovered OpenAI-compatible models to `openai-responses`.\n\n### Implicit llama.cpp discovery\n\nIf `llama.cpp` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `llama.cpp`\n- api: `openai-responses`\n- base URL: `LLAMA_CPP_BASE_URL` or `http://127.0.0.1:8080`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery calls llama.cpp model endpoints and synthesizes model entries with local defaults.\n\n### Implicit LM Studio discovery\n\nIf `lm-studio` is not explicitly configured, registry adds an implicit discoverable provider:\n\n- provider: `lm-studio`\n- api: `openai-completions`\n- base URL: `LM_STUDIO_BASE_URL` or `http://127.0.0.1:1234/v1`\n- auth mode: keyless (`auth: none` behavior)\n\nRuntime discovery fetches models (`GET /models`) and synthesizes model entries with local defaults.\n\n### Explicit provider discovery\n\nYou can configure discovery yourself:\n\n```yaml\nproviders:\n ollama:\n baseUrl: http://127.0.0.1:11434\n api: openai-responses\n auth: none\n discovery:\n type: ollama\n\n llama.cpp:\n baseUrl: http://127.0.0.1:8080\n api: openai-responses\n auth: none\n discovery:\n type: llama.cpp\n```\n\n### Extension provider registration\n\nExtensions can register providers at runtime (`pi.registerProvider(...)`), including:\n\n- model replacement/append for a provider\n- custom stream handler registration for new API IDs\n- custom OAuth provider registration\n\n## Auth and API key resolution order\n\nWhen requesting a key for a provider, effective order is:\n\n1. Runtime override (CLI `--api-key`)\n2. Stored API key credential in `agent.db`\n3. Stored OAuth credential in `agent.db` (with refresh)\n4. Environment variable mapping (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.)\n5. ModelRegistry fallback resolver (provider `apiKey` from `models.yml`, env-name-or-literal semantics)\n\n`models.yml` `apiKey` behavior:\n\n- Value is first treated as an environment variable name.\n- If no env var exists, the literal string is used as the token.\n\nIf `authHeader: true` and provider `apiKey` is set, models get:\n\n- `Authorization: Bearer ` header injected.\n\nKeyless providers:\n\n- Providers marked `auth: none` are treated as available without credentials.\n- `getApiKey*` returns `kNoAuth` for them.\n\n### Broker mode\n\nWhen `GJC_AUTH_BROKER_URL` (or `auth.broker.url`) is set, the local SQLite credential store is replaced by `RemoteAuthCredentialStore`. Layers 2 and 3 above (stored API key / OAuth in `agent.db`) are served from a broker-supplied snapshot whose `refresh` tokens are redacted; expiry triggers `POST /v1/credential/:id/refresh` on the broker rather than a local refresh.\n\n`AuthStorage.setConfigApiKey` lets a `models.yml` `apiKey` win over a broker-resolved OAuth token without overriding a runtime `--api-key`. See [`auth-broker-gateway.md`](./auth-broker-gateway.md) for the full broker / gateway design and env surface (`GJC_AUTH_BROKER_URL`, `GJC_AUTH_BROKER_TOKEN`, `auth.broker.url`, `auth.broker.token`).\n\n## Model availability vs all models\n\n- `getAll()` returns the loaded model registry (built-in + merged custom + discovered).\n- `getAvailable()` filters to models that are keyless or have resolvable auth.\n\nSo a model can exist in registry but not be selectable until auth is available.\n\n## Runtime model resolution\n\n### CLI and pattern parsing\n\n`model-resolver.ts` supports:\n\n- exact `provider/modelId`\n- exact canonical model id\n- exact model id (provider inferred)\n- fuzzy/substring matching\n- glob scope patterns in `--models` (e.g. `openai/*`, `*sonnet*`)\n- optional `:thinkingLevel` suffix (`off|minimal|low|medium|high|xhigh`)\n\n`--provider` is legacy; `--model` is preferred.\n\nResolution precedence for exact selectors:\n\n1. exact `provider/modelId` bypasses coalescing\n2. exact canonical id resolves through the canonical index\n3. exact bare concrete id still works\n4. fuzzy and glob matching run after the exact paths\n\nThinking suffixes are split once from the final `:` only after the complete selector does not resolve. This preserves concrete OpenRouter route IDs such as `openrouter/z-ai/glm-4.7:nitro`; `:high` can follow that route suffix. Multiple suffixes are not recursively consumed. A complete `provider/modelId` selector is exact-only: it never falls back to fuzzy, substring, glob, or another provider when that concrete selector is absent. Exact-case provider/model entries resolve deterministically for custom replacement semantics; a case-insensitive selector that remains ambiguous does not guess.\n\n### Initial model selection priority\n\n`findInitialModel(...)` uses this order:\n\n1. explicit CLI provider+model\n2. first scoped model (if not resuming)\n3. saved default provider/model\n4. known provider defaults (e.g. OpenAI/Anthropic/etc.) among available models\n5. first available model\n\n### Role aliases and settings\n\nSupported model roles:\n\n- `default` plus the agent assignment targets `executor`, `architect`, `planner`, `critic`\n\nRole aliases like `pi/default` expand through `settings.modelRoles`. Each role value can also append a thinking selector such as `:minimal`, `:low`, `:medium`, or `:high`.\n\nIf a role points at another role, the target model still inherits normally and any explicit suffix on the referring role wins for that role-specific use.\n\nRelated settings:\n\n- `modelRoles` (record)\n- `enabledModels` (scoped pattern list)\n- `modelProviderOrder` (global canonical-provider precedence)\n- `providers.kimiApiFormat` (`openai` or `anthropic` request format)\n- `providers.openaiWebsockets` (`auto|off|on` websocket preference for OpenAI code provider transport)\n\n`modelRoles` may store either:\n\n- `provider/modelId` to pin a concrete provider variant\n- a canonical id such as `gpt-5.3-openai-code` to allow provider coalescing\n\nFor `enabledModels` and CLI `--models`:\n\n- exact canonical ids expand to all concrete variants in that canonical group\n- explicit `provider/modelId` entries stay exact\n- globs and fuzzy matches still operate on concrete models\n\nGlobal `enabledModels` and `disabledProviders` entries may also be scoped to a path prefix:\n\n```yaml\nenabledModels:\n - anthropic-model-sonnet-4-5\n - path: ~/work\n models:\n - anthropic/anthropic-model-opus-4-5\ndisabledProviders:\n - ollama\n - path: ~/private\n providers:\n - anthropic\n```\n\nString entries apply everywhere. Scoped entries apply when the current working directory is the configured path or one of its subdirectories. Use `path`, `paths`, `pathPrefix`, or `pathPrefixes`; use `models` for `enabledModels`, `providers` for `disabledProviders`, or `values` for either.\n\n## `/model` and `--list-models`\n\nBoth surfaces keep provider-prefixed models visible and selectable.\n\nThey now also expose canonical/coalesced models:\n\n- `/model` includes a canonical view alongside provider tabs\n- `--list-models` prints a canonical section plus the concrete provider rows\n\nSelecting a canonical entry stores the canonical selector. Selecting a provider row stores the explicit `provider/modelId`.\n\n## Context promotion (model-level fallback chains)\n\nContext promotion is an overflow recovery mechanism for small-context variants (for example `*-spark`) that automatically promotes to a larger-context sibling when the API rejects a request with a context length error. It is **off by default** (`contextPromotion.enabled` is `false`); opt in to enable it.\n\n### Trigger and order\n\nWhen a turn fails with a context overflow error (e.g. `context_length_exceeded`), `AgentSession` attempts promotion **before** falling back to compaction:\n\n1. If `contextPromotion.enabled` is true, resolve a promotion target (see below).\n2. If a target is found, switch to it and retry the request — no compaction needed.\n3. If no target is available, fall through to auto-compaction on the current model.\n\n### Target selection\n\nSelection is model-driven, not role-driven:\n\n1. `currentModel.contextPromotionTarget` (if configured)\n2. smallest larger-context model on the same provider + API\n\nCandidates are ignored unless credentials resolve (`ModelRegistry.getApiKey(...)`).\n\n### OpenAI code provider websocket handoff\n\nIf switching from/to `openai-codex-responses`, session provider state key `openai-codex-responses` is closed before model switch. This drops websocket transport state so the next turn starts clean on the promoted model.\n\n### Persistence behavior\n\nPromotion uses temporary switching (`setModelTemporary`):\n\n- recorded as a temporary `model_change` in session history\n- does not rewrite saved role mapping\n\n### Configuring explicit fallback chains\n\nConfigure fallback directly in model metadata via `contextPromotionTarget`.\n\n`contextPromotionTarget` accepts either:\n\n- `provider/model-id` (explicit)\n- `model-id` (resolved within current provider)\n\nExample (`models.yml`) for Spark -> non-Spark on the same provider:\n\n```yaml\nproviders:\n openai-code:\n modelOverrides:\n gpt-5.3-openai-code-spark:\n contextPromotionTarget: openai-code/gpt-5.3-openai-code\n```\n\nThe built-in model generator also assigns this automatically for `*-spark` models when a same-provider base model exists.\n\n## Compatibility and routing fields\n\nThe `compat` block on a provider or model overrides the URL-based auto-detection in `packages/ai/src/providers/openai-completions-compat.ts`. It is validated by `OpenAICompatSchema` in `packages/coding-agent/src/config/model-registry.ts` and consumed by every `openai-completions` transport (`packages/ai/src/providers/openai-completions.ts`). The canonical type is `OpenAICompat` in `packages/ai/src/types.ts`.\n\n`models.yml` accepts the following keys (all optional; unset falls back to URL detection):\n\nRequest shaping:\n\n- `supportsStore` — emit `store: false` on requests. Default: auto (off for non-standard endpoints).\n- `supportsDeveloperRole` — use the `developer` system role for reasoning models instead of `system`. Default: auto.\n- `sendSessionHeaders` — forward the agent session id as `session_id` and `x-session-id` request headers so OpenAI-compatible relays/proxies can do session-affinity routing and reuse a server-side prompt cache. Default: `false`. Caller-set `headers`/`requestTransform` values are never overwritten.\n- `supportsUsageInStreaming` — send `stream_options: { include_usage: true }` to receive token usage on streaming responses. Default: `true`.\n- `maxTokensField` — `\"max_completion_tokens\"` or `\"max_tokens\"`. Default: auto.\n- `supportsToolChoice` — emit the `tool_choice` parameter when the caller forces a specific tool. Default: `true`. Set `false` for endpoints that 400 on `tool_choice` (e.g. DeepSeek when reasoning is on).\n- `disableReasoningOnForcedToolChoice` — drop `reasoning_effort` / OpenRouter `reasoning` whenever `tool_choice` forces a call. Default: auto (Kimi/Anthropic-fronted endpoints).\n- `extraBody` — extra top-level fields merged into every request body (gateway hints, controller selectors, etc.).\n\nReasoning / thinking:\n\n- `supportsReasoningEffort` — accept `reasoning_effort`. Default: auto (off for Grok and zAI).\n- `reasoningEffortMap` — partial map from internal effort levels (`minimal|low|medium|high|xhigh`) to provider-specific strings (e.g. DeepSeek maps `xhigh -> \"max\"`).\n- `thinkingFormat` — request shape for thinking: `\"openai\"` (`reasoning_effort`), `\"openrouter\"` (`reasoning: { effort }`), `\"zai\"` (`thinking: { type: \"enabled\" }`), `\"qwen\"` (top-level `enable_thinking`), or `\"qwen-chat-template\"` (`chat_template_kwargs.enable_thinking`). Default: `\"openai\"`.\n- `reasoningContentField` — assistant field carrying chain-of-thought: `\"reasoning_content\"`, `\"reasoning\"`, or `\"reasoning_text\"`. Default: auto.\n- `requiresReasoningContentForToolCalls` — assistant tool-call turns must round-trip the reasoning field (DeepSeek-R1, Kimi, OpenRouter when reasoning is on). Default: `false`.\n- `requiresAssistantContentForToolCalls` — assistant tool-call turns must include non-empty text content (Kimi). Default: `false`.\n\nTool / message normalization:\n\n- `requiresToolResultName` — tool-result messages need a `name` field (Mistral). Default: auto.\n- `requiresAssistantAfterToolResult` — a user message after a tool result needs an assistant turn in between. Default: auto.\n- `requiresThinkingAsText` — convert thinking blocks to text wrapped in `` delimiters (Mistral). Default: auto.\n- `requiresMistralToolIds` — normalize tool-call ids to exactly 9 alphanumeric chars. Default: auto.\n- `supportsStrictMode` — accept the per-tool `strict` field on tool schemas. Default: conservative auto-detect per provider/baseUrl.\n- `toolStrictMode` — `\"all_strict\"` forces strict on every tool, `\"none\"` forces it off; unset keeps the existing per-tool mixed behavior.\n\nGateway routing (only applied when `baseUrl` matches the gateway):\n\n- `openRouterRouting.only` / `openRouterRouting.order` — provider routing on `openrouter.ai` (see ).\n- `vercelGatewayRouting.only` / `vercelGatewayRouting.order` — provider routing on `ai-gateway.vercel.sh` (see ).\n\nProvider-level `compat` is the baseline; per-model `compat` is deep-merged on top, with `openRouterRouting`, `vercelGatewayRouting`, and `extraBody` merged as nested objects.\n\n### Anthropic compatibility (`anthropic-messages`)\n\nFor `anthropic-messages` models the runtime uses a separate `AnthropicCompat` shape (`packages/ai/src/types.ts`). The `models.yml` schema currently exposes only the strict-tools opt-out as a top-level provider field (see below); the remaining Anthropic-side knobs (`disableAdaptiveThinking`, `supportsEagerToolInputStreaming`, `supportsLongCacheRetention`) are set by built-in catalog metadata and are not user-configurable from `models.yml`.\n\n### Strict tool schemas (`disableStrictTools`)\n\nAnthropic's API supports a `strict` field on tool definitions that forces the model to always follow the provided schema exactly. This is enabled by default for all `anthropic-messages` providers because it guarantees schema conformance in agentic systems.\n\nThird-party providers that front the Anthropic API (AWS Bedrock, Azure, self-hosted proxies) do not always implement this field and will reject requests that include it. Set `disableStrictTools: true` at the provider level to opt out:\n\n```yaml\nproviders:\n bedrock-anthropic:\n baseUrl: https://bedrock-runtime.us-east-1.amazonaws.com/anthropic\n apiKey: AWS_BEARER_TOKEN\n api: anthropic-messages\n disableStrictTools: true\n models:\n - id: anthropic-model-sonnet-4-20250514\n name: Anthropic model Sonnet 4 (Bedrock)\n input: [text, image]\n contextWindow: 200000\n maxTokens: 16384\n cost:\n input: 3.00\n output: 15.00\n cacheRead: 0.30\n cacheWrite: 3.75\n```\n\n`disableStrictTools` is a provider-level flag that applies to all models in the provider.\n\nTool schemas going on the wire are normalized by the unified flow in\n`packages/ai/src/utils/schema/normalize.ts` (Google/CCA/MCP dispatchers\nplus the OpenAI strict-mode sanitize+enforce pipeline). See\n[`ai-schema-normalize.md`](./ai-schema-normalize.md) for the strict-mode\nedge cases (local `$ref` inlining, single-item `allOf` collapse,\n`anyOf`-wrapper description hoist, enum/const primitive-type inference)\nand the per-provider dispatcher mapping.\n## Practical examples\n\n### Local OpenAI-compatible endpoint (no auth)\n\n```yaml\nproviders:\n local-openai:\n baseUrl: http://127.0.0.1:8000/v1\n auth: none\n api: openai-completions\n models:\n - id: Qwen/Qwen2.5-Coder-32B-Instruct\n name: Qwen 2.5 Coder 32B (local)\n```\n\n### Hosted proxy with env-based key\n\n```yaml\nproviders:\n anthropic-proxy:\n baseUrl: https://proxy.example.com/anthropic\n apiKey: ANTHROPIC_PROXY_API_KEY\n api: anthropic-messages\n authHeader: true\n disableStrictTools: true # if the proxy doesn't support strict tool schemas\n models:\n - id: anthropic-model-sonnet-4-20250514\n name: Anthropic model Sonnet 4 (Proxy)\n reasoning: true\n input: [text, image]\n```\n\n### Override built-in provider route + model metadata\n\n```yaml\nproviders:\n openrouter:\n baseUrl: https://my-proxy.example.com/v1\n headers:\n X-Team: platform\n modelOverrides:\n anthropic/anthropic-model-sonnet-4:\n name: Sonnet 4 (Corp)\n compat:\n openRouterRouting:\n only: [anthropic]\n```\n\n## Legacy consumer caveat\n\nMost model configuration now flows through `models.yml` via `ModelRegistry`. Explicit `.json` / `.jsonc` paths remain supported only when passed programmatically to `ModelRegistry`; the default user config is `~/.gjc/agent/models.yml`.\n\n## Failure mode\n\nIf `models.yml` fails schema or validation checks:\n\n- registry keeps operating with built-in models\n- error is exposed via `ModelRegistry.getError()` and surfaced in UI/notifications\n", + "multi-vendor-profiles.md": "# Choosing models in GJC: role-based profiles\n\nA practical guide to picking models for GJC's roles, for every subscription situation — one vendor, two vendors, or the full multi-vendor set. It adds curated cross-vendor `profiles:` for `~/.gjc/agent/models.yml` and verified selector notes on top of the mechanism in [Model profiles](./models.md#model-profiles---mpreset). Everything here is **user config**; it complements the built-in `--mpreset` presets and overrides a built-in only when it shares its exact name.\n\n> Selectors, prices, and \"axis leaders\" are catalog- and time-sensitive (selectors and prices observed 2026-07 on the current bundled catalog; the measured latency and single-message-limit notes below were observed 2026-06 on `claude-opus-4-8` and have not been re-measured on `claude-opus-5`). Re-verify any selector with `gjc -p --no-session --no-tools --model \"Reply OK\"`.\n\n## The five roles\n\n`default` runs the main loop and most turns; `executor` / `architect` / `planner` / `critic` are the four bundled task agents, delegated only when the work calls for it.\n\n| Role | What it optimizes for |\n| --- | --- |\n| `default` | tool-calling reliability + honesty (it routes — its quality bounds the whole system) |\n| `executor` | real coding (SWE-bench Verified) |\n| `planner` | reasoning + sequencing (GPQA / ARC-AGI-2) |\n| `architect` | large-context + multimodal review |\n| `critic` | independent adversarial review (different family from what it reviews) |\n\n## Pick by what you subscribe to\n\n| You have | Use |\n| --- | --- |\n| **One vendor** | the built-in preset for that vendor — `claude-opus` (Anthropic), `codex-{eco,medium,pro}` (OpenAI/Codex), `opencodego` (OpenCode Go), or a single-vendor flagship tier (`zai/glm-5.2`, `kimi-code/...`, `xiaomi/...`, `xai/grok-4.3`, `minimax-code/...`). These already map all five roles inside one vendor. |\n| **Claude + Codex** | the built-in `opus-codex` (Claude main loop + Codex support roles). |\n| **Three or more / all five** | the cross-vendor profiles below — each role on its axis leader, `critic` kept cross-family. |\n\nThe single guiding rule across all of these: **keep `default` on the strongest router you have** (Anthropic Opus when available). A weak `default` caps quality regardless of the delegated models.\n\n## Cross-vendor profiles (3+ vendors)\n\nNo single vendor leads every axis, so these put each role on its axis leader and keep `critic` on a different family from the `executor` it reviews.\n\n```yaml\nprofiles:\n\n daily: # everyday balance\n required_providers: [anthropic, openai-codex, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-5:medium\n executor: openai-codex/gpt-5.4:high\n planner: google-antigravity/gemini-3.1-pro-low:high\n architect: google-antigravity/gemini-3.1-pro-low:high\n critic: xai/grok-4.3:medium\n\n ultimate: # cost-no-object, best per role\n required_providers: [anthropic, openai-codex, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-5:high\n executor: anthropic/claude-opus-5:max\n planner: openai-codex/gpt-5.5:xhigh\n architect: google-antigravity/gemini-3.1-pro-low:high\n critic: xai/grok-4.3:high\n\n eco: # cheapest delegated work; main loop stays on Opus\n required_providers: [anthropic, opencode-go, google-antigravity, xai]\n model_mapping:\n default: anthropic/claude-opus-5:low\n executor: opencode-go/deepseek-v4-flash\n planner: xai/grok-4-1-fast:high\n architect: google-antigravity/gemini-3.1-pro-low\n critic: google-antigravity/gemini-3.5-flash\n\n monorepo: # huge codebases (openai-codex excluded: 272k context cap)\n required_providers: [anthropic, google-antigravity, opencode-go]\n model_mapping:\n default: anthropic/claude-opus-5:medium\n executor: anthropic/claude-opus-5:high\n planner: google-antigravity/gemini-3.1-pro-low:high\n architect: anthropic/claude-opus-5:high\n critic: opencode-go/glm-5.2\n\n reviewer: # review/audit stance — the author-mode role split, inverted\n required_providers: [anthropic, openai-codex, google-antigravity]\n model_mapping:\n default: anthropic/claude-opus-5:high # aggregator restraint: preserve raw reviewer verdicts\n executor: openai-codex/gpt-5.5:high # support — repro PoCs, failing tests, harnesses\n planner: google-antigravity/gemini-3.1-pro-low:high # review checklists / audit scoping\n architect: anthropic/claude-opus-5:high # lead 1 — primary code-review judge (effective long-context)\n critic: openai-codex/gpt-5.5:high # lead 2 — merge gate, cross-family vs Claude-authored code\n```\n\n## Reviewer stance and the external review gate\n\nThe profiles above assume an **authoring** stance: `executor` is the lead and `architect`/`critic` verify its work. In a session whose primary job is reviewing or auditing (not writing) code, the roles invert — `architect`/`critic` become the leads and `executor` is support (reproduction PoCs, failing tests). The `reviewer` profile encodes that inversion, with one generalized provenance rule: **the reviewing model family must differ from the family that authored the code under review**, not merely from the session's own executor.\n\nA verified use is the cross-session final review gate: the authoring session launches a fresh, stateless reviewer sub-session so the finished diff is judged without the authoring context:\n\n```sh\n# the one-shot gate needs only a cross-family --model; add --mpreset reviewer as an\n# optional enhancement AFTER installing this profile in ~/.gjc/agent/models.yml:\ngjc -p --no-session --model openai-codex/gpt-5.5:xhigh --tools read,search,find \"\"\n```\n\nThe `--tools` allowlist is part of the contract: it enforces the reviewer's read-only boundary for the built-in tool surface instead of trusting the prompt (the runtime still injects the session `goal` tool unless `goal.enabled` is off — disabling it for the reviewer invocation is **mandatory**, via a dedicated gate directory outside the repo so the reviewed checkout stays clean, see the template — plus `generate_image` when an image credential exists). In this one-shot form the session's `default` model authors the verdict — a tool-restricted print session cannot delegate to the profile's `critic`/`architect` roles — so the explicit cross-family `--model` carries provenance, and the `reviewer` profile itself serves the interactive review-session case (activate it with `--mpreset reviewer` only after copying it into `models.yml`; otherwise activation fails with an unknown-profile error). Profile names in this document live in the user namespace — a user profile overrides a builtin preset only on an exact name match, and a future builtin with the same name would be silently shadowed by your copy.\n\nSee [Extragoal local skill template](./extragoal-skill-template.md) for the full gate workflow (verdict contract, findings triage, bounded re-sign loop, secret-scan and injection guards) built on this recipe.\n\n## Model cheatsheet (by need)\n\nCurrent axis leaders and the cheaper second option, with metered price ($/1M in/out; Gemini via Antigravity runs on the Google AI subscription):\n\n| Need | First pick | Cheaper option |\n| --- | --- | --- |\n| Router / tool-calling (`default`) | `anthropic/claude-opus-5` (5/25) | `anthropic/claude-sonnet-5` (3/15) |\n| Coding (`executor`) | `anthropic/claude-opus-5` (5/25) — the prior `claude-opus-4-8` scored SWE-bench Verified ~88.6; no Opus 5 measurement yet | `openai-codex/gpt-5.4` (2.5/15) · `opencode-go/deepseek-v4-flash` (0.14/0.28) |\n| Reasoning (`planner`) | `openai-codex/gpt-5.5` (ARC-AGI-2) / `google-antigravity/gemini-3.1-pro-low:high` (GPQA) | `xai/grok-4-1-fast` (0.2/0.5) |\n| Large context (`architect`) | `anthropic/claude-opus-5` (effective long-context) | `xai/grok-4-fast` (2M nominal, 0.2/0.5) |\n| Multimodal review (`architect`) | `google-antigravity/gemini-3.1-pro-low:high` | `google-antigravity/gemini-3.5-flash` |\n| Independent critic | `xai/grok-4.3` (1.25/2.5) | `opencode-go/glm-5.2` · `google-antigravity/gemini-3.5-flash` |\n\nOn standard tasks, all current frontier models in the catalog are accurate; **pick by cost, latency, and role fit, not by raw accuracy on easy prompts.** As an indicative GJC-routed latency reference (`gjc -p`, identical coding + reasoning prompts, all correct): `grok-4.3` and `glm-5.2` ≈ 2–3s, `deepseek-v4-pro` ≈ 3–4s, `claude-opus-4-8` / `gpt-5.5` ≈ 4–7s, `gemini-3.1-pro-low:high` ≈ 7s. `claude-opus-5` shares Opus 4.8's published context/output envelope but has not been latency-measured here.\n\n## Verified selector notes (current catalog)\n\nObserved via live `gjc -p` calls; useful when wiring the profiles above:\n\n- **Antigravity Gemini, high reasoning** → use `google-antigravity/gemini-3.1-pro-low:high`. The id `gemini-3.1-pro-high` returns HTTP 400 (no matching backend model); `thinkingLevel` is a per-request parameter, so raising it on `gemini-3.1-pro-low` invokes the model's native high-reasoning mode rather than a degraded one.\n- **openai-codex on a ChatGPT account** serves base GPT only (`gpt-5.5`, `gpt-5.4`). Standalone `-codex` variants (`gpt-5.3-codex`, `gpt-5.2-codex`, `gpt-5.1-codex-max` / `-mini`) return `not supported when using Codex with a ChatGPT account`.\n- **Single-message input limit is separate from the context window.** Measured on `claude-opus-4-8` (not yet re-measured on `claude-opus-5`, which publishes the same 1M window): the model runs with a 1M window via multi-turn accumulation, but a single `@file` message above ~400k tokens returns 400 on `anthropic` / `google-antigravity`; `xai` / `opencode-go` accept larger single messages. Chunk very large inputs across turns instead of pasting one block.\n- **Some selectors come from a provider's live catalog, not the bundled snapshot.** `opencode-go/glm-5.2` and `google-antigravity/gemini-3.5-flash` resolved in `gjc -p` tests but are **not** in `packages/ai/src/models.json`; they appear only after the provider's online model discovery has populated the registry. `required_providers` verifies credentials at activation — it does **not** guarantee fresh, non-stale discovery — so activation can still fail with `selector did not resolve` until discovery runs (re-login or retry to refresh). If you hit that, substitute a bundled id: `opencode-go/deepseek-v4-pro` for the critic, or `zai/glm-5.2` (add `zai` to `required_providers`) for GLM 5.2.\n\n## Activation\n\n```bash\ngjc --mpreset daily # this session only\ngjc --mpreset ultimate --default # persist as the startup default (config.yml)\n```\n\nActivation hard-blocks when any provider in `required_providers` lacks credentials, so log in first: `/login anthropic`, `/login openai-codex`, `/login google-antigravity`, `/login xai` (and `opencode-go` via `OPENCODE_API_KEY`).\n", "native-ffi-optimization-policy.md": "# ADR: Native FFI Optimization Policy\n\n- Status: Accepted\n- Scope: `crates/pi-natives` algorithmic ports proposed for performance reasons\n- Related: [`porting-to-natives.md`](./porting-to-natives.md), [`natives-architecture.md`](./natives-architecture.md), [`natives-binding-contract.md`](./natives-binding-contract.md), [`cpu-hotspot-map.json`](./cpu-hotspot-map.json), [`hotspot-map-successor.md`](./hotspot-map-successor.md)\n\n## Decision\n\nA new native (Rust N-API / FFI) port proposed **to optimize a leftover hot path** does not land unless **all** of the following gates pass:\n\n1. **Corpus evidence** — a profiling-corpus trace shows the path has user-visible latency or RSS impact on a representative workload (not just a static complexity argument).\n2. **Self-time attribution** — a `profilerSelfTime` artifact identifies the proposed hotspot, **or** fallback-toggle evidence proves an end-to-end benefit without byte changes. Wall-clock proxy timing alone is never sufficient.\n3. **Measured FFI overhead** — the N-API call/marshalling overhead is measured against the JS/TS baseline, not assumed away.\n4. **Representative win** — a representative p50/p95 win exists on realistic inputs, not only microbenchmark seed results.\n5. **Byte parity** — a byte-identical corpus covers rendered, persisted, and provider-visible bytes for the changed path.\n6. **Operational cost** — fallback, packaging, and rollback costs are documented.\n\nThis policy governs **speculative algorithmic ports**. It does **not** re-litigate already-native platform/system surfaces (see [Scope boundary](#scope-boundary)).\n\n## Context\n\nThe CPU/memory hotspot program (Optimization Suites v1–v3, tracked in [`cpu-hotspot-map.json`](./cpu-hotspot-map.json)) is closed out. Its prioritization was a **static structural ranking** (algorithmic complexity × trigger frequency), and the map's own `method` field records that real CPU self-time was \"to be measured by the agreed profiling corpus during optimization.\" That corpus is being built separately; until its evidence exists, new native ports for leftover hotspots would repeat the same evidence gap.\n\nThe suites already produced concrete decisions that this policy codifies so they are not re-discovered:\n\n- **v2 (#530)** measured and **rejected the five remaining Rust port candidates** per the FFI cost gates after shipping only `diffLines` (H03) natively. Native overhead did not beat the JS/TS baseline for those candidates on realistic inputs.\n- **v3 (#558) rejected a native word-diff (H04)** \"without a fresh FFI gate\" — the TS fast paths were retained instead; a native port would need to re-clear gates 1–6 above.\n- **Hunt-Szymanski LCS (H05)** was implemented as a native/algorithmic replacement, then **reverted** because it produced byte-different rendered diffs (reproduced by red-team). Byte parity is the gate, not raw speed.\n- **The custom JSON length counter (H08)** was implemented, made exact, then **deleted** — an exact JS reimplementation was not faster than native `JSON.stringify`. \"More native\" is not automatically \"faster.\"\n\nThese four precedents share a root cause: a plausible algorithmic/native win that failed a real gate (cost, byte parity, or end-to-end benefit). The policy makes those gates a precondition rather than a post-hoc discovery.\n\n## Evidence taxonomy\n\nNative-port claims must classify their evidence using the same separated classes as the profiling corpus. These classes must never be conflated:\n\n- **`wallClockPhase`** — elapsed timing around a phase or operation. Useful for perceived-latency and regression detection; **insufficient** to confirm CPU self-time or to justify a port on its own.\n- **`processCpuUsage`** — `process.cpuUsage()` user/system deltas, optionally normalized by elapsed time. Indicates process-level CPU pressure; **cannot** attribute self-time to a specific hotspot.\n- **`profilerSelfTime`** — profiler (or equivalent sampled/trace) attribution of self-time to a function, module, or native symbol. **Required** before a hotspot may be called \"CPU-self-time confirmed.\"\n\nA native-optimization proposal that cites only `wallClockPhase` or `processCpuUsage` is **not** CPU-self-time confirmed and does not clear gate 2.\n\n## Approval checklist\n\nBefore opening a native-optimization PR, confirm and attach evidence for each:\n\n- [ ] Corpus trace shows user-visible latency or RSS impact for the path (gate 1).\n- [ ] `profilerSelfTime` artifact identifies the hotspot, **or** fallback-toggle before/after evidence proves end-to-end benefit without byte changes (gate 2).\n- [ ] FFI/marshalling overhead measured vs the JS/TS baseline in the same benchmark run (gate 3).\n- [ ] Representative p50/p95 win on realistic inputs, not only seeded microbench results (gate 4).\n- [ ] Byte-identical corpus covers rendered, persisted, and provider-visible bytes (gate 5).\n- [ ] Fallback, packaging (platform variants / embedded addon), and rollback costs documented (gate 6).\n\nIf any box is unchecked, keep the work in TypeScript or hold it as a tracked candidate; do not switch callsites. This mirrors the existing **Rule of thumb** in [`porting-to-natives.md`](./porting-to-natives.md): if native is not faster *and* behavior-compatible, do not switch callsites.\n\n## Scope boundary\n\nThis policy targets **speculative algorithmic ports**, not the established native surface. The following are **already native** by design and are explicitly out of scope (see `alreadyNativeExcluded` in [`cpu-hotspot-map.json`](./cpu-hotspot-map.json)):\n\n`grep`, `fd`/`glob`, text width/wrap/truncate/slice, syntax highlighting, HTML→Markdown, token counting, AST, summary, process/PTY/shell, SIXEL, clipboard, `Bun.hash.xxHash32/64`, and `JSON.parse`/`JSON.stringify`.\n\nThese are native because they are I/O, OS/process integration, or platform primitives — the criteria in [`porting-to-natives.md`](./porting-to-natives.md#when-to-port). Distinguishing them from algorithmic ports matters: a leftover algorithmic hotspot must clear gates 1–6, whereas adding a new OS/process/native-primitive binding follows the standard porting guide.\n\n## Consequences\n\n- New native algorithmic ports require profiling-corpus evidence and a measured cost gate before review; this slows speculative optimization but prevents byte-parity regressions and dead native code.\n- The default answer for a leftover hotspot is \"keep it in TypeScript\" until the corpus proves it matters.\n- Already-native platform/system primitives and new OS/process bindings are unaffected; they follow [`porting-to-natives.md`](./porting-to-natives.md) as before.\n- Reviewers can reject a native-optimization PR purely on a missing gate, citing this ADR, without re-deriving the rationale.\n\n## Follow-ups\n\n- Held native candidates (H04 word-diff, H05 LCS, and other v2-rejected candidates) stay held unless a future PR clears gates 1–6 with fresh corpus evidence.\n- When the profiling corpus lands, link its threshold/evidence ledger here so native-port proposals can cite concrete corpus artifacts.\n", "natives-addon-loader-runtime.md": "# Natives Addon Loader Runtime\n\nThis document covers the runtime loader shipped by `@gajae-code/natives`: how `native/index.js` decides which `.node` file to require, how compiled-binary embedded payloads are extracted, and what startup failures report.\n\n## Implementation files\n\n- `packages/natives/native/index.js`\n- `packages/natives/native/loader-state.js`\n- `packages/natives/native/embedded-addon.js`\n- `packages/natives/scripts/embed-native.ts`\n- `packages/natives/package.json`\n\n## Scope and responsibility\n\nThe loader is intentionally narrow:\n\n- Build a platform/CPU-aware candidate list for addon filenames and directories.\n- Treat an embedded-addon manifest as the authoritative compiled-binary signal when present.\n- Optionally materialize an embedded addon into a versioned per-user cache directory.\n- Attempt candidates in deterministic order and return the first addon that `require(...)` loads.\n\nThe current loader does **not** run a separate `validateNative(...)` export-presence gate. API shape is provided by the generated N-API binding file (`native/index.d.ts`) and the loaded addon itself. A stale binary therefore normally fails as a missing property or native load error rather than as a custom \"missing exports\" validation error.\n\n## Runtime inputs and derived state\n\nAt module initialization, `native/index.js` computes:\n\n- **Platform tag**: `${process.platform}-${process.arch}` (for example `darwin-arm64`).\n- **Package version**: from `packages/natives/package.json`.\n- **Core directories**:\n - `nativeDir`: package-local `packages/natives/native`.\n - `execDir`: directory containing `process.execPath`.\n - `versionedDir`: `/`.\n - `userDataDir` fallback:\n - Windows: `%LOCALAPPDATA%/gjc` or `%USERPROFILE%/AppData/Local/gjc`.\n - Non-Windows: `~/.local/bin`.\n- **Natives cache root** (`getNativesDir()`):\n - if `$XDG_DATA_HOME/gjc` exists, `$XDG_DATA_HOME/gjc/natives`;\n - otherwise `~/.gjc/natives`.\n- **Compiled-binary mode** (`detectCompiledBinary`): true if any of:\n - embedded-addon manifest is non-null,\n - `GJC_COMPILED` env var is set,\n - `import.meta.url` contains Bun embedded markers (`$bunfs`, `~BUN`, `%7EBUN`).\n- **Variant override**: `GJC_NATIVE_VARIANT` (`modern`/`baseline` only; invalid values ignored).\n- **Selected variant**: explicit override, otherwise runtime AVX2 detection on x64 (`modern` if AVX2, else `baseline`).\n\n## Platform support and tag resolution\n\n`SUPPORTED_PLATFORMS` is fixed to:\n\n- `linux-x64`\n- `linux-arm64`\n- `darwin-arm64`\n- `win32-x64`\n\nUnsupported platforms are not rejected before probing. The loader first tries the computed candidate paths. If all fail and `platformTag` is unsupported, it throws an unsupported-platform error listing supported tags.\n\n## Variant selection (`modern` / `baseline` / default)\n\n### x64 behavior\n\n1. `GJC_NATIVE_VARIANT=modern|baseline` wins when valid.\n2. Otherwise AVX2 support is detected:\n - Linux: scan `/proc/cpuinfo` for `avx2`.\n - macOS: `sysctl -n machdep.cpu.leaf7_features`, then `machdep.cpu.features`.\n - Windows: PowerShell `[System.Runtime.Intrinsics.X86.Avx2]::IsSupported`.\n3. AVX2 selects `modern`; unavailable or undetectable AVX2 selects `baseline`.\n\n### Non-x64 behavior\n\nNo variant suffix is used; the filename is `pi_natives.-.node`.\n\n### Filename construction\n\n`loader-state.js#getAddonFilenames` returns:\n\n- Non-x64 or no variant: `pi_natives..node`\n- x64 + `modern`:\n 1. `pi_natives.-modern.node`\n 2. `pi_natives.-baseline.node`\n 3. `pi_natives..node`\n- x64 + `baseline`:\n 1. `pi_natives.-baseline.node`\n 2. `pi_natives..node`\n\nThe default unsuffixed fallback remains part of the x64 candidate list.\n\n## Candidate path construction and fallback ordering\n\n`resolveLoaderCandidates(...)` expands every filename across directories, then de-duplicates while preserving first occurrence order.\n\n### Non-compiled runtime\n\nFor each filename, candidates are:\n\n1. `/`\n2. `/`\n\n### Compiled runtime\n\nFor each filename, candidates are:\n\n1. `/`\n2. `/`\n3. `/`\n4. `/`\n\nAt load time, an extracted embedded candidate, when produced, is prepended ahead of these de-duplicated candidates.\n\n## Embedded addon extraction lifecycle\n\n`embedded-addon.js` is generated by `scripts/embed-native.ts`. The reset stub exports `embeddedAddon = null`. A populated manifest has:\n\n- `platformTag`\n- `version`\n- `files[]` entries with `variant`, `filename`, and `filePath`\n\nExtraction (`maybeExtractEmbeddedAddon`) runs only when:\n\n1. compiled-binary mode is true,\n2. `embeddedAddon` is non-null,\n3. manifest `platformTag` equals the runtime platform tag,\n4. manifest `version` equals the package version,\n5. a variant-appropriate embedded file exists.\n\nVariant file selection:\n\n- Non-x64: prefer `default`, then first available file.\n- x64 + `modern`: prefer `modern`, fallback to `baseline`.\n- x64 + `baseline`: require `baseline`.\n\nMaterialization:\n\n1. Ensure `` exists.\n2. Reuse `/` if it already exists.\n3. Otherwise read `selectedEmbeddedFile.filePath` and write the target path.\n4. Return the target path as the first candidate.\n\nDirectory creation or write failures are appended to the loader error list; probing continues through normal candidates.\n\n## Lifecycle and state transitions\n\n```text\nInit\n -> Load package metadata and embedded-addon manifest\n -> Compute platform/version/variant/filenames/candidate paths\n -> (compiled + embedded manifest matches?)\n yes -> try extract to versionedDir (record errors, continue)\n no -> skip extraction\n -> For each runtime candidate in order:\n require(candidate)\n -> success: return addon exports (READY)\n -> failure: record error, continue\n -> none loaded:\n if unsupported platform tag -> throw Unsupported platform\n else -> throw Failed to load (tried-path diagnostics + hints)\n```\n\n## Failure behavior and diagnostics\n\n### Unsupported platform\n\nIf all candidates fail and `platformTag` is not supported, the loader throws:\n\n- `Unsupported platform: `\n- supported platform list\n- issue-reporting guidance\n\n### No loadable candidate\n\nIf the platform is supported but no candidate can be loaded, the final error includes:\n\n- `Failed to load pi_natives native addon for ` or ` ()`\n- every attempted path with the corresponding `require(...)` error\n- mode-specific remediation hints\n\n### Compiled-binary startup failures\n\nCompiled mode diagnostics include:\n\n- expected versioned cache target paths (`/`),\n- remediation to delete the versioned cache and rerun,\n- direct release download `curl` commands for each expected filename.\n\n### Non-compiled startup failures\n\nNormal package/runtime diagnostics include:\n\n- reinstall hint (`bun install @gajae-code/natives`),\n- local rebuild command (`bun --cwd=packages/natives run build`),\n- optional x64 variant build hint (`TARGET_VARIANT=baseline|modern bun --cwd=packages/natives run build`).\n", "natives-architecture.md": "# Natives Architecture\n\n`@gajae-code/natives` is now a two-layer package around a loader:\n\n1. **CommonJS loader/package entrypoint** resolves and loads the correct `.node` addon and patches generated enum objects onto the export object.\n2. **Rust N-API module layer** implements the exported functions/classes and emits the generated TypeScript declarations.\n\nThis document is the foundation for deeper module-level docs. Performance-motivated native ports of leftover algorithmic hot paths are additionally gated by [`native-ffi-optimization-policy.md`](./native-ffi-optimization-policy.md).\n\n## Implementation files\n\n- `packages/natives/native/index.js`\n- `packages/natives/native/index.d.ts`\n- `packages/natives/native/loader-state.js`\n- `packages/natives/native/embedded-addon.js`\n- `packages/natives/scripts/build-native.ts`\n- `packages/natives/scripts/embed-native.ts`\n- `packages/natives/scripts/gen-enums.ts`\n- `packages/natives/package.json`\n- `crates/pi-natives/src/lib.rs`\n\n## Package entrypoint and public surface\n\n`packages/natives/package.json` points directly at generated native bindings:\n\n- `main`: `./native/index.js`\n- `types`: `./native/index.d.ts`\n- `exports[\".\"].types`: `./native/index.d.ts`\n- `exports[\".\"].import`: `./native/index.js`\n\nThere is no current `packages/natives/src` TypeScript wrapper layer. Consumers import functions/classes/enums directly from `@gajae-code/natives`; the type contract is the generated `native/index.d.ts` plus enum exports appended by `scripts/gen-enums.ts`.\n\nCurrent capability groups in the generated API include:\n\n- **Search/text/code primitives**: `grep`, `search`, `hasMatch`, `fuzzyFind`, `glob`, `astGrep`, `astEdit`, text width/slicing/wrapping/sanitization, syntax highlighting, token counting.\n- **Execution/process/terminal primitives**: `executeShell`, `Shell`, `PtySession`, process-tree helpers, key parsing.\n- **System/media/conversion primitives**: clipboard, image resize/encode/SIXEL, HTML-to-Markdown, macOS appearance/power helpers, work profiling, Windows ProjFS overlay helpers.\n\n## Loader layer\n\n`packages/natives/native/index.js` owns runtime addon selection and optional embedded extraction.\n\n### Candidate resolution model\n\n- Platform tag is `${process.platform}-${process.arch}`.\n- Supported tags are currently:\n - `linux-x64`\n - `linux-arm64`\n - `darwin-arm64`\n - `win32-x64`\n- x64 can use CPU variants:\n - `modern` (AVX2-capable)\n - `baseline` (fallback)\n- Non-x64 uses the default filename without a variant suffix.\n\nFilename strategy:\n\n- Default: `pi_natives.-.node`\n- x64 variant: `pi_natives.--modern.node` or `...-baseline.node`\n- x64 runtime fallback includes the unsuffixed default filename after variant candidates.\n\n### Platform-specific variant detection\n\nFor x64, variant selection uses:\n\n- Linux: `/proc/cpuinfo`\n- macOS: `sysctl -n machdep.cpu.leaf7_features`, then `machdep.cpu.features`\n- Windows: PowerShell check for `System.Runtime.Intrinsics.X86.Avx2`\n\n`GJC_NATIVE_VARIANT` can force `modern` or `baseline`; invalid values are ignored.\n\n### Binary distribution and extraction model\n\n`packages/natives/package.json` publishes `native/`, which contains the loader, generated declarations, generated enum patch, embedded-addon manifest stub, and prebuilt `.node` artifacts.\n\nFor compiled binaries, loader behavior is:\n\n1. Check versioned user cache path: `//...`.\n2. Check legacy compiled-binary location:\n - Windows: `%LOCALAPPDATA%/gjc` (fallback `%USERPROFILE%/AppData/Local/gjc`)\n - non-Windows: `~/.local/bin`\n3. Fall back to packaged `native/` and executable directory candidates.\n\n`getNativesDir()` uses `$XDG_DATA_HOME/gjc/natives` when `$XDG_DATA_HOME/gjc` exists; otherwise it uses `~/.gjc/natives`.\n\nIf a populated embedded addon manifest is present, it is also treated as a compiled-binary signal. The loader can extract the matching embedded `.node` into the versioned cache directory before candidate probing.\n\n### Failure modes\n\nLoader failures are explicit:\n\n- **Unsupported platform tag**: after failed probing, throws with supported platform list.\n- **No loadable candidate**: throws with all attempted paths and remediation hints.\n- **Embedded extraction errors**: directory/write failures are recorded and included in final load diagnostics if no candidate loads.\n\nThe current loader does not perform a separate post-`require` export validation pass.\n\n## Rust N-API module layer\n\n`crates/pi-natives/src/lib.rs` declares exported module ownership:\n\n- `appearance`\n- `ast`\n- `clipboard`\n- `fd`\n- `fs_cache`\n- `glob`\n- `glob_util`\n- `grep`\n- `highlight`\n- `html`\n- `image`\n- `keys`\n- `language`\n- `power`\n- `prof`\n- `projfs_overlay`\n- `ps`\n- `pty`\n- `shell`\n- `task`\n- `text`\n- `tokens`\n- `utils` (crate-private helpers)\n\nN-API exports are generated from Rust `#[napi]` functions/classes/objects/enums. Snake_case Rust names are exposed as camelCase JavaScript names unless explicitly configured by napi-rs.\n\n## Ownership boundaries\n\n- **Loader/package ownership (`packages/natives/native`, `packages/natives/scripts`)**\n - runtime binary selection\n - CPU variant selection and override handling\n - compiled-binary embedded extraction\n - generated TypeScript declarations and enum export patching\n- **Rust ownership (`crates/pi-natives/src`)**\n - algorithmic and system-level implementation\n - platform-native behavior and performance-sensitive logic\n - N-API symbol implementation consumed directly by package callers\n- **Consumer ownership (`packages/coding-agent`, `packages/tui`)**\n - user-facing policy and fallbacks that are not built into the native API\n - higher-level rendering, artifact, shell-session, and command behavior\n\n## Runtime flow (high level)\n\n1. Consumer imports from `@gajae-code/natives`.\n2. `native/index.js` computes platform/arch/variant and candidate paths.\n3. Optional embedded binary extraction occurs for compiled distributions.\n4. The first `require(candidate)` that succeeds becomes the exported addon object.\n5. Generated enum objects are appended to `module.exports`.\n6. Caller invokes generated N-API functions/classes directly.\n\n## Glossary\n\n- **Native addon**: A `.node` binary loaded via Node-API (N-API).\n- **Platform tag**: Runtime tuple `platform-arch` (for example `darwin-arm64`).\n- **Variant**: x64 CPU-specific build flavor (`modern` AVX2, `baseline` fallback).\n- **Generated binding declaration**: `native/index.d.ts` emitted by napi-rs during `build-native.ts`.\n- **Compiled binary mode**: Runtime mode where the CLI is bundled and native addons are resolved from embedded/cache paths before package-local paths.\n- **Embedded addon**: Build artifact metadata and file references generated into `native/embedded-addon.js` so compiled binaries can extract matching `.node` payloads.\n", diff --git a/packages/coding-agent/test/agent-session-profile-resume-default.test.ts b/packages/coding-agent/test/agent-session-profile-resume-default.test.ts index 486a1df4a2..164953f3d7 100644 --- a/packages/coding-agent/test/agent-session-profile-resume-default.test.ts +++ b/packages/coding-agent/test/agent-session-profile-resume-default.test.ts @@ -62,7 +62,7 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { function resolveModels(): { base: Model; profileMain: Model } { const base = modelRegistry.find("openai-codex", "gpt-5.5"); - const profileMain = modelRegistry.find("anthropic", "claude-opus-4-8"); + const profileMain = modelRegistry.find("anthropic", "claude-opus-5"); if (!base || !profileMain) { throw new Error("Expected codex and anthropic opus models to exist"); } @@ -82,7 +82,7 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { await session.setModelTemporary(profileMain, undefined, { persistAsSessionDefault: true }); // The default that resume restores is now the profile's main model. - expect(session.sessionManager.buildSessionContext().models.default).toBe("anthropic/claude-opus-4-8"); + expect(session.sessionManager.buildSessionContext().models.default).toBe("anthropic/claude-opus-5"); // Global default setting is untouched (apply-for-this-session semantics). expect(session.settings.getModelRole("default")).toBe(globalDefaultBefore); }); @@ -96,7 +96,7 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { await session.setModelTemporary(profileMain); expect(session.model?.provider).toBe("anthropic"); - expect(session.model?.id).toBe("claude-opus-4-8"); + expect(session.model?.id).toBe("claude-opus-5"); // Resume still restores the explicit base default, not the transient model. expect(session.sessionManager.buildSessionContext().models.default).toBe("openai-codex/gpt-5.5"); }); @@ -107,7 +107,7 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { // activation already recorded as the session default before throwing. const base = modelRegistry.find("openai-codex", "gpt-5.5"); const transient = modelRegistry.find("anthropic", "claude-sonnet-4-6"); - const profileMain = modelRegistry.find("anthropic", "claude-opus-4-8"); + const profileMain = modelRegistry.find("anthropic", "claude-opus-5"); if (!base || !transient || !profileMain) { throw new Error("Expected codex gpt-5.5 + anthropic sonnet/opus models to exist"); } @@ -131,7 +131,7 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { }); expect(prepared.previousModel?.id).toBe("claude-sonnet-4-6"); expect(prepared.previousSessionDefaultModel).toBe("openai-codex/gpt-5.5"); - expect(prepared.defaultModel?.id).toBe("claude-opus-4-8"); + expect(prepared.defaultModel?.id).toBe("claude-opus-5"); // Force the activation to fail AFTER the profile main model is recorded as // the session default: the agent-model-override step throws. @@ -167,10 +167,10 @@ describe("AgentSession setModelTemporary persistAsSessionDefault", () => { // Simulate a profile-activated configured chain [A, B]. session.setConfiguredModelChain( "default", - ["anthropic/claude-opus-4-8", "openai-codex/gpt-5.5"], + ["anthropic/claude-opus-5", "openai-codex/gpt-5.5"], "profile-activation", ); - expect(session.getConfiguredModelChain("default")).toEqual(["anthropic/claude-opus-4-8", "openai-codex/gpt-5.5"]); + expect(session.getConfiguredModelChain("default")).toEqual(["anthropic/claude-opus-5", "openai-codex/gpt-5.5"]); // Explicit user selection of C supersedes the stale chain: resume and // snapshots must follow the latest choice, without the old tail. diff --git a/packages/coding-agent/test/agent-session-resilient-retry.test.ts b/packages/coding-agent/test/agent-session-resilient-retry.test.ts index 496cb44a88..efed334a98 100644 --- a/packages/coding-agent/test/agent-session-resilient-retry.test.ts +++ b/packages/coding-agent/test/agent-session-resilient-retry.test.ts @@ -761,10 +761,11 @@ describe("AgentSession resilient retry", () => { expect(lastAssistant(sess).stopReason).toBe("stop"); }); - it("surfaces exact Alibaba Token Plan first-event timeouts without retrying", async () => { + it("surfaces exact Alibaba Token Plan first-event timeouts without duplicate model retries", async () => { const responsesModel = getBundledModel("alibaba-token-plan", "qwen3.8-max-preview"); const completionsModel = getBundledModel("alibaba-token-plan", "deepseek-v4-pro"); if (!responsesModel || !completionsModel) throw new Error("Expected bundled Alibaba Token Plan models"); + expect(responsesModel.api).toBe("openai-responses"); const cases = [ { @@ -798,6 +799,7 @@ describe("AgentSession resilient retry", () => { await session.waitForIdle(); expect(requestedModels).toEqual([`${testCase.model.provider}/${testCase.model.id}`]); + expect(new Set(requestedModels).size).toBe(requestedModels.length); expect(retryStartEvents).toHaveLength(0); expect(retryEndEvents).toHaveLength(0); expect(waitSpy).not.toHaveBeenCalled(); diff --git a/packages/coding-agent/test/model-preset-landing-redteam-qa.test.ts b/packages/coding-agent/test/model-preset-landing-redteam-qa.test.ts index a8dae1664b..9d7febf97e 100644 --- a/packages/coding-agent/test/model-preset-landing-redteam-qa.test.ts +++ b/packages/coding-agent/test/model-preset-landing-redteam-qa.test.ts @@ -28,7 +28,7 @@ const model = (provider: string, id: string, minLevel = Effort.Low): Model => }) as Model; const codexModel = model("openai-codex", "gpt-5.5", Effort.Low); -const anthropicModel = model("anthropic", "claude-opus-4-8"); +const anthropicModel = model("anthropic", "claude-opus-5"); const minimaxModel = model("minimax-code", "minimax-v3"); const noSuffixModel = model("provider-a", "default"); @@ -38,7 +38,7 @@ const builtinCodexModels = [ model("openai-codex", "gpt-5.6-sol", Effort.Low), ]; const builtinComboModels = [ - model("anthropic", "claude-opus-4-8", Effort.Low), + model("anthropic", "claude-opus-5", Effort.Low), model("anthropic", "claude-fable-5", Effort.Low), model("anthropic", "claude-sonnet-5"), model("opencode-go", "deepseek-v4-pro"), @@ -64,7 +64,7 @@ const codexEco: ModelProfileDefinition = { const combo: ModelProfileDefinition = { name: "opus-codex", requiredProviders: ["anthropic", "openai-codex"], - modelMapping: { default: "anthropic/claude-opus-4-8:xhigh", executor: "openai-codex/gpt-5.5:low" }, + modelMapping: { default: "anthropic/claude-opus-5:xhigh", executor: "openai-codex/gpt-5.5:low" }, source: "builtin", }; const comboOpencode: ModelProfileDefinition = { diff --git a/packages/coding-agent/test/model-profile-activation.test.ts b/packages/coding-agent/test/model-profile-activation.test.ts index 2afee436fc..37f8469567 100644 --- a/packages/coding-agent/test/model-profile-activation.test.ts +++ b/packages/coding-agent/test/model-profile-activation.test.ts @@ -86,7 +86,7 @@ function fakeRegistry(options?: { missingProviders?: string[]; profiles?: ModelP maxLevel: ThinkingLevel.Max, }), model("openai-codex", "gpt-5.3-codex-spark"), - model("anthropic", "claude-opus-4-8", { + model("anthropic", "claude-opus-5", { mode: "effort", minLevel: ThinkingLevel.Low, maxLevel: ThinkingLevel.XHigh, @@ -564,7 +564,7 @@ describe("model profile activation", () => { [ "opus-codex", { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", executor: "openai-codex/gpt-5.6-terra:low", planner: "anthropic/claude-sonnet-5", critic: "openai-codex/gpt-5.6-sol:xhigh", @@ -586,8 +586,8 @@ describe("model profile activation", () => { { default: "anthropic/claude-fable-5:high", executor: "openai-codex/gpt-5.6-terra:medium", - planner: "anthropic/claude-opus-4-8:medium", - critic: "anthropic/claude-opus-4-8:high", + planner: "anthropic/claude-opus-5:medium", + critic: "anthropic/claude-opus-5:high", architect: "openai-codex/gpt-5.6-sol:xhigh", }, ], diff --git a/packages/coding-agent/test/model-profiles-catalog.test.ts b/packages/coding-agent/test/model-profiles-catalog.test.ts index 80df71afea..27d7f802eb 100644 --- a/packages/coding-agent/test/model-profiles-catalog.test.ts +++ b/packages/coding-agent/test/model-profiles-catalog.test.ts @@ -67,11 +67,11 @@ const expectedProfiles: Array<{ name: string; requiredProviders: string[]; mappi name: "claude-opus", requiredProviders: ["anthropic"], mapping: { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", executor: "anthropic/claude-sonnet-5", - planner: "anthropic/claude-opus-4-8:low", - critic: "anthropic/claude-opus-4-8:high", - architect: "anthropic/claude-opus-4-8:xhigh", + planner: "anthropic/claude-opus-5:low", + critic: "anthropic/claude-opus-5:high", + architect: "anthropic/claude-opus-5:xhigh", }, }, { @@ -320,7 +320,7 @@ const expectedProfiles: Array<{ name: string; requiredProviders: string[]; mappi name: "opus-codex", requiredProviders: ["anthropic", "openai-codex"], mapping: { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", executor: "openai-codex/gpt-5.6-terra:low", planner: "anthropic/claude-sonnet-5", critic: "openai-codex/gpt-5.6-sol:xhigh", @@ -344,8 +344,8 @@ const expectedProfiles: Array<{ name: string; requiredProviders: string[]; mappi mapping: { default: "anthropic/claude-fable-5:high", executor: "openai-codex/gpt-5.6-terra:medium", - planner: "anthropic/claude-opus-4-8:medium", - critic: "anthropic/claude-opus-4-8:high", + planner: "anthropic/claude-opus-5:medium", + critic: "anthropic/claude-opus-5:high", architect: "openai-codex/gpt-5.6-sol:xhigh", }, }, @@ -390,7 +390,7 @@ function substituteCodexFamily(selector: string, source: "sol" | "terra", target const fixedNonCodexComboMappings: Record>> = { "opus-codex": { - default: "anthropic/claude-opus-4-8:xhigh", + default: "anthropic/claude-opus-5:xhigh", planner: "anthropic/claude-sonnet-5", }, "codex-opencodego": { @@ -400,8 +400,8 @@ const fixedNonCodexComboMappings: Record>> }, "fable-opus-codex": { default: "anthropic/claude-fable-5:high", - planner: "anthropic/claude-opus-4-8:medium", - critic: "anthropic/claude-opus-4-8:high", + planner: "anthropic/claude-opus-5:medium", + critic: "anthropic/claude-opus-5:high", }, }; diff --git a/packages/coding-agent/test/model-registry.test.ts b/packages/coding-agent/test/model-registry.test.ts index c93fc946fc..afdc0ecdc4 100644 --- a/packages/coding-agent/test/model-registry.test.ts +++ b/packages/coding-agent/test/model-registry.test.ts @@ -526,7 +526,7 @@ describe("ModelRegistry", () => { }); const registry = new ModelRegistry(authStorage, modelsJsonPath); - const opusVariants = registry.getCanonicalVariants("claude-opus-4-8"); + const opusVariants = registry.getCanonicalVariants("claude-opus-5"); const haikuVariants = registry.getCanonicalVariants("claude-haiku-4-5"); expect(opusVariants.some(variant => variant.selector === "demo/anthropic/claude-opus-latest")).toBe(true);