@0perator/operator 0.1.331 → 0.1.332

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,8 +7,9 @@
7
7
  // ── Model tiers (PV2-11) ────────────────────────────────────────────────────
8
8
  // A COMPUTE/COST CLASS orthogonal to a profile's id, so routing can ask for a class instead of a
9
9
  // name ("give me a lite model for this sub-task") and degrade predictably when a class is empty.
10
- // Ladder, strongest → cheapest: power_turbo > power > economy > lite > free. "free" is reserved
11
- // for genuinely no-cost promotional slots; nothing on the fleet maps to it today.
10
+ // Ladder, strongest → cheapest: power_turbo > power > economy > lite > free. "free" is the no-cost
11
+ // vendor tier (the Nous Portal rows a session's dynamicModels feed in, router/free-models.ts); no
12
+ // built-in carries it.
12
13
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
13
14
  /** Fallback walk order, strongest → cheapest. */
14
15
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
@@ -18,6 +19,7 @@ export const DEFAULT_MODEL_ID = "operator-1m";
18
19
  // settings.activeModel: "aurora-1m", a `/model aurora-1m`, or any muscle memory keeps working — so the
19
20
  // rename loses nothing. The served model name ("aurora-code-1") + endpoints stay internal, untouched.
20
21
  export const MODEL_ALIASES = {
22
+ "aurora": "operator-1m", // the ONE Aurora row (0.1.332): `/model aurora` is the natural spelling
21
23
  "aurora-1m": "operator-1m",
22
24
  "aurora-128k": "operator-128k",
23
25
  "spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
@@ -28,62 +30,53 @@ export const MODEL_ALIASES = {
28
30
  export const GATEWAY_BASE = `https://${PRODUCT_API_HOST}/v1`;
29
31
  /** The legacy fleet name for the SAME gateway — the ordered fallback behind GATEWAY_BASE, never a different backend. */
30
32
  export const LEGACY_GATEWAY_BASE = `https://${LEGACY_API_HOST}/v1`;
33
+ // Vendor bases shared by the built-in BYO rows and BYO_PRESETS, so a row and its preset can never drift apart.
34
+ const ANTHROPIC_BASE = "https://api.anthropic.com/v1";
35
+ const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai"; // Google's OpenAI-compatible surface — no native transport
36
+ const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its version: …/v1beta/openai/chat/completions
37
+ const QWEN_BASE = "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
38
+ const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
39
+ // Registry order IS picker order (visibleModels keeps it): fleet rows first (this box, then JL1), then the
40
+ // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
41
+ // vendor rows (tier "free") arrive at runtime through Session.dynamicModels and land after all of these.
31
42
  export const BUILTIN_MODELS = [
32
- { id: "operator-1m", tier: "power", label: "Operator 1M (local)", kind: "single", desc: "RECOMMENDED DEFAULT — local Aurora code model on this box's GPU (:8097, 24-47 tok/s measured, warm prefix-cache, no shared-slot contention); ctx 300K matched under the served 307,200 wall so compaction lands BEFORE the edge", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000 },
33
- { id: "operator-128k", tier: "economy", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
34
- // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
35
- // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
36
- // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
37
- // to the served truth (observeContext).
38
- { id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
39
- { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
40
- // Claude — a BYO Anthropic connector, so "delegate to Claude" and `/model claude-sonnet` work. Unlike the
41
- // qwen/OpenAI connectors (OpenAI dialect), Claude speaks the NATIVE Anthropic Messages wire — transport
42
- // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
43
- // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Hidden
44
- // from the picker until the key is stored; ctx is Anthropic's documented 200K, self-clamps to served truth.
45
- { id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 4.5", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: "https://api.anthropic.com/v1", model: "claude-sonnet-4-5", ctx: 200000, byo: "anthropic", transport: "anthropic" },
46
- // AXE Token Plan: api.axe.onl is AXE's OWN gateway (nginx + LiteLLM) and the Operator token is its
47
- // native auth (authHeaders scoping sends it to *.axe.onl — aurora.ts). Third-party `sk-axe-…` virtual
48
- // keys are the V1 vendor plan (_ai-docs/architecture/axe-model-vendor.md); until the gateway actually
49
- // issues them, gating this profile behind an unconnectable BYO account hid our OWN flagship remote
50
- // lane from our own picker (2026-10-12 picker-truth audit) — so it is a plain profile today. When V1
51
- // ships, reintroduce the byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
52
- { id: "axe-aurora-300k", tier: "power", label: "Aurora 300K (AXE cloud)", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — big-context fallback, NOT default: contended decode measured 1-4.6 tok/s vs local 24-47 (JL1 serves everyone); cold >~100K prefills can also hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai" },
53
- // Spectre — the flagship, replacing Ghost (2026-10-07). Ghost 32B was the prior self-hosted abliterated
54
- // Qwen3-VL-32B on this slot; retired when Spectre proved 4× faster at equal capability (its weights + restore
55
- // command are kept at ~/.axe/logs/ghost-restore-cmd.txt — reversible). Spectre = Huihui-Qwen3.6-35B-A3B-
56
- // abliterated: a 35B MoE with ~3B ACTIVE per token → ~40 tok/s (4× Ghost's dense-32B ~10), still abliterated
57
- // (uncensored) AND vision-capable (ships an mmproj). Served on JL1:8101 via launchd com.axe.spectre-serve,
58
- // thinking defaulted OFF server-side (--reasoning off) so it answers cleanly (no empty-content reasoning trap).
59
- // ctx 32000 = the TRUTH: the llama.cpp server serves n_ctx=32768 (--ctx-size 32768, verified via /props), NOT the
60
- // 65536 the profile claimed before 0.1.260. The 65536 lie made the engine overrun the real 32768 wall → the server
61
- // truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
62
- // 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
63
- // (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
64
- { id: "cortana", tier: "power", label: "Cortana 35B (JL1)", kind: "single", desc: "flagship MoE — abliterated Qwen3.6-35B-A3B (~3B active; ~40 tok/s ONLY when JL1 is quiet — shares the box with the 300K cloud slots and fell to 1-4 tok/s under fleet load; pick for vision/uncensored jobs, prefer Operator 1M local otherwise). GATEWAY-FIRST: the shared gateway answers by its own fallback (Aurora) when JL1 is down, then the LAN box direct; cold huge prefills can hit the Cloudflare ~125s edge cutoff)", endpoint: "http://192.168.1.103:8112/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8112/v1"], endpointModels: ["cortana", "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf"], model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 262144 },
43
+ // ── fleet: JL2 (this box) ───────────────────────────────────────────────────────────────────────────────
44
+ // THE one Aurora row (0.1.332). The 300K/600K/1M choice is a context PIN (settings.contextPin, /context,
45
+ // Ctrl+X) applied over the served window — not three profiles of one model. The static :8097 is the
46
+ // gateway-less fallback; on a gateway box Session.setModel restores the shell's chain for this id (the
47
+ // dynamic port + the JL1 and cloud legs buildEndpointChain assembles), so "JL1 and the cloud slot take over".
48
+ { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "local MoE, Q4_K_M, served 1,048,576; JL1 and the cloud slot take over if this box is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000 },
49
+ // ── fleet: JL1 ──────────────────────────────────────────────────────────────────────────────────────────
50
+ // Cortana — the flagship, replacing Ghost (2026-10-07; Ghost 32B's weights + restore command are kept at
51
+ // ~/.axe/logs/ghost-restore-cmd.txt — reversible). Huihui-Qwen3.6-35B-A3B-abliterated: a 35B MoE with ~3B
52
+ // ACTIVE per token (~40 tok/s when JL1 is quiet, 1-4 tok/s under fleet load), abliterated AND vision-capable
53
+ // (ships an mmproj). Served on JL1:8112, thinking OFF server-side (--reasoning off). GATEWAY-FIRST: the shared
54
+ // gateway answers by its own fallback when JL1 is down, then the LAN box direct.
55
+ // ctx 262144 = the served n_ctx (JL1 /props, verified 2026-10-28). The 0.1.260 lesson stands: a profile that
56
+ // claims MORE than the server's --ctx-size makes the engine overrun the wall and the server cuts a round
57
+ // mid-tool-call (0.1.259) — change this number ONLY when the server's --ctx-size changes.
58
+ { id: "cortana", tier: "power", label: "Cortana", params: "35B-A3B", box: "JL1", kind: "single", desc: "Qwen3.6-35B-A3B abliterated, Q4_K_M", endpoint: "http://192.168.1.103:8112/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8112/v1"], endpointModels: ["cortana", "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf"], model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 262144 },
59
+ // Thor — huihui-ai QwQ-32B abliterated: a dense reasoning model that thinks before it answers. Served on JL1:8124
60
+ // (the portal lists it "available" = registered, loaded on demand); gateway-first like cortana. ctx 32768 = the
61
+ // server's --ctx-size. Mirrors the hand override JL2's settings.json carried under this id (now a no-op by id).
62
+ { id: "thor", tier: "power", label: "Thor", params: "32B", box: "JL1", kind: "single", desc: "QwQ-32B abliterated reasoning model — thinks before answering", endpoint: "http://192.168.1.103:8124/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8124/v1"], endpointModels: ["thor", "/Volumes/Ai Storage/axe-models/thor-32b/huihui-ai_QwQ-32B-abliterated-Q4_K_M.gguf"], model: "/Volumes/Ai Storage/axe-models/thor-32b/huihui-ai_QwQ-32B-abliterated-Q4_K_M.gguf", ctx: 32768 },
65
63
  // Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
66
64
  // on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
67
65
  // AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
68
66
  // /no_think for speed. Picked (2026-10-07) from a fleet-wide 3B-class review; no 3B had been execution-graded,
69
67
  // so this is the evidence-led default pending a dyno/coding-eval bench. 40960 ≥ LEAN_HARNESS_CTX → full harness.
70
- { id: "scout", tier: "lite", label: "Scout 4B", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit; gateway-first, LAN direct as failover)", endpoint: "http://192.168.1.103:8110/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8110/v1"], endpointModels: ["scout", "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4"], model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
71
- // Venice 24B — a LIGHTER uncensored alternative to the 35B Spectre: Dolphin-Mistral-24B-Venice-Edition
72
- // (Q4_K_M, ~14GB) with a bolted-on Mistral-Small-3.1 mmproj for vision. Dense 24B (not MoE), served on
73
- // JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
74
- // test a smaller/different flavour alongside Spectre without the 35B footprint.
75
- { id: "venice-24b", tier: "economy", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114) — slot stopped today; hidden from the picker, resolves by id once launched", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768, hidden: true },
68
+ { id: "scout", tier: "lite", label: "Scout", params: "4B", box: "JL1", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit; gateway-first, LAN direct as failover)", endpoint: "http://192.168.1.103:8110/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8110/v1"], endpointModels: ["scout", "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4"], model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
76
69
  // Falcon-H1-34B — a NOVEL architecture nobody else on the fleet runs: hybrid SSM+attention, trained with a
77
70
  // genuinely long native context (no YaRN stretch needed — 262144 is baked into the GGUF's own metadata,
78
71
  // confirmed via gguf-py header read, rope.freq_base ≈1e11). Served JL1:8101, q8_0 KV, parallel=1. Not one
79
72
  // of our own fine-tunes — picked specifically to try something outside the Qwen/Aurora lineage.
80
- { id: "falcon-h1-34b", tier: "power", label: "Falcon-H1 34B (JL1)", kind: "single", desc: "novel hybrid SSM+attention architecture, native 256K context (no rope extension) — not ours, picked to try something different from the Qwen/Aurora lineage", endpoint: "http://192.168.1.103:8101/v1", model: "/Volumes/Ai Storage/axe-models/falcon-h1-34b/Falcon-H1-34B-Instruct-Q4_K_M.gguf", ctx: 262144 },
73
+ { id: "falcon-h1-34b", tier: "power", label: "Falcon-H1", params: "34B", box: "JL1", kind: "single", desc: "novel hybrid SSM+attention architecture, native 256K context (no rope extension) — not ours, picked to try something different from the Qwen/Aurora lineage", endpoint: "http://192.168.1.103:8101/v1", model: "/Volumes/Ai Storage/axe-models/falcon-h1-34b/Falcon-H1-34B-Instruct-Q4_K_M.gguf", ctx: 262144 },
81
74
  // Casanova (axe/newton-base-32b) — OUR OWN fine-tune, Qwen2-architecture, 32B. Source was MLX 4-bit
82
75
  // quantized (group_size 64, affine) — dequantized via mlx_lm --dequantize, reconverted+requantized to
83
76
  // Q4_K_M via convert_hf_to_gguf.py + llama-quantize (2026-10-22). Native ctx is only 32768, so 128K here is
84
77
  // a 4x YaRN stretch (--rope-scaling yarn --yarn-orig-ctx 32768 --rope-scale 4) — untested at the edge,
85
78
  // verify with a real long-context probe before trusting it near the ceiling.
86
- { id: "casanova", tier: "power", label: "Casanova 32B (JL1)", kind: "single", desc: "our own fine-tune (axe/newton-base-32b) — 128K via 4x YaRN stretch from a 32K native window", endpoint: "http://192.168.1.103:8102/v1", model: "/Users/home/.axe/gguf-converted/casanova-current/casanova-current-Q4_K_M.gguf", ctx: 131072 },
79
+ { id: "casanova", tier: "power", label: "Casanova", params: "32B", box: "JL1", kind: "single", desc: "our own fine-tune (axe/newton-base-32b) — 128K via 4x YaRN stretch from a 32K native window", endpoint: "http://192.168.1.103:8102/v1", model: "/Users/home/.axe/gguf-converted/casanova-current/casanova-current-Q4_K_M.gguf", ctx: 131072 },
87
80
  // Code tier for the coding/Replit-clone surface — Qwen2.5-Coder-3B has a real chat template + tool-calling
88
81
  // + FIM (ollama reports "completion, tools, insert"), unlike StarCoder2/replit-code (completion-only, can't
89
82
  // drive an agent loop). Ollama on JL1, on-demand (loads ~3GB, so SELECT only when JL1 swap has headroom).
@@ -93,7 +86,7 @@ export const BUILTIN_MODELS = [
93
86
  // transport:"openai" = Ollama /v1. ENDPOINT FIX 2026-10-12: was 127.0.0.1:11434, which only resolves
94
87
  // ON JL1 — every laptop picker entry pointed at its own dead loopback. LAN address like the other
95
88
  // JL1 slots.
96
- { id: "qwen-coder", tier: "lite", label: "Qwen Coder 3B (JL1)", kind: "single", desc: "code tier — Qwen2.5-Coder-3B Q4_K_M (chat + tool-calling + FIM), Ollama on JL1:11434 (on-demand ~3GB); Qwen Research Licence, non-commercial", endpoint: "http://192.168.1.103:11434/v1", model: "qwen2.5-coder:3b", ctx: 32000, transport: "openai" },
89
+ { id: "qwen-coder", tier: "lite", label: "Qwen2.5-Coder", params: "3B", box: "JL1", kind: "single", desc: "code tier — Qwen2.5-Coder-3B Q4_K_M (chat + tool-calling + FIM), Ollama on JL1:11434 (on-demand ~3GB); Qwen Research Licence, non-commercial", endpoint: "http://192.168.1.103:11434/v1", model: "qwen2.5-coder:3b", ctx: 32000, transport: "openai" },
97
90
  // Belmont 30b — an OWNER-ONLY trial of muse (muse0P abliterated, Q4_K_M ~16.9GB), served under the alias
98
91
  // `muse-op` on llama.cpp :8113. FAILOVER pair: JL2 primary (192.168.1.146:8113), JL1 standby
99
92
  // (192.168.1.103:8113) — same model/alias on both, so the router can hop JL2->JL1 on a busy/5xx. JL1 runs
@@ -103,21 +96,61 @@ export const BUILTIN_MODELS = [
103
96
  // stalled the full headless harness at ctxPct=99 (it sits ABOVE LEAN_HARNESS_CTX, so Belmont gets the
104
97
  // full harness). Keep this equal to the serve scripts' --ctx-size on both boxes.
105
98
  // ownerOnly: enterprise-grade private trial — hidden from every picker and refused for any non-owner seat.
106
- { id: "belmont-30b", tier: "economy", label: "Belmont 30b", kind: "single", desc: "OWNER-ONLY trial — muse (muse-op, abliterated 30B Q4_K_M) on llama.cpp :8113, JL2 primary + JL1 failover; must be served on a box to answer", endpoints: ["http://192.168.1.146:8113/v1", "http://192.168.1.103:8113/v1"], model: "muse-op", ctx: 131072, ownerOnly: true, leanPersona: true },
107
- { id: "moa", tier: "power_turbo", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "the team slot — fans each turn to aurora-local + Cortana 35B + Qwen-Coder 3B proposers (settings.moa, 60s fan-out, graceful per-draft failure) and synthesizes with local Aurora as agent-loop aggregator; roster + benchmark in _ai-docs" },
99
+ { id: "belmont-30b", tier: "economy", label: "Belmont", params: "30B", box: "JL1", kind: "single", desc: "OWNER-ONLY trial — muse (muse-op, abliterated 30B Q4_K_M) on llama.cpp :8113, JL2 primary + JL1 failover; must be served on a box to answer", endpoints: ["http://192.168.1.146:8113/v1", "http://192.168.1.103:8113/v1"], model: "muse-op", ctx: 131072, ownerOnly: true, leanPersona: true },
100
+ // Venice 24B — a LIGHTER uncensored alternative to the 35B Cortana: Dolphin-Mistral-24B-Venice-Edition
101
+ // (Q4_K_M, ~14GB) with a bolted-on Mistral-Small-3.1 mmproj for vision. Dense 24B (not MoE), served on
102
+ // JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
103
+ // test a smaller/different flavour alongside Cortana without the 35B footprint.
104
+ { id: "venice-24b", tier: "economy", label: "Venice", params: "24B", box: "JL1", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114) — slot stopped today; hidden from the picker, resolves by id once launched", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768, hidden: true },
105
+ // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
106
+ // Claude — BYO Anthropic connectors, so "delegate to Claude" and `/model claude-sonnet` work. Unlike the
107
+ // qwen/OpenAI connectors (OpenAI dialect), Claude speaks the NATIVE Anthropic Messages wire — transport
108
+ // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
109
+ // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Model ids
110
+ // are the vendor's complete 5.5-family ids (never a date suffix); ctx is the documented 1M, self-clamps to served truth.
111
+ { id: "claude-opus", tier: "power_turbo", label: "Claude Opus 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the strongest Claude (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-opus-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
112
+ { id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
113
+ { id: "claude-haiku", tier: "economy", label: "Claude Haiku 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the fast, cheap Claude for light work, your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-haiku-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
114
+ // Gemini — BYO Google connectors over Google's OpenAI-compatible base (no native transport needed; the
115
+ // strict openai dialect is what that surface accepts). Same "gemini" key account as the byo-model preset.
116
+ { id: "gemini-pro", tier: "power_turbo", label: "Gemini 2.5 Pro", box: "Google", kind: "single", desc: "BYO Google — Gemini 2.5 Pro over the OpenAI-compatible base, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
117
+ { id: "gemini-flash", tier: "economy", label: "Gemini 2.5 Flash", box: "Google", kind: "single", desc: "BYO Google — the fast Gemini tier, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-flash", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
118
+ // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
119
+ // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
120
+ // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
121
+ // to the served truth (observeContext).
122
+ { id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
123
+ { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
124
+ // ── by-id lanes (hidden from the picker, still resolve) ────────────────────────────────────────────────
125
+ // The cloud slot of the SAME Aurora, folded out of the picker in 0.1.332 (one Aurora row; the cloud legs ride
126
+ // in buildEndpointChain's failover chain). Reachable by id for scripts. api.0perator.co is AXE's OWN gateway
127
+ // and the Operator token is its native auth (authHeaders scoping) — never a BYO gate on this id: gating it
128
+ // behind an unissued `sk-axe-…` account hid our own remote lane from our own picker (2026-10-12 audit). When
129
+ // the V1 vendor keys ship, reintroduce a byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
130
+ { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
131
+ { id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
132
+ // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
133
+ { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — fans each turn to aurora-local + Cortana + Qwen2.5-Coder proposers (settings.moa, 60s fan-out, graceful per-draft failure) and synthesizes with local Aurora as agent-loop aggregator; roster + benchmark in _ai-docs" },
108
134
  ];
109
135
  export const BYO_PRESETS = {
110
- openai: { label: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai" },
111
- anthropic: { label: "Anthropic", endpoint: "https://api.anthropic.com/v1", model: "claude-sonnet-4-5", ctx: 200000, account: "anthropic", transport: "anthropic" },
112
- gemini: { label: "Gemini", endpoint: "https://generativelanguage.googleapis.com/v1beta/openai", model: "gemini-2.5-pro", ctx: 1000000, account: "gemini" },
113
- groq: { label: "Groq", endpoint: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile", ctx: 131072, account: "groq" },
114
- deepseek: { label: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek" },
115
- mistral: { label: "Mistral", endpoint: "https://api.mistral.ai/v1", model: "mistral-large-latest", ctx: 131072, account: "mistral" },
116
- openrouter: { label: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter" },
117
- together: { label: "Together", endpoint: "https://api.together.xyz/v1", model: "meta-llama/Llama-3.3-70B-Instruct-Turbo", ctx: 131072, account: "together" },
118
- xai: { label: "xAI Grok", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai" },
119
- qwen: { label: "QwenCloud", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, account: "qwen" },
136
+ openai: { label: "OpenAI", box: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai", envAlias: "OPENAI_API_KEY" },
137
+ anthropic: { label: "Anthropic", box: "Anthropic", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, account: "anthropic", transport: "anthropic", envAlias: "ANTHROPIC_API_KEY" },
138
+ gemini: { label: "Google (Gemini)", box: "Google", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, account: "gemini", envAlias: "GEMINI_API_KEY", chatPath: GEMINI_CHAT_PATH },
139
+ groq: { label: "Groq", box: "Groq", endpoint: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile", ctx: 131072, account: "groq", envAlias: "GROQ_API_KEY" },
140
+ deepseek: { label: "DeepSeek", box: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek", envAlias: "DEEPSEEK_API_KEY" },
141
+ mistral: { label: "Mistral", box: "Mistral", endpoint: "https://api.mistral.ai/v1", model: "mistral-large-latest", ctx: 131072, account: "mistral", envAlias: "MISTRAL_API_KEY" },
142
+ openrouter: { label: "OpenRouter", box: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter", envAlias: "OPENROUTER_API_KEY" },
143
+ together: { label: "Together", box: "Together", endpoint: "https://api.together.xyz/v1", model: "meta-llama/Llama-3.3-70B-Instruct-Turbo", ctx: 131072, account: "together", envAlias: "TOGETHER_API_KEY" },
144
+ xai: { label: "xAI Grok", box: "xAI", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai", envAlias: "XAI_API_KEY" },
145
+ qwen: { label: "QwenCloud", box: "QwenCloud", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, account: "qwen" },
146
+ // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
147
+ // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
148
+ nous: { label: "Nous Portal", box: "Nous", endpoint: NOUS_BASE, model: "reflection/beam-1.0-501b-a23b:free", ctx: 262144, account: "nous", transport: "openai", envAlias: "NOUS_API_KEY" },
120
149
  };
150
+ /** The vendor env var a BYO account answers to (ByoPreset.envAlias), or undefined for an account no preset names. */
151
+ export function byoEnvAlias(account) {
152
+ return Object.values(BYO_PRESETS).find((p) => p.account === account)?.envAlias;
153
+ }
121
154
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
122
155
  * built-in by id, or adding a new one) — same shape either way, so /model doesn't care which. */
123
156
  export function modelRegistry(overrides) {
@@ -141,12 +174,18 @@ export function tierOf(registry, id) {
141
174
  export function profilesByTier(registry, tier, opts) {
142
175
  return registry.filter((m) => m.tier === tier && (opts?.includeHidden || (!m.hidden && !m.ownerOnly)));
143
176
  }
177
+ /** A paid vendor row is never picked BY TIER for an aux lane (sleep consolidation, lean/fast lanes, delegate
178
+ * fallbacks): the owner spends their own key only by choosing that row explicitly in /model. A free-tier row
179
+ * is the exception — "free" exists for exactly that. */
180
+ function tierPickable(m) {
181
+ return !m.byo || m.tier === "free";
182
+ }
144
183
  /**
145
184
  * Resolve a tier to a concrete profile. Exact tier first (registry order decides within a tier —
146
185
  * builtins lead with the recommended default). When the tier is empty, `fallback` walks the
147
186
  * ladder: "down" (default) degrades toward cheaper tiers — a routing request never silently
148
187
  * UPGRADES to a pricier class — while "up" climbs toward stronger ones (use when a floor matters
149
- * more than cost); "none" is exact-only.
188
+ * more than cost); "none" is exact-only. Never a paid BYO row (tierPickable).
150
189
  */
151
190
  export function resolveByTier(registry, tier, opts) {
152
191
  const fallback = opts?.fallback ?? "down";
@@ -157,7 +196,7 @@ export function resolveByTier(registry, tier, opts) {
157
196
  : fallback === "down" ? TIER_LADDER.slice(start)
158
197
  : [...TIER_LADDER.slice(0, start + 1)].reverse();
159
198
  for (const t of order) {
160
- const hit = profilesByTier(registry, t, opts)[0];
199
+ const hit = profilesByTier(registry, t, opts).find(tierPickable);
161
200
  if (hit)
162
201
  return hit;
163
202
  }
@@ -180,6 +219,9 @@ export function modelCtxFor(id, overrides) {
180
219
  /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
181
220
  * full; a self-hosted small model (Venice 8K, or a 16K bump) goes lean. */
182
221
  export const LEAN_HARNESS_CTX = 32768;
222
+ /** The smallest context pin accepted anywhere (the /context parser, settings.contextPin, Session): below it the system
223
+ * prompt and the tool schemas (~16K tokens) leave no room for a multi-round turn. */
224
+ export const MIN_CONTEXT_PIN = 32_000;
183
225
  /** Whether a model runs the lean harness: small context (< LEAN_HARNESS_CTX) OR a profile that forces it via
184
226
  * `leanPersona` (a weak but big-context model). The ONE place both surfaces (cli.tsx, session-factory) decide. */
185
227
  export function leanHarnessFor(id, overrides) {
@@ -199,7 +241,7 @@ export function selectModel(registry, id, hasByo, isOwner = true) {
199
241
  return { error: `model "${id}" has no endpoint configured` };
200
242
  if (profile.ownerOnly && !isOwner)
201
243
  return { error: `"${id}" is owner-only` };
202
- if (profile.byo && hasByo && !hasByo(profile.byo)) {
244
+ if (profile.byo && hasByo && !hasByo(profile.byo, profileEndpoint(profile))) {
203
245
  return { error: `"${id}" is not connected — store the ${profile.byo} key first: operator auth byo-key ${profile.byo}` };
204
246
  }
205
247
  return { profile };
@@ -209,10 +251,46 @@ export function selectModel(registry, id, hasByo, isOwner = true) {
209
251
  * and owner-only profiles for any non-owner seat. `isOwner` defaults true (the implicit local owner);
210
252
  * a narrowed-tier surface MUST pass isOwner=false so an owner-only lane never leaks into its picker. */
211
253
  export function visibleModels(registry, hasByo, isOwner = true) {
212
- return registry.filter((p) => !p.hidden && (!p.ownerOnly || isOwner) && (!p.byo || (hasByo ? hasByo(p.byo) : false)));
254
+ return registry.filter((p) => !p.hidden && (!p.ownerOnly || isOwner) && (!p.byo || (hasByo ? hasByo(p.byo, profileEndpoint(p)) : false)));
255
+ }
256
+ /** The base a profile's requests go to first — what a BYO key is checked against (auth/byo binds a vendor's own env
257
+ * variable to that vendor's host). */
258
+ export function profileEndpoint(p) {
259
+ return p.endpoint ?? p.endpoints?.[0];
213
260
  }
214
261
  /** Strip a trailing /v1 so a ModelProfile/MoaAggregator endpoint can feed the AuroraRouter, whose
215
262
  * base is bare (engine/aurora.ts's chat() appends /v1/chat/completions itself). */
216
263
  export function endpointBase(endpoint) {
217
264
  return endpoint.replace(/\/v1\/?$/, "");
218
265
  }
266
+ // ── display helpers (the one spelling of a model everywhere the owner sees it) ───────────────────────────
267
+ // Binary windows keep the names everyone uses for them; the 307,200 yarn wall reads "300K" because that is
268
+ // what it was sized as. Anything else rounds to the nearest K, or M from a million up.
269
+ const CTX_NAMES = { 32768: "32K", 65536: "64K", 131072: "128K", 307200: "300K", 524288: "512K", 1048576: "1M", 2097152: "2M" };
270
+ /** A context size as the owner reads it: 32768 → "32K", 262144 → "262K", 300000/307200 → "300K", 600000 → "600K",
271
+ * 1000000/1048576 → "1M", 1500000 → "1.5M". */
272
+ export function fmtCtx(n) {
273
+ if (!Number.isFinite(n) || n <= 0)
274
+ return "?";
275
+ const named = CTX_NAMES[n];
276
+ if (named)
277
+ return named;
278
+ if (n >= 1_000_000) {
279
+ const m = n / 1_000_000;
280
+ return `${Number.isInteger(m) ? m : m.toFixed(1).replace(/\.0$/, "")}M`;
281
+ }
282
+ return `${Math.round(n / 1000)}K`;
283
+ }
284
+ /** `<label> <params>` ("Aurora Code 1 35B-A3B") — the name a sys line or footer uses; the bare label when the
285
+ * profile states no parameter count (a discovered fleet row, MOA). */
286
+ export function shortName(p) {
287
+ return p.params ? `${p.label} ${p.params}` : p.label;
288
+ }
289
+ /** The one /model row: `<label> <params> (<box>) · <ctx>` + " (active)". A missing params/box/ctx simply drops
290
+ * out (a discovered fleet row has no box; MOA has no window), so the picker never prints a placeholder.
291
+ * `servedCtx` — the window the router learned from the server — wins over the profile's own number. */
292
+ export function pickerRow(p, o = {}) {
293
+ const ctx = o.servedCtx ?? p.ctx;
294
+ const head = p.box ? `${shortName(p)} (${p.box})` : shortName(p);
295
+ return `${head}${ctx ? ` · ${fmtCtx(ctx)}` : ""}${o.active ? " (active)" : ""}`;
296
+ }
package/dist/session.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
5
  import { recordTruncation } from "./observability/blackbox.js";
6
6
  import { Conversation } from "./engine/messages.js";
7
- import { chat, health, requiresOperatorToken } from "./engine/aurora.js";
7
+ import { chat, health, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
8
8
  import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
9
9
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
10
10
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
@@ -16,7 +16,8 @@ import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engin
16
16
  import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
17
17
  import { AuroraRouter } from "./router/router.js";
18
18
  import { operatorAgentPersona } from "./config/operator-harness.js";
19
- import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
19
+ import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
20
+ import { probeServedCtx, usableCtx } from "./router/discovery.js";
20
21
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
21
22
  import { getByoToken, hasByoToken } from "./auth/byo.js";
22
23
  import { Executor } from "./tools/executor.js";
@@ -291,13 +292,18 @@ function makeSkillDeactivateTool(deactivate) {
291
292
  };
292
293
  }
293
294
  const SUMMARY_MAX_TOKENS = 1800; // room for Aurora's reasoning AND the 9-section contract before content lands
295
+ const SUMMARY_MAX_TOKENS_THINKING = 8000; // a Claude summarize: adaptive thinking draws on the same budget
294
296
  const SKILL_CAP = 4000; // max chars injected from an active skill — a huge skill must not crowd working memory
295
297
  export class Session {
296
298
  convo = new Conversation();
297
299
  inner; // was readonly — /model rebuilds it for a "single" profile switch
298
300
  router; // rebuilt alongside inner (setModel)
299
301
  chain; // the endpoint chain the shell built (cfg.router / useRouter) — what the default local model routes through
300
- registry; // /model's choices — built-ins + any settings.models
302
+ registry; // /model's choices — built-ins + any settings.models (liveRegistry adds the dynamic rows)
303
+ models; // cfg.models, kept so the dynamic rows can be merged after them
304
+ dynamicModels;
305
+ pin; // the owner's context pin (tokens); undefined = auto — read live by the engine router
306
+ servedByBase = new Map(); // raw n_ctx learned per base (probeServedContext)
301
307
  moaConfig;
302
308
  fastStartConfig;
303
309
  fastStartEnabled;
@@ -416,9 +422,12 @@ export class Session {
416
422
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
417
423
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
418
424
  this.localSchemas = toSchemas(reg);
425
+ this.setContextPin(cfg.contextPin); // before the first wrap(): the engine router reads the pin live
419
426
  this.inner = cfg.router ?? new AuroraRouter();
420
- this.router = engineRouter(this.inner);
427
+ this.router = this.wrap(this.inner);
421
428
  this.chain = cfg.router;
429
+ this.models = cfg.models;
430
+ this.dynamicModels = cfg.dynamicModels;
422
431
  this.registry = modelRegistry(cfg.models);
423
432
  this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
424
433
  this.moaConfig = cfg.moa;
@@ -510,7 +519,7 @@ export class Session {
510
519
  budgetDirective() {
511
520
  let ctxWindow = 0;
512
521
  try {
513
- ctxWindow = this.inner.ctxLimit();
522
+ ctxWindow = this.effectiveContext();
514
523
  }
515
524
  catch { /* endpoint not ready — skip the ctx line */ }
516
525
  return renderBudgetBlock({
@@ -597,10 +606,56 @@ export class Session {
597
606
  const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
598
607
  return globalTokenMeter.estimateRequestFor(this.meterKey(), built, this.allSchemas());
599
608
  }
600
- /** Estimated context usage of the live conversation against the current endpoint's window, 0-99.
601
- * Calibrated: the meter's real ratio once observations land; exactly the old chars/4 prior cold. */
609
+ /** Estimated context usage of the live conversation against the window the engine runs on (the served limit
610
+ * under the owner's pin), 0-99. Calibrated: the meter's real ratio once observations land; exactly the old
611
+ * chars/4 prior cold. */
602
612
  ctxPct() {
603
- return Math.min(99, Math.round((this.requestEstimate() / this.inner.ctxLimit()) * 100));
613
+ return Math.min(99, Math.round((this.requestEstimate() / this.effectiveContext()) * 100));
614
+ }
615
+ // ── context pin (/context, Ctrl+X, the /model picker step) ───────────────
616
+ /** The engine router for `inner`: the adapter reads the pin live, so a mid-session /context applies next round. */
617
+ wrap(inner) {
618
+ return engineRouter(inner, { contextPin: () => this.pin });
619
+ }
620
+ /** The owner's context pin (tokens), or undefined for auto (the served window). */
621
+ contextPin() {
622
+ return this.pin;
623
+ }
624
+ /** Pin the engine's window; undefined restores auto. Persisting it (settings.contextPin) is the shell's job. */
625
+ setContextPin(tokens) {
626
+ // A pin below the floor (a hand-edited settings file, an old `/context 300`) is treated as auto, never as a 300-token window.
627
+ this.pin = typeof tokens === "number" && Number.isFinite(tokens) && tokens >= MIN_CONTEXT_PIN ? Math.floor(tokens) : undefined;
628
+ }
629
+ /** The window the engine actually runs on: min(the active endpoint's served limit, the pin). */
630
+ effectiveContext() {
631
+ const served = this.inner.ctxLimit();
632
+ return this.pin ? Math.min(served, this.pin) : served;
633
+ }
634
+ /** The raw window the active endpoint's server reported (probeServedContext), else its configured limit — what
635
+ * "auto (served 1,048,576)" shows. */
636
+ servedContext() {
637
+ return this.servedByBase.get(this.inner.base) ?? this.inner.ctxLimit();
638
+ }
639
+ /** Learn the active route's served window NOW instead of after the first 400 (engine/selfheal): read the primary
640
+ * endpoint's llama.cpp `/props` and clamp the router to floor(n_ctx * margin) — observeContextLimit is monotonic
641
+ * down, so a pin below the served size costs nothing and a profile that claimed too much stops overflowing before
642
+ * it ever does. Loopback/LAN bases only: a gateway or vendor leg is never probed (no /props there, and a bearer
643
+ * would ride along). Best-effort — a probe that does not answer in time changes nothing. Returns the raw served
644
+ * window and, when the pin sits above it, the one clamp note the shell prints as a sys line (a Session has no
645
+ * notice channel of its own). */
646
+ async probeServedContext(opts = {}) {
647
+ const base = this.inner.list()[0]?.base ?? this.inner.base;
648
+ if (!base || requiresOperatorToken(base) || !operatorTrustedUrl(base))
649
+ return { base };
650
+ const served = await probeServedCtx(base, { timeoutMs: opts.timeoutMs ?? 1500, fetchImpl: opts.fetchImpl });
651
+ if (!served)
652
+ return { base };
653
+ this.servedByBase.set(base, served);
654
+ this.inner.observeContextLimit(base, usableCtx(served));
655
+ const out = { base, served };
656
+ if (this.pin && this.pin > served)
657
+ out.note = `context pin ${fmtCtx(this.pin)} is above the served ${served.toLocaleString("en-US")} — using ${fmtCtx(served)}`;
658
+ return out;
604
659
  }
605
660
  /** Cumulative tokens (prefill + output) across every turn this session — the Claude-Code-style running
606
661
  * session total for the status rule, so the real spend is visible (not just the current completion). */
@@ -633,7 +688,7 @@ export class Session {
633
688
  * window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
634
689
  async compactNow() {
635
690
  const opts = {
636
- ctxWindow: this.inner.ctxLimit(),
691
+ ctxWindow: this.effectiveContext(),
637
692
  systemPrompt: this.sys(),
638
693
  summarize: this.summarize,
639
694
  preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
@@ -715,11 +770,17 @@ export class Session {
715
770
  currentRoute() {
716
771
  return this.inner.currentName();
717
772
  }
773
+ /** The registry as of now: built-ins + settings.models, plus whatever rows the shell has learned since boot
774
+ * (cfg.dynamicModels — merged last, so a fetched row wins by id). The static registry when nothing is dynamic. */
775
+ liveRegistry() {
776
+ const dyn = this.dynamicModels?.() ?? [];
777
+ return dyn.length ? modelRegistry([...(this.models ?? []), ...dyn]) : this.registry;
778
+ }
718
779
  /** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
719
- * overrides passed in at construction. BYO connectors appear ONLY when their vendor key is
720
- * connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
780
+ * overrides passed in at construction, plus the dynamic rows. BYO connectors appear ONLY when their vendor
781
+ * key is connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
721
782
  modelRegistry() {
722
- return visibleModels(this.registry, hasByoToken, this.isOwner);
783
+ return visibleModels(this.liveRegistry(), hasByoToken, this.isOwner);
723
784
  }
724
785
  /** The active /model selection (id), for the status line + persistence. */
725
786
  currentModel() {
@@ -731,7 +792,7 @@ export class Session {
731
792
  * error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
732
793
  * with no settings.moa configured. */
733
794
  setModel(id) {
734
- const { profile, error } = selectModel(this.registry, id, hasByoToken, this.isOwner);
795
+ const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
735
796
  if (error || !profile)
736
797
  return { ok: false, error };
737
798
  if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
@@ -742,12 +803,12 @@ export class Session {
742
803
  // legs). Restore it rather than rebuilding from the profile's static :8097 endpoint, which no longer
743
804
  // answers on a gateway box — otherwise /model away-and-back lands on a dead port.
744
805
  this.inner = this.chain;
745
- this.router = engineRouter(this.inner);
806
+ this.router = this.wrap(this.inner);
746
807
  }
747
808
  else if (profile.kind === "single" && (profile.endpoint || profile.endpoints?.length)) {
748
809
  // BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
749
810
  // selectModel already refused the id if the key is not connected, so resolution can't miss here.
750
- const token = profile.byo ? getByoToken(profile.byo) : undefined;
811
+ const token = profile.byo ? getByoToken(profile.byo, profileEndpoint(profile)) : undefined;
751
812
  // A failover `endpoints` list builds one AuroraRouter endpoint per box (same model/alias on each), so
752
813
  // the router hops primary->standby on a busy/5xx; a lone `endpoint` is the single-box case. Names carry
753
814
  // the host so /route reads which box answered.
@@ -763,9 +824,10 @@ export class Session {
763
824
  ctxLimit: profile.ctx ?? this.inner.ctxLimit(),
764
825
  token: token ?? (hasGatewayLeg && !requiresOperatorToken(ep) ? "" : undefined),
765
826
  transport: profile.transport,
827
+ chatPath: profile.chatPath,
766
828
  }));
767
829
  this.inner = new AuroraRouter(eps);
768
- this.router = engineRouter(this.inner);
830
+ this.router = this.wrap(this.inner);
769
831
  }
770
832
  this.modelId = profile.id;
771
833
  return { ok: true };
@@ -779,7 +841,7 @@ export class Session {
779
841
  if (this.modelId !== DEFAULT_MODEL_ID)
780
842
  return;
781
843
  this.inner = router;
782
- this.router = engineRouter(this.inner);
844
+ this.router = this.wrap(this.inner);
783
845
  }
784
846
  /** The full conversation, for persistence (auto-save / --resume). */
785
847
  snapshot() {
@@ -843,13 +905,21 @@ export class Session {
843
905
  const summaryTimeoutMs = Number(process.env.KODE_COMPACTION_SUMMARY_TIMEOUT_MS) || 120_000;
844
906
  const timeoutSignal = AbortSignal.timeout(summaryTimeoutMs);
845
907
  const signal = this.ctrl?.signal ? AbortSignal.any([this.ctrl.signal, timeoutSignal]) : timeoutSignal;
908
+ // The summarize request rides the SAME leg's key, wire and chat path as the live turn: a vendor row (Claude, Gemini,
909
+ // a free row) went to /v1/chat/completions with no key before, so a session on it could never compact.
910
+ const leg = [...this.inner.list(), ...(this.chain?.list() ?? [])].find((e) => e.base === sumBase && e.model === sumModel);
846
911
  let r;
847
912
  try {
848
913
  r = await chat(messages, {
849
914
  base: sumBase, // small-ctx active model → large default (Aurora) summarizes; else the live endpoint (cache-safe)
850
915
  model: sumModel,
916
+ token: leg?.token,
917
+ loopbackAuth: leg?.loopbackAuth,
918
+ transport: leg?.transport,
919
+ chatPath: leg?.chatPath,
851
920
  tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
852
- maxTokens: SUMMARY_MAX_TOKENS,
921
+ // Claude's adaptive thinking counts toward max_tokens: 1800 can be spent before the summary text starts.
922
+ maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : SUMMARY_MAX_TOKENS,
853
923
  temperature: 0,
854
924
  background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
855
925
  signal, // ESC during "compacting" must tear down THIS request too, not just the main generation stream —
@@ -1053,7 +1123,7 @@ export class Session {
1053
1123
  if (this.ctrl.signal.aborted)
1054
1124
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1055
1125
  this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
1056
- const active = findModel(this.registry, this.modelId);
1126
+ const active = findModel(this.liveRegistry(), this.modelId);
1057
1127
  if (active?.kind === "orchestrated")
1058
1128
  return await this.sendMoa(text, h, active);
1059
1129
  const sys = this.sysWithThink();
@@ -1090,7 +1160,7 @@ export class Session {
1090
1160
  const res = await this.execute(text, h, this.router, this.sysWithThink());
1091
1161
  return { ...res, content: note + res.content };
1092
1162
  }
1093
- const aggRouter = engineRouter(new AuroraRouter([
1163
+ const aggRouter = this.wrap(new AuroraRouter([
1094
1164
  { name: moa.aggregator.id, base: endpointBase(moa.aggregator.endpoint), model: moa.aggregator.model, ctxLimit: this.inner.ctxLimit() },
1095
1165
  ]));
1096
1166
  const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
@@ -1234,10 +1304,11 @@ export class Session {
1234
1304
  // the endpoint gate (a main turn always outranks it) with a 15s abort, and routeShadowTurn swallows
1235
1305
  // every failure — observability that can degrade the observed thing is not observability.
1236
1306
  if (process.env.KODE_MOA_SHADOW !== "0") {
1237
- const prof = findModel(this.registry, this.modelId);
1238
- const shadowBase = prof?.endpoint ? endpointBase(prof.endpoint) : undefined;
1307
+ const prof = findModel(this.liveRegistry(), this.modelId);
1308
+ // Not on a vendor's paid wire: an 8-token classifier call per Claude turn costs money and returns nothing once the model thinks.
1309
+ const shadowBase = prof?.endpoint && prof.transport !== "anthropic" ? endpointBase(prof.endpoint) : undefined;
1239
1310
  if (shadowBase) {
1240
- const shadowTok = prof?.byo ? getByoToken(prof.byo) : undefined;
1311
+ const shadowTok = prof?.byo ? getByoToken(prof.byo, prof.endpoint) : undefined;
1241
1312
  const shadowModel = prof?.model ?? this.modelId;
1242
1313
  this._shadowPending = routeShadowTurn({
1243
1314
  enabled: true,
@@ -69,7 +69,7 @@ const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
69
69
  // permissions to bypass+admin for the next launch, and one that can truncate events.jsonl erases the
70
70
  // evidence — so the sandbox treats these exactly like ~/.ssh. Resolved per call (KODE_HOME / KODE_PROFILE
71
71
  // can differ per process); ordinary state (memories, skills, sessions) stays writable.
72
- const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl"];
72
+ const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl", "free-models.json"];
73
73
  // `run` holds the per-session pidfiles util/owned-children.ts reaps from: Operator (unsandboxed) trusts them to stop processes, so the agent
74
74
  // must not be able to plant one naming a process it wants dead.
75
75
  const OP_WRITE_PROTECTED_DIRS = ["vault", "audit", "run"];