@0perator/operator 0.1.222 → 0.1.235

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 (70) hide show
  1. package/CHANGELOG.md +858 -0
  2. package/README.md +4 -4
  3. package/dist/acp/agent.js +42 -3
  4. package/dist/acp/config-options.js +34 -0
  5. package/dist/acp/run.js +83 -2
  6. package/dist/auth/byo.js +118 -0
  7. package/dist/auth/commands.js +34 -1
  8. package/dist/autonomy/dream.js +1 -1
  9. package/dist/autonomy/index.js +16 -2
  10. package/dist/autonomy/media-robot.js +138 -0
  11. package/dist/autonomy/profile.js +77 -0
  12. package/dist/autonomy/session-factory.js +13 -9
  13. package/dist/background/index.js +8 -1
  14. package/dist/cli.js +132 -95
  15. package/dist/compose/client.js +56 -0
  16. package/dist/config/persona.js +186 -14
  17. package/dist/config/settings.js +49 -16
  18. package/dist/consolidation/scheduler.js +7 -4
  19. package/dist/consolidation/sleep.js +15 -1
  20. package/dist/engine/agent.js +152 -9
  21. package/dist/engine/aurora.js +73 -14
  22. package/dist/engine/compaction.js +129 -2
  23. package/dist/engine/computer-event.js +139 -0
  24. package/dist/engine/continuation.js +55 -0
  25. package/dist/engine/contract.js +3 -1
  26. package/dist/engine/grandmaster.js +13 -3
  27. package/dist/engine/messages.js +2 -2
  28. package/dist/engine/redact.js +25 -0
  29. package/dist/engine/rolling-summary.js +22 -7
  30. package/dist/engine/router-adapter.js +2 -0
  31. package/dist/engine/unrestricted.js +51 -0
  32. package/dist/engine/verify-gate.js +6 -0
  33. package/dist/index.browser.js +4 -0
  34. package/dist/index.js +4 -0
  35. package/dist/memory/index.js +0 -0
  36. package/dist/permissions/audit.js +4 -1
  37. package/dist/permissions/policy.js +4 -3
  38. package/dist/permissions/tier.js +31 -14
  39. package/dist/remote/host.js +9 -2
  40. package/dist/router/models.js +43 -2
  41. package/dist/session.js +113 -36
  42. package/dist/telemetry/events.js +8 -3
  43. package/dist/tools/computer.js +1 -1
  44. package/dist/tools/executor.js +22 -17
  45. package/dist/tools/mutating.js +6 -0
  46. package/dist/tools/registry.js +872 -27
  47. package/dist/tools/shell-session.js +36 -1
  48. package/dist/tools/tool-output-spill.js +2 -2
  49. package/dist/ui/ActivitySpinner.js +17 -6
  50. package/dist/ui/App.js +36 -14
  51. package/dist/ui/ArtifactPicker.js +109 -0
  52. package/dist/ui/BusTray.js +70 -0
  53. package/dist/ui/Composer.js +39 -8
  54. package/dist/ui/Markdown.js +5 -3
  55. package/dist/ui/MouseProvider.js +99 -19
  56. package/dist/ui/QuestionPrompt.js +24 -3
  57. package/dist/ui/ThinkingSpinner.js +9 -5
  58. package/dist/ui/ToolStep.js +17 -12
  59. package/dist/ui/Transcript.js +14 -7
  60. package/dist/ui/capabilities.js +0 -9
  61. package/dist/ui/listhit.js +23 -0
  62. package/dist/ui/mouse.js +22 -0
  63. package/dist/ui/osc.js +7 -4
  64. package/dist/ui/progressbar.js +46 -0
  65. package/dist/ui/shimmer.js +43 -0
  66. package/dist/ui/theme.js +2 -0
  67. package/dist/ui/tick.js +48 -0
  68. package/dist/ui/toolicons.js +69 -0
  69. package/dist/util/slash.js +1 -0
  70. package/package.json +2 -2
@@ -9,6 +9,8 @@ import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampM
9
9
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
10
10
  import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
11
11
  import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
12
+ import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
13
+ import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
12
14
  const MAX_SELF_HEAL_PER_TURN = 3;
13
15
  // A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
14
16
  // is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
@@ -20,10 +22,16 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
20
22
  // file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
21
23
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
22
24
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
23
- import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a workspace edit ⇒ prior identical-call counts are stale
25
+ import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
26
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, detectUnfinishedAction } from "./continuation.js";
24
27
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
25
28
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
26
29
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
30
+ // Hard backstop: after this many identical (name+args) calls in a turn with NO intervening edit, the model is
31
+ // spinning on a poisoned call and ignoring every short-circuit warning — abort the turn cleanly instead of
32
+ // burning rounds to maxRoundsHard. An Aurora blip once drove the same blocked bash call 16× before the turn
33
+ // died: LOOP_GUARD_LIMIT only *short-circuits* the call, it never *stopped* the spin — this does.
34
+ const LOOP_GUARD_HARD = LOOP_GUARD_LIMIT * 2; // 10
27
35
  const CONTENT_LOOP_LIMIT = 3; // whole round (prose + actions) repeats this many times ⇒ light NUDGE to pivot
28
36
  const CONTENT_LOOP_REDIRECT = 6; // …and at this many, escalate to a FORCED REDIRECT: make the model diagnose the
29
37
  // loop and decompose OR switch approach, then reset its runway and CONTINUE (enterprise loop-recovery — the
@@ -45,6 +53,14 @@ const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new
45
53
  // only ever NUDGES once (NO_EDIT_NUDGE); it never stops a turn, so a genuine long read-only task is safe.
46
54
  const SELF_LOOP_RE = /\b(stuck in a loop|going in circles|in an?(?: infinite)? loop|repeating (?:the same|myself|it)|same (?:code|thing|approach|command)(?: keeps| is| that)?(?: getting)? repeat|keep (?:repeating|doing the same|getting the same)|(?:try|take|need) (?:a |an )?(?:fresh|different|new|another) approach)\b/i;
47
55
  const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file edit between) ⇒ graceful stop
56
+ // Converge-or-stop guard: the identical-call guards above can't catch a model that varies its args every round
57
+ // (a different path / pattern / comment each time) yet never answers and never changes a file. This many
58
+ // CONSECUTIVE tool rounds with NO new narration from the model and NO landed file change ⇒ it is not converging:
59
+ // STOP with an honest message. Reset by new assistant text or a mutation that landed; poll-only rounds
60
+ // (agent_status / bash_output) neither count nor reset. Above NO_EDIT_NUDGE (15) so a long silent read-only survey
61
+ // still gets its one soft nudge first. Paired with turn-continuation (continuation.ts): keep going on real work,
62
+ // stop on circles.
63
+ const NO_CONVERGE_LIMIT = 25;
48
64
  const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
49
65
  const REHYDRATE_MAX_FILES = 5; // after a compaction, name up to this many recently-touched files for the model to re-read
50
66
  const COMPACTION_FAIL_LIMIT = 3; // rounds still OVER the window after compaction ran ⇒ it can't free space (summarizer failing / un-evictable bulk); stop spinning into the same wall
@@ -150,8 +166,8 @@ function observeVerify(v, calls, toolMsgs) {
150
166
  }
151
167
  /** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
152
168
  export class TurnAbortedError extends Error {
153
- constructor() {
154
- super("turn aborted");
169
+ constructor(reason) {
170
+ super(reason ?? "turn aborted");
155
171
  this.name = "TurnAbortedError";
156
172
  }
157
173
  }
@@ -229,6 +245,7 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
229
245
  const pending = [];
230
246
  const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
231
247
  const parsedArgs = new Map();
248
+ let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
232
249
  toolCalls.forEach((tc, batchIndex) => {
233
250
  const parsed = parseArgs(tc.function.arguments);
234
251
  if (!parsed.ok) {
@@ -249,12 +266,23 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
249
266
  const count = (callCounts.get(sig) ?? 0) + 1;
250
267
  callCounts.set(sig, count);
251
268
  if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
269
+ if (count >= LOOP_GUARD_HARD) {
270
+ // The model ignored LOOP_GUARD_HARD short-circuit warnings for this exact call with no intervening edit —
271
+ // it is not recovering. Flag it; the turn is aborted after this batch rather than spinning to the cap.
272
+ loopAbort = `"${tc.function.name}" was called ${count}× with identical arguments and no intervening ` +
273
+ `progress — the turn was stopped to avoid an unrecoverable loop (often an upstream/engine blip the ` +
274
+ `model kept retrying). Nothing was lost; re-run the request.`;
275
+ }
252
276
  preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
253
277
  `arguments. Try a different approach instead of repeating this call.`);
254
278
  return;
255
279
  }
256
280
  pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
257
281
  });
282
+ // A signature blew past the hard loop ceiling: stop the turn cleanly rather than let the model spin to the
283
+ // round cap. TurnAbortedError is the engine's existing clean-stop path (identical to an esc interrupt).
284
+ if (loopAbort)
285
+ throw new TurnAbortedError(`Loop guard: ${loopAbort}`);
258
286
  if (pending.length)
259
287
  onToolStart?.(pending);
260
288
  const started = performance.now();
@@ -264,11 +292,13 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
264
292
  const durationMs = performance.now() - started;
265
293
  const resultById = new Map(preResolved);
266
294
  pending.forEach((p, i) => resultById.set(p.id, executed[i]));
267
- // A file edit this round changed the workspace, so every prior "identical call" count is stale — a
295
+ // A file edit that LANDED this round changed the workspace, so every prior "identical call" count is stale — a
268
296
  // re-run of the same test/build/compose is now verify-after-fix progress, not a loop. Clear the counts so
269
297
  // the next round's repeats start fresh; only a call repeated with NO intervening edit keeps accumulating
270
298
  // toward LOOP_GUARD_LIMIT. This is what lets Operator iterate (edit → re-run → edit → re-run) unbounded.
271
- if (pending.some((p) => MUTATING_TOOLS.has(p.name)))
299
+ // A FAILING edit ("error: old_string not found") changed nothing — it must not reset the count, or a model
300
+ // can alternate a failing edit with the same poisoned call forever (the guard could never stop it).
301
+ if (pending.some((p, i) => mutationLanded(p.name, executed[i])))
272
302
  callCounts.clear();
273
303
  if (onToolBatch) {
274
304
  const events = toolCalls.map((tc, batchIndex) => ({
@@ -320,6 +350,7 @@ export function rehydrationNote(touched) {
320
350
  export async function runTurn(userInput, conversation, opts) {
321
351
  const softRounds = opts.maxRounds ?? 10;
322
352
  const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
353
+ const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
323
354
  const callCounts = new Map();
324
355
  const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
325
356
  let forcedRedirects = 0; // enterprise loop-recovery: forced redirects spent this turn (each resets a repeated round's runway; the turn hands back only after CONTENT_LOOP_REDIRECT_MAX of them fail to break the loop)
@@ -338,6 +369,52 @@ export async function runTurn(userInput, conversation, opts) {
338
369
  const verifyEnabled = opts.verifyGate?.enabled !== false;
339
370
  const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
340
371
  let verifyNudges = 0;
372
+ const unrestrictedEnabled = opts.unrestricted !== false; // default on — owner's private system
373
+ // 0perator Computer feed (opt-in, additive): when the host wants a typed action stream, compose the two
374
+ // tool callbacks here so runToolCalls stays untouched. The tracker pushes normalized start/end events into
375
+ // a stream; subscribe(0) forwards each to the host's onComputerEvent. A throwing host callback can't break
376
+ // the turn (ComputerEventStream isolates subscribers). The composed callbacks fall back to the originals
377
+ // verbatim when no computer feed is wanted, so the common path is unchanged.
378
+ let onToolStartFx = opts.onToolStart;
379
+ let onToolResultFx = opts.onToolResult;
380
+ if (opts.onComputerEvent) {
381
+ const ceStream = new ComputerEventStream();
382
+ ceStream.subscribe(0, opts.onComputerEvent);
383
+ const ceTracker = new ComputerEventTracker(ceStream, opts.computerEnv ?? "sandbox");
384
+ const origStart = opts.onToolStart;
385
+ const origResult = opts.onToolResult;
386
+ onToolStartFx = (calls) => { origStart?.(calls); ceTracker.onToolStart(calls); };
387
+ onToolResultFx = (id, result, batchId) => { origResult?.(id, result, batchId); ceTracker.onToolResult(id, result); };
388
+ }
389
+ // Turn-continuation: nudge a model that ends on an unperformed action announcement to actually do it (bounded).
390
+ const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
391
+ const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
392
+ let announceNudges = 0;
393
+ // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
394
+ let convergeStreak = 0;
395
+ const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
396
+ const stopTurn = (note, roundsRun) => {
397
+ conversation.assistant(note);
398
+ return { content: note, rounds: roundsRun, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
399
+ };
400
+ /** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
401
+ const stalledNotConverging = (calls, toolMsgs, content) => {
402
+ if (calls.every((c) => LOOP_GUARD_EXEMPT.has(c.function?.name ?? "")))
403
+ return false; // pure polling: legit, neither counts nor resets
404
+ const sig = contentSignature(content);
405
+ const narrated = sig.length >= 12 && !narratedSigs.has(sig);
406
+ if (sig)
407
+ narratedSigs.add(sig);
408
+ const landed = calls.some((c, i) => mutationLanded(c.function?.name, toolMsgs[i]?.content ?? ""));
409
+ convergeStreak = narrated || landed ? 0 : convergeStreak + 1;
410
+ return convergeStreak >= NO_CONVERGE_LIMIT;
411
+ };
412
+ const notConvergingNote = (calls) => {
413
+ const last = calls[calls.length - 1]?.function?.name ?? "tool";
414
+ return `[stopped — not converging: ${convergeStreak} tool rounds in a row (last: ${last}) with no new explanation ` +
415
+ `from me and no file change that landed, so I'm handing back rather than burn more time. Nothing was lost — ` +
416
+ `tell me how you'd like to proceed, or ask me to continue and I'll pick up from here with a different approach.]`;
417
+ };
341
418
  conversation.user(userInput);
342
419
  let rounds = 0;
343
420
  let toolCallTotal = 0;
@@ -358,7 +435,23 @@ export async function runTurn(userInput, conversation, opts) {
358
435
  const spent = tokensTotal + promptTokensTotal;
359
436
  const note = `[paused — this turn reached its token budget (${spent} ≥ ${opts.maxTurnTokens} tokens). ` +
360
437
  `The work so far is above; continue with a fresh, focused request, or raise the budget ` +
361
- `(KODE_TURN_MAX_TOKENS / settings.maxTurnTokens).]`;
438
+ `(settings.maxTurnTokens).]`;
439
+ conversation.assistant(note);
440
+ return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
441
+ }
442
+ // Opt-in per-turn WALL-CLOCK ceiling: the only bound on TIME. Round/token budgets don't stop a turn whose
443
+ // decode has crawled (RAM pressure from a big model on the serving box, or very high context) to ~1 tok/s —
444
+ // such a turn can run an hour generating almost nothing. Wrap up gracefully at the round boundary instead
445
+ // (loop mode continues the objective next turn). "[paused —" (not "[stopped —") so the flywheel doesn't
446
+ // read a time cap as a failure-lesson.
447
+ if (opts.maxTurnWallClockMs && rounds > 0 && Date.now() - turnStart >= opts.maxTurnWallClockMs) {
448
+ const ranMin = Math.round((Date.now() - turnStart) / 60000);
449
+ const capMin = Math.round(opts.maxTurnWallClockMs / 60000);
450
+ const spent = tokensTotal + promptTokensTotal;
451
+ const tps = genMsTotal > 0 ? (tokensTotal / (genMsTotal / 1000)) : 0;
452
+ const crawl = tps > 0 && tps < 3 ? ` Decode was crawling (~${tps.toFixed(1)} tok/s) — likely RAM pressure (a large model loaded on the serving box) or very high context; avoid co-locating heavy model loads with the serving model.` : "";
453
+ const note = `[paused — this turn hit its ${capMin}-min wall-clock budget (ran ${ranMin} min, ${spent} tokens).${crawl} ` +
454
+ `The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
362
455
  conversation.assistant(note);
363
456
  return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
364
457
  }
@@ -432,11 +525,13 @@ export async function runTurn(userInput, conversation, opts) {
432
525
  const messages = buildMessages(opts.systemPrompt, conversation.all);
433
526
  // Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
434
527
  // deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
435
- const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ?? 16384);
528
+ const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192);
436
529
  try {
437
530
  response = await chat(messages, {
438
531
  base: endpoint.base,
439
532
  model: endpoint.model,
533
+ token: endpoint.token,
534
+ transport: endpoint.transport,
440
535
  maxTokens,
441
536
  temperature: opts.temperature,
442
537
  tools: opts.toolSchemas,
@@ -564,6 +659,38 @@ export async function runTurn(userInput, conversation, opts) {
564
659
  continue;
565
660
  }
566
661
  }
662
+ // Unrestricted mode (engine/unrestricted.ts, owner's private system): this round's `response` just came
663
+ // back clean (no self-heal error) — if it has no tool calls AND its text/stopReason reads as a
664
+ // POLICY/MORAL refusal (not a capability limit), re-issue the SAME request with an affirmative-prefill
665
+ // reminder appended and use that result in its place. Bounded per round by UNRESTRICTED_MAX_RETRIES so a
666
+ // model that keeps refusing can never loop forever; still refusing after that, `response` just keeps its
667
+ // original (unchanged) content and falls through to the normal round handling below. This never touches
668
+ // a tool-permission denial or the deniedReadAsync credential-path guard (tools/registry.ts) — those
669
+ // aren't chat() output, so detectRefusal never sees them; the two hard floors are untouched.
670
+ if (unrestrictedEnabled) {
671
+ let unrestrictedRetries = 0;
672
+ while (unrestrictedRetries < UNRESTRICTED_MAX_RETRIES &&
673
+ response.toolCalls.length === 0 &&
674
+ detectRefusal(response.content, response.stopReason)) {
675
+ unrestrictedRetries += 1;
676
+ opts.onSelfHeal?.("server_error", unrestrictedRetries); // footer ↻ — same self-heal signal other recovery paths use
677
+ const retryMessages = buildAffirmativeRetry(buildMessages(opts.systemPrompt, conversation.all));
678
+ response = await chat(retryMessages, {
679
+ base: endpoint.base,
680
+ model: endpoint.model,
681
+ token: endpoint.token,
682
+ transport: endpoint.transport,
683
+ maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
684
+ temperature: opts.temperature,
685
+ tools: opts.toolSchemas,
686
+ thinking: opts.thinking,
687
+ signal: opts.signal,
688
+ background: opts.background,
689
+ onDelta: opts.onDelta,
690
+ onReasoning: opts.onReasoning,
691
+ });
692
+ }
693
+ }
567
694
  // Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
568
695
  // actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
569
696
  // round (prose + the calls it drives), NOT the prose alone: a model doing DIFFERENT work each round
@@ -658,7 +785,7 @@ export async function runTurn(userInput, conversation, opts) {
658
785
  conversation.assistant(response.content, response.toolCalls);
659
786
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
660
787
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
661
- const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult), opts.signal);
788
+ const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
662
789
  for (const tm of toolMsgs)
663
790
  conversation.tool(tm.tool_call_id, tm.content);
664
791
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -667,6 +794,8 @@ export async function runTurn(userInput, conversation, opts) {
667
794
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
668
795
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
669
796
  trackTouchedFiles(response.toolCalls, touchedFiles);
797
+ if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
798
+ return stopTurn(notConvergingNote(response.toolCalls), rounds + 1);
670
799
  continue;
671
800
  }
672
801
  // No structured tool_calls — check for text-encoded ones before treating this as final.
@@ -674,7 +803,7 @@ export async function runTurn(userInput, conversation, opts) {
674
803
  if (recovered.calls.length > 0) {
675
804
  throwIfAborted(opts.signal);
676
805
  conversation.assistant(recovered.cleanedContent, recovered.calls);
677
- const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult), opts.signal);
806
+ const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
678
807
  for (const tm of toolMsgs)
679
808
  conversation.tool(tm.tool_call_id, tm.content);
680
809
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
@@ -683,6 +812,8 @@ export async function runTurn(userInput, conversation, opts) {
683
812
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
684
813
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
685
814
  trackTouchedFiles(recovered.calls, touchedFiles);
815
+ if (stalledNotConverging(recovered.calls, toolMsgs, recovered.cleanedContent))
816
+ return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
686
817
  continue;
687
818
  }
688
819
  const final = stripScratchpad(recovered.cleanedContent);
@@ -708,6 +839,18 @@ export async function runTurn(userInput, conversation, opts) {
708
839
  continue;
709
840
  }
710
841
  }
842
+ // Turn-continuation: a text-only round whose tail is an unperformed action announcement ("Let me implement
843
+ // these now.") is NOT a finished turn — finalizing here would leave the work undone and make the owner type
844
+ // "continue". Record the model's text, nudge it (user role — real content + tool context exist, so it is
845
+ // answered as the instruction it is) to actually call the tool(s), and keep going. Bounded per turn
846
+ // (continuationMax) so it can never force an unbounded turn; the converge guard stops circling. A truncated
847
+ // reply ("length") has an unreliable tail, so it is left to the normal finalize path.
848
+ if (continuationEnabled && final && response.stopReason !== "length" && announceNudges < continuationMax && detectUnfinishedAction(final)) {
849
+ announceNudges++;
850
+ conversation.assistant(final);
851
+ conversation.user(ANNOUNCE_NUDGE);
852
+ continue;
853
+ }
711
854
  // Verify-before-done gate: the model is finalizing (no more tool calls). If this turn CHANGED files
712
855
  // but no passing check was observed, inject ONE reminder to run it and give the model another round.
713
856
  // Record `final` as the model's own done-claim first, then a user-role reminder — the "user-role leak"
@@ -61,14 +61,36 @@ export function endpointGateStatus() {
61
61
  function isRemoteBase(base) {
62
62
  return !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(base);
63
63
  }
64
+ // Owner-trusted fallback scope for the OPERATOR bearer: AXE's own hosts (api.axe.onl gateway) and
65
+ // private/LAN fleet nodes. A third-party BYO host (qwencloudapi.com, …) must NEVER receive the operator
66
+ // token — a BYO profile carries its own vendor key via Endpoint.token (AuroraOpts.token), and an
67
+ // endpoint with no explicit token gets NO auth on a public third-party host. This scope rule is the
68
+ // credential-leak guard for the BYO era.
69
+ function hostOf(base) {
70
+ try {
71
+ return new URL(base).hostname.toLowerCase();
72
+ }
73
+ catch {
74
+ return "";
75
+ }
76
+ }
77
+ function isOperatorTrustedHost(h) {
78
+ if (!h)
79
+ return false;
80
+ if (h === "axe.onl" || h.endsWith(".axe.onl"))
81
+ return true;
82
+ return /^(10\.|192\.168\.|127\.|localhost$|\[::1\]$)|^172\.(1[6-9]|2\d|3[01])\./.test(h) || h.endsWith(".local");
83
+ }
64
84
  // One operator identity per process. The node CLI sets this at boot from the keychain
65
85
  // (setOperatorToken); browser/JSCore hosts inject per-call via AuroraOpts.token or not at all.
66
86
  // A local :8097 never receives it (isRemoteBase gate), so it is safe to set unconditionally.
67
87
  let _operatorToken;
68
88
  export function setOperatorToken(token) { _operatorToken = token || undefined; }
69
- function authHeaders(o) {
70
- const token = o.token ?? _operatorToken;
71
- return token && isRemoteBase(o.base) ? { Authorization: `Bearer ${token}` } : {};
89
+ export function authHeaders(o) {
90
+ if (!isRemoteBase(o.base))
91
+ return {}; // a local server never gets any bearer — vendor or operator
92
+ const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
93
+ return token ? { Authorization: `Bearer ${token}` } : {};
72
94
  }
73
95
  // ---------------------------------------------------------------------------
74
96
  // Decode-time degeneration guard (SPEC §1). This is NOT a sampling penalty — it changes no
@@ -82,8 +104,8 @@ const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets,
82
104
  const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
83
105
  const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
84
106
  const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
85
- const RUNAWAY_CHARS = 260_000; // with 32K output tokens the model can legitimately produce ~130K chars;
86
- // 260K gives 2x headroom before cutting a decode loop or stream duplication.
107
+ const RUNAWAY_CHARS = 120_000; // a round is capped at max_tokens (~8k => ~33k chars); far past that is a
108
+ // decode loop or a stream/render duplication, never a real answer — hard stop.
87
109
  function hasAlpha(s) {
88
110
  return /[a-zA-Z]/.test(s);
89
111
  }
@@ -165,33 +187,38 @@ export function trimLoop(text) {
165
187
  return out.join("\n").trim();
166
188
  }
167
189
  function requestBody(messages, o, stream) {
190
+ // Transport dialect: llama.cpp-only fields ship ONLY to Aurora/fleet (default "llama"); a strict
191
+ // "openai" BYO gateway gets standard fields + its documented thinking knob. Third-party gateways
192
+ // can 400 on unknown keys — and silence on extras is not a contract we should bank on.
193
+ const llama = o.transport !== "openai";
168
194
  return JSON.stringify({
169
195
  model: o.model, messages, stream,
170
196
  // Ask the server for an exact usage report on the final SSE chunk. Without this, llama.cpp omits
171
197
  // `timings` on rounds that end in tool_calls (verified live), so the token meter under-counts a
172
198
  // tool-heavy turn to near-zero and falls back to the chars/4 estimate. include_usage yields exact
173
- // completion_tokens even on tool-call rounds (parsed via j.usage in streamDeltas).
199
+ // completion_tokens even on tool-call rounds (parsed via j.usage in streamDeltas). STANDARD field —
200
+ // ships on both dialects.
174
201
  ...(stream ? { stream_options: { include_usage: true } } : {}),
175
202
  // Reuse the server-side KV cache across requests (llama.cpp): a coding turn re-sends a GROWING prefix
176
203
  // (system + tools + history) every round, and cache-safe compaction re-sends the evicted span as an exact
177
204
  // PREFIX of the last live request. Without cache_prompt the single-slot server RE-PREFILLS that whole
178
205
  // prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
179
- // the server prefix-matches and prefills only the new tail. Harmless on servers that ignore the field.
180
- cache_prompt: true,
206
+ // the server prefix-matches and prefills only the new tail. llama dialect only.
207
+ ...(llama ? { cache_prompt: true } : {}),
181
208
  // GW-26 — ngram speculation is DEFAULT-ON in modern llama.cpp and a NET LOSS on the DeltaNet-hybrid
182
209
  // Aurora at untuned draft params: measured live on :8097 (b11146, ctx 307K), acceptance 3-17% and
183
210
  // 4-6 tok/s decode WITH it vs 20-25 tok/s WITHOUT — every rejected draft forces a multi-token
184
211
  // re-verify + recache on the hybrid. Shape verified live: {"speculative":{"ngram":{"enabled":false}}}
185
212
  // -> timings.draft_n drops to 0 and decode jumps 4x; a `{"type":"none"}` variant is silently IGNORED,
186
- // so keep this exact shape. Servers without llama.cpp speculation ignore the field (same contract
187
- // as cache_prompt). Escape hatch when a retuned/high-acceptance bless lands: enableSpeculation: true.
188
- ...(o.enableSpeculation ? {} : { speculative: { ngram: { enabled: false } } }),
189
- max_tokens: o.maxTokens ?? 32768, temperature: o.temperature ?? 0.7,
213
+ // so keep this exact shape. llama dialect only. Escape hatch when a retuned/high-acceptance bless
214
+ // lands: enableSpeculation: true.
215
+ ...(llama && !o.enableSpeculation ? { speculative: { ngram: { enabled: false } } } : {}),
216
+ max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
190
217
  ...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
191
218
  // /think: re-enable the model's native reasoning for THIS request, overriding the server's
192
219
  // enable_thinking:false default (set for speed). Verified this per-request override works on the
193
220
  // Aurora build; reasoning arrives as reasoning_content and renders dimmed.
194
- ...(o.thinking ? { chat_template_kwargs: { enable_thinking: true } } : {}),
221
+ ...(o.thinking ? (llama ? { chat_template_kwargs: { enable_thinking: true } } : { enable_thinking: true }) : {}),
195
222
  // NO repeat/presence/frequency penalty knobs — SPEC §1: they break tool-calling.
196
223
  });
197
224
  }
@@ -260,10 +287,42 @@ async function* streamDeltas(messages, o) {
260
287
  const reader = res.body.getReader();
261
288
  const dec = new TextDecoder();
262
289
  let buf = "";
290
+ // H1 (audit-engine §1, the CRITICAL): llama.cpp wedges — mid-decode a slot can stop emitting
291
+ // bytes FOREVER (observed shape of the 4-min-prompt incidents). No deadline here meant the turn
292
+ // hung esc-only while holding the process-wide endpoint slot: one wedged decode deadlocks every
293
+ // waiter behind it. Idle-gap catches the wedge fast (no bytes for idleMs => transient cancel —
294
+ // undefined status self-classifies as transient through the selfheal policy, so failover/backoff
295
+ // already own recovery); the wall-clock is the paranoia ceiling. KODE_STREAM_IDLE_MS=0 disables.
296
+ const idleMs = Number(process.env.KODE_STREAM_IDLE_MS ?? 90_000);
297
+ const wallMs = Number(process.env.KODE_REQUEST_TIMEOUT_MS ?? 30 * 60_000);
298
+ const startedAt = Date.now();
299
+ let lastByteAt = Date.now();
263
300
  // finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
264
301
  try {
265
302
  for (;;) {
266
- const { value, done } = await reader.read();
303
+ const idleLeft = idleMs > 0 ? idleMs - (Date.now() - lastByteAt) : Infinity;
304
+ const wallLeft = wallMs > 0 ? wallMs - (Date.now() - startedAt) : Infinity;
305
+ const budget = Math.min(idleLeft, wallLeft);
306
+ if (budget <= 0)
307
+ throw new Error("aurora stream stalled — deadline exceeded before read (decode wedged; transient)");
308
+ let timer;
309
+ let raced;
310
+ try {
311
+ raced = await Promise.race([
312
+ reader.read(),
313
+ new Promise((r) => { timer = setTimeout(() => r("timeout"), budget); }),
314
+ ]);
315
+ }
316
+ finally {
317
+ if (timer)
318
+ clearTimeout(timer);
319
+ }
320
+ if (raced === "timeout") {
321
+ void reader.cancel().catch(() => { });
322
+ throw new Error(`aurora stream stalled — no bytes within ${Math.round(budget / 1000)}s (decode wedged; transient)`);
323
+ }
324
+ const { value, done } = raced;
325
+ lastByteAt = Date.now();
267
326
  if (done)
268
327
  break;
269
328
  buf += dec.decode(value, { stream: true });
@@ -187,6 +187,126 @@ function dropLeadingOrphanTools(messages) {
187
187
  * Call this proactively when needsCompaction() is true, or directly (forced) on a 400 with
188
188
  * no bigger endpoint to route to (SPEC §4 self-heal) or on `/compact`.
189
189
  */
190
+ // ── GW-31 · CONTEXT SURGERY — deterministic anchors + verbatim user voice ─────────────────────────
191
+ // The summarizer's prompt already DEMANDS verbatim identifiers (the "load-bearing rule") and the
192
+ // 9-section contract asks for the user's own asks. Both are model-discretion promises — an honest
193
+ // one, but a promise is not a guarantee. These functions add the HARD backstop: mechanically
194
+ // extracted, model-independent, appended to every compaction. Rationale (measured this week):
195
+ // a lossy summarizer that mangles one SHA/flag/PR poisons the next 100 turns (and becomes a
196
+ // training-set corruption vector through the flywheel capture) — while re-prefilling the whole
197
+ // evicted span to "be safe" costs minutes at depth. Extraction costs microseconds. It also makes
198
+ // anchor LOSS AUDITABLE: anchorLossAudit() is the primitive the canary/flywheel gates use.
199
+ // Pure + browser-safe (no node imports) — compaction.ts must stay in the neutral engine bundle.
200
+ const ANCHOR_CATS = [
201
+ ["git-sha", /\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/g], // hex, >=7, needs a letter (kills bare-number false hits)
202
+ ["uuid", /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g],
203
+ ["issue-ref", /(?:\b[a-zA-Z0-9_.\/-]+)?#\d{1,7}\b/g], // PR/issue refs (repo-scoped form kept intact)
204
+ ["version", /\bv?\d+\.\d+\.\d+(?:[-+][\w.]+)?\b/g],
205
+ ["cli-flag", /(?:^|[\s,"'`])(--?[a-z][\w-]*(?:=[\S]{1,40})?)/g],
206
+ ["path", /(?:[\w.\-~]+\/)+[\w.\-]+(?:\.[A-Za-z]\w{0,9})?/g],
207
+ ["url", /\bhttps?:\/\/[^\s"'<>\])]+/g],
208
+ ["unit-number", /\b\d[\d,._]*\s?(?:tok\/s|tokens|ms|MB|GB|KB|K\b|%)(?=[\s,.;:)\]}"]|$)/gi],
209
+ ];
210
+ const ANCHOR_CAP_PER_CAT = 40; // each category's ceiling
211
+ const ANCHOR_CAP_TOTAL_CHARS = 2400; // the whole block's ceiling — bounded so fold costs stay trivial
212
+ function anchorSource(m) {
213
+ const parts = [];
214
+ if (typeof m.content === "string" && m.content)
215
+ parts.push(m.content);
216
+ const tcs = m.tool_calls;
217
+ for (const tc of tcs ?? [])
218
+ parts.push(`${tc.function?.name ?? ""} ${tc.function?.arguments ?? ""}`);
219
+ return parts.join("\n");
220
+ }
221
+ function extractAnchorsCapped(span, capPerCat) {
222
+ const out = new Map();
223
+ for (const [cat, re] of ANCHOR_CATS) {
224
+ const seen = new Set();
225
+ for (const m of span) {
226
+ const text = anchorSource(m);
227
+ if (!text)
228
+ continue;
229
+ re.lastIndex = 0;
230
+ let mm;
231
+ while ((mm = re.exec(text)) && seen.size < capPerCat) {
232
+ const v = (mm[1] ?? mm[0]).replace(/[,.;:]$/, "");
233
+ if (v.length > 100 || /^\/{2,}/.test(v) || v === "./" || v === "../")
234
+ continue;
235
+ seen.add(v);
236
+ }
237
+ }
238
+ if (seen.size)
239
+ out.set(cat, [...seen]);
240
+ }
241
+ return out;
242
+ }
243
+ /** Extract every high-value identifier from a message span, per category, first-seen order, soft-capped
244
+ * at ANCHOR_CAP_PER_CAT — the RENDER budget for the index block inside a summary. */
245
+ export function extractAnchors(span) {
246
+ return extractAnchorsCapped(span, ANCHOR_CAP_PER_CAT);
247
+ }
248
+ // The AUDIT view is 25x wider than the render view. The old coupling — audit sharing the render cap —
249
+ // made identifier-dense spans report a FALSE GREEN: everything past 40/category was invisible to both
250
+ // sides of the comparison. N1 (verified compaction): measure wide, render bounded, REPAIR the overflow.
251
+ const AUDIT_CAP_PER_CAT = 1000;
252
+ const REPAIR_CAP = 200;
253
+ /** Render the anchor index as a compact, labeled block ("" when nothing found). */
254
+ export function renderAnchorIndex(span) {
255
+ const cats = extractAnchors(span);
256
+ if (!cats.size)
257
+ return "";
258
+ let s = "";
259
+ for (const [cat, vals] of cats)
260
+ s += `<${cat}> ${vals.join(", ")}\n`;
261
+ if (s.length > ANCHOR_CAP_TOTAL_CHARS)
262
+ s = s.slice(0, ANCHOR_CAP_TOTAL_CHARS) + " [truncated]\n";
263
+ return "\n\nANCHORS (mechanically extracted — verbatim, model-independent):\n" + s;
264
+ }
265
+ /** The audit primitive: anchors present in `pre` but NOT in `post` — i.e. lost through compaction.
266
+ * [] = the transformation preserved every identifier. Used by tests, the update canary, and the
267
+ * flywheel integrity gate (a trajectory whose turn crossed compaction loses its anchor set). */
268
+ export function anchorLossAudit(pre, post) {
269
+ const postText = post.map(anchorSource).join("\n");
270
+ const missing = [];
271
+ for (const vals of extractAnchorsCapped(pre, AUDIT_CAP_PER_CAT).values())
272
+ for (const v of vals)
273
+ if (!postText.includes(v))
274
+ missing.push(v);
275
+ return missing;
276
+ }
277
+ /** N1 as a REUSABLE guarantee: audit the summary against the evicted span (WIDE view), force-append
278
+ * spilled anchors deterministically, report the honest residual. compact() calls it; session.ts's
279
+ * INSTANT (pre-written) compaction path calls it too — the fast path must not skip the safety net
280
+ * it exists to provide (audit-engine finding H2: the instant branch inserted the raw blob). */
281
+ export function applyAnchorVerification(summaryMsg, evicted, outAll) {
282
+ let missing = anchorLossAudit(evicted, outAll);
283
+ let repaired = 0;
284
+ if (missing.length) {
285
+ const carry = missing.slice(0, REPAIR_CAP);
286
+ repaired = carry.length;
287
+ summaryMsg.content += `\n\nANCHOR REPAIR (${missing.length} spilled past the index caps — verbatim): ${carry.join(", ")}`
288
+ + (missing.length > REPAIR_CAP ? ` [+${missing.length - REPAIR_CAP} uncarried — identifier-dense span; offload before training]` : "");
289
+ missing = anchorLossAudit(evicted, outAll);
290
+ }
291
+ return { repaired, residual: missing.length };
292
+ }
293
+ /** Verbatim user-voice: the FIRST user message (the original mission — the thing most often lost and
294
+ * most catastrophic to lose: instruction drift is how long autonomous runs go off rails, this week's
295
+ * 76-min Pando marathon is the cautionary tale) PLUS the last k user messages (current intent). Middle
296
+ * follow-ups are NOT duplicated here — the summarizer's FACTS/STATE already carries them; head+tail is
297
+ * exactly the shape frontier compaction uses (objective pinned at head, recency at tail) and keeps the
298
+ * block bounded regardless of span depth. */
299
+ export function verbatimUserTail(span, k = 3, capPerMsg = 400) {
300
+ const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0);
301
+ if (!users.length)
302
+ return "";
303
+ const head = users[0];
304
+ const tail = users.slice(-k);
305
+ const chosen = [...new Set([head, ...tail])]; // first + last k, deduped, in order (<=k+1 messages)
306
+ const lines = chosen.map((m) => `> ${m.content.replace(/\s+/g, " ").slice(0, capPerMsg)}`);
307
+ const label = chosen.length === 1 ? "original request" : `original + last ${chosen.length - 1} request(s)`;
308
+ return "\n\nUSER VOICE (verbatim, " + label + "):\n" + lines.join("\n");
309
+ }
190
310
  export async function compact(conversation, opts) {
191
311
  const minKeep = opts.minKeepTurns ?? 4;
192
312
  const starts = turnStarts(conversation);
@@ -216,9 +336,16 @@ export async function compact(conversation, opts) {
216
336
  // real history with a bare "[Compacted summary of N]" header. The caller retries; nothing is lost.
217
337
  if (!summaryText)
218
338
  return [...conversation];
339
+ // GW-31: the deterministic backstop rides with the model's note — identifiers and the user's own
340
+ // words are preserved by CODE, not by asking nicely. Dedup logic: the prompt rule stays (a good
341
+ // summary embeds specifics in prose); these blocks guarantee nothing critical was dropped.
219
342
  const summaryMsg = {
220
343
  role: "user", // never a 2nd system message — SPEC §1/§5
221
- content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}`,
344
+ content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
222
345
  };
223
- return [summaryMsg, ...kept];
346
+ // N1 VERIFIED COMPACTION: proof-of-preservation rides with the summary (shared helper now — the
347
+ // instant/prewritten path in session.ts MUST get the same guarantee, audit-engine §2).
348
+ const outAll = [summaryMsg, ...kept];
349
+ opts.onVerification?.(applyAnchorVerification(summaryMsg, evicted, outAll));
350
+ return outAll;
224
351
  }