@0perator/operator 0.1.285 → 0.1.321

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 (118) 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 +308 -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 +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
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
@@ -776,6 +949,28 @@ export class Session {
776
949
  await this.discoverMcp();
777
950
  return this.mcpToolCount();
778
951
  }
952
+ /** `/mcp reload`: rebuild the hub from disk (base + `$KODE_MCP_EXTRA` merge) and rediscover tools
953
+ * without restarting Operator — live-drive after `/mcp add powertools …`. */
954
+ async reloadMcp() {
955
+ this.wantMcp = true;
956
+ try {
957
+ if (this.hub) {
958
+ this.hub.shutdown();
959
+ this.hub = undefined;
960
+ }
961
+ this.hub = await McpHub.fromConfig();
962
+ if (!this.hub)
963
+ return 0;
964
+ this.hub.spillSink = spillToolOutput;
965
+ await this.hub.discover({ force: true });
966
+ this.tools = this.buildTools();
967
+ this.mcpSchemas = this.hub.schemas();
968
+ this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
969
+ this.tools = this.buildTools();
970
+ }
971
+ catch { /* stay local-only */ }
972
+ return this.mcpToolCount();
973
+ }
779
974
  /** Local registry schemas plus any fleet MCP tool schemas discovered this session.
780
975
  * Under HV3-04 deferral: locals + only the MCP tools described this session + the meta trio. */
781
976
  allSchemas() {
@@ -805,6 +1000,10 @@ export class Session {
805
1000
  disposeShell() {
806
1001
  disposeShellSessionKey(this.shellKey);
807
1002
  }
1003
+ /** ctrl+b: move this session's running shell command to the background. False when none is running. */
1004
+ detachShell() {
1005
+ return requestShellDetach(this.shellKey);
1006
+ }
808
1007
  /** Store a durable memory note (for /remember and end-of-session capture). Best-effort. */
809
1008
  remember(text, tags) {
810
1009
  return this.memory.capture(text, tags);
@@ -821,7 +1020,10 @@ export class Session {
821
1020
  * an interrupt resolves (interrupted:true), it does not throw — only a real transport error does.
822
1021
  * Dispatches to sendMoa when the active /model is "moa"; otherwise runs the normal single-model
823
1022
  * turn against whatever setModel last pointed the router at. */
824
- async send(text, h = {}) {
1023
+ // `turnDirective` is an optional strong, high-priority instruction appended to THIS turn's system prompt
1024
+ // (e.g. the classifier gate's options-vs-act directive). Per-turn + reversible: it touches only this turn,
1025
+ // the same way thinkDirective/budgetDirective fold into sysWithThink.
1026
+ async send(text, h = {}, turnDirective) {
825
1027
  if (this.ctrl)
826
1028
  throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
827
1029
  // Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
@@ -836,7 +1038,9 @@ export class Session {
836
1038
  const active = findModel(this.registry, this.modelId);
837
1039
  if (active?.kind === "orchestrated")
838
1040
  return await this.sendMoa(text, h, active);
839
- return await this.execute(text, h, this.router, this.sysWithThink());
1041
+ const sys = this.sysWithThink();
1042
+ const sysForTurn = turnDirective ? `${sys ?? ""}${turnDirective}` : sys;
1043
+ return await this.sendWithFastStart(text, h, sysForTurn);
840
1044
  }
841
1045
  finally {
842
1046
  this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
@@ -873,6 +1077,70 @@ export class Session {
873
1077
  const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
874
1078
  return this.execute(text, h, aggRouter, aggSys, moa.aggregator.id);
875
1079
  }
1080
+ /** Fire scout (settings.fastStart) with a bounded, independent timeout — never the real turn's own
1081
+ * abort signal, so a user esc during the real turn doesn't need to also race scout's cleanup. Any
1082
+ * failure (timeout, network, unparseable) resolves null: "didn't win," the real turn is untouched. */
1083
+ async fastStart(userInput) {
1084
+ if (!this.fastStartConfig)
1085
+ return null;
1086
+ try {
1087
+ const r = await chat([
1088
+ { role: "system", content: FAST_START_INSTRUCTION },
1089
+ { role: "user", content: userInput },
1090
+ ], {
1091
+ base: endpointBase(this.fastStartConfig.endpoint),
1092
+ model: this.fastStartConfig.model,
1093
+ maxTokens: 400,
1094
+ temperature: 0,
1095
+ signal: AbortSignal.timeout(this.fastStartConfig.timeoutMs ?? 1500),
1096
+ });
1097
+ return parseFastStartReply(pickSummaryContent(r.content, r.reasoningContent));
1098
+ }
1099
+ catch {
1100
+ return null;
1101
+ }
1102
+ }
1103
+ /** Races the configured fast model (settings.fastStart — any OpenAI-compatible small model, freely
1104
+ * swappable; "scout" is just today's default) against the real turn (feature: fastStart, default
1105
+ * OFF — see fast-start.ts). It runs on its OWN endpoint, never the shared Aurora slot, so this is
1106
+ * genuine parallelism, not a sequential gate. If it answers a tool-free request before the real
1107
+ * turn's first round resolves, the real turn's controller is ABORTED mid-flight (execute() already
1108
+ * returns `{interrupted:true}` cleanly on abort — see TurnAbortedError handling below) and its
1109
+ * answer is used instead: a genuine speedup, since the expensive round never ran to completion. If
1110
+ * the real turn resolves first — finished, errored, or genuinely esc'd by the user — the fast
1111
+ * model's result (whenever it lands) is discarded and nothing about today's behavior changes.
1112
+ * `wonByFastStart` is the one bit that tells an interrupted result apart from a real user esc,
1113
+ * which must never be overwritten. */
1114
+ async sendWithFastStart(text, h, sys) {
1115
+ if (!this.fastStartEnabled)
1116
+ return this.execute(text, h, this.router, sys);
1117
+ let wonByFastStart = false;
1118
+ const convoStart = this.convo.all.length;
1119
+ const fastStartPromise = this.fastStart(text).then((r) => {
1120
+ if (r?.kind === "answered" && this.ctrl && !this.ctrl.signal.aborted) {
1121
+ wonByFastStart = true;
1122
+ this.ctrl.abort();
1123
+ }
1124
+ return r;
1125
+ });
1126
+ const turnResult = await this.execute(text, h, this.router, sys);
1127
+ if (turnResult.interrupted && wonByFastStart) {
1128
+ const r = await fastStartPromise; // already settled — it's the thing that just won
1129
+ if (r?.kind === "answered") {
1130
+ // execute()/runTurn may have already pushed a lone user message (no reply) before the abort
1131
+ // landed — truncate back to the pre-turn snapshot and push OUR clean {user, assistant} pair,
1132
+ // rather than trust runTurn's exact abort timing to have left a consistent state.
1133
+ this.convo.replaceAll(this.convo.all.slice(0, convoStart));
1134
+ this.convo.user(text);
1135
+ this.convo.assistant(r.text);
1136
+ h.onRoute?.(this.fastStartConfig?.model ?? "fast-start", this.ctxPct());
1137
+ h.onDelta?.(r.text);
1138
+ this.telemetry.record({ type: "fast_start", answered: true });
1139
+ return { content: r.text, rounds: 0, toolCalls: 0, interrupted: false };
1140
+ }
1141
+ }
1142
+ return turnResult;
1143
+ }
876
1144
  /** Shared turn execution: runs the tool-calling loop (runTurn) against the given router + system
877
1145
  * prompt, streaming via handlers, and records telemetry. Used by both a normal single-model turn
878
1146
  * (send) and a MOA aggregator turn (sendMoa) — the only difference between them is which router
@@ -885,6 +1153,10 @@ export class Session {
885
1153
  const controller = this.ctrl ?? new AbortController();
886
1154
  this.ctrl = controller;
887
1155
  const _t0 = performance.now();
1156
+ // Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
1157
+ // for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
1158
+ // message itself, so everything from here on is this turn's.
1159
+ const convoStart = this.convo.all.length;
888
1160
  try {
889
1161
  const res = await runTurn(text, this.convo, {
890
1162
  router,
@@ -897,6 +1169,8 @@ export class Session {
897
1169
  maxTokens: this.maxTokens,
898
1170
  maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
899
1171
  maxTurnWallClockMs: this.maxTurnWallClockMs, // opt-in per-turn TIME ceiling; the brake on hour-long crawling turns
1172
+ loopGuard: this.loopGuard, // settings.loopGuard thresholds; undefined → engine defaults
1173
+ unattended: this.unattended, // headless runs hard-stop a tool loop by default; interactive sessions only warn
900
1174
  maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
901
1175
  maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
902
1176
  compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
@@ -906,6 +1180,7 @@ export class Session {
906
1180
  signal: controller.signal,
907
1181
  onDelta: h.onDelta,
908
1182
  onReasoning: h.onReasoning,
1183
+ onPromptProgress: h.onPromptProgress,
909
1184
  onTokens: h.onTokens,
910
1185
  onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
911
1186
  onToolStart: h.onToolStart,
@@ -914,6 +1189,13 @@ export class Session {
914
1189
  onAutoContinue: h.onAutoContinue,
915
1190
  onCacheStats: h.onCacheStats,
916
1191
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
1192
+ // Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
1193
+ // local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
1194
+ // still goes to telemetry so dashboards can count incidents without reading content.
1195
+ onTruncationEvidence: (e) => {
1196
+ this.telemetry.record({ type: "self_heal", kind: e.recovered ? "truncation_recovered" : "truncation_dispatched", attempt: 1 });
1197
+ recordTruncation(e);
1198
+ },
917
1199
  // Verify-before-done: enabled unless KODE_VERIFY_GATE=0 (projected from settings.verifyGate). One
918
1200
  // reminder round when a turn changed files but ran no passing check. Every surface routes through
919
1201
  // here, so the gate is uniform across CLI, web/RC, headless, and loop turns.
@@ -968,10 +1250,20 @@ export class Session {
968
1250
  }
969
1251
  // Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
970
1252
  // (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" }, {
1253
+ // Steps = the messages THIS turn added (user prompt → assistant rounds → tool results). A mid-turn
1254
+ // compaction can splice the array (replaceAll), making the start index stale; if so the slice would be
1255
+ // wrong, so we drop steps in that case and SRFT falls back cleanly rather than masking the wrong rounds.
1256
+ const turnMsgs = this.convo.all.length >= convoStart ? this.convo.all.slice(convoStart) : [];
1257
+ const steps = turnMsgs.length ? turnMsgs.map((m) => ({
1258
+ role: m.role, content: m.content, tool_calls: m.tool_calls, tool_call_id: m.tool_call_id,
1259
+ })) : undefined;
1260
+ // memory sink honors settings.selfImprove.memory (projected to KODE_SELFIMPROVE_MEMORY) and is ON by
1261
+ // default — the proven failure-lesson → .operator/memories.md loop; set the setting / env to "0" to opt out.
1262
+ void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY !== "0" }, {
972
1263
  input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
973
1264
  tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
974
1265
  cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
1266
+ steps,
975
1267
  });
976
1268
  return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
977
1269
  }
@@ -2,7 +2,7 @@
2
2
  // ships in the repo (operator-home/skills-catalogue/), activating a skill = copying its tree into
3
3
  // $KODE_HOME/skills/<category>/<name>/ where the operator-home-v2 phase-3 local-skills index picks it
4
4
  // up immediately (skill_list/skill_fetch unchanged). Nothing in the catalogue is ever injected on its
5
- // own — that gating is the whole point (Hermes ships these as "not activated by default").
5
+ // own — that gating is the whole point (shipped as "not activated by default").
6
6
  // Node builtins stay behind lazy variable-specifier imports (purity contract, session-rewind idiom).
7
7
  import { operatorPath } from "../config/home.js";
8
8
  async function nodeImport(id) {