@0perator/operator 0.2.1 → 0.2.2-next.0

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.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +8 -2
  4. package/dist/autonomy/agent-cli.js +1 -1
  5. package/dist/autonomy/headless.js +30 -6
  6. package/dist/autonomy/pr-isolation.js +92 -0
  7. package/dist/autonomy/pr-preflight.js +474 -0
  8. package/dist/autonomy/session-factory.js +2 -0
  9. package/dist/browser/capture.js +505 -0
  10. package/dist/browser/engine.js +4 -3
  11. package/dist/browser/page-capture.js +167 -0
  12. package/dist/browser/png.js +116 -0
  13. package/dist/browser/visual-compare.js +229 -0
  14. package/dist/bus/beam-drop.js +55 -0
  15. package/dist/bus/inbox.js +7 -1
  16. package/dist/cli.js +126 -25
  17. package/dist/config/managed.js +40 -1
  18. package/dist/config/persona.js +51 -26
  19. package/dist/config/product-hosts.js +2 -0
  20. package/dist/config/settings.js +30 -13
  21. package/dist/config/skills-index.js +37 -14
  22. package/dist/engine/agent.js +1 -1
  23. package/dist/engine/aurora.js +18 -9
  24. package/dist/engine/continuation.js +36 -0
  25. package/dist/engine/identity.js +42 -0
  26. package/dist/engine/moa.js +7 -0
  27. package/dist/engine/net-error.js +15 -0
  28. package/dist/engine/rolling-summary.js +142 -93
  29. package/dist/engine/waterfall.js +33 -0
  30. package/dist/gateway-cli.js +10 -1
  31. package/dist/memory/session-index.js +3 -3
  32. package/dist/permissions/index.js +2 -1
  33. package/dist/permissions/policy.js +9 -2
  34. package/dist/permissions/tier.js +9 -1
  35. package/dist/products/craft.js +90 -1
  36. package/dist/products/temple.js +20 -1
  37. package/dist/products/voice.js +112 -0
  38. package/dist/router/free-models.js +5 -9
  39. package/dist/router/models.js +58 -14
  40. package/dist/router/provider-models.js +78 -0
  41. package/dist/router/router.js +15 -3
  42. package/dist/selfimprove/lessons.js +23 -0
  43. package/dist/session.js +192 -87
  44. package/dist/skills/catalogue.js +5 -2
  45. package/dist/skills/finder.js +4 -4
  46. package/dist/skills/install-guard.js +1 -1
  47. package/dist/tools/beam.js +246 -0
  48. package/dist/tools/craft.js +23 -0
  49. package/dist/tools/deferred.js +7 -3
  50. package/dist/tools/doc-text.js +1 -1
  51. package/dist/tools/registry.js +55 -9
  52. package/dist/tools/sandbox.js +6 -6
  53. package/dist/ui/App.js +3 -3
  54. package/dist/ui/ApprovalPrompt.js +1 -1
  55. package/dist/ui/Composer.js +44 -2
  56. package/dist/ui/StatusRule.js +2 -1
  57. package/dist/ui/Transcript.js +5 -0
  58. package/dist/ui/modelPicker.js +10 -6
  59. package/dist/ui/phase.js +4 -2
  60. package/dist/ui/slashCommands.js +1 -0
  61. package/dist/ui/voice.js +185 -0
  62. package/dist/update.js +1 -2
  63. package/dist/util/audio-io.js +82 -0
  64. package/dist/util/slash.js +2 -2
  65. package/dist/vision/pairs.js +239 -0
  66. package/package.json +1 -1
@@ -0,0 +1,112 @@
1
+ // One door for voice: every surface's speech goes to OUR gateway's audio routes — transcription to the route behind
2
+ // `POST /audio/transcriptions`, speech to the route named in `POST /audio/speech` — and the router owns which speech
3
+ // servers back them (an on-request model, the always-on service, in that order or any other). This module holds no
4
+ // host, port, model or path: it asks the same gateways vision does (the local router on loopback, then the public
5
+ // gateway with the sign-in token; `services.voice.gateway` pins one or turns voice "off").
6
+ //
7
+ // Voice is input and output AROUND a session, never its brain: speech becomes the owner's turn as text, the session's
8
+ // own model answers with its tools, and that answer is spoken. Nothing here asks a speech model a question.
9
+ import { visionGateways } from "../tools/vision-gateway.js";
10
+ import { retry, retryAfterMs, realClock, ROUTE_RETRY } from "../util/retry.js";
11
+ /** `timeoutMs` covers one whole call, a cold model load included. `loadingAfterMs`: a call still unanswered by then
12
+ * is reported through `onWait` every `tickMs`, so a cold start shows elapsed time instead of hanging. */
13
+ export const VOICE_DEFAULTS = { sttRoute: "audio.stt", ttsRoute: "audio.tts", timeoutMs: 180_000, loadingAfterMs: 3_000, tickMs: 1_000, probeMs: 3_000 };
14
+ export function voiceConfig(v = {}) {
15
+ return {
16
+ gateways: visionGateways({ gateway: v.gateway }),
17
+ sttRoute: v.sttRoute?.trim() || VOICE_DEFAULTS.sttRoute,
18
+ ttsRoute: v.ttsRoute?.trim() || VOICE_DEFAULTS.ttsRoute,
19
+ ...(v.voice?.trim() ? { voice: v.voice.trim() } : {}),
20
+ timeoutMs: v.timeoutMs && v.timeoutMs > 0 ? v.timeoutMs : VOICE_DEFAULTS.timeoutMs,
21
+ };
22
+ }
23
+ const headers = (gw) => ({ "User-Agent": "operator/kode-tsi", ...gw.auth });
24
+ const failure = (e, timeoutMs) => {
25
+ const name = e?.name;
26
+ return name === "TimeoutError" || name === "AbortError" ? `no answer in ${Math.max(1, Math.round(timeoutMs / 1000))}s` : "unreachable";
27
+ };
28
+ /** Why a route is not there, or null when the gateway lists it. Asks the gateway's model list only: no speech server
29
+ * is touched and no model is loaded. */
30
+ async function routeMissing(gw, route) {
31
+ try {
32
+ const res = await fetch(`${gw.base}/models/${encodeURIComponent(route)}`, { headers: headers(gw), signal: AbortSignal.timeout(VOICE_DEFAULTS.probeMs) });
33
+ return res.ok ? null : res.status === 404 ? `no "${route}" route` : `returned ${res.status}`;
34
+ }
35
+ catch (e) {
36
+ return failure(e, VOICE_DEFAULTS.probeMs);
37
+ }
38
+ }
39
+ /** The first gateway that has both voice routes, or one plain line saying why none does. */
40
+ export async function findVoiceGateway(cfg) {
41
+ if (!cfg.gateways.length)
42
+ return { error: "voice is off (services.voice.gateway is \"off\")" };
43
+ const down = [];
44
+ for (const gw of cfg.gateways) {
45
+ if (gw.skip) {
46
+ down.push(`${gw.label}: ${gw.skip}`);
47
+ continue;
48
+ }
49
+ const missing = (await Promise.all([routeMissing(gw, cfg.sttRoute), routeMissing(gw, cfg.ttsRoute)])).filter(Boolean);
50
+ if (!missing.length)
51
+ return { ok: gw };
52
+ down.push(`${gw.label}: ${[...new Set(missing)].join(", ")}`);
53
+ }
54
+ return { error: `voice is unavailable: ${down.join("; ")}` };
55
+ }
56
+ /** One request with the route's retry (a busy or restarting leg answers 503 at once) inside one deadline, reporting
57
+ * the wait. Throws one plain line, never a response body. */
58
+ async function call(what, timeoutMs, o, send, read) {
59
+ const clock = o.clock ?? realClock;
60
+ const started = clock.now(), deadline = started + timeoutMs;
61
+ const tick = o.tickMs ?? VOICE_DEFAULTS.tickMs, after = o.loadingAfterMs ?? VOICE_DEFAULTS.loadingAfterMs;
62
+ const timer = o.onWait ? setInterval(() => { const ms = clock.now() - started; if (ms >= after)
63
+ o.onWait?.(Math.round(ms / 1000)); }, tick) : undefined;
64
+ try {
65
+ const { result } = await retry(async () => {
66
+ const left = Math.max(1, deadline - clock.now());
67
+ try {
68
+ const res = await send(AbortSignal.timeout(left));
69
+ if (res.status === 503 || res.status === 429)
70
+ return { error: `the gateway returned ${res.status}`, retry: true, retryAfterMs: retryAfterMs(res.headers.get("retry-after"), clock.now()) };
71
+ if (!res.ok)
72
+ return { error: res.status === 404 ? "the route is not configured" : `the gateway returned ${res.status}` };
73
+ const value = await read(res).catch(() => undefined);
74
+ return value === undefined ? { error: "the gateway returned nothing usable" } : { ok: value };
75
+ }
76
+ catch (e) {
77
+ const reason = failure(e, timeoutMs);
78
+ return reason === "unreachable" ? { error: "the gateway is unreachable", retry: true } : { error: reason };
79
+ }
80
+ }, { ...ROUTE_RETRY, deadline }, clock);
81
+ if ("ok" in result)
82
+ return result.ok;
83
+ throw new Error(`${what} failed: ${result.error}`);
84
+ }
85
+ finally {
86
+ if (timer)
87
+ clearInterval(timer);
88
+ }
89
+ }
90
+ /** Recorded audio → the words said ("" when none were heard). */
91
+ export function transcribe(gw, cfg, audio, o = {}) {
92
+ return call("transcription", cfg.timeoutMs, o, (signal) => {
93
+ const form = new FormData();
94
+ form.append("file", new Blob([audio], { type: "audio/wav" }), "speech.wav");
95
+ form.append("model", cfg.sttRoute);
96
+ form.append("response_format", "json");
97
+ return fetch(`${gw.base}/audio/transcriptions`, { method: "POST", signal, headers: headers(gw), body: form }); // no Content-Type: FormData sets the boundary
98
+ }, async (res) => {
99
+ const text = (await res.json()).text;
100
+ return typeof text === "string" ? text.trim() : undefined;
101
+ });
102
+ }
103
+ /** Text → spoken WAV bytes. */
104
+ export function speak(gw, cfg, text, o = {}) {
105
+ return call("speech", cfg.timeoutMs, o, (signal) => fetch(`${gw.base}/audio/speech`, {
106
+ method: "POST", signal, headers: { "Content-Type": "application/json", ...headers(gw) },
107
+ body: JSON.stringify({ model: cfg.ttsRoute, input: text, response_format: "wav", ...(cfg.voice ? { voice: cfg.voice } : {}) }),
108
+ }), async (res) => {
109
+ const bytes = new Uint8Array(await res.arrayBuffer());
110
+ return bytes.length ? bytes : undefined;
111
+ });
112
+ }
@@ -1,21 +1,17 @@
1
1
  // Free cloud models — the rows a vendor gateway serves at zero price, found the way discovery.ts finds fleet
2
2
  // servers: models are DATA the serving layer advertises, never hand-typed into the catalog. Today the gateway is
3
- // the Nous preset (BYO_PRESETS.nous); an OpenRouter `:free` listing is the same shape with another preset. Two
4
- // public JSON reads (no auth), both best-effort and both inside ONE 4 s budget so /model never waits on them: the
3
+ // 0perator's own free catalog (BYO_PRESETS.operator); an OpenRouter `:free` listing is the same shape with another
4
+ // preset. Two public JSON reads (no auth), both best-effort and both inside ONE 4 s budget so /model never waits on them: the
5
5
  // catalog (`${endpoint}/models`, OpenRouter-style `pricing.prompt`/`completion`, strings or numbers) decides what is
6
- // free, the vendor's recommended feed decides the order. The last good list is cached on disk (10 min TTL) and
6
+ // free, an optional recommended feed decides the order. The last good list is cached on disk (10 min TTL) and
7
7
  // served `stale` when the vendor is unreachable, so the rows survive a flaky link. Pure core exported for tests.
8
8
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
9
  import { dirname } from "node:path";
10
10
  import { operatorPath } from "../config/home.js";
11
- /** Vendor feeds that rank the free rows (`freeRecommendedModels[].modelName`), by preset account. */
12
- export const RECOMMENDED_FEEDS = {
13
- nous: "https://portal.nousresearch.com/api/nous/recommended-models",
14
- };
15
11
  /** The window free rows serve when the catalog states none (the vendor's free tier, not its paid 1M). */
16
12
  export const DEFAULT_FREE_CTX = 262144;
17
13
  /** The caveat every free row carries — the owner reads it in the picker and again in the /model sys line. */
18
- export const FREE_TIER_CAVEAT = "free tier — prompts may be used for training (vendor ToS §12.3); 50 RPM / 500k TPM";
14
+ export const FREE_TIER_CAVEAT = "free tier — the model's provider may log or train on prompts; rate limits apply";
19
15
  /** Promotional rows with a published end date, by an id fragment. */
20
16
  const PROMO_EXPIRY = { laguna: "2026-10-31" };
21
17
  const DEFAULTS = { timeoutMs: 4000, ttlMs: 10 * 60_000 };
@@ -164,7 +160,7 @@ export function fetchFreeModels(preset, opts = {}) {
164
160
  if (running)
165
161
  return running;
166
162
  const f = opts.fetchImpl ?? fetch;
167
- const feedUrl = opts.recommendedUrl ?? RECOMMENDED_FEEDS[preset.account];
163
+ const feedUrl = opts.recommendedUrl;
168
164
  const read = (async () => {
169
165
  const ac = new AbortController();
170
166
  const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? DEFAULTS.timeoutMs);
@@ -8,9 +8,9 @@
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
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
11
+ // vendor tier (the 0perator Free rows a session's dynamicModels feed in, router/free-models.ts); no
12
12
  // built-in carries it.
13
- import { LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
13
+ import { INFERENCE_API_HOST, LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
14
14
  /** Fallback walk order, strongest → cheapest. */
15
15
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
16
16
  export function isRetired(p) {
@@ -57,29 +57,29 @@ const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its ve
57
57
  /** Output ceilings (ModelProfile.maxOutput) — only where the vendor's limit is cited. Anthropic: the current Claude
58
58
  * family's max_tokens ceiling (a larger value is a 400). */
59
59
  export const ANTHROPIC_MAX_OUTPUT = 128_000;
60
- const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
61
60
  // Registry order IS picker order (visibleModels keeps it): the main three, the local row, then the gateway rows, then the
62
61
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
63
62
  // vendor rows (tier "free") arrive at runtime through Session.dynamicModels and land after all of these.
64
63
  // A deployment's own servers (direct endpoints, owner-only trials, its labels and descriptions) are NOT listed
65
64
  // here: they come from settings.models, which adds rows and overrides these by id (modelRegistry).
66
65
  export const BUILTIN_MODELS = [
67
- // ── main (0.1.361): the three /model rows, in this order (ui/modelPicker.ts MAIN_MODEL_IDS) ─────────────────
66
+ // ── main: the /model rows, in this order (ui/modelPicker.ts MAIN_MODEL_IDS; operator-dense hidden 11/30) ─────────────────
68
67
  // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
69
68
  { id: "operator-flash", tier: "power", label: "Operator-Flash", params: "125B-A6B", box: "gateway", kind: "single", desc: "the default model: a fast MoE with n-gram speculation", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-flash", "operator-flash"], model: "operator-flash", ctx: 131072 },
70
69
  { id: "kimi-linear-48b", tier: "power", label: "Kimi-Linear", params: "48B-A3B", box: "gateway", kind: "single", desc: "long-context MoE", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["kimi-linear-48b", "kimi-linear-48b"], model: "kimi-linear-48b", ctx: 262144 },
71
- { id: "operator-dense", tier: "power", label: "Operator-Dense", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-dense", "operator-dense"], model: "operator-dense", ctx: 131072 },
72
- // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
70
+ { id: "operator-dense", tier: "power", label: "Operator-Dense", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-dense", "operator-dense"], model: "operator-dense", ctx: 131072, hidden: true },
71
+ // ── retired ─────────────────────────────────────────────────────────────────────────────────────────────
73
72
  // THE one Aurora row (0.1.332), retired 11/25 (`status: "retired"`): kept so the id resolves, and every pick of it
74
- // resolves to the fallback model (selectModel). Nothing in the client starts its gateway.
75
- { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "served on this machine; the gateway takes over when it is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000, hidden: true, status: "retired" },
73
+ // resolves to the fallback model (selectModel). Its loopback :8097 is gone (12/01): operator-flash is a route on
74
+ // Operator Portal.
75
+ { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "Operator Portal", kind: "single", desc: "retired: every pick runs on main", endpoint: `https://${INFERENCE_API_HOST}/v1`, model: "operator-flash", ctx: 1000000, hidden: true, status: "retired" },
76
76
  // ── gateway ─────────────────────────────────────────────────────────────────────────────────────────────
77
77
  // GATEWAY-FIRST: the local gateway when this machine runs one, then the public face. `ctx` is the window the
78
78
  // gateway serves. The 0.1.260 lesson stands: a profile that claims MORE than the server's --ctx-size makes the
79
79
  // engine overrun the wall and the server cuts a round mid-tool-call (0.1.259) — change a number ONLY when the
80
80
  // served window changes. cortana, thor and scout are retired from the picker (RETIRED_MODEL_IDS) and resolve by id.
81
81
  { id: "cortana", tier: "power", label: "Cortana", params: "35B-A3B", box: "gateway", kind: "single", desc: "general model with vision", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["cortana", "cortana"], model: "cortana", ctx: 262144, hidden: true },
82
- { id: "gpt-oss-20b", tier: "economy", label: "gpt-oss", params: "20B-A3.6B", box: "gateway", kind: "single", desc: "OpenAI gpt-oss-20b — the MoA specialist", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["gpt-oss-20b", "gpt-oss-20b"], model: "gpt-oss-20b", ctx: 65536 },
82
+ { id: "gpt-oss-20b", tier: "economy", label: "gpt-oss", params: "20B-A3.6B", box: "gateway", kind: "single", desc: "OpenAI gpt-oss-20b — the MoA specialist", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["gpt-oss-20b", "gpt-oss-20b"], model: "gpt-oss-20b", ctx: 65536, hidden: true },
83
83
  { id: "thor", tier: "power", label: "Thor", params: "32B", box: "gateway", kind: "single", desc: "reasoning model — thinks before answering", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["thor", "thor"], model: "thor", ctx: 32768, hidden: true },
84
84
  { id: "scout", tier: "lite", label: "Scout", params: "4B", box: "gateway", kind: "single", desc: "fast small model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["scout", "scout"], model: "scout", ctx: 32000, hidden: true },
85
85
  // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
@@ -101,7 +101,7 @@ export const BUILTIN_MODELS = [
101
101
  // and the Operator token is its native auth (authHeaders scoping) — never a BYO gate on this id: gating it
102
102
  // behind an unissued `sk-axe-…` account hid our own remote lane from our own picker (2026-10-12 audit). When
103
103
  // the V1 vendor keys ship, reintroduce a byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
104
- { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "the default model on the shared gateway", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
104
+ { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "the default model on the shared gateway", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "operator-flash", ctx: 307200, transport: "openai", hidden: true },
105
105
  { id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "128K context, lighter RAM (:8096); hidden from the picker, resolves by id when the slot is served", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
106
106
  // ── capabilities (0.1.355) ──────────────────────────────────────────────────────────────────────────────
107
107
  // A capability is a name the gateway resolves (the portal's aliases and routes), so the owner asks for a KIND of worker and
@@ -111,8 +111,16 @@ export const BUILTIN_MODELS = [
111
111
  // is the smallest window any model in the chain serves, so compaction is safe wherever the request lands.
112
112
  { id: "main", tier: "power", label: "Main", box: "gateway", kind: "single", desc: "capability: the router's main route — owns the shell's endpoint chain and answers a failed turn", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["main", "main"], model: "main", ctx: 262144, hidden: true },
113
113
  { id: "subagent", tier: "power", label: "Sub-agent", box: "fleet", kind: "single", desc: "capability: the default sub-agent — the gateway picks the best healthy model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["subagent", "subagent"], model: "subagent", ctx: 262144, hidden: true },
114
+ // ── Waterfall seats (engine/waterfall.ts): the gateway decides which model sits in each; hidden, selected by the harness ──
115
+ { id: "operator-executor", tier: "power", label: "operator-executor", box: "gateway", kind: "single", desc: "Waterfall: the one-model tier", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-executor", "operator-executor"], model: "operator-executor", ctx: 262144, hidden: true, maxOutput: 32768 },
116
+ { id: "dexter-planner", tier: "power", label: "dexter-planner", box: "gateway", kind: "single", desc: "Waterfall: plans code work", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["dexter-planner", "dexter-planner"], model: "dexter-planner", ctx: 262144, hidden: true, maxOutput: 32768 },
117
+ { id: "dexter-executor", tier: "power", label: "dexter-executor", box: "gateway", kind: "single", desc: "Waterfall: runs code steps on the local fleet", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["dexter-executor", "dexter-executor"], model: "dexter-executor", ctx: 262144, hidden: true, maxOutput: 32768 },
118
+ { id: "moa-planner", tier: "power", label: "moa-planner", box: "gateway", kind: "single", desc: "Waterfall: plans research and multi-step work", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["moa-planner", "moa-planner"], model: "moa-planner", ctx: 262144, hidden: true, maxOutput: 32768 },
119
+ { id: "moa-executor", tier: "power", label: "moa-executor", box: "gateway", kind: "single", desc: "Waterfall: runs steps on the cloud and local fleet", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["moa-executor", "moa-executor"], model: "moa-executor", ctx: 262144, hidden: true, maxOutput: 32768 },
120
+ { id: "external-executor", tier: "power", label: "external-executor", box: "gateway", kind: "single", desc: "Waterfall: a remote agent with its own browser and sandbox, for steps that need the open web", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["external-executor", "external-executor"], model: "external-executor", ctx: 262144, hidden: true, maxOutput: 32768 },
114
121
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
115
122
  { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — a planner hands steps to specialists, checks their work and writes the answer (settings.moa overrides)" },
123
+ { id: "waterfall", tier: "power_turbo", label: "Waterfall", box: "agent harness", kind: "orchestrated", desc: "picks the tier for each message — one model, a local team or the full team — and plans, delegates and checks" },
116
124
  ];
117
125
  export const OPERATOR_FREE_ACCOUNT = "0perator";
118
126
  export const BYO_PRESETS = {
@@ -125,24 +133,55 @@ export const BYO_PRESETS = {
125
133
  openrouter: { label: "OpenRouter", box: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter", envAlias: "OPENROUTER_API_KEY" },
126
134
  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" },
127
135
  xai: { label: "xAI Grok", box: "xAI", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai", envAlias: "XAI_API_KEY" },
128
- // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
129
- // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
130
136
  // 0perator's own free catalog (portal router behind AuthGate): the free models we serve with OUR provider accounts,
131
137
  // listed for every signed-in Operator with no vendor key. The rows come from its /models (pricing 0).
138
+ // Operator Portal: our model gateway as a provider (the same edge and router as GATEWAY_BASE). Its account is the sign-in
139
+ // one, so the Operator token is its key; its rows are the gateway's /v1/models (router/provider-models.ts).
132
140
  operator: { label: "0perator Free", box: "0perator", endpoint: `https://${PRODUCT_API_HOST}/free/v1`, model: "nvidia/nemotron-3-ultra-550b-a55b:free", ctx: 262144, account: OPERATOR_FREE_ACCOUNT, transport: "openai", signIn: true, freeCaveat: "free via 0perator — the model's provider may log or train on prompts; shared rate limits" },
133
- 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" },
141
+ portal: { label: "Operator Portal", box: "Operator Portal", endpoint: `https://${INFERENCE_API_HOST}/v1`, model: "main", ctx: 262144, account: OPERATOR_FREE_ACCOUNT, transport: "openai", signIn: true },
134
142
  };
143
+ /** Providers taken out of the product (2026-12-01), by account → the preset that replaced them. A saved row on that
144
+ * account, a persisted `<account>-…` id or a `--preset` naming it maps to the replacement, never an error: the session
145
+ * runs on `main` (the old vendor's model ids do not exist on our gateway) and says so once. */
146
+ export const REPLACED_PROVIDERS = { nous: { label: "Nous Portal", by: "portal" } };
147
+ /** The replacement for a replaced provider's account (or a preset name), or undefined for any other. */
148
+ export function replacedProvider(account) {
149
+ return account && Object.hasOwn(REPLACED_PROVIDERS, account) ? REPLACED_PROVIDERS[account] : undefined;
150
+ }
135
151
  /** The vendor env var a BYO account answers to (ByoPreset.envAlias), or undefined for an account no preset names. */
136
152
  export function byoEnvAlias(account) {
137
153
  return Object.values(BYO_PRESETS).find((p) => p.account === account)?.envAlias;
138
154
  }
139
155
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
140
156
  * built-in by id, or adding a new one) — same shape either way, so /model doesn't care which. */
157
+ /** Retired Aurora's address, loopback :8097 (12/01). Nothing serves it any more. */
158
+ export function isRetiredAuroraBase(base) {
159
+ try {
160
+ const u = new URL(base ?? "");
161
+ return u.port === "8097" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname);
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ /** The id our gateway serves for a model a retired :8097 setting named: operator-flash stays, Aurora's own ids
168
+ * (aurora-code-1, aurora, operator-1m) become `main`. */
169
+ export function gatewayModelFor(model) {
170
+ return model === "operator-flash" ? model : "main";
171
+ }
172
+ /** A saved settings.models row on the retired :8097 runs on Operator Portal (BYO_PRESETS.portal), never an error. */
173
+ function migrateRetiredRow(m) {
174
+ if (!isRetiredAuroraBase(m.endpoint) && !m.endpoints?.some(isRetiredAuroraBase))
175
+ return m;
176
+ const portal = BYO_PRESETS.portal;
177
+ return { ...m, box: portal.box, endpoint: portal.endpoint, endpoints: undefined, endpointModels: undefined, model: gatewayModelFor(m.model), byo: portal.account, transport: "openai" };
178
+ }
141
179
  export function modelRegistry(overrides) {
142
180
  if (!overrides?.length)
143
181
  return BUILTIN_MODELS;
144
182
  const byId = new Map(BUILTIN_MODELS.map((m) => [m.id, m]));
145
- for (const m of overrides) {
183
+ for (const o of overrides) {
184
+ const m = migrateRetiredRow(o);
146
185
  const merged = { ...byId.get(m.id), ...m };
147
186
  byId.set(m.id, RETIRED_MODEL_IDS.has(m.id) && merged.hidden === undefined ? { ...merged, hidden: true } : merged);
148
187
  }
@@ -247,6 +286,11 @@ export function leanHarnessFor(id, overrides) {
247
286
  * gates BYO connector profiles: honest "not connected" beats a request-time 401. */
248
287
  export function selectModel(registry, id, hasByo, isOwner = true) {
249
288
  const profile = findModel(registry, id);
289
+ const old = replacedProvider(profile ? profile.byo : id.split("-", 1)[0]);
290
+ if (old) {
291
+ const by = BYO_PRESETS[old.by].label;
292
+ return { profile: fallbackProfile(registry, CHAIN_MODEL_ID), replaced: `${old.label} is no longer offered — ${by} answers instead (main); /model picks another` };
293
+ }
250
294
  if (!profile)
251
295
  return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
252
296
  if (isRetired(profile))
@@ -0,0 +1,78 @@
1
+ // A provider's chat rows read from its own `/models` (OpenAI shape) at runtime — Operator Portal today (BYO_PRESETS.portal).
2
+ // The gateway lists every route it serves, so the list is trimmed to what a /model row can use: retired rows and their
3
+ // aliases, and the speech, image and vision routes, never become rows. Signed out, a 401, junk or a timeout yields the
4
+ // preset's public routes (PROVIDER_DEFAULT_ROUTES), so the provider never vanishes from the picker. Never throws.
5
+ import { authHeaders } from "../engine/aurora.js";
6
+ import { catalogRows, DEFAULT_FREE_CTX, freeModelSlug } from "./free-models.js";
7
+ import { MODEL_ALIASES, RETIRED_MODEL_IDS } from "./models.js";
8
+ /** The routes listed when the catalog cannot be read: public route names only, never a retired one. */
9
+ export const PROVIDER_DEFAULT_ROUTES = ["main", "operative"];
10
+ /** Routes that are not chat models (speech, images, vision helpers) or are retired under another spelling. */
11
+ const NOT_A_CHAT_ROW = /^(audio\.|image|vision|tts-|whisper-|aurora)/;
12
+ /** Whether a catalog id may become a row. */
13
+ export function isChatRoute(id) {
14
+ return !!id && !RETIRED_MODEL_IDS.has(id) && !Object.hasOwn(MODEL_ALIASES, id) && !NOT_A_CHAT_ROW.test(id);
15
+ }
16
+ /** Pure: the preset's rows from a catalog's rows (catalogRows output), catalog order, duplicates dropped. `key` is the
17
+ * preset's name in BYO_PRESETS and prefixes every id (`portal-main`), so a row never shadows a built-in. */
18
+ export function providerModelsFromCatalog(rows, key, preset) {
19
+ const seen = new Set();
20
+ const out = [];
21
+ for (const row of rows) {
22
+ const r = row;
23
+ if (typeof r?.id !== "string" || !isChatRoute(r.id) || seen.has(r.id))
24
+ continue;
25
+ seen.add(r.id);
26
+ out.push({
27
+ id: `${key}-${freeModelSlug(r.id)}`,
28
+ label: r.id,
29
+ box: preset.box ?? preset.label,
30
+ kind: "single",
31
+ desc: `${preset.label}: the ${r.id} route on our gateway, signed in with your Operator account`,
32
+ endpoint: preset.endpoint,
33
+ model: r.id,
34
+ ctx: typeof r.context_length === "number" && r.context_length > 0 ? r.context_length : DEFAULT_FREE_CTX,
35
+ byo: preset.account,
36
+ transport: "openai",
37
+ });
38
+ }
39
+ return out;
40
+ }
41
+ const DEFAULTS = { timeoutMs: 4000, ttlMs: 60_000 };
42
+ const cache = new Map();
43
+ const inflight = new Map();
44
+ /** The preset's rows: the last good list within its TTL, else a live read under one timeout; a failed read serves the
45
+ * public routes. Concurrent callers share one read. The bearer is whatever authHeaders sends to that host — for our
46
+ * gateway, the Operator sign-in token. */
47
+ export function fetchProviderModels(key, preset, opts = {}) {
48
+ const now = opts.now ?? Date.now;
49
+ const hit = cache.get(preset.endpoint);
50
+ if (hit && now() - hit.at < (opts.ttlMs ?? DEFAULTS.ttlMs))
51
+ return Promise.resolve(hit.models);
52
+ const running = inflight.get(preset.endpoint);
53
+ if (running)
54
+ return running;
55
+ const f = opts.fetchImpl ?? fetch;
56
+ const url = `${preset.endpoint}/models`;
57
+ const read = (async () => {
58
+ const ac = new AbortController();
59
+ const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? DEFAULTS.timeoutMs);
60
+ try {
61
+ const res = await f(url, { headers: { Accept: "application/json", ...authHeaders({ base: preset.endpoint, model: "" }) }, signal: ac.signal });
62
+ const rows = res.ok ? catalogRows(await res.json()) : undefined;
63
+ const models = rows ? providerModelsFromCatalog(rows, key, preset) : [];
64
+ if (models.length) {
65
+ cache.set(preset.endpoint, { at: now(), models });
66
+ return models;
67
+ }
68
+ }
69
+ catch { /* offline, timeout or junk: the public routes below */ }
70
+ finally {
71
+ clearTimeout(timer);
72
+ inflight.delete(preset.endpoint);
73
+ }
74
+ return providerModelsFromCatalog(PROVIDER_DEFAULT_ROUTES.map((id) => ({ id })), key, preset);
75
+ })();
76
+ inflight.set(preset.endpoint, read);
77
+ return read;
78
+ }
@@ -1,7 +1,19 @@
1
- // ONE model: Aurora at its native 1M context on :8097 (the air/1m/saddle roster collapsed here once 1M
2
- // served at full speed). The router still handles N endpoints generically; this default just has one.
1
+ // Endpoint routing & self-heal — SPEC §4. Two Aurora endpoints: Air (fast, small ctx) and
2
+ // 1M (slow, huge ctx). Interface consumed by the engine (Karpathy's lane):
3
+ // base, model -> current endpoint's connection info
4
+ // ctxLimit() -> current endpoint's context window
5
+ // routeBySize(n) -> pick the smallest endpoint that fits n tokens, escalating Air->1M as
6
+ // the conversation grows; NEVER moves to a smaller endpoint on its own
7
+ // escalate() -> jump straight to the largest endpoint (used on repeated 400s with no
8
+ // room left to compact)
9
+ // failover() -> hop to a healthy endpoint after a busy/5xx response; prefers a smaller
10
+ // endpoint over the one that just failed, per SPEC §4's "self-heal"
11
+ // KODE_NO_ROUTER=1 pins the router to whatever endpoint is current and disables all movement.
12
+ import { LOCAL_GATEWAY_BASE } from "./models.js";
13
+ // One endpoint by default: the local router's `main` (buildEndpointChain's built-in primary). The router still handles
14
+ // N endpoints generically.
3
15
  const DEFAULT_ENDPOINTS = [
4
- { name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit: 1000000 },
16
+ { name: "main", base: LOCAL_GATEWAY_BASE.replace(/\/v1\/?$/, ""), model: "main", ctxLimit: 262144 },
5
17
  ];
6
18
  // Leave headroom under the hard ctx limit — mirrors SPEC §5's 0.85 compaction threshold, so
7
19
  // routing and compaction agree on what "fits."
@@ -338,6 +338,29 @@ export function orderLessons(lines) {
338
338
  .sort((a, b) => rank(a.t.kind) - rank(b.t.kind) || (a.t.last === b.t.last ? (a.t.cls < b.t.cls ? -1 : a.t.cls > b.t.cls ? 1 : 0) : a.t.last < b.t.last ? 1 : -1))
339
339
  .map((x) => x.l);
340
340
  }
341
+ /** Lessons the system prompt loads (settings.memory.promptLessons overrides). On 12/01 the owner's file held 76 lessons
342
+ * (5.5K tokens of every cold start), 70 of them seen once; the rest stay in the file, and memory_search finds them. */
343
+ export const PROMPT_LESSONS = 20;
344
+ /** The `n` lessons with the most hits, ties to the most recently confirmed, in their canonical order; `rest` = how many
345
+ * were left out. */
346
+ export function topLessons(lines, n) {
347
+ if (lines.length <= n)
348
+ return { kept: [...lines], rest: 0 };
349
+ const ranked = lines.map((l) => ({ l, t: parseLessonTag(l) }))
350
+ .sort((a, b) => b.t.count - a.t.count || (a.t.last === b.t.last ? 0 : a.t.last < b.t.last ? 1 : -1));
351
+ const keep = new Set(ranked.slice(0, Math.max(0, n)).map((x) => x.l));
352
+ return { kept: lines.filter((l) => keep.has(l)), rest: lines.length - keep.size };
353
+ }
354
+ /** The lessons of memories files (global, then a project's) whose text contains `query`, case-insensitive: what
355
+ * memory_search adds to the store's notes, so a lesson the prompt left out is still found. */
356
+ export function matchLessons(fileTexts, query) {
357
+ const q = query.trim().toLowerCase();
358
+ if (!q)
359
+ return [];
360
+ const taught = reinforcedRules(fileTexts[0] ?? "");
361
+ const all = fileTexts.reduce((acc, t) => mergeLessons(acc, splitLessons(t, taught).lessons), []);
362
+ return all.filter((l) => l.toLowerCase().includes(q));
363
+ }
341
364
  /** Lines from two files (the global store and a project's older stuck lessons) as one list: a kind + class in both is
342
365
  * one line — the counts add (different turns), the newer line's words and `last` win. */
343
366
  export function mergeLessons(a, b) {