@0perator/operator 0.2.0 → 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 (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. package/dist/tools/mutating.js +0 -15
@@ -1,5 +1,6 @@
1
1
  import { frameKey as deriveFrameKey, pairingId as derivePairingId, encryptFrame, decryptFrame } from "./pairing.js";
2
2
  import { redactSecrets } from "../engine/redact.js";
3
+ import { grantsEnabled, isGrantScope } from "./grants.js";
3
4
  let socketCtor = globalThis.WebSocket;
4
5
  /** The WebSocket constructor for this runtime: the global one, else `ws`'s (same addEventListener / send / close shape). */
5
6
  async function loadSocketCtor() {
@@ -28,8 +29,8 @@ const RECONNECT_MAX_MS = 15_000;
28
29
  // control frames stay plaintext so the relay can route blind. These sets mirror the mobile's frozen
29
30
  // dataFrameTypes byte-for-byte (kode-mobile RemoteSession.swift). The INNER encrypted bytes are
30
31
  // JSON.stringify(payloadDict) — just the payload dict, never {type,payload}.
31
- const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta", "agents"]);
32
- const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer"]);
32
+ const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta", "agents", "grants"]);
33
+ const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer", "grant_revoke"]);
33
34
  // A paired snapshot is encrypted (base64 ≈ 1.37× plaintext), and the relay drops/truncates any frame over
34
35
  // its 256 KB cap — which would corrupt ciphertext. Cap the paired snapshot's plaintext so the encrypted
35
36
  // frame stays comfortably under 256 KB; token-mode keeps the full 512 KB budget.
@@ -149,7 +150,7 @@ export class RemoteHost {
149
150
  ws.addEventListener("open", () => {
150
151
  // §1: advertise the engine contract + features so the relay/followers can version-gate. sessionId (when
151
152
  // set) makes this a RESUME. Additive — an old relay ignores proto/features.
152
- this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined, proto: ENGINE_CONTRACT, features: HOST_FEATURES });
153
+ this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined, proto: ENGINE_CONTRACT, features: grantsEnabled() ? [...HOST_FEATURES, "grants.v1"] : HOST_FEATURES });
153
154
  });
154
155
  ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
155
156
  ws.addEventListener("close", () => {
@@ -284,6 +285,8 @@ export class RemoteHost {
284
285
  break;
285
286
  case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
286
287
  this.sendSnapshot();
288
+ if (grantsEnabled())
289
+ this.state("grants", { items: this.grantItems });
287
290
  break;
288
291
  // Drive frames (follower -> host actions). Defense-in-depth: the relay is SUPPOSED to only
289
292
  // ever forward a frame that belongs to this connection's session, but a relay bug or a
@@ -295,8 +298,24 @@ export class RemoteHost {
295
298
  this.cb.onPrompt(f.payload.text);
296
299
  break;
297
300
  case "approval_response":
298
- if (this.isOwnFrame(f) && f.payload?.id)
299
- this.cb.onApprovalResponse(String(f.payload.id), !!f.payload.approve);
301
+ if (this.isOwnFrame(f) && f.payload?.id) {
302
+ const approve = !!f.payload.approve;
303
+ // Only a scope is read from the follower. The target is derived host-side from the pending call.
304
+ const scope = f.payload.grant?.scope;
305
+ const grant = approve && grantsEnabled() && isGrantScope(scope) ? { scope } : undefined;
306
+ if (grant)
307
+ this.cb.onApprovalResponse(String(f.payload.id), approve, grant);
308
+ else
309
+ this.cb.onApprovalResponse(String(f.payload.id), approve);
310
+ }
311
+ break;
312
+ case "grant_revoke":
313
+ if (this.isOwnFrame(f) && grantsEnabled()) {
314
+ if (f.payload?.all === true)
315
+ this.cb.onGrantRevoke?.({ all: true });
316
+ else if (typeof f.payload?.id === "string")
317
+ this.cb.onGrantRevoke?.({ id: f.payload.id });
318
+ }
300
319
  break;
301
320
  case "ask_user_response":
302
321
  if (this.isOwnFrame(f) && f.payload?.id)
@@ -511,4 +530,13 @@ export class RemoteHost {
511
530
  * follower's ask_user_response race first-wins in the host (settleQuestion in cli.tsx); local
512
531
  * ask_user keeps working unchanged when no remote-control session is active. */
513
532
  askUser(id, question, options) { this.state("ask_user", { id, question, options }); }
533
+ grantItems = [];
534
+ /** Mirror the live grants to followers (owner-scoped `grants` state frame) so their list is what the host holds. */
535
+ setGrants(items) {
536
+ if (!grantsEnabled())
537
+ return;
538
+ this.grantItems = items;
539
+ if (this.sessionId)
540
+ this.state("grants", { items });
541
+ }
514
542
  }
@@ -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,20 +8,25 @@
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
- /** The Aurora row whose endpoints are the shell's own chain (endpoints.aurora + its failover legs). Since 0.1.361 it is
17
- * no longer the model a fresh install starts on — that is DEFAULT_ACTIVE_MODEL. */
18
- export const DEFAULT_MODEL_ID = "operator-1m";
16
+ export function isRetired(p) {
17
+ return p?.status === "retired";
18
+ }
19
+ /** The row that owns the shell's endpoint chain (buildEndpointChain: the router's `main`, then the fleet and cloud legs):
20
+ * a session with no /model pick runs on it, and `/model main` restores the chain. Was the Aurora row `operator-1m` until
21
+ * Aurora was retired (11/25). Not the model a fresh install starts on — that is DEFAULT_ACTIVE_MODEL. */
22
+ export const CHAIN_MODEL_ID = "main";
19
23
  /** The model a session starts on when settings.activeModel is not set (a fresh install): the router's
20
24
  * `operator-flash` route. A persisted activeModel always wins. */
21
25
  export const DEFAULT_ACTIVE_MODEL = "operator-flash";
22
26
  /** Rows retired from the picker (11/25): never in /model or the ACP dropdown, still resolvable by id so a persisted
23
27
  * activeModel, a script or a delegate target keeps working. A settings.models row with one of these ids is hidden too
24
- * unless it says `hidden: false`. */
28
+ * unless it says `hidden: false`. Hidden is not the lifecycle: a row whose `status` is "retired" (operator-1m) resolves
29
+ * to the fallback model; the others here still answer as themselves. */
25
30
  export const RETIRED_MODEL_IDS = new Set([
26
31
  "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "belmont-30b", "venice-24b", "dolphin-7b",
27
32
  ]);
@@ -52,31 +57,29 @@ const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its ve
52
57
  /** Output ceilings (ModelProfile.maxOutput) — only where the vendor's limit is cited. Anthropic: the current Claude
53
58
  * family's max_tokens ceiling (a larger value is a 400). */
54
59
  export const ANTHROPIC_MAX_OUTPUT = 128_000;
55
- const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
56
60
  // Registry order IS picker order (visibleModels keeps it): the main three, the local row, then the gateway rows, then the
57
61
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
58
62
  // vendor rows (tier "free") arrive at runtime through Session.dynamicModels and land after all of these.
59
63
  // A deployment's own servers (direct endpoints, owner-only trials, its labels and descriptions) are NOT listed
60
64
  // here: they come from settings.models, which adds rows and overrides these by id (modelRegistry).
61
65
  export const BUILTIN_MODELS = [
62
- // ── 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) ─────────────────
63
67
  // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
64
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 },
65
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 },
66
- { 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 },
67
- // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
68
- // THE one Aurora row (0.1.332), retired from the picker 11/25 (RETIRED_MODEL_IDS). The 300K/600K/1M choice is a
69
- // context PIN (settings.contextPin, /context, Ctrl+X) applied over the served window — not three profiles of one
70
- // model. The static :8097 is the gateway-less fallback; on a gateway box Session.setModel restores the shell's chain
71
- // for this id (the dynamic port + the fleet and cloud legs buildEndpointChain assembles).
72
- { 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 },
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 ─────────────────────────────────────────────────────────────────────────────────────────────
72
+ // THE one Aurora row (0.1.332), retired 11/25 (`status: "retired"`): kept so the id resolves, and every pick of it
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" },
73
76
  // ── gateway ─────────────────────────────────────────────────────────────────────────────────────────────
74
77
  // GATEWAY-FIRST: the local gateway when this machine runs one, then the public face. `ctx` is the window the
75
78
  // gateway serves. The 0.1.260 lesson stands: a profile that claims MORE than the server's --ctx-size makes the
76
79
  // engine overrun the wall and the server cuts a round mid-tool-call (0.1.259) — change a number ONLY when the
77
80
  // served window changes. cortana, thor and scout are retired from the picker (RETIRED_MODEL_IDS) and resolve by id.
78
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 },
79
- { 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 },
80
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 },
81
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 },
82
85
  // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
@@ -98,7 +101,7 @@ export const BUILTIN_MODELS = [
98
101
  // and the Operator token is its native auth (authHeaders scoping) — never a BYO gate on this id: gating it
99
102
  // behind an unissued `sk-axe-…` account hid our own remote lane from our own picker (2026-10-12 audit). When
100
103
  // the V1 vendor keys ship, reintroduce a byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
101
- { 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 },
102
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 },
103
106
  // ── capabilities (0.1.355) ──────────────────────────────────────────────────────────────────────────────
104
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
@@ -106,9 +109,18 @@ export const BUILTIN_MODELS = [
106
109
  // chain instead of queueing. Swapping or promoting a model moves a pointer on the server and no client changes. Hidden: never
107
110
  // a picker row and never offered by tier (profilesByTier skips hidden rows), reached by id (delegate_task, spawn_agent). `ctx`
108
111
  // is the smallest window any model in the chain serves, so compaction is safe wherever the request lands.
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 },
109
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 },
110
121
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
111
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" },
112
124
  ];
113
125
  export const OPERATOR_FREE_ACCOUNT = "0perator";
114
126
  export const BYO_PRESETS = {
@@ -121,24 +133,55 @@ export const BYO_PRESETS = {
121
133
  openrouter: { label: "OpenRouter", box: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter", envAlias: "OPENROUTER_API_KEY" },
122
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" },
123
135
  xai: { label: "xAI Grok", box: "xAI", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai", envAlias: "XAI_API_KEY" },
124
- // Nous Portal — the free cloud tier (router/free-models.ts lists its `:free` rows once this key is connected;
125
- // the vendor requires an account even for free models). 50 RPM / 500k TPM; prompts may be used for training.
126
136
  // 0perator's own free catalog (portal router behind AuthGate): the free models we serve with OUR provider accounts,
127
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).
128
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" },
129
- 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 },
130
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
+ }
131
151
  /** The vendor env var a BYO account answers to (ByoPreset.envAlias), or undefined for an account no preset names. */
132
152
  export function byoEnvAlias(account) {
133
153
  return Object.values(BYO_PRESETS).find((p) => p.account === account)?.envAlias;
134
154
  }
135
155
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
136
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
+ }
137
179
  export function modelRegistry(overrides) {
138
180
  if (!overrides?.length)
139
181
  return BUILTIN_MODELS;
140
182
  const byId = new Map(BUILTIN_MODELS.map((m) => [m.id, m]));
141
- for (const m of overrides) {
183
+ for (const o of overrides) {
184
+ const m = migrateRetiredRow(o);
142
185
  const merged = { ...byId.get(m.id), ...m };
143
186
  byId.set(m.id, RETIRED_MODEL_IDS.has(m.id) && merged.hidden === undefined ? { ...merged, hidden: true } : merged);
144
187
  }
@@ -153,12 +196,11 @@ export function findModel(registry, id) {
153
196
  export const DEFAULT_FALLBACK_MODEL = "main";
154
197
  /** The model that answers a turn whose own legs all failed (Session.turnModel). A registry row with that id answers as
155
198
  * itself; any other id is a router capability, reached through the gateway (loopback first, then the public face).
156
- * Never the launchd-owned default row: a fallback must not wake a model the owner parked, so that id resolves to the
157
- * default capability instead. */
199
+ * Never a retired row: that id resolves to the default capability instead. */
158
200
  export function fallbackProfile(registry, id) {
159
201
  const want = id?.trim() || DEFAULT_FALLBACK_MODEL;
160
202
  const canon = MODEL_ALIASES[want] ?? want;
161
- const name = canon === DEFAULT_MODEL_ID ? DEFAULT_FALLBACK_MODEL : canon;
203
+ const name = isRetired(findModel(registry, canon)) ? DEFAULT_FALLBACK_MODEL : canon;
162
204
  const row = findModel(registry, name);
163
205
  if (row?.kind === "single")
164
206
  return row;
@@ -213,7 +255,12 @@ export function laneTier(lane) {
213
255
  export function modelCtxFor(id, overrides) {
214
256
  if (!id)
215
257
  return Number.POSITIVE_INFINITY;
216
- return findModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
258
+ return resolveModel(modelRegistry(overrides), id)?.ctx ?? Number.POSITIVE_INFINITY;
259
+ }
260
+ /** The row a session on `id` actually runs: a retired row's successor, else the row itself. */
261
+ export function resolveModel(registry, id) {
262
+ const p = findModel(registry, id);
263
+ return isRetired(p) ? fallbackProfile(registry, undefined) : p;
217
264
  }
218
265
  /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora and the gateway models (128K+) stay
219
266
  * full; a self-hosted small model (8K, or a 16K bump) goes lean. */
@@ -231,7 +278,7 @@ export const MIN_CONTEXT_PIN = 32_000;
231
278
  export function leanHarnessFor(id, overrides) {
232
279
  if (modelCtxFor(id, overrides) < LEAN_HARNESS_CTX)
233
280
  return true;
234
- return !!findModel(modelRegistry(overrides), id ?? "")?.leanPersona;
281
+ return !!resolveModel(modelRegistry(overrides), id ?? "")?.leanPersona;
235
282
  }
236
283
  /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
237
284
  * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
@@ -239,8 +286,15 @@ export function leanHarnessFor(id, overrides) {
239
286
  * gates BYO connector profiles: honest "not connected" beats a request-time 401. */
240
287
  export function selectModel(registry, id, hasByo, isOwner = true) {
241
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
+ }
242
294
  if (!profile)
243
295
  return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
296
+ if (isRetired(profile))
297
+ return { profile: fallbackProfile(registry, undefined), retired: profile };
244
298
  if (profile.kind === "single" && !profile.endpoint && !profile.endpoints?.length)
245
299
  return { error: `model "${id}" has no endpoint configured` };
246
300
  if (profile.ownerOnly && !isOwner)
@@ -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."
@@ -5,7 +5,7 @@
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
6
  import { operatorPath, globalMemoriesPath } from "../config/home.js";
7
7
  import { redactSecrets } from "../engine/redact.js";
8
- import { isEngineFinal } from "../engine/continuation.js"; // a stop/pause/no-reply note is the engine's text, never a promotable answer
8
+ import { engineEnded } from "../engine/continuation.js"; // an engine stop is the engine's text, never a promotable answer
9
9
  import { isLooped } from "../engine/loop-guard.js";
10
10
  import { fixLessonLine, isSubagentBrief, loopLessonLine, ownerWords, reinforcedRules, stuckLessonLine, upsertLesson } from "./lessons.js";
11
11
  import { inferType } from "../engine/grandmaster.js";
@@ -33,7 +33,7 @@ export function hasLeakedToolCall(content) {
33
33
  * engine-final note, not looped, not interrupted. The one source of this predicate: flywheelRow tags rows with it and
34
34
  * the skill distiller (captureSkill) gates on it (the second save-time verify gate). */
35
35
  export function isGraded(r) {
36
- return !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !hasLeakedToolCall(r.content) && !isEngineFinal(r.content) && !isLooped(r.loop) && !r.interrupted;
36
+ return !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !hasLeakedToolCall(r.content) && !engineEnded(r) && !isLooped(r.loop) && !r.interrupted;
37
37
  }
38
38
  /** One turn's flywheel row: the day file it goes in (under the operator home's flywheel/) and the JSONL line. Pure. */
39
39
  export function flywheelRow(r, ts) {
@@ -65,11 +65,13 @@ async function captureFlywheel(r, ts) {
65
65
  }
66
66
  catch { /* best-effort — capture never blocks or fails a turn */ }
67
67
  }
68
- /** True when a turn ended STUCK — a loop/guard stop, not a normal completion. The forced-redirect and
69
- * self-loop guards both hand back a "[stopped — …]" note; a repetition stopReason is the other signal.
70
- * A normal answer, or an empty (aborted) turn, is NOT a lesson. */
68
+ /** The engine stops that mean the turn got STUCK: the loop, circling, repetition and window guards and the owner's
69
+ * ignored "answer now". A pause, the round cap, a sub-agent yield or nothing answering is not a lesson. */
70
+ const STUCK_STOPS = new Set(["stopped", "repetition", "reasoning_budget", "window", "owner"]);
71
+ /** True when a turn ended STUCK — a guard stop (its typed stopKind) or a reply cut for repetition, not a normal
72
+ * completion. A normal answer, or an empty (aborted) turn, is NOT a lesson. */
71
73
  function endedStuck(r) {
72
- return r.stopReason === "repetition" || /^\[stopped\s[—-]/.test(r.content.trim());
74
+ return r.stopReason === "repetition" || (r.stopKind !== undefined && STUCK_STOPS.has(r.stopKind));
73
75
  }
74
76
  /** MEMORY sink (the closed self-improvement loop). A LOOPED turn — it ignored its loop warnings (engine/loop-guard.ts
75
77
  * isLooped) — or one that ended STUCK on an engine stop becomes a lesson in the GLOBAL memories.md, which every session
@@ -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) {