@0perator/operator 0.1.352 → 0.1.353

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 (90) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1066 -175
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +43 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +350 -30
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/tools/deferred.js +28 -18
  46. package/dist/tools/executor.js +7 -3
  47. package/dist/tools/registry.js +34 -4
  48. package/dist/ui/ActivitySpinner.js +21 -12
  49. package/dist/ui/App.js +107 -30
  50. package/dist/ui/ApprovalPrompt.js +5 -3
  51. package/dist/ui/ArtifactPicker.js +3 -3
  52. package/dist/ui/BgPanel.js +105 -5
  53. package/dist/ui/Composer.js +85 -9
  54. package/dist/ui/PlanPane.js +72 -8
  55. package/dist/ui/QuestionPrompt.js +6 -4
  56. package/dist/ui/SecretPrompt.js +8 -3
  57. package/dist/ui/SessionPicker.js +2 -2
  58. package/dist/ui/SkillFinder.js +153 -0
  59. package/dist/ui/StatusRule.js +5 -2
  60. package/dist/ui/SummaryCard.js +3 -1
  61. package/dist/ui/ThinkingSpinner.js +11 -2
  62. package/dist/ui/ToolBatch.js +11 -2
  63. package/dist/ui/ToolStep.js +36 -13
  64. package/dist/ui/Transcript.js +13 -2
  65. package/dist/ui/actNow.js +61 -0
  66. package/dist/ui/batchLine.js +165 -0
  67. package/dist/ui/conversations.js +154 -0
  68. package/dist/ui/decodeHealth.js +77 -0
  69. package/dist/ui/expand.js +17 -0
  70. package/dist/ui/fit.js +40 -0
  71. package/dist/ui/fitTail.js +14 -0
  72. package/dist/ui/fold.js +149 -0
  73. package/dist/ui/format.js +46 -2
  74. package/dist/ui/liveTools.js +163 -13
  75. package/dist/ui/modelPicker.js +78 -6
  76. package/dist/ui/nextStep.js +103 -0
  77. package/dist/ui/pending.js +57 -0
  78. package/dist/ui/phase.js +105 -0
  79. package/dist/ui/planExit.js +0 -5
  80. package/dist/ui/progressbar.js +4 -26
  81. package/dist/ui/readForecast.js +44 -0
  82. package/dist/ui/readProgress.js +119 -0
  83. package/dist/ui/reportLine.js +62 -0
  84. package/dist/ui/slashCommands.js +1 -1
  85. package/dist/ui/theme.js +1 -0
  86. package/dist/ui/turnFlow.js +72 -0
  87. package/dist/ui/turnLedger.js +121 -0
  88. package/dist/ui/turnScope.js +11 -0
  89. package/dist/util/slash.js +18 -0
  90. package/package.json +1 -1
@@ -153,13 +153,18 @@ async function* anthropicDeltas(messages, o) {
153
153
  // user-facing string (branding-boundary: no KODE_* name in prose a user reads).
154
154
  if (!key)
155
155
  throw new Error("anthropic: no API key — store it: operator auth byo-key anthropic");
156
- await acquireEndpoint(o.base, o.background === true, o.model);
156
+ const owner = o.owner ?? (o.background ? "sub-agent" : "main");
157
+ await acquireEndpoint(o.base, o.background === true, o.model, { owner, onQueued: o.onQueued });
157
158
  let released = false;
158
159
  const release = () => { if (!released) {
159
160
  released = true;
160
- releaseEndpoint(o.base, o.model);
161
+ releaseEndpoint(o.base, o.model, owner);
161
162
  } };
162
163
  try {
164
+ try {
165
+ o.onSent?.();
166
+ }
167
+ catch { /* a UI callback never breaks the request */ }
163
168
  const res = await fetchMessages(o, key, anthropicRequestBody(messages, o, true));
164
169
  if (!res.ok || !res.body) {
165
170
  let detail = "";
@@ -315,6 +320,12 @@ export async function anthropicChat(messages, o) {
315
320
  if (d.tool.partial)
316
321
  e.args += d.tool.partial;
317
322
  tools.set(idx, e);
323
+ if (e.name) {
324
+ try {
325
+ o.onToolDraft?.({ index: idx, id: e.id ?? `call_${idx}`, name: e.name, args: e.args });
326
+ }
327
+ catch { /* display only */ }
328
+ }
318
329
  }
319
330
  // Loop breaker: only scan a tool-free reply (a tool-calling turn is legitimately terminal), amortized.
320
331
  if (tools.size === 0) {
@@ -13,7 +13,7 @@ export function endpointSlots(_base) {
13
13
  function endpointGate(base) {
14
14
  let g = _endpointGates.get(base);
15
15
  if (!g) {
16
- g = { inUse: 0, queue: [] };
16
+ g = { inUse: 0, holders: [], queue: [] };
17
17
  _endpointGates.set(base, g);
18
18
  }
19
19
  return g;
@@ -21,43 +21,56 @@ function endpointGate(base) {
21
21
  /** Reserve a request slot on `base`. Interactive (main-turn) requests are served ahead of background
22
22
  * (sub-agent) ones: an interactive caller inserts before the first queued background caller, and a
23
23
  * background caller never claims a free slot while any interactive caller is waiting. Resolves when the
24
- * slot is granted; the caller MUST releaseEndpoint(base) exactly once when its request+stream is done. */
25
- export function acquireEndpoint(base, background, model) {
24
+ * slot is granted; the caller MUST releaseEndpoint(base) exactly once when its request+stream is done.
25
+ * `owner` labels the slot while held ("main", a sub-agent's name, "compaction"), and `onQueued` fires synchronously
26
+ * — only when the request really waits — with how many are ahead and who holds the slot (the live phase line's
27
+ * "waiting for cortana · Iris holds its slot"). Labels never change the order. */
28
+ export function acquireEndpoint(base, background, model, opts = {}) {
26
29
  base = gateKey(base, model);
27
30
  const g = endpointGate(base);
31
+ const owner = opts.owner ?? (background ? "sub-agent" : "main");
28
32
  const interactiveWaiting = g.queue.some((w) => !w.background);
29
33
  if (g.inUse < endpointSlots(base) && !(background && interactiveWaiting)) {
30
34
  g.inUse++;
35
+ g.holders.push(owner);
31
36
  return Promise.resolve();
32
37
  }
33
38
  return new Promise((resolve) => {
34
- const entry = { background, resolve };
35
- if (background) {
36
- g.queue.push(entry);
37
- return;
38
- } // background always at the back
39
- const i = g.queue.findIndex((w) => w.background); // interactive: ahead of the first background, behind other interactives (FIFO)
40
- if (i === -1)
41
- g.queue.push(entry);
42
- else
43
- g.queue.splice(i, 0, entry);
39
+ const entry = { background, owner, resolve };
40
+ if (background)
41
+ g.queue.push(entry); // background always at the back
42
+ else {
43
+ const i = g.queue.findIndex((w) => w.background); // interactive: ahead of the first background, behind other interactives (FIFO)
44
+ if (i === -1)
45
+ g.queue.push(entry);
46
+ else
47
+ g.queue.splice(i, 0, entry);
48
+ }
49
+ try {
50
+ opts.onQueued?.({ ahead: g.queue.indexOf(entry), holder: g.holders[0] });
51
+ }
52
+ catch { /* a UI callback never breaks the gate */ }
44
53
  });
45
54
  }
46
55
  /** Release a slot on `base` and wake the highest-priority waiter (first interactive, else the front). */
47
- export function releaseEndpoint(base, model) {
56
+ export function releaseEndpoint(base, model, owner) {
48
57
  base = gateKey(base, model);
49
58
  const g = endpointGate(base);
50
59
  g.inUse = Math.max(0, g.inUse - 1);
60
+ const h = owner === undefined ? 0 : g.holders.indexOf(owner);
61
+ if (g.holders.length)
62
+ g.holders.splice(h < 0 ? 0 : h, 1);
51
63
  if (g.inUse >= endpointSlots(base) || g.queue.length === 0)
52
64
  return;
53
65
  const i = g.queue.findIndex((w) => !w.background);
54
66
  const [next] = g.queue.splice(i === -1 ? 0 : i, 1);
55
67
  g.inUse++;
68
+ g.holders.push(next.owner);
56
69
  next.resolve();
57
70
  }
58
- /** Snapshot of every endpoint gate (for tests + a live status surface). */
71
+ /** Snapshot of every endpoint gate (for tests + a live status surface): who holds each slot, and who waits. */
59
72
  export function endpointGateStatus() {
60
- return [..._endpointGates.entries()].map(([base, g]) => ({ base, inUse: g.inUse, queued: g.queue.length, slots: endpointSlots(base) }));
73
+ return [..._endpointGates.entries()].map(([base, g]) => ({ base, inUse: g.inUse, queued: g.queue.length, slots: endpointSlots(base), holders: [...g.holders], waiting: g.queue.map((w) => w.owner) }));
61
74
  }
62
75
  // A remote engine (api.axe.onl) fronts the model with gateway auth; a local :8097 does not. Only a
63
76
  // non-loopback base needs (and should ever receive) the operator bearer, so a token is never sent to
@@ -373,13 +386,18 @@ async function* streamDeltas(messages, o) {
373
386
  // time it streams — releasing on completion, early break (loop breaker / first-answer), error, or abort.
374
387
  // Interactive turns preempt the queue ahead of background sub-agents (see acquireEndpoint). A single call is
375
388
  // never re-entrant, so acquire/release balance exactly once.
376
- await acquireEndpoint(o.base, o.background === true, o.model);
389
+ const owner = o.owner ?? (o.background ? "sub-agent" : "main");
390
+ await acquireEndpoint(o.base, o.background === true, o.model, { owner, onQueued: o.onQueued });
377
391
  let _slotReleased = false;
378
392
  const _releaseSlot = () => { if (!_slotReleased) {
379
393
  _slotReleased = true;
380
- releaseEndpoint(o.base, o.model);
394
+ releaseEndpoint(o.base, o.model, owner);
381
395
  } };
382
396
  try {
397
+ try {
398
+ o.onSent?.();
399
+ }
400
+ catch { /* a UI callback never breaks the request */ }
383
401
  const res = await fetchChat(o, requestBody(messages, o, true));
384
402
  if (!res.ok || !res.body) {
385
403
  let detail = "";
@@ -462,7 +480,7 @@ async function* streamDeltas(messages, o) {
462
480
  if (j.prompt_progress) {
463
481
  const pp = j.prompt_progress;
464
482
  if (Number(pp.total) > 0)
465
- o.onPromptProgress?.({ processed: Number(pp.processed) || 0, total: Number(pp.total), cached: Number(pp.cache) || 0 });
483
+ o.onPromptProgress?.({ processed: Number(pp.processed) || 0, total: Number(pp.total), cached: Number(pp.cache) || 0, ...(typeof pp.time_ms === "number" ? { timeMs: pp.time_ms } : {}) });
466
484
  }
467
485
  if (j.timings || j.usage)
468
486
  o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms, promptTokens: j.timings?.prompt_n ?? j.usage?.prompt_tokens, promptMs: j.timings?.prompt_ms, cacheN: j.timings?.cache_n ?? j.usage?.prompt_tokens_details?.cached_tokens });
@@ -566,6 +584,12 @@ export async function chat(messages, o) {
566
584
  if (tc.function?.arguments)
567
585
  entry.args += tc.function.arguments;
568
586
  acc.set(idx, entry);
587
+ if (entry.name) {
588
+ try {
589
+ o.onToolDraft?.({ index: idx, id: entry.id ?? `call_${idx}`, name: entry.name, args: entry.args });
590
+ }
591
+ catch { /* display only */ }
592
+ }
569
593
  }
570
594
  }
571
595
  // Loop breaker: only scan a tool-free response (a tool-calling turn is legitimately terminal),
@@ -22,6 +22,25 @@
22
22
  // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
23
23
  // failure never strands its dependents — the chain advances regardless.
24
24
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
25
+ /** The report runBatch hands each runOne — and a hand-rolled batch loop builds the same way: `started` fires `onStart`
26
+ * once, `why` holds the refusal. */
27
+ export function callReport(onStart, signal) {
28
+ let began = false;
29
+ const r = {
30
+ started: () => {
31
+ if (began)
32
+ return;
33
+ began = true;
34
+ try {
35
+ onStart?.();
36
+ }
37
+ catch { /* UI never breaks execution */ }
38
+ },
39
+ refused: (why) => { r.why = why; },
40
+ ...(signal ? { signal } : {}),
41
+ };
42
+ return r;
43
+ }
25
44
  export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
26
45
  /** Foreground shells that may run concurrently within one model round (matches Cursor). */
27
46
  const SHELL_EXACT = new Set(["bash", "shell_exec"]);
@@ -174,11 +193,16 @@ export function runBatch(calls, opts) {
174
193
  const ready = Promise.all(gate);
175
194
  const run = (aborted ? Promise.race([ready, aborted]) : ready).then(async () => {
176
195
  let r;
177
- if (signal?.aborted)
196
+ const report = callReport(opts.onStart && (() => opts.onStart(i)), signal);
197
+ if (signal?.aborted) {
178
198
  r = cancelledResult(c.name);
199
+ report.refused("cancelled");
200
+ }
179
201
  else {
202
+ if (!opts.startsBelow)
203
+ report.started();
180
204
  try {
181
- r = await opts.runOne(c);
205
+ r = await opts.runOne(c, report);
182
206
  }
183
207
  catch (e) {
184
208
  r = `error running ${c.name}: ${e?.message ?? String(e)}`;
@@ -186,7 +210,7 @@ export function runBatch(calls, opts) {
186
210
  }
187
211
  results[i] = r;
188
212
  try {
189
- opts.onSettle?.(i, r);
213
+ opts.onSettle?.(i, r, report.why);
190
214
  }
191
215
  catch { /* UI never breaks execution */ }
192
216
  });
@@ -388,14 +388,21 @@ export function verbatimUserTail(span, k = 3, capPerMsg = 400) {
388
388
  const label = chosen.length === 1 ? "original request" : `original + last ${chosen.length - 1} request(s)`;
389
389
  return "\n\nUSER VOICE (verbatim, " + label + "):\n" + lines.join("\n");
390
390
  }
391
- export async function compact(conversation, opts) {
392
- const minKeep = opts.minKeepTurns ?? 4;
391
+ /** Where compact() cuts: everything before the last `minKeep` turns is evicted (summarized), the rest is kept verbatim
392
+ * (a leading orphan tool result dropped). Null when there are no more turns than that. Pure, and shared with the
393
+ * shell's before-it-runs bound ("61K → ≤18K", Session.compactionEstimate), so the bound and the cut never disagree. */
394
+ export function compactionSplit(conversation, minKeep) {
393
395
  const starts = turnStarts(conversation);
394
396
  if (starts.length <= minKeep)
395
- return [...conversation];
397
+ return null;
396
398
  const cutIndex = starts[starts.length - minKeep];
397
- const evicted = conversation.slice(0, cutIndex);
398
- const kept = dropLeadingOrphanTools(conversation.slice(cutIndex));
399
+ return { evicted: conversation.slice(0, cutIndex), kept: dropLeadingOrphanTools(conversation.slice(cutIndex)) };
400
+ }
401
+ export async function compact(conversation, opts) {
402
+ const split = compactionSplit(conversation, opts.minKeepTurns ?? 4);
403
+ if (!split)
404
+ return [...conversation];
405
+ const { evicted, kept } = split;
399
406
  if (!evicted.length)
400
407
  return kept;
401
408
  // The summarizer is a network round-trip (it hits the model). If it THROWS — a transient 5xx, a timeout, a
@@ -178,19 +178,17 @@ function tasksBlock(activeTasks) {
178
178
  const t = (activeTasks ?? "").replace(/^\[Your active task list[^\n]*\]\n?/, "").trim();
179
179
  return t ? `\n\nOpen items:\n${t}` : "";
180
180
  }
181
- /** What the owner (or their client) reads when the engine ends a turn itself. The `[stopped — …]` / `[paused — …]` note
182
- * stays in history and in `content` — the model and the flywheel, delegate and self-improve detectors key on it — but on
183
- * screen a bracketed engine note reads as an error. This is the same situation said plainly, ending in a question. */
184
181
  const STOP_QUESTIONS = [
185
- { match: /sub-agents? (?:are running|dispatched)|waiting on sub-agents/i, lead: "I've handed parts of this to helpers and will pick it up as soon as they report back.", ask: "Want me to keep going on the next step meanwhile, change what one of them is doing, or take a step over myself?" },
186
- { match: /repetition loop/i, lead: "That answer wasn't coming out right, so I held it back.", ask: "Want me to take another pass with a different approach, or is there one part you'd like me to focus on first?" },
187
- { match: /reasoned a long time/i, lead: "I've thought this through but haven't acted on it yet.", ask: "Should I go ahead with the next concrete step, or would you like to point me somewhere first?" },
188
- { match: /^\[paused/i, lead: "This is taking longer than I expected.", ask: "Want me to keep going from here?" },
189
- { match: /over this model's window/i, lead: "This conversation has grown too long for me to keep working in it.", ask: "Want me to compact it (/compact) and carry on?" },
190
- { match: /stopped after \d+ tool rounds/i, lead: "I've worked through a lot of steps and may not be finished.", ask: "Want me to continue from here?" },
191
- { match: /no reply came back/i, lead: "I didn't get a response back that time.", ask: "Want me to try again?" },
192
- { match: /hit the output limit/i, lead: "I ran out of room before finishing that answer.", ask: "Want me to continue?" },
193
- { match: /^\[stopped/i, lead: "I'm not making progress with the approach I was taking.", ask: "Should I try a different way, or can you tell me which part matters most?" },
182
+ { key: "yield", match: /sub-agents? (?:are running|dispatched)|waiting on sub-agents/i, lead: "I've handed parts of this to helpers and will pick it up as soon as they report back.", ask: "Want me to keep going on the next step meanwhile, change what one of them is doing, or take a step over myself?" },
183
+ { key: "repetition", match: /repetition loop/i, lead: "That answer wasn't coming out right, so I held it back.", ask: "Want me to take another pass with a different approach, or is there one part you'd like me to focus on first?" },
184
+ { key: "reasoning_budget", match: /reasoned a long time/i, lead: "I've thought this through but haven't acted on it yet.", ask: "Should I go ahead with the next concrete step, or would you like to point me somewhere first?" },
185
+ { key: "paused", match: /^\[paused/i, lead: "This is taking longer than I expected.", ask: "Want me to keep going from here?" },
186
+ { key: "window", match: /over this model's window/i, lead: "This conversation has grown too long for me to keep working in it.", ask: "Want me to compact it (/compact) and carry on?" },
187
+ { key: "rounds", match: /stopped after \d+ tool rounds/i, lead: "I've worked through a lot of steps and may not be finished.", ask: "Want me to continue from here?" },
188
+ { key: "empty", match: /no reply came back/i, lead: "I didn't get a response back that time.", ask: "Want me to try again?" },
189
+ { key: "length", match: /hit the output limit/i, lead: "I ran out of room before finishing that answer.", ask: "Want me to continue?" },
190
+ { key: "owner", match: /owner asked for an answer/i, lead: "You asked me to answer with what I had, and I kept reaching for tools instead.", ask: "Want me to answer from what I have now, or keep working on it?" },
191
+ { key: "stopped", match: /^\[stopped/i, lead: "I'm not making progress with the approach I was taking.", ask: "Should I try a different way, or can you tell me which part matters most?" },
194
192
  ];
195
193
  /** The owner-facing version of an engine stop note, or undefined when `note` is not one (a normal answer). */
196
194
  export function stopQuestion(note, activeTasks) {
@@ -199,6 +197,10 @@ export function stopQuestion(note, activeTasks) {
199
197
  return undefined;
200
198
  return [q.lead + tasksBlock(activeTasks), q.ask].filter(Boolean).join("\n\n");
201
199
  }
200
+ /** The STOP_QUESTIONS key an engine stop note matches, or undefined for a normal answer. */
201
+ export function stopKind(note) {
202
+ return STOP_QUESTIONS.find((x) => x.match.test(note.trim()))?.key;
203
+ }
202
204
  /** The engine's own closing status when the model gives nothing: the active task list (when any) and a steer. */
203
205
  export function emptyReplyStatus(activeTasks, tries) {
204
206
  const tasks = tasksBlock(activeTasks) || "\n\nNo open items on the task list.";
@@ -5,6 +5,6 @@
5
5
  // PATCH internal fix, no contract change (e.g. clampMaxTokens)
6
6
  // Bump MAJOR only when a host must change how it calls the engine. This is the single source of truth;
7
7
  // both barrels (index.ts, index.browser.ts) re-export it, and the SPEC conformance fixtures pin it.
8
- export const ENGINE_CONTRACT = "1.5.0"; // 1.5.0: + AgentOpts.onComputerEvent / computerEnv — runTurn now EMITS each typed ComputerEvent (start/end) through an optional host callback, so a prebuilt host that only sees bridge callbacks (the mobile JSCore bundle) gets the stream without wiring a tracker; additive (opt-in, default off)
8
+ export const ENGINE_CONTRACT = "1.6.0"; // 1.6.0: + AgentOpts.ownerText / request / owner / ownerSteer / ownerAct and the turn-signal callbacks onTurnState, onQueued, onSent, onToolDraft, onToolCallStart, onCompactionStart / onCompactionEnd, onLoopRecovery / onLoopCompaction / onLoopProceed, onOwnerAct — all optional, so older hosts keep working (0.1.353). 1.5.0: + AgentOpts.onComputerEvent / computerEnv — runTurn now EMITS each typed ComputerEvent (start/end) through an optional host callback, so a prebuilt host that only sees bridge callbacks (the mobile JSCore bundle) gets the stream without wiring a tracker; additive (opt-in, default off)
9
9
  // 1.4.0: + 0perator Computer event stream (ComputerEvent, ComputerEventStream, ComputerEventTracker) — a typed, retained, replayable action log a surface feeds from the existing tool callbacks; runTurn/AgentOpts unchanged, so additive (older hosts ignore it)
10
10
  // 1.3.0: + permissions surface (withPermissions, PermissionPolicy, ApproveFn) for client-side gating (additive)
@@ -3,7 +3,8 @@
3
3
  // (vs 3,132 bash calls) — the persona told it to bias to doing, and nothing said WHEN options are wanted. The
4
4
  // persona + ask_user description now say when; this module is the small engine backstop: on a build-shaped
5
5
  // owner turn, the FIRST mutating call before any ask_user is held back once and the model is told to offer a
6
- // plan + options first. Pure and dependency-free so the gate's trigger logic is unit-testable.
6
+ // plan + options first — or, in Autonomous mode, to put the plan up for review. Pure and dependency-free so the
7
+ // gate's trigger logic is unit-testable.
7
8
  import { isMutatingTool } from "../tools/mutating.js";
8
9
  const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background", "shell_task_start"]);
9
10
  // Shell commands that change the workspace or the machine. Read-only probes (ls, cat, grep, git status, a test
@@ -61,6 +62,11 @@ export const DECISION_POINT_NUDGE = "Before changing anything: this is a multi-s
61
62
  "the recommended one FIRST and labelled \"(recommended)\", each a short line saying what happens (e.g. \"Go with " +
62
63
  "this plan (recommended)\", \"Smaller scope: …\", \"Different approach: …\"). After the owner answers, proceed " +
63
64
  "with their choice without asking again.";
65
+ /** The same hold in Autonomous mode (permissions/modes.ts), where a plan review replaces the options. */
66
+ export const PLAN_REVIEW_NUDGE = "Before changing anything: this is multi-step work in Autonomous mode, and the owner reviews the plan before it " +
67
+ "runs. Do NOT make the change yet. Write the plan with task_add (each step its own item), keep working notes in the " +
68
+ "scratchpad, then call ask_user once with planReview: true — a one-line summary as the question and, in risks, every " +
69
+ "money / prod / destructive class a step needs. Once the owner approves, carry the plan out without asking again.";
64
70
  /** Resolve whether decision points are on: settings.decisionPoints (default true), overridden off by
65
71
  * KODE_DECISION_POINTS=0. */
66
72
  export function decisionPointsEnabled(setting, env = process.env) {
@@ -0,0 +1,59 @@
1
+ import { authHeaders } from "./aurora.js";
2
+ /** The gateway gives its classifier ~0.4 s and the fast model ~8 s; past this the turn goes ahead without them. */
3
+ const DEFAULT_TIMEOUT_MS = 10_000;
4
+ /** The recent conversation the gateway hands the fast model: the user and assistant texts (no tool traffic, no empty
5
+ * tool-call rounds), newest last, within `budget` characters, starting at a user turn. */
6
+ export function recentTurns(msgs, budget = 4000) {
7
+ const out = [];
8
+ let used = 0;
9
+ for (let i = msgs.length - 1; i >= 0; i--) {
10
+ const m = msgs[i];
11
+ if ((m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string" || !m.content.trim())
12
+ continue;
13
+ if (used + m.content.length > budget)
14
+ break;
15
+ used += m.content.length;
16
+ out.unshift({ role: m.role, content: m.content });
17
+ }
18
+ while (out.length && out[0].role !== "user")
19
+ out.shift();
20
+ return out;
21
+ }
22
+ /** Asks the gateway about the last message of `messages`. `model` is a gateway route id; `name` is the model as the
23
+ * owner knows it, which the fast model gives as its own when asked. Null when the gateway could not say (down, slow,
24
+ * refused, malformed): the caller runs the turn as it would without a front door. */
25
+ export async function askFrontDoor(cfg, req, signal) {
26
+ // a hand-edited settings.frontDoor without a usable portal fails open, like a gateway that is down
27
+ if (typeof cfg?.portal !== "string" || !/^https?:\/\//.test(cfg.portal))
28
+ return null;
29
+ const base = cfg.portal.replace(/\/+$/, "").replace(/\/v1$/, "");
30
+ const ctrl = new AbortController();
31
+ const stop = () => ctrl.abort();
32
+ signal?.addEventListener("abort", stop, { once: true });
33
+ const timer = setTimeout(stop, cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS);
34
+ try {
35
+ const res = await fetch(`${base}/v1/front-door`, {
36
+ method: "POST",
37
+ headers: { "content-type": "application/json", ...authHeaders({ base, model: req.model }) },
38
+ body: JSON.stringify(req),
39
+ signal: ctrl.signal,
40
+ });
41
+ if (!res.ok)
42
+ return null;
43
+ const j = (await res.json());
44
+ if (j.route === "direct" && typeof j.content === "string" && j.content.trim())
45
+ return { route: "direct", content: j.content, ...(typeof j.servedBy === "string" ? { servedBy: j.servedBy } : {}) };
46
+ if (j.route === "work")
47
+ return { route: "work", ...(typeof j.role === "string" ? { role: j.role } : {}), line: typeof j.line === "string" && j.line.trim() ? j.line : "On it" };
48
+ if (j.route === "unrouted")
49
+ return { route: "unrouted" };
50
+ return null;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ finally {
56
+ clearTimeout(timer);
57
+ signal?.removeEventListener("abort", stop);
58
+ }
59
+ }
@@ -363,7 +363,7 @@ export function routeLane(brief, hint) {
363
363
  * "[stopped]" so its work is never thrown away (10/30: two research agents ran 8 rounds each, were stopped, and
364
364
  * every finding was lost). Built from the child's own conversation: its latest notes, the pages it read, the
365
365
  * searches it ran, and short excerpts of the last pages. Pure: the caller passes session.snapshot(). */
366
- export function partialReport(msgs, why) {
366
+ function partialFindings(msgs) {
367
367
  const urls = [];
368
368
  const queries = [];
369
369
  const fetchIds = new Set();
@@ -385,6 +385,18 @@ export function partialReport(msgs, why) {
385
385
  }
386
386
  }
387
387
  const notes = [...msgs].reverse().find((m) => m.role === "assistant" && m.content.trim() && !m.content.startsWith("[engine note"))?.content.trim() ?? "";
388
+ return { urls, queries, fetchIds, notes };
389
+ }
390
+ /** What a stopped child had gathered, as counts for the owner's one-line report ("partial: 3 sources · 2 searches"). */
391
+ export function partialCounts(msgs) {
392
+ const { urls, queries, notes } = partialFindings(msgs);
393
+ const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
394
+ const sources = new Set(urls).size, searches = new Set(queries).size;
395
+ const parts = [sources ? n(sources, "source", "sources") : "", searches ? n(searches, "search", "searches") : "", notes ? "notes" : ""].filter(Boolean);
396
+ return parts.length ? `partial: ${parts.join(" · ")}` : "partial: nothing gathered yet";
397
+ }
398
+ export function partialReport(msgs, why) {
399
+ const { urls, queries, fetchIds, notes } = partialFindings(msgs);
388
400
  const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && fetchIds.has(m.tool_call_id) && m.content.trim())
389
401
  .slice(-2).map((m) => m.content.replace(/\s+/g, " ").trim().slice(0, 600));
390
402
  const uniq = (xs) => [...new Set(xs)];