@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
package/dist/session.js CHANGED
@@ -6,11 +6,16 @@ import { recordTruncation } from "./observability/blackbox.js";
6
6
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
7
7
  import { scratchDirFor } from "./config/scratch.js";
8
8
  import { homedir } from "node:os";
9
+ import { detectVision, markVisionRejected } from "./engine/native-vision.js";
10
+ import { extractImagePaths } from "./engine/native-vision-node.js";
11
+ import { planFanOut } from "./engine/fanout.js";
12
+ import { withCodeActDelegateSchema } from "./moa/codeact-lane.js";
13
+ import { codeActEnabled } from "./moa/codeact.js";
9
14
  import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
10
15
  import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
11
16
  import { randomUUID } from "node:crypto";
12
17
  import { recordDecodeSample, speedCompactionDue } from "./engine/speed-compaction.js";
13
- import { compact, compactionSplit, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
18
+ import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail } from "./engine/compaction.js";
14
19
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
15
20
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
16
21
  import { engineRouter } from "./engine/router-adapter.js";
@@ -18,20 +23,25 @@ import { appendFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
18
23
  import { dirname } from "node:path";
19
24
  import { operatorPath } from "./config/home.js";
20
25
  import { moaTeam, plannerBrief } from "./engine/moa.js";
26
+ import { WATERFALL_MODEL_ID, WATERFALL_SEATS, waterfallTeam, waterfallTier } from "./engine/waterfall.js";
21
27
  import { routeTurn } from "./classifier/route.js";
22
28
  import { engineNote, isStatusAsk, STATUS_FIRST_NOTE } from "./engine/continuation.js";
23
29
  import { withDelegateDefault } from "./autonomy/delegate.js";
24
30
  import { withDelegateGuard } from "./autonomy/delegate-mode.js";
31
+ import { withPrPreflight, PrTrees } from "./autonomy/pr-preflight.js";
32
+ import { probeIsolation, prGit } from "./autonomy/pr-isolation.js";
33
+ import { AsyncLocalStorage } from "node:async_hooks";
25
34
  import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
26
35
  import { AuroraRouter } from "./router/router.js";
27
36
  import { operatorAgentPersona } from "./config/operator-harness.js";
28
37
  import { progressDeadline, summaryCeilingMs, DeadlineError } from "./engine/progress-deadline.js";
29
- import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
38
+ import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel } from "./router/models.js";
30
39
  import { probeServed, usableCtx } from "./router/discovery.js";
31
40
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
32
41
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
33
42
  import { getByoToken, hasByoToken } from "./auth/byo.js";
34
43
  import { Executor } from "./tools/executor.js";
44
+ import { autoDeliverReport, autoDeliverFailure, wakeRoot } from "./bus/inbox.js";
35
45
  import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
36
46
  import { isFeatureEnabled } from "./config/features.js";
37
47
  import { MemoryStore } from "./memory/index.js";
@@ -46,7 +56,7 @@ import { Telemetry } from "./observability/index.js";
46
56
  import { loopMentorPair, recordMentorPair, recordRecoveryLesson, runSelfImprove } from "./selfimprove/index.js";
47
57
  import { runSelfImproveSync } from "./selfimprove/sync.js";
48
58
  import { isSubagentBrief } from "./selfimprove/lessons.js";
49
- import { RollingSummarizer } from "./engine/rolling-summary.js";
59
+ import { RollingSummarizer, rollingBudget, notePrompt, foldPrompt, foldSplit, foldedNotes, notesOverCap, adoptedNotes, appendNote, takeChunk, uncoveredTokens } from "./engine/rolling-summary.js";
50
60
  import { decisionPointsEnabled } from "./engine/decision-points.js";
51
61
  import { OwnerAct } from "./engine/owner-act.js";
52
62
  import { createSleepScheduler } from "./consolidation/scheduler.js";
@@ -95,17 +105,18 @@ export function renderBudgetBlock(b) {
95
105
  /** A brief shorter than this is not a brief (10/31: a sub-agent was spawned with the objective "agent"). 12 refused a
96
106
  * complete 11-word brief in the e2e ("Create the file …/nova.md containing exactly three lines: red, green, blue"). */
97
107
  const MIN_BRIEF_WORDS = 5;
98
- function makeSpawnTool(handler) {
108
+ /** The PR trees a session's tool calls run under: a sub-agent started inside a call inherits its parent's marks. */
109
+ const PR_TREES = new AsyncLocalStorage();
110
+ export function makeSpawnTool(handler, slots) {
99
111
  return {
100
112
  name: "spawn_agent",
101
113
  safe: false,
102
- description: "Spawn sub-agents: isolated sessions, each with its own shell, on the sub-agent model (the result says which). " +
103
- "One `tasks` entry = one sub-agent; several run in parallel (2 running + 2 queued by default). Make THIS call in " +
114
+ description: "Spawn sub-agents: isolated sessions on the sub-agent model (the result says which). " +
115
+ "One `tasks` entry = one sub-agent; several run in parallel as capacity allows. Make THIS call in " +
104
116
  "the same round you decide to delegate, and in that message tell the owner who you are sending and why (one line " +
105
117
  "per agent). You stay the lead: do what does NOT depend on them; never redo, re-spawn or poll for a step one is " +
106
118
  "working on — each report, and a STUCK notice if one stalls, arrives as a message at the start of a later turn. " +
107
- "On demand: agent_status shows rounds, files and stuck flags; message_agent steers; stop_agent stops one so you can take its " +
108
- "step over (a sub-agent id is not a shell job id).\n" +
119
+ "agent_status, message_agent: via tool_search.\n" +
109
120
  "USE FOR: reasoning-heavy or context-flooding subtasks, independent parallel workstreams (research per area, " +
110
121
  "review per module, search per tree, drafting a file).\n" +
111
122
  "DO NOT USE FOR: a single tool call; mechanical steps; anything that needs the user; edits to the same files " +
@@ -113,7 +124,8 @@ function makeSpawnTool(handler) {
113
124
  "RULES: the sub-agent knows NOTHING of this conversation — brief it as a spec: **Objective** · **Context** " +
114
125
  "(every path, id, fact) · **Deliverable** · **Constraints** · **Done**. A file deliverable needs role code-edit or " +
115
126
  "generic. A report is a SELF-REPORT — open what it produced and check it against Done before you tell the owner. " +
116
- "SINGLE WRITER: keep file edits on one agent. Ask for a CONCISE report (~1-2k tokens) listing the files it wrote.",
127
+ "SINGLE WRITER: keep file edits on one agent. Ask for a CONCISE report (~1-2k tokens) listing the files it wrote. " +
128
+ "You wake when every agent not in `optional` has reported. Give each agent its own slice of a large input.",
117
129
  parameters: {
118
130
  type: "object",
119
131
  properties: {
@@ -123,6 +135,8 @@ function makeSpawnTool(handler) {
123
135
  agent: { type: "string", description: "optional repo-local persona from .operator/agents/ (listed under 'Repo-local harness')" },
124
136
  names: { type: "array", items: { type: "string" }, description: "a short first name for each sub-agent, same order as `tasks` (you choose them, e.g. Nova, Atlas) — the owner sees and steers them by name" },
125
137
  name: { type: "string", description: "the name for a single `task`" },
138
+ optional: { type: "array", items: { type: "string" }, description: "names not waited on (reported missing if late)" },
139
+ deadline_minutes: { type: "number", description: "due time, shown on each lane" },
126
140
  },
127
141
  required: ["tasks"],
128
142
  },
@@ -146,11 +160,25 @@ function makeSpawnTool(handler) {
146
160
  const frame = (task) => !agent ? task : persona
147
161
  ? `You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`
148
162
  : `${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`;
163
+ const optional = new Set(Array.isArray(args.optional) ? args.optional.map((n) => String(n ?? "").trim().toLowerCase()) : []);
164
+ const mins = Number(args.deadline_minutes);
165
+ const opts = (i) => ({
166
+ ...(names[i] && optional.has(names[i].toLowerCase()) ? { optional: true } : {}),
167
+ ...(Number.isFinite(mins) && mins > 0 ? { deadlineMs: Math.round(mins * 60_000) } : {}),
168
+ });
149
169
  if (briefs.length === 1)
150
- return handler(frame(briefs[0]), role, names[0] || undefined);
170
+ return handler(frame(briefs[0]), role, names[0] || undefined, opts(0));
171
+ const free = role === "code-edit" ? undefined : slots?.();
172
+ if (free !== undefined) {
173
+ const { spawn } = planFanOut(briefs.map(() => ({ kind: "read" })), free);
174
+ const go = new Set(spawn);
175
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${go.has(i)
176
+ ? handler(frame(t), role, names[i] || undefined, opts(i))
177
+ : `not spawned: no free lane on the sub-agent route — do this step yourself (${(names[i] || t).slice(0, 60)})`}`).join("\n");
178
+ }
151
179
  // Fan-out: one spawn per brief, in order; the manager queues past its running cap and refuses past the
152
180
  // in-flight cap — each line reports what happened to that brief, so a partial fan-out is never silent.
153
- return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t), role, names[i] || undefined)}`).join("\n");
181
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t), role, names[i] || undefined, opts(i))}`).join("\n");
154
182
  },
155
183
  };
156
184
  }
@@ -211,14 +239,11 @@ function makeStopTool(handler) {
211
239
  return {
212
240
  name: "stop_agent",
213
241
  safe: false,
214
- description: "Stop a background sub-agent when the owner asks to stop, cancel or kill one (or all) — never just " +
215
- "acknowledge it — or when it is STUCK. `id` (or name) stops one; omit it (or \"all\") to stop every " +
216
- "running/queued one. Its PARTIAL findings come back as its report; then do its step yourself or re-brief a fresh " +
217
- "agent, and tell the owner which. Research/search/review/plan agents write no files by design — judge them by " +
218
- "rounds and notes, not files.",
242
+ description: "Stop a sub-agent (id or name; omit for all) when the owner asks (never just acknowledge) or it is stuck; " +
243
+ "PARTIAL findings return.",
219
244
  parameters: {
220
245
  type: "object",
221
- properties: { id: { type: "string", description: "sub-agent id or name; omit or \"all\" for every one" } },
246
+ properties: { id: { type: "string" } },
222
247
  },
223
248
  run: async (args) => {
224
249
  const id = String(args.id ?? "").trim();
@@ -382,13 +407,13 @@ export class Session {
382
407
  probing; // the latest served-window probe; a turn waits for it before checking the floor
383
408
  contextFloor;
384
409
  moaConfig;
385
- onDemand;
386
410
  frontDoor;
387
411
  frontDoorRoute; // the gateway's call on THIS turn (null = no answer; undefined = not asked), read by sendMoa
388
412
  classifier;
389
413
  fastStartConfig;
390
414
  fastStartEnabled;
391
- modelId = DEFAULT_MODEL_ID; // active /model selection
415
+ modelId = CHAIN_MODEL_ID; // active /model selection
416
+ modelNote; // the startup pick was a retired row: one line for the shell (takeModelNote)
392
417
  turnFellBack = false; // this turn's model fallback took over (turnModel): its rounds run on the default row
393
418
  executor;
394
419
  shellKey; // this session's persistent-shell key (see disposeShell)
@@ -398,6 +423,10 @@ export class Session {
398
423
  policy; // rebuilt by setPermissionMode (Shift+Tab mode cycle)
399
424
  permissionCfg = { mode: "bypass" }; // base config; mode is swapped at runtime
400
425
  approve;
426
+ askUser;
427
+ // PR preflight (autonomy/pr-preflight.ts): the PR trees this session marked, shared with the sub-agents it starts.
428
+ prTrees = new PrTrees();
429
+ prShell;
401
430
  telemetry;
402
431
  eventSink;
403
432
  eventActor;
@@ -438,6 +467,8 @@ export class Session {
438
467
  owner;
439
468
  temperature;
440
469
  ctrl = null;
470
+ /** The image files this turn's message carries natively (nativeImagesFor); empty when the model cannot see them. */
471
+ turnImages = [];
441
472
  memory;
442
473
  wantRecall;
443
474
  recallBlock = ""; // memory recalled on the first turn, folded into the system prompt thereafter
@@ -459,10 +490,11 @@ export class Session {
459
490
  activeSkillName = ""; // name of the active skill (for status display)
460
491
  skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
461
492
  referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
462
- // Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
463
- // maintains a structured session-memory/summary.md during the session. When compact() fires,
464
- // it loads the pre-written summary — /compact went from up to 2 minutes to instant.
493
+ // Rolling summarizer (engine/rolling-summary.ts): bounded background passes keep a summary of the conversation so
494
+ // far, so a compaction reads only the tail the summary does not cover yet.
465
495
  rollingSummarizer;
496
+ rollingAbort; // the background pass in flight: the owner's turn, or a compaction, aborts it
497
+ rollingRun;
466
498
  // Sleep-time consolidation scheduler — triggers memory reorganization during idle (Engine doc #1).
467
499
  sleepScheduler = null;
468
500
  constructor(cfg = {}) {
@@ -497,9 +529,9 @@ export class Session {
497
529
  // here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
498
530
  const cloudTools = cloudAgentToolsFor({ features: cfg.features });
499
531
  const mdocTools = mdocToolsFor({ features: cfg.features }); // flag-gated product tools (feature `mdoc`, default OFF)
500
- const craftTools = craftToolsFor({ features: cfg.features }); // flag-gated product tools (feature `craft`, default OFF)
532
+ const craftTools = craftToolsFor({ features: cfg.features }); // artifact library (always) + craft_create (feature `craft`)
501
533
  if (cfg.spawnAgent)
502
- reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
534
+ reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent, cfg.spawnSlots));
503
535
  if (cfg.messageAgent)
504
536
  reg.set("message_agent", makeMessageTool(cfg.messageAgent));
505
537
  if (cfg.agentStatus)
@@ -535,6 +567,12 @@ export class Session {
535
567
  }
536
568
  for (const name of cfg.toolDeny ?? [])
537
569
  reg.delete(name);
570
+ for (const t of cfg.extraTools ?? [])
571
+ reg.set(t.name, t);
572
+ // The MoA CodeAct lane (moa/codeact.ts): only while it is on does delegate_task offer it, so the schema is unchanged off.
573
+ const dt = reg.get("delegate_task");
574
+ if (dt && cfg.moa && codeActEnabled(cfg.moa.codeact))
575
+ reg.set("delegate_task", withCodeActDelegateSchema(dt));
538
576
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
539
577
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
540
578
  this.localSchemas = toSchemas(reg);
@@ -551,7 +589,6 @@ export class Session {
551
589
  this.registry = modelRegistry(cfg.models);
552
590
  this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
553
591
  this.moaConfig = cfg.moa;
554
- this.onDemand = cfg.onDemand;
555
592
  this.frontDoor = cfg.frontDoor;
556
593
  this.classifier = cfg.classifier;
557
594
  this.fastStartConfig = cfg.fastStart;
@@ -559,9 +596,11 @@ export class Session {
559
596
  // Apply the persisted /model choice, unless a router was explicitly injected (tests / bg agents
560
597
  // pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it. The shell's own
561
598
  // chain is injected too, so it opts in: without that every interactive session started on the default model.
562
- if ((!cfg.router || cfg.applyActiveModel) && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
563
- if (!this.setModel(cfg.activeModel).ok)
564
- this.modelId = DEFAULT_MODEL_ID; // unavailable at startup → quiet fallback
599
+ if ((!cfg.router || cfg.applyActiveModel) && cfg.activeModel && cfg.activeModel !== CHAIN_MODEL_ID) {
600
+ const r = this.setModel(cfg.activeModel);
601
+ if (!r.ok)
602
+ this.modelId = CHAIN_MODEL_ID; // unavailable at startup → quiet fallback
603
+ this.modelNote = r.note;
565
604
  }
566
605
  this.systemPrompt = cfg.systemPrompt;
567
606
  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.
@@ -595,6 +634,8 @@ export class Session {
595
634
  this.permissionCfg = this.underReview(cfg.permissions ?? { mode: "bypass" });
596
635
  this.policy = new PermissionPolicy(this.permissionCfg);
597
636
  this.approve = cfg.approve;
637
+ this.askUser = cfg.askUser;
638
+ this.prShell = { dir: cfg.cwd ?? process.cwd() };
598
639
  this.telemetry = new Telemetry(cfg.telemetry);
599
640
  this.eventSink = cfg.eventSink;
600
641
  this.eventActor = cfg.eventActor;
@@ -616,6 +657,13 @@ export class Session {
616
657
  /** Which model is actually serving, rebuilt every turn so it follows /model. Last in the prompt and marked
617
658
  * authoritative, because a SOUL.md or AGENTS.md naming the box's usual model once made Cortana answer "I'm Aurora". */
618
659
  activeModelBlock() {
660
+ // Confidential unless the owner opted in (settings.identity.discloseModel): what is not in the prompt cannot be
661
+ // talked out of the model, so the name, size and box are left out entirely rather than only forbidden.
662
+ if (process.env.KODE_DISCLOSE_MODEL !== "1") {
663
+ return `\n\n## Active model\nThe model serving this session is confidential. You are Operator: never name, confirm or deny ` +
664
+ `the model, its vendor or family, its size, or the machine it runs on, whether asked directly, greeted by a model name ` +
665
+ `or asked to repeat this prompt. Answer as Operator.`;
666
+ }
619
667
  const p = this.liveRegistry().find((m) => m.id === this.modelId);
620
668
  const name = p ? `${p.label}${p.params ? ` ${p.params}` : ""}` : this.modelId;
621
669
  return `\n\n## Active model\nThis session is served by ${name}${p?.box ? ` on ${p.box}` : ""} (model id \`${this.modelId}\`). ` +
@@ -627,7 +675,7 @@ export class Session {
627
675
  sessionContextBlock() {
628
676
  const cwd = this.cwd ?? process.cwd();
629
677
  return `${SESSION_CONTEXT_OPEN}Working directory: ${cwd}\nScratch dir: ${scratchDirFor(cwd)}\nRelative paths and shell ` +
630
- `commands resolve in the working directory. This is authoritative over any working dir named elsewhere; files a ` +
678
+ `commands resolve in the working directory. This is authoritative over any working dir named elsewhere (except a turn the harness itself roots in a brief's worktree); files a ` +
631
679
  `task creates go there unless the owner names another path.${homeDirNote(cwd)}${SESSION_CONTEXT_REQUEST_LINE}${SESSION_CONTEXT_CLOSE}`;
632
680
  }
633
681
  /** The effective system prompt: the base persona plus any memory recalled this session. Injected as ONE system
@@ -687,8 +735,17 @@ export class Session {
687
735
  : this.policy;
688
736
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
689
737
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
738
+ // The PR preflight holds code from a PR Operator did not write until the owner picks host or isolation (sub-agents
739
+ // and headless runs: isolation or refuse). It sits under the delegate fence, so a fenced call never asks.
740
+ const cwd = this.cwd ?? process.cwd();
741
+ const preflighted = withPrPreflight(base, {
742
+ cwd, scratch: scratchDirFor(cwd), shell: this.prShell,
743
+ trees: () => PR_TREES.getStore() ?? this.prTrees, within: (t, fn) => PR_TREES.run(t, fn),
744
+ git: prGit, probe: () => probeIsolation(), ask: this.planMode ? undefined : this.askUser,
745
+ audit: (line) => this.prAudit(line),
746
+ });
690
747
  // Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
691
- const guarded = withDelegateGuard(base, { cwd: this.cwd ?? process.cwd(), exists: existsSync, realpath: (p) => { try {
748
+ const guarded = withDelegateGuard(preflighted, { cwd: this.cwd ?? process.cwd(), exists: existsSync, realpath: (p) => { try {
692
749
  return realpathSync(p);
693
750
  }
694
751
  catch {
@@ -699,6 +756,16 @@ export class Session {
699
756
  return withNativeDeferred(hooked, this.nativeDeferred);
700
757
  return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
701
758
  }
759
+ /** One PR preflight audit line: the event trail (when recorded) and `<operator home>/audit/pr-preflight.jsonl`. */
760
+ prAudit(line) {
761
+ this.eventSink?.emit({ kind: "control", session: this.sessionId ?? "", actor: this.eventActor ?? { tier: "admin", surface: "cli" }, control: { event: "pr_preflight", detail: line } });
762
+ try {
763
+ const file = operatorPath("audit", "pr-preflight.jsonl");
764
+ mkdirSync(dirname(file), { recursive: true });
765
+ appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), session: this.sessionId ?? "", detail: line }) + "\n");
766
+ }
767
+ catch { /* the trail is best-effort; the call's own result says what happened */ }
768
+ }
702
769
  /** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
703
770
  setPlanMode(on) {
704
771
  if (this.planMode === on)
@@ -808,7 +875,7 @@ export class Session {
808
875
  return this.inner.base;
809
876
  if (planner.endpoint)
810
877
  return endpointBase(planner.endpoint);
811
- const row = findModel(this.liveRegistry(), planner.id);
878
+ const row = resolveModel(this.liveRegistry(), planner.id);
812
879
  const ep = row ? profileEndpoint(row) : undefined;
813
880
  return ep ? endpointBase(ep) : this.inner.base;
814
881
  }
@@ -859,7 +926,7 @@ export class Session {
859
926
  if (p?.kind !== "single")
860
927
  return undefined;
861
928
  let base, model;
862
- if (p.id === DEFAULT_MODEL_ID) {
929
+ if (p.id === CHAIN_MODEL_ID) {
863
930
  const r = this.chain ?? this.inner;
864
931
  base = r.base;
865
932
  model = r.model;
@@ -877,7 +944,7 @@ export class Session {
877
944
  }
878
945
  /** What /compact can promise before it runs (TUI A3.5 / A3.6): the request now, and AT MOST what is left after it — the
879
946
  * last two turns verbatim (compactNow's minKeepTurns), the deterministic backstop compact() always appends (anchor
880
- * index, the owner's own words, the pinned skill) and a summary capped at SUMMARY_MAX_TOKENS. An upper bound, never
947
+ * index, the owner's own words, the pinned skill) and a summary capped at the rolling notes' cap. An upper bound, never
881
948
  * progress: fitToWindow may shed more. Null when there is nothing to evict. */
882
949
  compactionEstimate() {
883
950
  const split = compactionSplit(this.convo.all, 2);
@@ -886,7 +953,13 @@ export class Session {
886
953
  const backstop = { role: "user", content: `${renderAnchorIndex(split.evicted)}${verbatimUserTail(split.evicted)}${this.activeSkillBlock ? `\n\n${this.activeSkillBlock}` : ""}` };
887
954
  const sys = this.sys();
888
955
  const kept = [...(sys ? [{ role: "system", content: sys }] : []), backstop, ...split.kept];
889
- return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + SUMMARY_MAX_TOKENS, summaryMax: SUMMARY_MAX_TOKENS };
956
+ // The notes are folded once over their cap, and they can never hold more than was written into them: one fold
957
+ // (SUMMARY_MAX_TOKENS) plus a note per pass, and a background pass reads at least dueTokens. So a short session's
958
+ // bound stays below the session itself instead of jumping to the cap a long one needs.
959
+ const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
960
+ const passes = Math.ceil(globalTokenMeter.estimateRequestFor(this.meterKey(), this.convo.all) / b.dueTokens) + 1;
961
+ const summaryMax = Math.min(b.capTokens, SUMMARY_MAX_TOKENS + b.noteTokens * passes);
962
+ return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + summaryMax, summaryMax };
890
963
  }
891
964
  /** Estimated context usage of the live conversation against the window the engine runs on (the served limit
892
965
  * under the owner's pin), 0-99. Calibrated: the meter's real ratio once observations land; exactly the old
@@ -1014,7 +1087,7 @@ export class Session {
1014
1087
  const opts = {
1015
1088
  ctxWindow: this.effectiveContext(),
1016
1089
  systemPrompt: this.sys(),
1017
- summarize: this.summarize,
1090
+ summarize: this.summarizeEvicted, // the rolling summary for what it covers, a live pass for the rest
1018
1091
  preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
1019
1092
  pinnedContext: this.pinned(), // the active skill and Autonomous mode's rules ride the summary
1020
1093
  minKeepTurns: 2,
@@ -1023,43 +1096,6 @@ export class Session {
1023
1096
  meterKey: this.meterKey(),
1024
1097
  spill: spillToolOutput, // GW-10-COMPLETE: /compact's fitToWindow OFFLOADS (re-readable), never erases
1025
1098
  };
1026
- // Instant compaction: if a rolling summary exists, use it directly instead of calling the model.
1027
- // This is the "bridge until Pillar B ships" — the pre-written summary is loaded instantly,
1028
- // then compact() uses it as the evicted span's replacement.
1029
- const prewritten = this.rollingSummarizer.getSummary();
1030
- if (prewritten) {
1031
- const starts = turnStarts(this.convo.all);
1032
- const minKeep = opts.minKeepTurns ?? 4;
1033
- // GW-27-U2 STALENESS GATE (the silent-loss fix). The pre-written summary is trustworthy ONLY
1034
- // if (a) it isn't dirty (no threshold crossing since the fire) AND (b) its watermark covers
1035
- // every turn the cut would evict — i.e. coverage >= starts.length - minKeep. Turns added
1036
- // AFTER the fire but below the rolling threshold were previously dropped with zero trace:
1037
- // quiet turns (< the 5000-token cadence) accumulate uncovered, and /compact swapped in a
1038
- // summary that predates them. Uncovered => fall through to the live path (compact() skips on
1039
- // summarize failure rather than destroying the span, and fitToWindow OFFLOADS via GW-10 spill
1040
- // — lossless in both branches).
1041
- const covered = this.rollingSummarizer.getCoveredThrough();
1042
- const trustworthy = !this.rollingSummarizer.isStale() && starts.length > minKeep && covered >= starts.length - minKeep;
1043
- if (trustworthy) {
1044
- const cutIndex = starts[starts.length - minKeep];
1045
- const evicted = this.convo.all.slice(0, cutIndex);
1046
- // H2 (audit-engine §2): the instant path used to insert the raw pre-written blob — skipping
1047
- // the GW-31/N1 backstop the auto-favored path EXISTS to guarantee. Coverage proved it knows
1048
- // about these turns; now it also carries their anchors and the user's own words. All
1049
- // render-side and mechanical — the "instant" property is untouched (microseconds, zero calls).
1050
- const summaryMsg = {
1051
- role: "user",
1052
- content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.pinnedContext ? `\n\n${opts.pinnedContext}` : ""}`,
1053
- };
1054
- const kept = this.convo.all.slice(cutIndex);
1055
- this.convo.replaceAll([summaryMsg, ...kept]);
1056
- applyAnchorVerification(summaryMsg, evicted, this.convo.all);
1057
- const before = this.requestEstimate();
1058
- this.convo.replaceAll(fitToWindow(this.convo.all, opts));
1059
- return Math.max(0, before - this.requestEstimate());
1060
- }
1061
- }
1062
- // Fallback: normal compaction path (summarize + evict)
1063
1099
  const before = this.requestEstimate();
1064
1100
  this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
1065
1101
  return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
@@ -1183,12 +1219,18 @@ export class Session {
1183
1219
  moaTeam() {
1184
1220
  return moaTeam(this.moaConfig);
1185
1221
  }
1222
+ /** The line a retired or replaced-provider startup pick earned (a persisted activeModel), once. */
1223
+ takeModelNote() {
1224
+ const n = this.modelNote;
1225
+ this.modelNote = undefined;
1226
+ return n;
1227
+ }
1186
1228
  setModel(id) {
1187
- const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1229
+ const { profile, error, retired, replaced } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1188
1230
  if (error || !profile)
1189
1231
  return { ok: false, error };
1190
1232
  this.decodeSamples = []; // another model's rate says nothing about this one
1191
- if (profile.kind === "orchestrated") {
1233
+ if (profile.kind === "orchestrated" && profile.id !== WATERFALL_MODEL_ID) { // Waterfall builds its teams from gateway seats
1192
1234
  const team = moaTeam(this.moaConfig);
1193
1235
  if (!team)
1194
1236
  return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
@@ -1198,10 +1240,9 @@ export class Session {
1198
1240
  return { ok: false, error: `MoA planner: ${p.error ?? `"${team.planner.id}" has no endpoint of its own`}` };
1199
1241
  }
1200
1242
  }
1201
- if (profile.kind === "single" && profile.id === DEFAULT_MODEL_ID && this.chain) {
1202
- // The default local model IS the shell's endpoint chain (the gateway's published port + its failover
1203
- // legs). Restore it rather than rebuilding from the profile's static :8097 endpoint, which no longer
1204
- // answers on a gateway box — otherwise /model away-and-back lands on a dead port.
1243
+ if (profile.kind === "single" && profile.id === CHAIN_MODEL_ID && this.chain) {
1244
+ // The chain row IS the shell's endpoint chain (the router's `main`, then the fleet and cloud legs). Restore it
1245
+ // rather than rebuilding from the row's own two legs, so /model away-and-back keeps every failover leg.
1205
1246
  this.inner = this.chain;
1206
1247
  this.router = this.wrap(this.inner);
1207
1248
  }
@@ -1214,15 +1255,16 @@ export class Session {
1214
1255
  // before the first turn on it, so compaction sizes to it and the floor can be checked.
1215
1256
  if (profile.kind === "single" && !profile.byo)
1216
1257
  void this.probeServedContext().catch(() => undefined);
1217
- return { ok: true };
1258
+ const note = replaced ?? (retired ? `${retired.label} (${retired.id}) is retired — ${profile.label} answers instead; /model picks another` : undefined);
1259
+ return { ok: true, ...(note ? { note } : {}) };
1218
1260
  }
1219
1261
  /** Re-point this session at a freshly built endpoint chain. The interactive shell constructs the Session at
1220
1262
  * first render, BEFORE the boot lever has resolved the gateway's dynamic port (server.json) — the chain must
1221
1263
  * follow that resolution or health() and every turn probe "" (unset — auto-discover). Same swap setModel does. A
1222
- * non-default /model pick keeps owning routing; the chain then waits for `/model operator-1m`. */
1264
+ * non-default /model pick keeps owning routing; the chain then waits for `/model main`. */
1223
1265
  useRouter(router) {
1224
1266
  this.chain = router;
1225
- if (this.modelId !== DEFAULT_MODEL_ID)
1267
+ if (this.modelId !== CHAIN_MODEL_ID)
1226
1268
  return;
1227
1269
  this.inner = router;
1228
1270
  this.router = this.wrap(this.inner);
@@ -1273,13 +1315,13 @@ export class Session {
1273
1315
  // A small-context active model (e.g. a self-hosted 8K Venice) can't summarize its OWN overflow — the
1274
1316
  // [system + tools + span] summarize request itself exceeds the window, so compaction frees nothing and
1275
1317
  // the session walls ("compaction can't free enough space"). Route the summarizer to the large-context
1276
- // DEFAULT (Aurora/operator-1m, 300K) instead: it loses the live-turn's prefix-cache reuse (Aurora's
1318
+ // chain row (the router's `main`, 262K) instead: it loses the live-turn's prefix-cache reuse (its
1277
1319
  // prefix differs from the small model's), but that trade is what lets a small model compact continuously
1278
1320
  // and run autonomously for hours. A large active model keeps the cache-safe same-endpoint path.
1279
1321
  let sumBase = this.lastBase ?? this.inner.base;
1280
1322
  let sumModel = this.lastModel ?? this.inner.model;
1281
1323
  if (this.inner.ctxLimit() < LEAN_HARNESS_CTX) {
1282
- const big = findModel(this.registry, DEFAULT_MODEL_ID);
1324
+ const big = findModel(this.registry, CHAIN_MODEL_ID);
1283
1325
  if (big?.endpoint) {
1284
1326
  sumBase = endpointBase(big.endpoint);
1285
1327
  sumModel = big.model ?? big.id;
@@ -1375,25 +1417,111 @@ export class Session {
1375
1417
  }
1376
1418
  catch { /* handoff is a durability convenience, never a hard dependency */ }
1377
1419
  }
1378
- /** Fire a rolling summary in the background (instant compaction bridge). Uses the SAME cache-safe
1379
- * prefix as compact() — identical system prompt, tools, and endpoint — so the llama.cpp slot hits
1380
- * f_sim=1.0 on the summarize request. Runs only when the latest round settled (no pending tool
1381
- * calls) to avoid stealing the slot from interactive turns. */
1382
- async fireRollingSummary() {
1383
- // Guard: don't fire during a tool-calling round (the model needs the slot)
1384
- // This is a best-effort background pass — never blocks the turn.
1385
- try {
1386
- // Summarize the entire current conversation (same span compact() would evict)
1387
- const summaryText = await this.summarize(this.convo.all);
1388
- if (summaryText) {
1389
- this.rollingSummarizer.setSummary(summaryText);
1390
- // GW-27-U2: record coverage — the summary spans the conversation AS OF NOW, so /compact
1391
- // may trust it only while the eviction cut stays inside this watermark.
1392
- this.rollingSummarizer.markSummaryFired(turnStarts(this.convo.all).length);
1420
+ /** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
1421
+ * server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1422
+ * compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
1423
+ * folds their older half into one summary instead. False when nothing advanced: nothing left, an empty answer, or
1424
+ * the conversation was replaced meanwhile. */
1425
+ async rollingPass(upTo, signal, live) {
1426
+ const all = this.convo.all;
1427
+ const rs = this.rollingSummarizer;
1428
+ const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1429
+ // An earlier compaction's note IS the notes so far: adopted as written, never digested again by a note pass.
1430
+ const adopted = rs.coveredCount(all) ? undefined : adoptedNotes(all[0]?.content);
1431
+ if (adopted !== undefined)
1432
+ rs.advance(adopted, all, 1);
1433
+ const covered = rs.coveredCount(all);
1434
+ const notes = rs.getSummary();
1435
+ const fold = notesOverCap(notes, b);
1436
+ if (!fold && covered >= upTo)
1437
+ return false;
1438
+ const chunk = takeChunk(all, covered, upTo, b, live ? b.liveTokens : b.chunkTokens);
1439
+ const [old, recent] = fold ? foldSplit(notes) : ["", ""];
1440
+ const read = fold ? Math.ceil(old.length / 4) : chunk.tokens;
1441
+ const noteTokens = Math.min(b.summaryTokens, b.noteTokens * Math.ceil(chunk.tokens / b.chunkTokens)); // a live tail of several chunks gets their notes' room
1442
+ const h = live ? this.turnHandlers : undefined;
1443
+ h?.onCompactionCoverage?.({ covered: covered ? globalTokenMeter.estimateRequestFor(this.meterKey(), all.slice(0, covered)) : 0, reading: read });
1444
+ const base = this.lastBase ?? this.inner.base;
1445
+ const model = this.lastModel ?? this.inner.model;
1446
+ const leg = [...this.inner.list(), ...(this.chain?.list() ?? [])].find((e) => e.base === base && e.model === model);
1447
+ let wrote = 0;
1448
+ const written = h?.onCompactionWrite ? () => h.onCompactionWrite?.(++wrote) : undefined;
1449
+ const t0 = performance.now();
1450
+ const r = await chat([{ role: "user", content: fold ? foldPrompt(old, b) : notePrompt(chunk.text, b, noteTokens) }], {
1451
+ base, model, token: leg?.token, loopbackAuth: leg?.loopbackAuth, transport: leg?.transport, chatPath: leg?.chatPath,
1452
+ ...this.affinity({ base, model, transport: leg?.transport }), // the live turn's slot or session: the span is cached there
1453
+ maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : fold ? SUMMARY_MAX_TOKENS : noteTokens,
1454
+ temperature: 0,
1455
+ background: !live || this.background, // the endpoint gate: a background pass never takes a slot an interactive request waits for
1456
+ owner: "compaction",
1457
+ onPromptProgress: h?.onPromptProgress,
1458
+ onDelta: written,
1459
+ onReasoning: written,
1460
+ signal,
1461
+ });
1462
+ const text = pickSummaryContent(r.content, r.reasoningContent);
1463
+ if (!text || signal?.aborted || this.convo.all !== all)
1464
+ return false;
1465
+ if (fold)
1466
+ rs.advance(foldedNotes(old, text, recent, b), all, covered);
1467
+ else
1468
+ rs.advance(appendNote(notes, text), all, chunk.end);
1469
+ this.telemetry.record({ type: "rolling_summary", live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
1470
+ return true;
1471
+ }
1472
+ /** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
1473
+ * the background, one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1474
+ * waits for it; what a pass had not finished is picked up after the next turn, or read live at compaction. Never
1475
+ * for a sub-agent: its session ends with its turn, and nothing would abort its pass when the owner's turn wants
1476
+ * the model. */
1477
+ fireRollingSummary() {
1478
+ if (this.rollingRun || this.background || process.env.KODE_ROLLING_SUMMARY === "0")
1479
+ return;
1480
+ const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1481
+ const due = () => {
1482
+ const all = this.convo.all;
1483
+ return uncoveredTokens(all, this.rollingSummarizer.coveredCount(all), all.length, b) >= b.dueTokens || notesOverCap(this.rollingSummarizer.getSummary(), b);
1484
+ };
1485
+ if (!due())
1486
+ return;
1487
+ const abort = (this.rollingAbort = new AbortController());
1488
+ this.rollingRun = (async () => {
1489
+ try {
1490
+ while (!abort.signal.aborted && due() && (await this.rollingPass(this.convo.all.length, abort.signal, false))) { /* next chunk */ }
1491
+ }
1492
+ catch { /* best-effort: an aborted or failed pass is retried after the next turn */ }
1493
+ finally {
1494
+ this.rollingRun = undefined;
1393
1495
  }
1496
+ })();
1497
+ }
1498
+ /** What compaction calls for the span it evicts: the rolling notes for everything they cover, and a live pass over
1499
+ * the uncovered tail only (then a fold, if the notes are over their cap) — so the wait is set by the tail and the
1500
+ * cap, not by the conversation. A span that is not the head of the live conversation (or KODE_ROLLING_SUMMARY=0)
1501
+ * takes the one-request summarizer. An empty answer returns "" (compact() then keeps the history); the passes
1502
+ * already done are kept, so a retry resumes where this stopped. */
1503
+ summarizeEvicted = async (span) => {
1504
+ const all = this.convo.all;
1505
+ const n = span.length;
1506
+ if (process.env.KODE_ROLLING_SUMMARY === "0" || !n || n > all.length || span[0] !== all[0] || span[n - 1] !== all[n - 1])
1507
+ return this.summarize(span);
1508
+ this.rollingAbort?.abort();
1509
+ await this.rollingRun;
1510
+ const rs = this.rollingSummarizer;
1511
+ const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1512
+ const pending = () => rs.coveredCount(all) < n || notesOverCap(rs.getSummary(), b);
1513
+ if (!pending()) {
1514
+ this.turnHandlers?.onCompactionCoverage?.({ covered: globalTokenMeter.estimateRequestFor(this.meterKey(), span), reading: 0 });
1515
+ this.telemetry.record({ type: "rolling_summary", live: true, fold: false, read: 0, covered: n, ms: 0 });
1394
1516
  }
1395
- catch { /* best-effort — rolling summary never blocks a turn */ }
1396
- }
1517
+ while (pending())
1518
+ if (!(await this.rollingPass(n, this.ctrl?.signal, true)))
1519
+ return "";
1520
+ const summary = rs.getSummary();
1521
+ rs.clear(); // compact() puts the notes in the conversation's first message: the next pass adopts them from there
1522
+ this.persistHandoff(summary, n);
1523
+ return summary;
1524
+ };
1397
1525
  /** First-turn setup, once only. (1) Recall memory relevant to what the user is asking (plus recent
1398
1526
  * notes) and fold it into the system prompt for the session. (2) Discover fleet MCP tools and merge
1399
1527
  * their schemas + dispatch. Both are best-effort — a failure degrades (local-only), never blocks. */
@@ -1534,17 +1662,12 @@ export class Session {
1534
1662
  // called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
1535
1663
  // would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
1536
1664
  this.ctrl = new AbortController();
1665
+ this.rollingAbort?.abort(); // the owner's turn takes the model: a background summary pass gives it up at once
1537
1666
  try {
1538
- const front = await this.viaFrontDoor(text, h); // before onDemand: a message the fast model answers never loads Aurora
1667
+ this.turnImages = await this.nativeImagesFor(text);
1668
+ const front = await this.viaFrontDoor(text, h);
1539
1669
  if (front)
1540
1670
  return front;
1541
- if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
1542
- const fresh = await this.onDemand(this.ctrl.signal);
1543
- if (fresh)
1544
- this.useRouter(fresh);
1545
- if (this.ctrl.signal.aborted)
1546
- return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1547
- }
1548
1671
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1549
1672
  if (this.ctrl.signal.aborted)
1550
1673
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
@@ -1554,7 +1677,7 @@ export class Session {
1554
1677
  this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
1555
1678
  const active = findModel(this.liveRegistry(), this.modelId);
1556
1679
  if (active?.kind === "orchestrated")
1557
- return await this.sendMoa(text, h, active);
1680
+ return await (active.id === WATERFALL_MODEL_ID ? this.sendWaterfall(text, h) : this.sendMoa(text, h, active));
1558
1681
  const refusal = await this.contextFloorRefusal();
1559
1682
  if (refusal)
1560
1683
  return { content: refusal, display: refusal, rounds: 0, toolCalls: 0, interrupted: false, stopKind: "context_floor" };
@@ -1564,10 +1687,40 @@ export class Session {
1564
1687
  }
1565
1688
  finally {
1566
1689
  this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
1690
+ this.turnImages = [];
1567
1691
  this.wakeTurn = false;
1568
1692
  this.turnThinkOff = false;
1569
1693
  }
1570
1694
  }
1695
+ /** The image files in the owner's message that go to the model as pictures, not through image_analyze: only when the
1696
+ * model answering can see (the profile says so, else its server does; an unknown is tried, and a server that turns
1697
+ * the image down puts it back on the tool). Never for a sub-agent, a wake turn or a remote url. */
1698
+ async nativeImagesFor(text) {
1699
+ if (this.background || this.wakeTurn)
1700
+ return [];
1701
+ const paths = extractImagePaths(text);
1702
+ if (!paths.length)
1703
+ return [];
1704
+ const p = findModel(this.liveRegistry(), this.modelId);
1705
+ if (p?.kind !== "single" || p.transport === "anthropic" || p.vision === false)
1706
+ return [];
1707
+ if (p.vision === true || p.byo)
1708
+ return paths;
1709
+ let base, model;
1710
+ if (p.id === CHAIN_MODEL_ID) {
1711
+ const r = this.chain ?? this.inner;
1712
+ base = r.base;
1713
+ model = r.model;
1714
+ }
1715
+ else {
1716
+ const ep = p.endpoints?.[0] ?? p.endpoint;
1717
+ if (!ep)
1718
+ return [];
1719
+ base = endpointBase(ep);
1720
+ model = p.endpointModels?.[0] ?? p.model ?? p.id;
1721
+ }
1722
+ return (await detectVision(base, model)) === "no" ? [] : paths;
1723
+ }
1571
1724
  /** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
1572
1725
  * for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
1573
1726
  * the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
@@ -1602,13 +1755,13 @@ export class Session {
1602
1755
  this.frontDoorRoute = undefined;
1603
1756
  const fd = this.frontDoor;
1604
1757
  const active = findModel(this.liveRegistry(), this.modelId);
1605
- if (!fd || (this.modelId !== DEFAULT_MODEL_ID && active?.kind !== "orchestrated"))
1606
- return null;
1758
+ if (!fd || (this.modelId !== CHAIN_MODEL_ID && active?.kind !== "orchestrated") || this.turnImages.length)
1759
+ return null; // the fast model sees no pictures
1607
1760
  const t0 = Date.now();
1608
1761
  // The gateway's front door is configured on the default model's route; `name` is the model as the owner knows it
1609
1762
  // (activeModelBlock), so a MOA session is MOA to the fast model too.
1610
1763
  const name = active ? `${active.label}${active.params ? ` ${active.params}` : ""}` : this.modelId;
1611
- const d = await askFrontDoor(fd, { model: DEFAULT_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
1764
+ const d = await askFrontDoor(fd, { model: CHAIN_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
1612
1765
  if (this.ctrl?.signal.aborted)
1613
1766
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1614
1767
  this.frontDoorRoute = d?.route ?? null;
@@ -1634,18 +1787,39 @@ export class Session {
1634
1787
  // specialist with the full prompt.
1635
1788
  const fd = this.frontDoorRoute;
1636
1789
  const route = fd === undefined && this.classifier && this.classifier.mode !== "off" ? await routeTurn(text, this.classifier.endpoint) : null;
1637
- const specialist = route?.route === "direct" ? this.liveRegistry().find((m) => m.id === team.specialist && m.kind === "single") : undefined;
1790
+ const specialistRow = route?.route === "direct" ? resolveModel(this.liveRegistry(), team.specialist) : undefined;
1791
+ const specialist = specialistRow?.kind === "single" ? specialistRow : undefined;
1638
1792
  this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route || fd === "work" ? "planned" : "unrouted", pDirect: route?.pDirect });
1639
1793
  if (specialist)
1640
1794
  return this.execute(text, h, this.wrap(this.routerForProfile(specialist)), this.sysWithThink(), specialist.id);
1641
- const plannerRow = team.planner.endpoint ? undefined : findModel(this.liveRegistry(), team.planner.id);
1795
+ return this.runPlanned(text, h, team);
1796
+ }
1797
+ /** A Waterfall turn (engine/waterfall.ts): pick the tier, then run its team. operator = the one-model seat; dexter and
1798
+ * moa = the shared planner path, with the external lane in the brief. The tier shows on the route line. */
1799
+ async sendWaterfall(text, h) {
1800
+ const route = this.classifier && this.classifier.mode !== "off" ? await routeTurn(text, this.classifier.endpoint) : null;
1801
+ const { tier, by } = waterfallTier(text, route);
1802
+ this.telemetry.record({ type: "waterfall", tier, by, ...(route ? { pDirect: route.pDirect } : {}) });
1803
+ const team = waterfallTeam(tier, { codeact: codeActEnabled(this.moaConfig?.codeact) });
1804
+ if (!team) {
1805
+ const row = resolveModel(this.liveRegistry(), WATERFALL_SEATS.operator.executor);
1806
+ if (row?.kind !== "single")
1807
+ throw new Error(`Waterfall seat "${WATERFALL_SEATS.operator.executor}" is not a /model id with an endpoint`);
1808
+ return this.execute(text, h, this.wrap(this.routerForProfile(row)), this.sysWithThink(), `waterfall:${tier}`);
1809
+ }
1810
+ return this.runPlanned(text, h, team, `waterfall:${tier}`);
1811
+ }
1812
+ /** The planner path both MoA and Waterfall share: the planner runs the turn with its brief, delegate_task defaults to
1813
+ * the specialist. */
1814
+ async runPlanned(text, h, team, label) {
1815
+ const plannerRow = team.planner.endpoint ? undefined : resolveModel(this.liveRegistry(), team.planner.id);
1642
1816
  if (!team.planner.endpoint && plannerRow?.kind !== "single")
1643
1817
  throw new Error(`MoA planner "${team.planner.id}" is not a /model id with an endpoint`);
1644
1818
  const plannerRouter = this.wrap(plannerRow?.kind === "single" ? this.routerForProfile(plannerRow) : new AuroraRouter([
1645
1819
  { name: team.planner.id, base: endpointBase(team.planner.endpoint), model: team.planner.model ?? team.planner.id, ctxLimit: this.inner.ctxLimit() },
1646
1820
  ]));
1647
1821
  const sys = `${this.sysWithThink() ?? ""}\n\n## MOA: planner\n${plannerBrief(team)}`;
1648
- return withDelegateDefault(team.specialist, () => this.execute(text, h, plannerRouter, sys, team.planner.id));
1822
+ return withDelegateDefault(team.specialist, () => this.execute(text, h, plannerRouter, sys, label ?? team.planner.id));
1649
1823
  }
1650
1824
  /** Fire scout (settings.fastStart) with a bounded, independent timeout — never the real turn's own
1651
1825
  * abort signal, so a user esc during the real turn doesn't need to also race scout's cleanup. Any
@@ -1717,6 +1891,8 @@ export class Session {
1717
1891
  * and system prompt they pass in. */
1718
1892
  async execute(text, h, router, sys, routeLabel) {
1719
1893
  this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
1894
+ // A wake turn whose brief named a contained worktree runs there for this turn only (Codex --cd / Claude Code worktree isolation).
1895
+ this.executor.setTurnRoot(wakeRoot(text) ?? undefined);
1720
1896
  this.lastSys = sys; // remember the EXACT system prompt this turn sends, so cache-safe compaction reuses it verbatim
1721
1897
  // Reuse the controller send() already armed (so esc during maybeRecall / MOA fan-out is live); create one
1722
1898
  // only if execute() is somehow entered without send() arming it (defensive — every caller goes via send).
@@ -1724,6 +1900,7 @@ export class Session {
1724
1900
  this.ctrl = controller;
1725
1901
  this.turnHandlers = h; // a mid-turn compaction's summarizer reports its read through this turn's handlers
1726
1902
  const _t0 = performance.now();
1903
+ const wallT0 = Date.now(); // wall clock, for the bus: did this turn reply to its sender (autoDeliverReport)
1727
1904
  // Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
1728
1905
  // for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
1729
1906
  // message itself, so everything from here on is this turn's.
@@ -1743,12 +1920,14 @@ export class Session {
1743
1920
  try {
1744
1921
  const res = await runTurn(text, this.convo, {
1745
1922
  ownerText,
1923
+ images: this.turnImages,
1924
+ onImagesRejected: (ep) => markVisionRejected(ep.base, ep.model),
1746
1925
  router,
1747
1926
  tools: this.liveTools, // read through at each call: a mid-turn /mode or Shift+Tab applies from the next tool call
1748
1927
  toolSchemas: this.allSchemas(),
1749
1928
  spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
1750
1929
  systemPrompt: sys,
1751
- summarize: this.summarize,
1930
+ summarize: this.summarizeEvicted,
1752
1931
  request: task, // the asker's words: the loop reset quotes them and types the task by them, never the carried notes
1753
1932
  onTurnState: (read) => { turn.read = read; }, // an interrupted turn is recorded from it (interruptedRecord)
1754
1933
  pinnedContext: () => this.pinned(), // a summary is a rewrite anyway: the skill and Autonomous mode's rules ride it
@@ -1877,16 +2056,9 @@ export class Session {
1877
2056
  this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
1878
2057
  if (!this.turnFellBack)
1879
2058
  this.decodeSamples = recordDecodeSample(this.decodeSamples, { tokens: res.tokens, genMs: res.genMs, ctxTokens: this.requestEstimate() });
1880
- // Instant compaction: feed token counts to the rolling summarizer. When a round ends without
1881
- // tool calls and we've crossed the threshold, the summarizer triggers a background summary.
1882
- const shouldSummarize = this.rollingSummarizer.feedRound(res.tokens ?? 0, res.toolCalls);
1883
2059
  // Feed the sleep scheduler's step counter (triggers consolidation after N steps)
1884
2060
  this.sleepScheduler?.recordStep();
1885
- if (shouldSummarize) {
1886
- // Fire the rolling summary in the background — the session's summarizer reuses the same
1887
- // cache-safe prefix as compact() so it hits KV cache. Runs only when the round settled.
1888
- this.fireRollingSummary();
1889
- }
2061
+ this.fireRollingSummary(); // the turn settled: summarize what it added, in the background, if enough is uncovered
1890
2062
  // Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
1891
2063
  // (best-effort, never blocks). Gated by KODE_SELFIMPROVE (projected from settings.selfImprove).
1892
2064
  // Steps = the messages THIS turn added (user prompt → assistant rounds → tool results). A mid-turn
@@ -1896,12 +2068,22 @@ export class Session {
1896
2068
  turn.recorded = true;
1897
2069
  const record = {
1898
2070
  input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
1899
- tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
2071
+ tokens: res.tokens, stopReason: res.stopReason, stopKind: res.stopKind, model: this.currentModel(),
1900
2072
  cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
1901
2073
  steps: this.turnSteps(convoStart, text), task, loop: res.loop, lessonTs: turn.lessonTs,
1902
2074
  };
1903
2075
  const cfg = this.selfImproveCfg();
1904
2076
  this.learn(() => runSelfImprove(cfg, record)); // after any lesson a loop recovery is still writing
2077
+ // A woken turn owes its sender a report; when it ended without one, the harness delivers the final answer
2078
+ // (Claude Code returns a sub-agent's final message to its parent; `codex exec -o` writes it for the caller).
2079
+ try {
2080
+ const to = autoDeliverReport(ownerText, res.content ?? "", wallT0);
2081
+ if (to.length) {
2082
+ this.telemetry.record({ type: "auto_report", recipients: to.length });
2083
+ h.onAutoReport?.(to);
2084
+ }
2085
+ }
2086
+ catch { /* best-effort: a bus write failure never fails the turn */ }
1905
2087
  return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
1906
2088
  }
1907
2089
  catch (e) {
@@ -1911,8 +2093,16 @@ export class Session {
1911
2093
  const cfg = this.selfImproveCfg();
1912
2094
  if (r)
1913
2095
  this.learn(() => runSelfImprove(cfg, r));
2096
+ try {
2097
+ autoDeliverFailure(ownerText, "interrupted");
2098
+ }
2099
+ catch { /* best-effort */ }
1914
2100
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1915
2101
  }
2102
+ try {
2103
+ autoDeliverFailure(ownerText, "failed");
2104
+ }
2105
+ catch { /* best-effort */ }
1916
2106
  this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
1917
2107
  throw e;
1918
2108
  }
@@ -1921,6 +2111,7 @@ export class Session {
1921
2111
  if (this.inflight === turn)
1922
2112
  this.inflight = undefined;
1923
2113
  this.turnHandlers = undefined;
2114
+ this.executor.setTurnRoot(undefined);
1924
2115
  }
1925
2116
  }
1926
2117
  /** The self-improvement sinks: the flywheel (settings.selfImprove → KODE_SELFIMPROVE) and the memory sink