@0perator/operator 0.1.352 → 0.1.354

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 (92) hide show
  1. package/dist/acp/agent.js +4 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +55 -2
  4. package/dist/autonomy/headless.js +4 -1
  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 +1072 -178
  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 +547 -92
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +135 -30
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +51 -22
  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/net-error.js +2 -1
  27. package/dist/engine/owner-act.js +52 -0
  28. package/dist/engine/selfheal.js +48 -0
  29. package/dist/engine/verify-gate.js +52 -0
  30. package/dist/flywheel/processor.js +3 -1
  31. package/dist/flywheel/srft.js +8 -4
  32. package/dist/hooks/index.js +12 -8
  33. package/dist/mcp/index.js +9 -4
  34. package/dist/permissions/index.js +32 -11
  35. package/dist/permissions/modes.js +42 -0
  36. package/dist/permissions/plan-review.js +100 -0
  37. package/dist/permissions/policy.js +16 -5
  38. package/dist/permissions/signature.js +8 -3
  39. package/dist/remote/safe-commands.js +1 -1
  40. package/dist/router/read-rates.js +152 -0
  41. package/dist/selfimprove/backfill.js +174 -0
  42. package/dist/selfimprove/index.js +146 -57
  43. package/dist/selfimprove/lessons.js +429 -0
  44. package/dist/selfimprove/sync.js +58 -0
  45. package/dist/session.js +375 -31
  46. package/dist/skills/finder.js +219 -0
  47. package/dist/tools/deferred.js +28 -18
  48. package/dist/tools/executor.js +7 -3
  49. package/dist/tools/registry.js +34 -4
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. 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
@@ -122,6 +135,41 @@ export function authHeaders(o) {
122
135
  const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
123
136
  return token ? { Authorization: `Bearer ${token}` } : {};
124
137
  }
138
+ /** A server error that came INSIDE an HTTP 200: an SSE error event (`data: {"error":…}`, llama-server's `error: {…}` line,
139
+ * an `event: error` frame), a JSON error body, or a stream that ended with no content and no finish_reason. 11/04: JL1's
140
+ * Metal backend failed and llama-server answered every request 200 with "Compute error." in the stream — /health stayed
141
+ * ok, the router logged 200s, and chat() returned an empty reply. It carries the server's own status (500 when it names
142
+ * none; 502 for an empty stream), so selfheal.ts classifies it like that status and the router marks the leg unhealthy. */
143
+ export class StreamServerError extends Error {
144
+ serverMessage;
145
+ via;
146
+ status;
147
+ constructor(serverMessage, via, status, label) {
148
+ super(`${label} ${status}: ${serverMessage} (${via === "empty" ? "an HTTP 200 stream with no content and no finish_reason" : `server error inside an HTTP 200 ${via === "body" ? "body" : "stream"}`})`);
149
+ this.serverMessage = serverMessage;
150
+ this.via = via;
151
+ this.name = "StreamServerError";
152
+ this.status = status;
153
+ }
154
+ }
155
+ function streamError(o, payload, via) {
156
+ const e = payload && typeof payload === "object" && "error" in payload ? payload.error : payload;
157
+ const f = e && typeof e === "object" ? e : {};
158
+ const text = typeof e === "string" ? e : typeof f.message === "string" ? f.message : JSON.stringify(e);
159
+ const code = Number(f.code ?? f.status);
160
+ const status = Number.isInteger(code) && code >= 400 && code <= 599 ? code : 500;
161
+ return new StreamServerError((text || "server error").slice(0, 300), via, status, httpErrorLabel(o));
162
+ }
163
+ function parseJson(s) {
164
+ try {
165
+ return JSON.parse(s);
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ const SSE_FIELD = /^(?:data|event|error|id|retry):/;
172
+ const HEAD_MAX = 65_536; // a non-SSE body is read whole up to this: a JSON error body or a one-shot reply is one object
125
173
  // ---------------------------------------------------------------------------
126
174
  // Decode-time degeneration guard (SPEC §1). This is NOT a sampling penalty — it changes no
127
175
  // logits and touches no request knob, so a healthy model is completely unaffected. It only
@@ -373,13 +421,18 @@ async function* streamDeltas(messages, o) {
373
421
  // time it streams — releasing on completion, early break (loop breaker / first-answer), error, or abort.
374
422
  // Interactive turns preempt the queue ahead of background sub-agents (see acquireEndpoint). A single call is
375
423
  // never re-entrant, so acquire/release balance exactly once.
376
- await acquireEndpoint(o.base, o.background === true, o.model);
424
+ const owner = o.owner ?? (o.background ? "sub-agent" : "main");
425
+ await acquireEndpoint(o.base, o.background === true, o.model, { owner, onQueued: o.onQueued });
377
426
  let _slotReleased = false;
378
427
  const _releaseSlot = () => { if (!_slotReleased) {
379
428
  _slotReleased = true;
380
- releaseEndpoint(o.base, o.model);
429
+ releaseEndpoint(o.base, o.model, owner);
381
430
  } };
382
431
  try {
432
+ try {
433
+ o.onSent?.();
434
+ }
435
+ catch { /* a UI callback never breaks the request */ }
383
436
  const res = await fetchChat(o, requestBody(messages, o, true));
384
437
  if (!res.ok || !res.body) {
385
438
  let detail = "";
@@ -418,9 +471,13 @@ async function* streamDeltas(messages, o) {
418
471
  const decodeMon = createDecodeMonitor(); // GAP 2: abort a CPU-fallback-slow decode so self-heal fails over
419
472
  const startedAt = Date.now();
420
473
  let lastByteAt = Date.now();
474
+ let event = ""; // the SSE `event:` name of the frame being read: an `event: error` frame's data is the error
475
+ let sse = false; // the body has sent an SSE field; until then it is kept whole in `head`
476
+ let head = "";
477
+ let answered = false; // a delta carried content, reasoning, a tool call or a finish_reason
421
478
  // finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
422
479
  try {
423
- for (;;) {
480
+ read: for (;;) {
424
481
  const idleLeft = idleMs > 0 ? idleMs - (Date.now() - lastByteAt) : Infinity;
425
482
  const wallLeft = wallMs > 0 ? wallMs - (Date.now() - startedAt) : Infinity;
426
483
  const budget = Math.min(idleLeft, wallLeft);
@@ -444,25 +501,47 @@ async function* streamDeltas(messages, o) {
444
501
  }
445
502
  const { value, done } = raced;
446
503
  lastByteAt = Date.now();
447
- if (done)
448
- break;
449
- buf += dec.decode(value, { stream: true });
450
- for (const line of buf.split("\n")) {
504
+ buf += done ? dec.decode() : dec.decode(value, { stream: true });
505
+ // Whole lines only: the tail waits for its newline, so a line split across two reads is read once.
506
+ const lines = buf.split("\n");
507
+ buf = done ? "" : lines.pop() ?? "";
508
+ for (const line of lines) {
451
509
  const t = line.trim();
452
- if (!t.startsWith("data:"))
510
+ if (!sse) {
511
+ if (!SSE_FIELD.test(t)) {
512
+ if (head.length < HEAD_MAX)
513
+ head += line + "\n";
514
+ continue;
515
+ }
516
+ sse = true;
517
+ }
518
+ if (!t) {
519
+ event = "";
520
+ continue;
521
+ }
522
+ if (t.startsWith("event:")) {
523
+ event = t.slice(6).trim();
524
+ continue;
525
+ }
526
+ const errorLine = t.startsWith("error:"); // llama-server before its 2025 rewrite sent an in-stream error as an `error:` line
527
+ if (!errorLine && !t.startsWith("data:"))
528
+ continue;
529
+ const d = t.slice(errorLine ? 6 : 5).trim();
530
+ if (!errorLine && d === "[DONE]")
531
+ break read;
532
+ const j = parseJson(d);
533
+ if (errorLine || event === "error" || j?.error)
534
+ throw streamError(o, j ?? d, "event");
535
+ if (j === undefined)
453
536
  continue;
454
- const d = t.slice(5).trim();
455
- if (d === "[DONE]")
456
- return;
457
537
  try {
458
- const j = JSON.parse(d);
459
538
  // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
460
539
  // cache_n / prompt_tokens_details.cached_tokens = how much of the prompt the server SERVED FROM
461
540
  // ITS PREFIX CACHE this round (vs re-prefilled) — GW-05: parse it, don't throw away the truth.
462
541
  if (j.prompt_progress) {
463
542
  const pp = j.prompt_progress;
464
543
  if (Number(pp.total) > 0)
465
- o.onPromptProgress?.({ processed: Number(pp.processed) || 0, total: Number(pp.total), cached: Number(pp.cache) || 0 });
544
+ 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
545
  }
467
546
  if (j.timings || j.usage)
468
547
  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 });
@@ -484,17 +563,37 @@ async function* streamDeltas(messages, o) {
484
563
  void reader.cancel().catch(() => { });
485
564
  throw new Error(`aurora endpoint degraded — decode ${slowRate.toFixed(1)} tok/s under the ${DECODE_FLOOR_TPS} tok/s floor (CPU fallback; transient)`);
486
565
  }
566
+ if (delta.content || delta.reasoning_content || delta.tool_calls?.length || delta.finish_reason)
567
+ answered = true;
487
568
  yield delta;
488
569
  }
489
570
  }
490
571
  catch { }
491
572
  }
492
- buf = buf.slice(buf.lastIndexOf("\n") + 1);
573
+ if (done)
574
+ break;
493
575
  }
494
576
  }
495
577
  finally {
496
578
  await reader.cancel().catch(() => { });
497
579
  }
580
+ if (!sse) {
581
+ // No SSE at all: a JSON error body, or a server that answered the stream request with one whole reply.
582
+ const j = parseJson(head.trim());
583
+ if (j?.error)
584
+ throw streamError(o, j, "body");
585
+ const choice = j?.choices?.[0];
586
+ const m = choice?.message;
587
+ if (m && (m.content || m.reasoning_content || m.tool_calls?.length || choice.finish_reason)) {
588
+ answered = true;
589
+ yield {
590
+ content: m.content ?? undefined, reasoning_content: m.reasoning_content ?? undefined, finish_reason: choice.finish_reason ?? undefined,
591
+ tool_calls: m.tool_calls?.map((tc, index) => ({ ...tc, index })),
592
+ };
593
+ }
594
+ }
595
+ if (!answered)
596
+ throw new StreamServerError("empty stream", "empty", 502, httpErrorLabel(o));
498
597
  }
499
598
  finally {
500
599
  _releaseSlot(); // free the endpoint slot for the next (interactive-first) waiter
@@ -566,6 +665,12 @@ export async function chat(messages, o) {
566
665
  if (tc.function?.arguments)
567
666
  entry.args += tc.function.arguments;
568
667
  acc.set(idx, entry);
668
+ if (entry.name) {
669
+ try {
670
+ o.onToolDraft?.({ index: idx, id: entry.id ?? `call_${idx}`, name: entry.name, args: entry.args });
671
+ }
672
+ catch { /* display only */ }
673
+ }
569
674
  }
570
675
  }
571
676
  // 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
@@ -77,9 +77,9 @@ export function detectAnnouncedDelegation(content, calledTools) {
77
77
  // 1. an engine note is MARKED as such, so the model can tell it from the owner;
78
78
  // 2. a reply that reacts to a speaker who did not speak (after round 0 nothing but tool results and engine notes
79
79
  // arrive) is redirected into a one-line status for the owner;
80
- // 3. a turn never ends on nothing: an empty reply gets one reframed retry and then an engine-composed status, and
81
- // a final with open tasks and no question or report gets one nudge to close with a status plus a steering
82
- // question — the owner is always left with something to answer, never a silent stop.
80
+ // 3. a turn never ends on nothing: an empty reply gets one reframed retry, then the model's fallback answers or the
81
+ // turn ends naming what was tried (noAnswer), and a final with open tasks and no question or report gets one nudge
82
+ // to close with a status plus a steering question — the owner is always left with something, never a silent stop.
83
83
  /** Prefix every engine-injected user-role message so the model never mistakes it for the owner. */
84
84
  export const ENGINE_NOTE_PREFIX = "[engine note — automatic, not from the owner] ";
85
85
  export function engineNote(text) {
@@ -166,10 +166,11 @@ export function needsClosingSteer(content, hasOpenTasks) {
166
166
  return false;
167
167
  return true;
168
168
  }
169
- /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-reply status) rather than the model — the
170
- * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. */
169
+ /** True for a final the ENGINE wrote (a stop/pause/yield note or the no-answer note) rather than the model — the
170
+ * flywheel must not grade it as the model's answer and a planner must not accept it as a sub-agent's result. "no reply
171
+ * came back" is the no-answer note before 11/04, still in saved conversations and flywheel rows. */
171
172
  export function isEngineFinal(content) {
172
- return /^\s*(?:\[(?:stopped|paused|turn ended|no reply came back from the model|declined by the provider)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
173
+ return /^\s*(?:\[(?:stopped|paused|turn ended|no answer|no reply came back from the model|declined by the provider)\b|\((?:the model returned an empty response|hit the output limit before an answer landed))/i.test(content ?? "");
173
174
  }
174
175
  export const EMPTY_REPLY_NUDGE = "Your reply was empty. Answer the owner now in plain text: what is done, what you are doing or about to do, and " +
175
176
  "one question if you are blocked. If a tool call is needed, make the call — but never return nothing.";
@@ -178,19 +179,17 @@ function tasksBlock(activeTasks) {
178
179
  const t = (activeTasks ?? "").replace(/^\[Your active task list[^\n]*\]\n?/, "").trim();
179
180
  return t ? `\n\nOpen items:\n${t}` : "";
180
181
  }
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
182
  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?" },
183
+ { 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?" },
184
+ { 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?" },
185
+ { 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?" },
186
+ { key: "paused", match: /^\[paused/i, lead: "This is taking longer than I expected.", ask: "Want me to keep going from here?" },
187
+ { 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?" },
188
+ { 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?" },
189
+ { key: "unanswered", match: /^\[no answer\b/i, lead: "Nothing answered this turn.", ask: "" },
190
+ { key: "length", match: /hit the output limit/i, lead: "I ran out of room before finishing that answer.", ask: "Want me to continue?" },
191
+ { 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?" },
192
+ { 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
193
  ];
195
194
  /** The owner-facing version of an engine stop note, or undefined when `note` is not one (a normal answer). */
196
195
  export function stopQuestion(note, activeTasks) {
@@ -199,10 +198,40 @@ export function stopQuestion(note, activeTasks) {
199
198
  return undefined;
200
199
  return [q.lead + tasksBlock(activeTasks), q.ask].filter(Boolean).join("\n\n");
201
200
  }
202
- /** The engine's own closing status when the model gives nothing: the active task list (when any) and a steer. */
203
- export function emptyReplyStatus(activeTasks, tries) {
204
- const tasks = tasksBlock(activeTasks) || "\n\nNo open items on the task list.";
205
- return `[no reply came back from the model after ${tries} tries. Where things stand:${tasks}\n\nTell me which step to take next, or say "continue" to resume from here.]`;
201
+ /** The STOP_QUESTIONS key an engine stop note matches, or undefined for a normal answer. */
202
+ export function stopKind(note) {
203
+ return STOP_QUESTIONS.find((x) => x.match.test(note.trim()))?.key;
204
+ }
205
+ /** The owner's one line when the model's fallback answered this turn: what failed, why, and what answered. */
206
+ export function fallbackLine(o) {
207
+ const what = o.silent ? `${o.from} sent ${o.silent} empty replies` : `${o.from}'s server is failing (${o.cause})`;
208
+ return `${what} — ${o.to} answered this turn`;
209
+ }
210
+ /** The live line while a request recovers (the TUI's recovering phase): what failed and what happens next, so a slow
211
+ * answer never reads as a broken model. */
212
+ export function recoveryLine(s) {
213
+ const n = s.next;
214
+ const next = n.kind === "leg" ? `reconnecting via ${n.host}` : n.kind === "fallback" ? `${n.to} takes this turn` : `retrying in ${Math.max(1, Math.round(n.waitMs / 1000))} s`;
215
+ return `${s.failed.model} at ${s.failed.host}: ${s.failed.cause} — ${next}`;
216
+ }
217
+ /** The fallback line as a notice on screen: the TUI (mirrored to followers), ACP. */
218
+ export function fallbackNotice(e) {
219
+ return `⚠ ${e.line}`;
220
+ }
221
+ /** A turn nothing answered — every leg of the owner's model and of its fallback failed, or finished with nothing in the
222
+ * reply: each leg's cause in the order tried, and what the next turn does. `note` stays in history (the next turn's model
223
+ * reads it, isEngineFinal keys on it); `display` is what the owner reads. Never "want me to try again?". */
224
+ export function noAnswer(o) {
225
+ const legs = o.tried.map((l) => {
226
+ const more = [l.detail, l.tries > 1 ? `${l.tries} tries` : undefined].filter(Boolean);
227
+ return `- ${l.model} at ${l.host}: ${l.cause}${more.length ? ` (${more.join(", ")})` : ""}`;
228
+ }).join("\n");
229
+ const next = `Next: the next turn tries ${o.owner} first again${o.fallback ? `, then ${o.fallback}` : ""}.`;
230
+ const tasks = tasksBlock(o.tasks);
231
+ return {
232
+ note: `[no answer — nothing answered this turn. Tried, in order:\n${legs}\n${next}]${tasks}`,
233
+ display: `Nothing answered this turn. I tried, in order:\n${legs}\n${next}${tasks}`,
234
+ };
206
235
  }
207
236
  /** Append the active task list and a steer to an engine stop note. A yield note (sub-agents will resume the turn)
208
237
  * gets its own steer: the owner can always take the delegated work back. */
@@ -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.7.0"; // 1.7.0: + AgentOpts.model (TurnModel: the owner's name for the model and its fallback) / onFallback, and onSelfHeal's optional third argument (RecoveryStep); a server error inside an HTTP 200 throws StreamServerError; a turn nothing answers returns stopKind "unanswered" (was "empty") instead of throwing — all optional, so older hosts keep working (0.1.354). 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)];