@0perator/operator 0.1.285 → 0.1.313

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 (98) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/net-error.js +24 -0
  34. package/dist/engine/repetition-guard.js +180 -0
  35. package/dist/engine/selfheal.js +8 -0
  36. package/dist/engine/toolcalls.js +51 -1
  37. package/dist/engine/verify-gate.js +2 -0
  38. package/dist/flywheel/processor.js +78 -31
  39. package/dist/flywheel/srft.js +13 -0
  40. package/dist/hooks/index.js +196 -0
  41. package/dist/mcp/config.js +21 -1
  42. package/dist/memory/index.js +0 -0
  43. package/dist/memory/providers.js +210 -0
  44. package/dist/memory/session-catalog.js +422 -0
  45. package/dist/memory/session-providers.js +121 -0
  46. package/dist/memory/session-sources.js +335 -0
  47. package/dist/memory/skylark.js +131 -0
  48. package/dist/models/bench.js +103 -0
  49. package/dist/models/registry.js +144 -0
  50. package/dist/models/switch.js +69 -0
  51. package/dist/observability/blackbox.js +37 -0
  52. package/dist/permissions/policy.js +31 -6
  53. package/dist/router/discovery.js +127 -0
  54. package/dist/router/models.js +107 -16
  55. package/dist/router/portal.js +100 -0
  56. package/dist/router/router.js +1 -1
  57. package/dist/services/preflight.js +55 -7
  58. package/dist/session.js +316 -46
  59. package/dist/tools/chauffeur.js +12 -0
  60. package/dist/tools/executor.js +19 -9
  61. package/dist/tools/find-files.js +483 -0
  62. package/dist/tools/git-pr.js +94 -0
  63. package/dist/tools/incident-tools.js +82 -0
  64. package/dist/tools/memory.js +12 -2
  65. package/dist/tools/registry.js +281 -85
  66. package/dist/tools/semantic-compress.js +124 -0
  67. package/dist/tools/shell-context.js +1 -0
  68. package/dist/tools/shell-jobs.js +160 -0
  69. package/dist/tools/shell-session.js +170 -4
  70. package/dist/tools/wave-tools.js +609 -0
  71. package/dist/tools/wave2-tools.js +411 -0
  72. package/dist/ui/App.js +15 -4
  73. package/dist/ui/BgPanel.js +30 -6
  74. package/dist/ui/Composer.js +11 -1
  75. package/dist/ui/QuestionPrompt.js +31 -11
  76. package/dist/ui/SessionPicker.js +86 -0
  77. package/dist/ui/StatusRule.js +5 -5
  78. package/dist/ui/ToolStep.js +2 -1
  79. package/dist/ui/Transcript.js +17 -1
  80. package/dist/ui/index.js +1 -1
  81. package/dist/ui/liveTools.js +21 -3
  82. package/dist/ui/slashCommands.js +2 -0
  83. package/dist/util/screenshots.js +74 -8
  84. package/dist/util/slash.js +2 -2
  85. package/package.json +8 -2
  86. package/dist/engine/cli.js +0 -1171
  87. package/dist/router/models.js.bak +0 -78
  88. package/dist/router/models.js.bak-1791259923 +0 -78
  89. package/dist/router/models.js.bak-pre-gateway +0 -78
  90. package/dist/router/models.js.bak-pre-patch2 +0 -78
  91. package/dist/router/models.js.bak2 +0 -78
  92. package/dist/services/model-autodetect.js +0 -240
  93. package/dist/tools/native-redirect.js +0 -140
  94. package/dist/tools/power-tools.js +0 -627
  95. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  96. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  97. package/dist/ui/BusTray.js +0 -70
  98. package/dist/ui/resize.js +0 -160
package/dist/session.js CHANGED
@@ -2,8 +2,9 @@
2
2
  // with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
3
3
  // that maps these callbacks onto React state; a test can drive the same `send()` directly.
4
4
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
+ import { recordTruncation } from "./observability/blackbox.js";
5
6
  import { Conversation } from "./engine/messages.js";
6
- import { chat, health } from "./engine/aurora.js";
7
+ import { chat, health, requiresOperatorToken } from "./engine/aurora.js";
7
8
  import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
8
9
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
9
10
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
@@ -16,13 +17,16 @@ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0
16
17
  import { AuroraRouter } from "./router/router.js";
17
18
  import { operatorAgentPersona } from "./config/operator-harness.js";
18
19
  import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
20
+ import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
19
21
  import { getByoToken, hasByoToken } from "./auth/byo.js";
20
22
  import { Executor } from "./tools/executor.js";
21
- import { toSchemas, registry, disposeShellSessionKey } from "./tools/registry.js";
23
+ import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor } from "./tools/registry.js";
24
+ import { isFeatureEnabled } from "./config/features.js";
22
25
  import { MemoryStore } from "./memory/index.js";
23
26
  import { McpHub, withMcp } from "./mcp/index.js";
24
27
  import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred } from "./tools/deferred.js";
25
28
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
29
+ import { withHooks } from "./hooks/index.js";
26
30
  import { Telemetry } from "./observability/index.js";
27
31
  import { runSelfImprove } from "./selfimprove/index.js";
28
32
  import { RollingSummarizer } from "./engine/rolling-summary.js";
@@ -211,36 +215,98 @@ function makeAskTool(handler) {
211
215
  safe: false,
212
216
  description: "Ask the owner a single, clarifying multiple-choice question when the task is genuinely ambiguous " +
213
217
  "and a wrong assumption would waste real work. Blocks until they choose, then returns the chosen " +
214
- "option. Use SPARINGLY — prefer a sensible default and proceeding; never ask what you can determine " +
215
- "from the code or the request. Provide 2-4 concrete, mutually-exclusive options — the owner ALWAYS " +
216
- "also gets a free-text 'type your own' choice, so list the likely paths, don't try to enumerate every one.",
218
+ "option(s). Use SPARINGLY — prefer a sensible default and proceeding; never ask what you can determine " +
219
+ "from the code or the request. Provide 2-4 concrete options — the owner ALWAYS also gets a free-text " +
220
+ "'type your own' choice, so list the likely paths, don't try to enumerate every one. By default the " +
221
+ "owner picks exactly ONE option; set multiSelect:true when the options are not mutually exclusive and " +
222
+ "the owner may pick several (they toggle each with Space and confirm the set) — the reply then lists " +
223
+ "every option they chose.",
217
224
  parameters: {
218
225
  type: "object",
219
226
  properties: {
220
227
  question: { type: "string", description: "The clarifying question, one sentence." },
221
228
  options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices." },
229
+ multiSelect: { type: "boolean", description: "Allow the owner to select more than one option (default false = pick exactly one)." },
222
230
  },
223
231
  required: ["question", "options"],
224
232
  },
225
233
  run: async (args) => {
226
234
  const question = String(args.question ?? "").trim();
227
235
  const options = Array.isArray(args.options) ? args.options.map((o) => String(o)).filter(Boolean) : [];
236
+ const multiSelect = args.multiSelect === true || args.allowMultiple === true;
228
237
  if (!question)
229
238
  return "error: ask_user needs a question";
230
239
  if (options.length < 2)
231
240
  return "error: ask_user needs at least 2 options";
232
- const answer = await handler(question, options.slice(0, 4));
241
+ const answer = await handler(question, options.slice(0, 4), multiSelect);
233
242
  return `The user replied: ${answer}`;
234
243
  },
235
244
  };
236
245
  }
246
+ // self_status — grounded self-knowledge (2026-10-19). A model asked about its own budgets/state invents
247
+ // an answer ("context near the compaction threshold" while the real meter read 4% — seen live, twice).
248
+ // This read-only tool returns the ACTUAL numbers the engine runs on, and the persona/system prompt can
249
+ // steer "questions about your own state" to it. Facts only — no prose for the model to reinterpret.
250
+ function makeSelfStatusTool(facts) {
251
+ return {
252
+ name: "self_status",
253
+ safe: true,
254
+ description: "Your OWN live runtime facts: active model + route, context % used, session token total, the " +
255
+ "max-output-tokens cap, thinking mode, permission mode, turn count. Call it when the user asks about " +
256
+ "your model, context budget, or runtime state, or before you state one of those numbers — it is exact " +
257
+ "where your own introspection is not. It returns the same facts for the whole turn, so call it at most " +
258
+ "once per turn, and never call it to decide what to do next — that is not what it is for.",
259
+ parameters: { type: "object", properties: {} },
260
+ run: async () => JSON.stringify(facts()),
261
+ };
262
+ }
263
+ // The `skill_activate` / `skill_deactivate` pair — unlike skill_fetch (skill text returned as tool-result
264
+ // DATA), activation injects the skill's instructions into the system prompt as a privileged behavioral
265
+ // directive for every subsequent turn, until deactivated or replaced. The fetch itself reuses the registry's
266
+ // skill_fetch (profile skills first, then hub), so activation accepts any slug skill_fetch does.
267
+ function makeSkillActivateTool(activate) {
268
+ return {
269
+ name: "skill_activate",
270
+ safe: false,
271
+ description: "Activate a skill as a system-prompt-level behavioral directive. Unlike skill_fetch (which returns " +
272
+ "skill text as data), this injects the skill's instructions directly into the system prompt so they " +
273
+ "guide your behavior for the remainder of the session (or until deactivated). Use this when you need " +
274
+ "to FOLLOW a skill's instructions, not just read them. Only one skill can be active at a time — " +
275
+ "activating a new one replaces the previous.",
276
+ parameters: {
277
+ type: "object",
278
+ properties: {
279
+ name: { type: "string", description: "The skill slug (same as skill_fetch's slug param)." },
280
+ },
281
+ required: ["name"],
282
+ },
283
+ run: async (args) => {
284
+ const name = String(args.name ?? "").trim();
285
+ if (!name)
286
+ return "error: skill_activate needs a skill name";
287
+ return activate(name);
288
+ },
289
+ };
290
+ }
291
+ function makeSkillDeactivateTool(deactivate) {
292
+ return {
293
+ name: "skill_deactivate",
294
+ safe: true,
295
+ description: "Remove the active skill from the system prompt. No-op if no skill is active.",
296
+ parameters: { type: "object", properties: {} },
297
+ run: async () => deactivate(),
298
+ };
299
+ }
237
300
  const SUMMARY_MAX_TOKENS = 1800; // room for Aurora's reasoning AND the 9-section contract before content lands
301
+ const SKILL_CAP = 4000; // max chars injected from an active skill — a huge skill must not crowd working memory
238
302
  export class Session {
239
303
  convo = new Conversation();
240
304
  inner; // was readonly — /model rebuilds it for a "single" profile switch
241
305
  router; // rebuilt alongside inner (setModel)
242
306
  registry; // /model's choices — built-ins + any settings.models
243
307
  moaConfig;
308
+ fastStartConfig;
309
+ fastStartEnabled;
244
310
  modelId = DEFAULT_MODEL_ID; // active /model selection
245
311
  executor;
246
312
  shellKey; // this session's persistent-shell key (see disposeShell)
@@ -253,6 +319,9 @@ export class Session {
253
319
  telemetry;
254
320
  eventSink;
255
321
  eventActor;
322
+ /** Owner seat? The implicit local owner is admin (no actor, or tier "admin"); a narrowed-tier seat is not.
323
+ * Gates owner-only model profiles in the picker (modelRegistry) and resolution (setModel). */
324
+ isOwner;
256
325
  sessionId;
257
326
  mcpSchemas = []; // merged in after first-turn discovery (empty until then)
258
327
  deferred = null; // HV3-04: set when the MCP surface crosses the threshold
@@ -261,6 +330,10 @@ export class Session {
261
330
  maxTokens;
262
331
  maxTurnTokens;
263
332
  maxTurnWallClockMs;
333
+ loopGuard;
334
+ hooks;
335
+ cwd;
336
+ unattended;
264
337
  maxRounds;
265
338
  maxRoundsHard;
266
339
  compactionThreshold;
@@ -281,6 +354,8 @@ export class Session {
281
354
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
282
355
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
283
356
  recalled = false;
357
+ activeSkillBlock = ""; // capped skill instructions injected into the system prompt
358
+ activeSkillName = ""; // name of the active skill (for status display)
284
359
  // Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
285
360
  // maintains a structured session-memory/summary.md during the session. When compact() fires,
286
361
  // it loads the pre-written summary — /compact went from up to 2 minutes to instant.
@@ -295,30 +370,63 @@ export class Session {
295
370
  // state dir, so the FIRST deep session after a restart already sizes correctly instead of running
296
371
  // on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
297
372
  globalTokenMeter.setPersistence(operatorPath("token-calibration.json"));
298
- // Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
299
- // handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
300
- // are built from the same map, so the tool is advertised iff it's runnable.
301
- let reg = registry;
302
- if (cfg.spawnAgent || cfg.askUser || cfg.messageAgent || cfg.agentStatus || cfg.stopAgent) {
303
- reg = new Map(registry);
304
- if (cfg.spawnAgent)
305
- reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
306
- if (cfg.messageAgent)
307
- reg.set("message_agent", makeMessageTool(cfg.messageAgent));
308
- if (cfg.agentStatus)
309
- reg.set("agent_status", makeStatusTool(cfg.agentStatus));
310
- if (cfg.stopAgent)
311
- reg.set("stop_agent", makeStopTool(cfg.stopAgent));
312
- if (cfg.askUser)
313
- reg.set("ask_user", makeAskTool(cfg.askUser));
314
- }
373
+ // Per-session tool registry: the base set, plus session-scoped tools (skill_activate/skill_deactivate
374
+ // are always available since they mutate THIS session's system prompt; spawn_agent/message_agent/
375
+ // ask_user only when the shell provides delegate handlers). Both the executor (dispatch) and
376
+ // localSchemas (what the model sees) are built from the same map, so a tool is advertised iff runnable.
377
+ const reg = new Map(registry);
378
+ reg.set("skill_activate", makeSkillActivateTool(async (name) => {
379
+ const fetchTool = registry.get("skill_fetch");
380
+ if (!fetchTool)
381
+ return "error: skill system not available";
382
+ const content = await fetchTool.run({ slug: name });
383
+ if (content.startsWith("error:"))
384
+ return content;
385
+ this.activateSkill(name, content);
386
+ return `skill '${name}' activated — its instructions are now injected into the system prompt. Deactivate with skill_deactivate.`;
387
+ }));
388
+ reg.set("skill_deactivate", makeSkillDeactivateTool(() => {
389
+ const was = this.activeSkillName;
390
+ this.deactivateSkill();
391
+ return was ? `skill '${was}' deactivated` : "no skill was active";
392
+ }));
393
+ // Flag-gated cloud-agent tools (config/features.ts `cloudAgents`): absent from the base registry, merged in
394
+ // here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
395
+ const cloudTools = cloudAgentToolsFor({ features: cfg.features });
396
+ if (cfg.spawnAgent)
397
+ reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
398
+ if (cfg.messageAgent)
399
+ reg.set("message_agent", makeMessageTool(cfg.messageAgent));
400
+ if (cfg.agentStatus)
401
+ reg.set("agent_status", makeStatusTool(cfg.agentStatus));
402
+ if (cfg.stopAgent)
403
+ reg.set("stop_agent", makeStopTool(cfg.stopAgent));
404
+ if (cfg.askUser)
405
+ reg.set("ask_user", makeAskTool(cfg.askUser));
406
+ reg.set("self_status", makeSelfStatusTool(() => ({
407
+ model: this.currentModel(),
408
+ route: this.currentRoute(),
409
+ ctxPct: this.ctxPct(),
410
+ sessionTokens: this.sessionTokens(),
411
+ maxOutputTokens: this.maxTokens,
412
+ thinkMode: this.thinkMode,
413
+ permissionMode: this.currentPermissionMode(),
414
+ planMode: this.planMode,
415
+ turns: this.turnCount(),
416
+ background: this.background,
417
+ })));
418
+ for (const t of cloudTools)
419
+ reg.set(t.name, t);
315
420
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
316
421
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
317
422
  this.localSchemas = toSchemas(reg);
318
423
  this.inner = cfg.router ?? new AuroraRouter();
319
424
  this.router = engineRouter(this.inner);
320
425
  this.registry = modelRegistry(cfg.models);
426
+ this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
321
427
  this.moaConfig = cfg.moa;
428
+ this.fastStartConfig = cfg.fastStart;
429
+ this.fastStartEnabled = isFeatureEnabled("fastStart", { features: cfg.features }) && !!cfg.fastStart;
322
430
  // Apply the persisted /model choice, unless a router was explicitly injected (tests / bg agents
323
431
  // pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it.
324
432
  if (!cfg.router && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
@@ -329,6 +437,10 @@ export class Session {
329
437
  this.maxTokens = cfg.maxTokens ?? 32768; // == settings DEFAULTS.maxTokens (session-defaults.test.mts locks the pair); ACP/headless callers that omit cfg used to silently get a tight 2048 cap. clampMaxTokens still trims to the live window.
330
438
  this.maxTurnTokens = cfg.maxTurnTokens;
331
439
  this.maxTurnWallClockMs = cfg.maxTurnWallClockMs;
440
+ this.loopGuard = cfg.loopGuard;
441
+ this.hooks = cfg.hooks;
442
+ this.cwd = cfg.cwd;
443
+ this.unattended = cfg.unattended === true;
332
444
  this.maxRounds = cfg.maxRounds;
333
445
  this.maxRoundsHard = cfg.maxRoundsHard;
334
446
  this.compactionThreshold = cfg.compactionThreshold;
@@ -361,12 +473,15 @@ export class Session {
361
473
  });
362
474
  }
363
475
  }
364
- /** The effective system prompt: the base persona plus any memory recalled this session. Injected as
365
- * ONE system prompt — never a second system message, which 400s llama.cpp's chat template. */
476
+ /** The effective system prompt: the base persona plus any memory recalled this session, plus any
477
+ * active skill. Injected as ONE system prompt — never a second system message, which 400s llama.cpp's
478
+ * chat template. */
366
479
  sys() {
367
- const base = this.recallBlock
480
+ let base = this.recallBlock
368
481
  ? (this.systemPrompt ? `${this.systemPrompt}\n\n${this.recallBlock}` : this.recallBlock)
369
482
  : this.systemPrompt;
483
+ if (this.activeSkillBlock)
484
+ base = (base ?? "") + this.activeSkillBlock;
370
485
  if (!this.planMode)
371
486
  return base;
372
487
  // Plan mode: the model researches read-only and proposes a plan; the read-only enforcement is in
@@ -417,7 +532,8 @@ export class Session {
417
532
  : this.policy;
418
533
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
419
534
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
420
- return this.deferred ? withDeferred(base, this.deferred) : base;
535
+ const hooked = withHooks(base, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
536
+ return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
421
537
  }
422
538
  /** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
423
539
  setPlanMode(on) {
@@ -450,6 +566,23 @@ export class Session {
450
566
  currentThinkMode() {
451
567
  return this.thinkMode;
452
568
  }
569
+ /** Activate a skill as a system-prompt-level behavioral directive. The skill's instructions are
570
+ * injected into every subsequent turn's system prompt until deactivated. Capped at SKILL_CAP chars
571
+ * so a huge skill doesn't crowd working memory. */
572
+ activateSkill(name, content) {
573
+ const capped = content.length > SKILL_CAP
574
+ ? content.slice(0, SKILL_CAP) + "\n\n[… skill truncated at " + SKILL_CAP + " chars]"
575
+ : content;
576
+ this.activeSkillBlock = `\n\n## Active skill: ${name}\nFollow these instructions for this task:\n\n${capped}`;
577
+ this.activeSkillName = name;
578
+ }
579
+ deactivateSkill() {
580
+ this.activeSkillBlock = "";
581
+ this.activeSkillName = "";
582
+ }
583
+ currentSkill() {
584
+ return this.activeSkillName || null;
585
+ }
453
586
  /** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
454
587
  health() {
455
588
  return health(this.inner.base);
@@ -587,7 +720,7 @@ export class Session {
587
720
  * overrides passed in at construction. BYO connectors appear ONLY when their vendor key is
588
721
  * connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
589
722
  modelRegistry() {
590
- return visibleModels(this.registry, hasByoToken);
723
+ return visibleModels(this.registry, hasByoToken, this.isOwner);
591
724
  }
592
725
  /** The active /model selection (id), for the status line + persistence. */
593
726
  currentModel() {
@@ -599,17 +732,33 @@ export class Session {
599
732
  * error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
600
733
  * with no settings.moa configured. */
601
734
  setModel(id) {
602
- const { profile, error } = selectModel(this.registry, id, hasByoToken);
735
+ const { profile, error } = selectModel(this.registry, id, hasByoToken, this.isOwner);
603
736
  if (error || !profile)
604
737
  return { ok: false, error };
605
738
  if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
606
739
  return { ok: false, error: `MOA needs a "moa" block (proposers + aggregator) in settings.json — see MOA-DESIGN.md` };
607
740
  }
608
- if (profile.kind === "single" && profile.endpoint) {
741
+ if (profile.kind === "single" && (profile.endpoint || profile.endpoints?.length)) {
609
742
  // BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
610
743
  // selectModel already refused the id if the key is not connected, so resolution can't miss here.
611
744
  const token = profile.byo ? getByoToken(profile.byo) : undefined;
612
- this.inner = new AuroraRouter([{ name: profile.id, base: endpointBase(profile.endpoint), model: profile.model ?? profile.id, ctxLimit: profile.ctx ?? this.inner.ctxLimit(), token, transport: profile.transport }]);
745
+ // A failover `endpoints` list builds one AuroraRouter endpoint per box (same model/alias on each), so
746
+ // the router hops primary->standby on a busy/5xx; a lone `endpoint` is the single-box case. Names carry
747
+ // the host so /route reads which box answered.
748
+ const bases = profile.endpoints?.length ? profile.endpoints : [profile.endpoint];
749
+ // A fleet entry that lists the AXE gateway beside direct LAN legs: authHeaders trusts LAN hosts, so
750
+ // without this the Operator bearer would ride along to the LAN leg. "" is falsy (no Authorization
751
+ // header) yet not nullish, so it also stops authHeaders falling back to the signed-in token.
752
+ const hasGatewayLeg = !profile.byo && bases.some((b) => requiresOperatorToken(b));
753
+ const eps = bases.map((ep, i) => ({
754
+ name: bases.length > 1 ? `${profile.id}@${endpointBase(ep).replace(/^https?:\/\//, "")}` : profile.id,
755
+ base: endpointBase(ep),
756
+ model: profile.endpointModels?.[i] ?? profile.model ?? profile.id,
757
+ ctxLimit: profile.ctx ?? this.inner.ctxLimit(),
758
+ token: token ?? (hasGatewayLeg && !requiresOperatorToken(ep) ? "" : undefined),
759
+ transport: profile.transport,
760
+ }));
761
+ this.inner = new AuroraRouter(eps);
613
762
  this.router = engineRouter(this.inner);
614
763
  }
615
764
  this.modelId = profile.id;
@@ -669,18 +818,42 @@ export class Session {
669
818
  sumModel = big.model ?? big.id;
670
819
  }
671
820
  }
672
- const r = await chat(messages, {
673
- base: sumBase, // small-ctx active model → large default (Aurora) summarizes; else the live endpoint (cache-safe)
674
- model: sumModel,
675
- tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
676
- maxTokens: SUMMARY_MAX_TOKENS,
677
- temperature: 0,
678
- background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
679
- signal: this.ctrl?.signal, // ESC during "compacting" must tear down THIS request too, not just the main
680
- // generation stream — without it a compaction summarize (which can be a large request on a slow/deep
681
- // endpoint) runs to completion after the user already hit esc. Null ctrl (background pass outside a turn)
682
- // → undefined → no abort, which is correct.
683
- });
821
+ // FAILSAFE (2026-10-22 live incident — Σ810k session wedged on "compacting context…" with no way out):
822
+ // the summarize request had only the USER's esc to stop it, so a slow/wedged endpoint on a huge evicted
823
+ // span hung the whole session indefinitely — no throw, nothing for compact()'s catch to catch. Compose
824
+ // an independent wall-clock timeout onto the signal so this network round-trip can NEVER hang forever,
825
+ // same as every other long network call in this engine (KODE_REQUEST_TIMEOUT_MS, KODE_STREAM_IDLE_MS).
826
+ const summaryTimeoutMs = Number(process.env.KODE_COMPACTION_SUMMARY_TIMEOUT_MS) || 120_000;
827
+ const timeoutSignal = AbortSignal.timeout(summaryTimeoutMs);
828
+ const signal = this.ctrl?.signal ? AbortSignal.any([this.ctrl.signal, timeoutSignal]) : timeoutSignal;
829
+ let r;
830
+ try {
831
+ r = await chat(messages, {
832
+ base: sumBase, // small-ctx active model → large default (Aurora) summarizes; else the live endpoint (cache-safe)
833
+ model: sumModel,
834
+ tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
835
+ maxTokens: SUMMARY_MAX_TOKENS,
836
+ temperature: 0,
837
+ background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
838
+ signal, // ESC during "compacting" must tear down THIS request too, not just the main generation stream —
839
+ // without it a compaction summarize (which can be a large request on a slow/deep endpoint) runs to
840
+ // completion after the user already hit esc. Null ctrl (background pass outside a turn) → timeout-only.
841
+ });
842
+ }
843
+ catch (e) {
844
+ // Only our OWN timeout firing (not the user's esc, not a real transport error) gets swallowed here —
845
+ // everything else rethrows unchanged so compact()'s existing catch (skip + caller retries) still applies.
846
+ if (timeoutSignal.aborted && !this.ctrl?.signal?.aborted) {
847
+ // No model response in time. Return a short, HONEST, non-empty placeholder — not a fabricated summary —
848
+ // so compact() actually evicts (an empty summary would hit its own skip-and-preserve guard, which is
849
+ // exactly the infinite-retry trap that wedged live). The deterministic anchor-index + verbatim-tail
850
+ // backstop still rides with this unconditionally (compact() appends it to EVERY summaryMsg), so no
851
+ // identifier is lost even though the model never got to summarize in prose.
852
+ return `[Auto-compaction: the model did not respond within ${Math.round(summaryTimeoutMs / 1000)}s — ` +
853
+ `evicted without a model summary. Key facts below are from the deterministic backstop, not prose.]`;
854
+ }
855
+ throw e;
856
+ }
684
857
  // Return "" on a genuinely empty response so compact()'s empty-summary guard fires and PRESERVES history
685
858
  // rather than replacing it with a useless placeholder — the old "(summary unavailable)" sentinel was
686
859
  // non-empty, so it DEFEATED that guard and could silently destroy the evicted span. A summary is never
@@ -805,6 +978,10 @@ export class Session {
805
978
  disposeShell() {
806
979
  disposeShellSessionKey(this.shellKey);
807
980
  }
981
+ /** ctrl+b: move this session's running shell command to the background. False when none is running. */
982
+ detachShell() {
983
+ return requestShellDetach(this.shellKey);
984
+ }
808
985
  /** Store a durable memory note (for /remember and end-of-session capture). Best-effort. */
809
986
  remember(text, tags) {
810
987
  return this.memory.capture(text, tags);
@@ -821,7 +998,10 @@ export class Session {
821
998
  * an interrupt resolves (interrupted:true), it does not throw — only a real transport error does.
822
999
  * Dispatches to sendMoa when the active /model is "moa"; otherwise runs the normal single-model
823
1000
  * turn against whatever setModel last pointed the router at. */
824
- async send(text, h = {}) {
1001
+ // `turnDirective` is an optional strong, high-priority instruction appended to THIS turn's system prompt
1002
+ // (e.g. the classifier gate's options-vs-act directive). Per-turn + reversible: it touches only this turn,
1003
+ // the same way thinkDirective/budgetDirective fold into sysWithThink.
1004
+ async send(text, h = {}, turnDirective) {
825
1005
  if (this.ctrl)
826
1006
  throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
827
1007
  // Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
@@ -836,7 +1016,9 @@ export class Session {
836
1016
  const active = findModel(this.registry, this.modelId);
837
1017
  if (active?.kind === "orchestrated")
838
1018
  return await this.sendMoa(text, h, active);
839
- return await this.execute(text, h, this.router, this.sysWithThink());
1019
+ const sys = this.sysWithThink();
1020
+ const sysForTurn = turnDirective ? `${sys ?? ""}${turnDirective}` : sys;
1021
+ return await this.sendWithFastStart(text, h, sysForTurn);
840
1022
  }
841
1023
  finally {
842
1024
  this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
@@ -873,6 +1055,70 @@ export class Session {
873
1055
  const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
874
1056
  return this.execute(text, h, aggRouter, aggSys, moa.aggregator.id);
875
1057
  }
1058
+ /** Fire scout (settings.fastStart) with a bounded, independent timeout — never the real turn's own
1059
+ * abort signal, so a user esc during the real turn doesn't need to also race scout's cleanup. Any
1060
+ * failure (timeout, network, unparseable) resolves null: "didn't win," the real turn is untouched. */
1061
+ async fastStart(userInput) {
1062
+ if (!this.fastStartConfig)
1063
+ return null;
1064
+ try {
1065
+ const r = await chat([
1066
+ { role: "system", content: FAST_START_INSTRUCTION },
1067
+ { role: "user", content: userInput },
1068
+ ], {
1069
+ base: endpointBase(this.fastStartConfig.endpoint),
1070
+ model: this.fastStartConfig.model,
1071
+ maxTokens: 400,
1072
+ temperature: 0,
1073
+ signal: AbortSignal.timeout(this.fastStartConfig.timeoutMs ?? 1500),
1074
+ });
1075
+ return parseFastStartReply(pickSummaryContent(r.content, r.reasoningContent));
1076
+ }
1077
+ catch {
1078
+ return null;
1079
+ }
1080
+ }
1081
+ /** Races the configured fast model (settings.fastStart — any OpenAI-compatible small model, freely
1082
+ * swappable; "scout" is just today's default) against the real turn (feature: fastStart, default
1083
+ * OFF — see fast-start.ts). It runs on its OWN endpoint, never the shared Aurora slot, so this is
1084
+ * genuine parallelism, not a sequential gate. If it answers a tool-free request before the real
1085
+ * turn's first round resolves, the real turn's controller is ABORTED mid-flight (execute() already
1086
+ * returns `{interrupted:true}` cleanly on abort — see TurnAbortedError handling below) and its
1087
+ * answer is used instead: a genuine speedup, since the expensive round never ran to completion. If
1088
+ * the real turn resolves first — finished, errored, or genuinely esc'd by the user — the fast
1089
+ * model's result (whenever it lands) is discarded and nothing about today's behavior changes.
1090
+ * `wonByFastStart` is the one bit that tells an interrupted result apart from a real user esc,
1091
+ * which must never be overwritten. */
1092
+ async sendWithFastStart(text, h, sys) {
1093
+ if (!this.fastStartEnabled)
1094
+ return this.execute(text, h, this.router, sys);
1095
+ let wonByFastStart = false;
1096
+ const convoStart = this.convo.all.length;
1097
+ const fastStartPromise = this.fastStart(text).then((r) => {
1098
+ if (r?.kind === "answered" && this.ctrl && !this.ctrl.signal.aborted) {
1099
+ wonByFastStart = true;
1100
+ this.ctrl.abort();
1101
+ }
1102
+ return r;
1103
+ });
1104
+ const turnResult = await this.execute(text, h, this.router, sys);
1105
+ if (turnResult.interrupted && wonByFastStart) {
1106
+ const r = await fastStartPromise; // already settled — it's the thing that just won
1107
+ if (r?.kind === "answered") {
1108
+ // execute()/runTurn may have already pushed a lone user message (no reply) before the abort
1109
+ // landed — truncate back to the pre-turn snapshot and push OUR clean {user, assistant} pair,
1110
+ // rather than trust runTurn's exact abort timing to have left a consistent state.
1111
+ this.convo.replaceAll(this.convo.all.slice(0, convoStart));
1112
+ this.convo.user(text);
1113
+ this.convo.assistant(r.text);
1114
+ h.onRoute?.(this.fastStartConfig?.model ?? "fast-start", this.ctxPct());
1115
+ h.onDelta?.(r.text);
1116
+ this.telemetry.record({ type: "fast_start", answered: true });
1117
+ return { content: r.text, rounds: 0, toolCalls: 0, interrupted: false };
1118
+ }
1119
+ }
1120
+ return turnResult;
1121
+ }
876
1122
  /** Shared turn execution: runs the tool-calling loop (runTurn) against the given router + system
877
1123
  * prompt, streaming via handlers, and records telemetry. Used by both a normal single-model turn
878
1124
  * (send) and a MOA aggregator turn (sendMoa) — the only difference between them is which router
@@ -885,6 +1131,10 @@ export class Session {
885
1131
  const controller = this.ctrl ?? new AbortController();
886
1132
  this.ctrl = controller;
887
1133
  const _t0 = performance.now();
1134
+ // Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
1135
+ // for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
1136
+ // message itself, so everything from here on is this turn's.
1137
+ const convoStart = this.convo.all.length;
888
1138
  try {
889
1139
  const res = await runTurn(text, this.convo, {
890
1140
  router,
@@ -897,6 +1147,8 @@ export class Session {
897
1147
  maxTokens: this.maxTokens,
898
1148
  maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
899
1149
  maxTurnWallClockMs: this.maxTurnWallClockMs, // opt-in per-turn TIME ceiling; the brake on hour-long crawling turns
1150
+ loopGuard: this.loopGuard, // settings.loopGuard thresholds; undefined → engine defaults
1151
+ unattended: this.unattended, // headless runs hard-stop a tool loop by default; interactive sessions only warn
900
1152
  maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
901
1153
  maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
902
1154
  compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
@@ -906,6 +1158,7 @@ export class Session {
906
1158
  signal: controller.signal,
907
1159
  onDelta: h.onDelta,
908
1160
  onReasoning: h.onReasoning,
1161
+ onPromptProgress: h.onPromptProgress,
909
1162
  onTokens: h.onTokens,
910
1163
  onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
911
1164
  onToolStart: h.onToolStart,
@@ -914,6 +1167,13 @@ export class Session {
914
1167
  onAutoContinue: h.onAutoContinue,
915
1168
  onCacheStats: h.onCacheStats,
916
1169
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
1170
+ // Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
1171
+ // local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
1172
+ // still goes to telemetry so dashboards can count incidents without reading content.
1173
+ onTruncationEvidence: (e) => {
1174
+ this.telemetry.record({ type: "self_heal", kind: e.recovered ? "truncation_recovered" : "truncation_dispatched", attempt: 1 });
1175
+ recordTruncation(e);
1176
+ },
917
1177
  // Verify-before-done: enabled unless KODE_VERIFY_GATE=0 (projected from settings.verifyGate). One
918
1178
  // reminder round when a turn changed files but ran no passing check. Every surface routes through
919
1179
  // here, so the gate is uniform across CLI, web/RC, headless, and loop turns.
@@ -968,10 +1228,20 @@ export class Session {
968
1228
  }
969
1229
  // Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
970
1230
  // (best-effort, never blocks). Gated by KODE_SELFIMPROVE (projected from settings.selfImprove).
971
- void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY === "1" }, {
1231
+ // Steps = the messages THIS turn added (user prompt → assistant rounds → tool results). A mid-turn
1232
+ // compaction can splice the array (replaceAll), making the start index stale; if so the slice would be
1233
+ // wrong, so we drop steps in that case and SRFT falls back cleanly rather than masking the wrong rounds.
1234
+ const turnMsgs = this.convo.all.length >= convoStart ? this.convo.all.slice(convoStart) : [];
1235
+ const steps = turnMsgs.length ? turnMsgs.map((m) => ({
1236
+ role: m.role, content: m.content, tool_calls: m.tool_calls, tool_call_id: m.tool_call_id,
1237
+ })) : undefined;
1238
+ // memory sink honors settings.selfImprove.memory (projected to KODE_SELFIMPROVE_MEMORY) and is ON by
1239
+ // default — the proven failure-lesson → .operator/memories.md loop; set the setting / env to "0" to opt out.
1240
+ void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY !== "0" }, {
972
1241
  input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
973
1242
  tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
974
1243
  cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
1244
+ steps,
975
1245
  });
976
1246
  return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
977
1247
  }
@@ -22,11 +22,23 @@ export const CHAUFFEUR_READ_TOOLS = [
22
22
  // Bounded post-condition check (read-only verification, not an input event) — lets the model confirm an
23
23
  // action landed instead of guessing from the next screenshot.
24
24
  "verify_state",
25
+ // Browser READS (web front-end testing/driving — non-mutating inspection, unprompted). get_browser_state
26
+ // = the live page's DOM/a11y as text; get_page_text = its rendered text; find = locate an element by
27
+ // text/role; get_accessibility_tree = the AX tree. gif_creator records a short clip of what just happened
28
+ // for the owner to review (a capture, not an input event). This is Operator's browser surface for FE
29
+ // testing — pair get_browser_state + verify_state around each step (see the fe-testing skill).
30
+ "get_browser_state", "get_page_text", "find", "get_accessibility_tree", "gif_creator",
25
31
  ];
26
32
  export const CHAUFFEUR_ACTION_TOOLS = [
27
33
  "launch_app", "bring_to_front", // window/app management
28
34
  "click", "double_click", "right_click", "type_text", "press_key", "hotkey", // input
29
35
  "scroll", "move_cursor", "drag", "invoke_menu", "set_value", "clipboard_write",
36
+ // Browser ACTIONS (web front-end testing/driving — navigation + input, gated "ask" fg / "deny" bg).
37
+ // browser_prepare opens/attaches a tab; browser_navigate loads a URL; browser_click/type/pointer drive
38
+ // the page; browser_set_input_files uploads; browser_dialog handles a native dialog (never trigger one
39
+ // blindly — it blocks events); browser_download pulls a file.
40
+ "browser_prepare", "browser_navigate", "browser_click", "browser_type", "browser_pointer",
41
+ "browser_set_input_files", "browser_dialog", "browser_download",
30
42
  ];
31
43
  export const CHAUFFEUR_TOOLS = [...CHAUFFEUR_READ_TOOLS, ...CHAUFFEUR_ACTION_TOOLS];
32
44
  // Namespaced names (server:tool) the hub exposes. ACTION names are what cli.tsx forces to "ask" (fg);