@0perator/operator 0.1.359-next.0 → 0.1.360-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dashboard/index.html +2 -2
  2. package/dist/autonomy/cloud-agent.js +2 -2
  3. package/dist/autonomy/headless.js +15 -6
  4. package/dist/autonomy/session-factory.js +2 -1
  5. package/dist/background/notices.js +1 -1
  6. package/dist/browser/session.js +7 -0
  7. package/dist/cli.js +94 -52
  8. package/dist/config/features.js +6 -5
  9. package/dist/config/persona.js +57 -40
  10. package/dist/config/settings.js +39 -55
  11. package/dist/engine/agent.js +72 -33
  12. package/dist/engine/aurora.js +24 -2
  13. package/dist/engine/compaction.js +27 -7
  14. package/dist/engine/decision-points.js +16 -4
  15. package/dist/engine/kv-slot.js +87 -0
  16. package/dist/engine/loop-guard.js +49 -18
  17. package/dist/engine/messages.js +8 -1
  18. package/dist/engine/progress-deadline.js +37 -0
  19. package/dist/engine/verify-gate.js +134 -9
  20. package/dist/enterprise/cli.js +13 -1
  21. package/dist/mcp/craft-server.js +5 -3
  22. package/dist/memory/live-progress.js +35 -6
  23. package/dist/permissions/policy.js +8 -0
  24. package/dist/permissions/signature.js +9 -0
  25. package/dist/products/artifact-library.js +47 -0
  26. package/dist/products/craft.js +58 -94
  27. package/dist/products/temple.js +230 -0
  28. package/dist/remote/host.js +28 -1
  29. package/dist/router/discovery.js +23 -6
  30. package/dist/router/models.js +29 -70
  31. package/dist/services/preflight.js +3 -41
  32. package/dist/session.js +121 -38
  33. package/dist/skills/catalogue.js +2 -0
  34. package/dist/skills/finder.js +1 -1
  35. package/dist/tools/background-result.js +26 -0
  36. package/dist/tools/chauffeur-native.js +6 -0
  37. package/dist/tools/craft.js +17 -6
  38. package/dist/tools/deferred.js +64 -30
  39. package/dist/tools/executor.js +4 -2
  40. package/dist/tools/paths.js +3 -3
  41. package/dist/tools/read-ledger.js +44 -0
  42. package/dist/tools/registry.js +218 -264
  43. package/dist/tools/sandbox.js +52 -39
  44. package/dist/tools/shell-context.js +5 -0
  45. package/dist/tools/shell-session.js +61 -29
  46. package/dist/tools/vision-gateway.js +79 -34
  47. package/dist/tools/wave-tools.js +2 -2
  48. package/dist/tools/wave2-tools.js +6 -6
  49. package/dist/ui/ArtifactPicker.js +2 -2
  50. package/dist/ui/Composer.js +9 -2
  51. package/dist/ui/StatusRule.js +1 -1
  52. package/dist/ui/modelPicker.js +1 -1
  53. package/dist/ui/nextStep.js +1 -0
  54. package/dist/ui/pending.js +10 -0
  55. package/dist/update.js +78 -4
  56. package/dist/util/retry.js +34 -0
  57. package/dist/util/slash.js +2 -1
  58. package/dist/vault/tool.js +3 -1
  59. package/mcp/powertools-toolbox.mjs +166 -1
  60. package/package.json +9 -13
  61. package/dashboard/README.md +0 -62
  62. package/dist/compose/client.js +0 -56
  63. package/mcp/README.md +0 -88
  64. package/mcp/powertools.md +0 -210
@@ -10,7 +10,7 @@ import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampM
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
11
  import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
12
  import { hostOf } from "./net-error.js";
13
- import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder, pendingVerifyCriterion } from "./verify-gate.js";
13
+ import { TaskVerification, VERIFY_REMINDER, backgroundCheckReminder, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder, pendingVerifyCriterion, failedCheckReminder, failedCheckBanner } from "./verify-gate.js";
14
14
  import { isFeatureEnabled } from "../config/features.js";
15
15
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
16
16
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
@@ -30,7 +30,7 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
30
30
  // file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
31
31
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
32
32
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
33
- import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
33
+ import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision, unwrapToolCall } from "./decision-points.js";
34
34
  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
35
35
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
36
36
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
@@ -250,15 +250,16 @@ function batchProgressed(toolMsgs) {
250
250
  /** Feed one settled tool batch to the verify-before-done ledger: zip each call's name + (parsed)
251
251
  * `command` arg with its result string (index-aligned — runToolCalls preserves call order). */
252
252
  function observeVerify(v, calls, toolMsgs) {
253
- const names = calls.map((c) => c.function.name);
254
- const commands = calls.map((c) => {
253
+ const real = calls.map((c) => {
255
254
  try {
256
- return String(JSON.parse(c.function.arguments || "{}").command ?? "");
255
+ return unwrapToolCall(c.function.name, JSON.parse(c.function.arguments || "{}"));
257
256
  }
258
257
  catch {
259
- return "";
258
+ return { name: c.function.name, args: {} };
260
259
  }
261
260
  });
261
+ const names = real.map((r) => r.name);
262
+ const commands = real.map((r) => String(r.args.command ?? ""));
262
263
  const results = toolMsgs.map((m) => m.content || "");
263
264
  v.observe(names, commands, results);
264
265
  }
@@ -711,7 +712,7 @@ export async function runTurn(userInput, conversation, opts) {
711
712
  const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
712
713
  const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
713
714
  const yieldGuard = guardCfg.enabled ? new YieldAfterDispatchGuard(undefined, undefined, (opts.liveSubAgents?.() ?? 0) > 0) : undefined; // after spawn_agent (or from round one of a wake turn with sub-agents live): non-mutating rounds are waiting-with-busywork — yield so the reports resume the turn
714
- const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
715
+ const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite) : undefined; // investigate-loop detector — mode-gated hard stop (FIX 2); the attended read-only-loop backstop is the LoopGuard terminal (FIX 1)
715
716
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
716
717
  // Loop reset (loop-guard.ts "Loop evidence"): every loop-family nudge is counted; the Nth one the model has seen and
717
718
  // answered with no landed write since, while the turn repeats itself (a warning ignored), is not injected — before
@@ -745,16 +746,27 @@ export async function runTurn(userInput, conversation, opts) {
745
746
  let budgetWarned = false; // the one-time "near the time budget, converge" warning fires before the hard wall-clock stop
746
747
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
747
748
  let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
748
- let ceilingSummaryFailed; // a ceiling-only compaction's summarizer failed this turn — don't re-pay it every round
749
+ // The summarizer's last failure this turn, and how it is not re-paid every round (a failure can cost a whole idle
750
+ // window): a ceiling-only trigger never asks again; an over-window one sits out 1, 2, 4… gate trips between asks.
751
+ let summaryFailed = {};
752
+ let summaryFailures = 0;
753
+ let summarySitOut = 0;
749
754
  let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
750
755
  // Verify-before-done: a turn-local ledger of "changed files but never ran a passing check" (computed
751
756
  // from observed tool execution, never self-reported). At the done-exit it injects ONE reminder to run
752
757
  // the check; if the model still doesn't, the answer is finalized with an honest "not verified" banner.
753
758
  const verify = new TaskVerification();
754
759
  const verifyEnabled = opts.verifyGate?.enabled !== false;
755
- const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
760
+ // FIX 3: in UNATTENDED (headless/autonomous) runs the verify gate is a HARD precondition — a mutating turn
761
+ // loops back (re-injecting the reminder) until a STRONG check (test/build/typecheck/run) ran, not merely an
762
+ // allowlisted command like `npm ls`. Bounded by verifyMaxNudges so it never hangs: after the budget the turn
763
+ // ends with the honest "not verified" banner (the owner's "nothing runnable" escape is preserved). Attended
764
+ // runs keep the one-shot advisory nudge (default 1). Override: verifyGate.maxNudges / verifyGate.enabled:false.
765
+ const verifyHard = opts.unattended === true;
766
+ const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? (verifyHard ? 3 : 1));
756
767
  let verifyNudges = 0;
757
- let unrunNudged = false; // the reported-check reminder fires at most once per turn
768
+ let unrunNudges = 0; // the reported-check reminder: once (attended), up to verifyMaxNudges (unattended hard precondition)
769
+ let failedNudges = 0; // the failed-check reminder: a failing check the answer does not own up to
758
770
  // The method ladder's completion criterion (verify-gate.ts): the pending check for a turn that changed files but has
759
771
  // not passed one, named to the model as the "done" fact. undefined when nothing is pending — the ladder then uses its
760
772
  // own generic wording. Read fresh at each halt (it tracks the turn's verify state and the model's own narration).
@@ -792,7 +804,8 @@ export async function runTurn(userInput, conversation, opts) {
792
804
  const decisionGate = opts.decisionPoints?.enabled === true && hasAskTool;
793
805
  const buildTurn = decisionGate && isBuildRequest(opts.ownerText ?? userInput);
794
806
  let askedThisTurn = false; // ask_user ran this turn — the owner already chose a direction
795
- let decisionNudged = false; // the decision-point hold fires at most once per turn
807
+ let decisionHolds = 0; // the decision-point hold RE-FIRES every mutating round (FIX 4) until ask_user runs, bounded by decisionMaxHolds
808
+ const decisionMaxHolds = Math.max(1, opts.decisionPoints?.maxHolds ?? 3); // ceiling so a model that never asks still proceeds — tunable, not a trap
796
809
  const decisionNudge = opts.decisionPoints?.planReview === true ? PLAN_REVIEW_NUDGE : DECISION_POINT_NUDGE; // Autonomous: a plan review replaces the options
797
810
  let repliesSinceOwner = 0; // non-empty model replies since the owner last spoke (turn start, or an ask_user answer) — the first is never self-dialogue
798
811
  let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
@@ -1191,19 +1204,26 @@ export async function runTurn(userInput, conversation, opts) {
1191
1204
  // turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
1192
1205
  // so a request is NEVER dispatched over the current endpoint's window. Layer-3 backstop; Layer 1
1193
1206
  // (servedContextLimit, in the catch below) keeps that window itself honest after a learned n_ctx.
1194
- // Once a summarizer failed on a ceiling-only trigger, later rounds of this turn only shed tool outputs:
1195
- // the over-window case always retries, a soft speed ceiling must not add a failing request per round.
1207
+ // Once a summarizer failed, later rounds of this turn only shed tool outputs: a soft speed ceiling never asks
1208
+ // again, the over-window case asks again after sitting out 1, 2, 4… trips (the circuit breaker below still
1209
+ // stops a turn that stays over the window).
1196
1210
  const beforeLen = conversation.all.length;
1197
1211
  const before = fullRequestEstimate(conversation.all, cOpts);
1198
1212
  const overWindow = needsCompaction(conversation.all, cOpts);
1199
- let skipped = overWindow ? undefined : ceilingSummaryFailed;
1200
- const evicted = skipped ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } }, before);
1201
- if (!overWindow)
1202
- ceilingSummaryFailed = skipped;
1213
+ const sitOut = summaryFailed.skipped !== undefined && (!overWindow || summarySitOut-- > 0);
1214
+ let skip = sitOut ? summaryFailed : {};
1215
+ const evicted = sitOut ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (skipped, detail) => { skip = { skipped, detail }; } }, before);
1216
+ if (!sitOut) {
1217
+ summaryFailed = skip;
1218
+ if (skip.skipped)
1219
+ summarySitOut = 2 ** summaryFailures++;
1220
+ else
1221
+ summaryFailures = 0;
1222
+ }
1203
1223
  conversation.replaceAll(fitToWindow(evicted, cOpts));
1204
1224
  const after = fullRequestEstimate(conversation.all, cOpts);
1205
- if (skipped || after < before)
1206
- opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), skipped });
1225
+ if (skip.skipped || after < before)
1226
+ opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), ...skip });
1207
1227
  // Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
1208
1228
  // model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
1209
1229
  if (conversation.all.length < beforeLen && !resetNow)
@@ -1269,6 +1289,7 @@ export async function runTurn(userInput, conversation, opts) {
1269
1289
  thinking: (truncatedThisTurn || thinkLatched) ? false : thinkingNow(), // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
1270
1290
  signal: watch.signal,
1271
1291
  background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
1292
+ ...opts.affinity?.(endpoint),
1272
1293
  onDelta: watch.onDelta,
1273
1294
  onReasoning: watch.onReasoning,
1274
1295
  onServed: opts.onServed,
@@ -1505,6 +1526,7 @@ export async function runTurn(userInput, conversation, opts) {
1505
1526
  thinking: (truncatedThisTurn || thinkLatched) ? false : thinkingNow(), // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
1506
1527
  signal: opts.signal,
1507
1528
  background: opts.background,
1529
+ ...opts.affinity?.(endpoint),
1508
1530
  onDelta: opts.onDelta,
1509
1531
  onReasoning: opts.onReasoning,
1510
1532
  onServed: opts.onServed,
@@ -1671,8 +1693,8 @@ export async function runTurn(userInput, conversation, opts) {
1671
1693
  // Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
1672
1694
  // gets a plan + options (ask_user), or in Autonomous mode a plan review, instead of a silently picked approach.
1673
1695
  // This round's calls are not dispatched.
1674
- if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1675
- decisionNudged = true;
1696
+ if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, holds: decisionHolds, maxHolds: decisionMaxHolds, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1697
+ decisionHolds++;
1676
1698
  if (response.content.trim())
1677
1699
  conversation.assistant(cleanAssistantProse(response.content));
1678
1700
  engineUser(decisionNudge);
@@ -1810,8 +1832,8 @@ export async function runTurn(userInput, conversation, opts) {
1810
1832
  if (fromReasoning.calls.length > 0)
1811
1833
  recovered = { ...recovered, calls: fromReasoning.calls };
1812
1834
  }
1813
- if (recovered.calls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: recovered.calls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1814
- decisionNudged = true;
1835
+ if (recovered.calls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, holds: decisionHolds, maxHolds: decisionMaxHolds, calls: recovered.calls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1836
+ decisionHolds++;
1815
1837
  if (recovered.cleanedContent.trim())
1816
1838
  conversation.assistant(recovered.cleanedContent);
1817
1839
  engineUser(decisionNudge);
@@ -2016,22 +2038,39 @@ export async function runTurn(userInput, conversation, opts) {
2016
2038
  // warning above applies only to an EMPTY round; here real content + tool results exist, so the reminder
2017
2039
  // is answered as the intended verify step, not mistaken for the request. Capped (verifyMaxNudges) →
2018
2040
  // ≤1 extra round, the main-loop mirror of grandmaster's single repair round.
2019
- if (verifyEnabled && final && !isEngineFinal(final) && verify.gate() && verifyNudges < verifyMaxNudges) {
2041
+ // The gate: advisory `verify.gate()` for attended runs; the ENFORCED `verify.gateStrong()` for unattended, so
2042
+ // an allowlisted-but-empty command (`npm ls`) can't clear it. Unattended loops back up to verifyMaxNudges (a
2043
+ // hard precondition); attended is the one-shot advisory nudge. Either way bounded → never hangs.
2044
+ const changedNotVerified = verifyHard ? verify.gateStrong() : verify.gate();
2045
+ if (verifyEnabled && final && !isEngineFinal(final) && changedNotVerified && verifyNudges < verifyMaxNudges) {
2020
2046
  verifyNudges++;
2021
2047
  conversation.assistant(final);
2022
- engineUser(VERIFY_REMINDER);
2048
+ const jobId = verify.backgroundCheck();
2049
+ engineUser(jobId ? backgroundCheckReminder(jobId) : VERIFY_REMINDER);
2023
2050
  continue;
2024
2051
  }
2025
2052
  // Reported-check gate: an answer that reports a clean type-check or passing tests, in a turn that did work but never ran
2026
- // that check, gets ONE reminder to run it (11/02: "✅ No TypeScript errors" after vite builds, tsc never run).
2027
- // only a turn that changed files owes its reported checks: a read-only turn reporting CI or a log is quoting it
2028
- const unrunChecks = verifyEnabled && final && !isEngineFinal(final) && toolCallTotal > 0 && verify.changedFiles() ? verify.unrun(final) : [];
2029
- if (unrunChecks.length && !unrunNudged) {
2030
- unrunNudged = true;
2053
+ // that check, gets a reminder to run it (11/02: "✅ No TypeScript errors" after vite builds, tsc never run).
2054
+ // Attended: only a turn that CHANGED files owes its reported checks (a read-only turn quoting CI/logs is fine).
2055
+ // Unattended (FIX 3): extended to read-only turns that ASSERT a check — a headless run that claims "tests pass"
2056
+ // without running them is gated too. Bounded by verifyMaxNudges, then the banner (never a blanket free pass).
2057
+ const unrunGateApplies = verifyEnabled && final && !isEngineFinal(final) && toolCallTotal > 0 && (verify.changedFiles() || verifyHard);
2058
+ const unrunChecks = unrunGateApplies ? verify.unrun(final) : [];
2059
+ if (unrunChecks.length && unrunNudges < verifyMaxNudges) {
2060
+ unrunNudges++;
2031
2061
  conversation.assistant(final);
2032
2062
  engineUser(unrunCheckReminder(unrunChecks));
2033
2063
  continue;
2034
2064
  }
2065
+ // Failed-check gate: a check whose latest run this turn failed, and an answer that never says so or explains it away
2066
+ // ("expected", "normal") — 11/23: tests run from ~ hit "no package.json" and the answer called the task complete.
2067
+ const failedChecks = verifyEnabled && final && !isEngineFinal(final) ? verify.unreportedFailures(final) : [];
2068
+ if (failedChecks.length && failedNudges < verifyMaxNudges) {
2069
+ failedNudges++;
2070
+ conversation.assistant(final);
2071
+ engineUser(failedCheckReminder(failedChecks));
2072
+ continue;
2073
+ }
2035
2074
  // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
2036
2075
  // one nudge to continue or to close with a status line per item and ONE steering question.
2037
2076
  if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
@@ -2051,8 +2090,8 @@ export async function runTurn(userInput, conversation, opts) {
2051
2090
  engineUser(DELIVER_FINDINGS_NUDGE);
2052
2091
  continue;
2053
2092
  }
2054
- const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
2055
- const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : "") +
2093
+ const unverified = verifyEnabled && (verifyHard ? verify.gateStrong() : verify.gate()); // changed files, still no (strong) check after the nudge budget
2094
+ const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : failedChecks.length ? failedCheckBanner(failedChecks) : "") +
2056
2095
  (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
2057
2096
  "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)");
2058
2097
  fallbackLanded(); // an answer from the fallback's reasoning channel
@@ -2062,7 +2101,7 @@ export async function runTurn(userInput, conversation, opts) {
2062
2101
  if (final && !isEngineFinal(final))
2063
2102
  proceeded([], final);
2064
2103
  const display = final ? undefined : stopQuestion(answer, opts.preservedState?.()); // the engine's own empty/length status, said plainly
2065
- return { content: answer, display, stopKind: display ? stopKind(answer) : undefined, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || unrunChecks.length > 0 || undefined, loop: loopEv.evidence() };
2104
+ return { content: answer, display, stopKind: display ? stopKind(answer) : undefined, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || unrunChecks.length > 0 || failedChecks.length > 0 || undefined, loop: loopEv.evidence() };
2066
2105
  }
2067
2106
  const timeoutMsg = `[stopped after ${rounds} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
2068
2107
  return stopTurn(timeoutMsg, rounds);
@@ -75,7 +75,7 @@ export function endpointGateStatus() {
75
75
  // A remote engine (api.axe.onl) fronts the model with gateway auth; a local :8097 does not. Only a
76
76
  // non-loopback base needs (and should ever receive) the operator bearer, so a token is never sent to
77
77
  // a local llama-server and the header is omitted entirely when there is nothing to send.
78
- function isRemoteBase(base) {
78
+ export function isRemoteBase(base) {
79
79
  return !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(base);
80
80
  }
81
81
  // Owner-trusted fallback scope for the OPERATOR bearer: AXE's own hosts (api.axe.onl gateway) and
@@ -124,6 +124,12 @@ export function getOperatorToken() { return _operatorToken; }
124
124
  /** Whether the operator bearer may be sent to `url` (same scope rule authHeaders applies to a model base, minus the
125
125
  * loopback exclusion: an ingest on a loopback AuthGate is exactly where the bearer is required). */
126
126
  export function operatorTrustedUrl(url) { return isOperatorTrustedHost(hostOf(url)); }
127
+ /** Names the conversation a request belongs to, for a router or gateway in front of llama.cpp: opaque, stable for the
128
+ * session, shared by its summarizer, different for each sub-agent. The router leases a slot per value. */
129
+ export const SESSION_HEADER = "x-0perator-session";
130
+ /** Sent with SESSION_HEADER: `interactive` for the owner's own turns and their summarizer, `background` for a sub-agent
131
+ * or a headless run. The router never lets a background lease evict an interactive one. */
132
+ export const SESSION_ROLE_HEADER = "x-0perator-session-role";
127
133
  export function authHeaders(o) {
128
134
  if (!isRemoteBase(o.base)) {
129
135
  // A local llama-server normally gets no bearer. The one exception is the local gateway (server.json),
@@ -296,6 +302,7 @@ export function requestBody(messages, o, stream) {
296
302
  // prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
297
303
  // the server prefix-matches and prefills only the new tail. llama dialect (and our own gateway).
298
304
  ...(cacheKnobs ? { cache_prompt: true } : {}),
305
+ ...(cacheKnobs && o.slot !== undefined ? { id_slot: o.slot } : {}), // the conversation's own slot (engine/kv-slot.ts)
299
306
  // Prefill progress (llama.cpp return_progress): the server sends NOTHING while it reads the prompt, so a
300
307
  // cold re-read of a long session (159K tokens after a restart: minutes) looked like a wedged decode to the
301
308
  // idle-gap deadline below and was cancelled as "stalled" on every retry. Progress chunks keep the stream
@@ -347,7 +354,7 @@ async function fetchChat(o, body) {
347
354
  try {
348
355
  return await fetch(chatUrl(o.base, o.chatPath), {
349
356
  method: "POST",
350
- headers: { "Content-Type": "application/json", ...authHeaders(o) },
357
+ headers: { "Content-Type": "application/json", ...authHeaders(o), ...(o.session ? { [SESSION_HEADER]: o.session, ...(o.sessionRole ? { [SESSION_ROLE_HEADER]: o.sessionRole } : {}) } : {}) },
351
358
  body,
352
359
  signal: o.signal, // SPEC §9 interrupt handling: tears down the in-flight stream on abort, not at the next loop boundary
353
360
  });
@@ -771,3 +778,18 @@ export async function reachable(base, timeoutMs = 3000) {
771
778
  return false;
772
779
  }
773
780
  }
781
+ /** True as soon as one base answers `reachable`. The boot gate asks this about the legs AFTER the primary: a machine
782
+ * with no local model (a tester's laptop) still has the cloud tier, and the router falls through to it on the first
783
+ * turn, so refusing to start there was wrong (0.1.359: "Can't reach Operator … launchctl kickstart" on Linux). */
784
+ export function anyReachable(bases, timeoutMs = 3000) {
785
+ const targets = bases.filter(Boolean);
786
+ if (!targets.length)
787
+ return Promise.resolve(false);
788
+ return new Promise((resolve) => {
789
+ let left = targets.length;
790
+ const miss = () => { if (--left === 0)
791
+ resolve(false); };
792
+ for (const base of targets)
793
+ reachable(base, timeoutMs).then((ok) => (ok ? resolve(true) : miss()), miss);
794
+ });
795
+ }
@@ -96,8 +96,28 @@ export function usageRatio(conversation, opts) {
96
96
  return 0;
97
97
  return fullRequestEstimate(conversation, opts) / opts.ctxWindow;
98
98
  }
99
+ // What a request at the trigger must still leave free in the window, in tokens. The larger of two needs:
100
+ // the reply TOOL_CALL_HEADROOM_TOKENS 4096 + 256 template margin = 4,352
101
+ // the summarize call system + tools + span (≤ the request that tripped the trigger) + the instruction
102
+ // (SUMMARY_INSTRUCTION, ~1.8K chars ≈ 450 tokens, taken as 768) + its output (the largest
103
+ // max_tokens a host sends: 8000 for a thinking summarizer) + 256 template margin = 9,024
104
+ export const TRIGGER_RESERVE_TOKENS = 9_024;
105
+ const DEFAULT_THRESHOLD = 0.92;
106
+ // A window too small for the reserve keeps the ratio it always had: 9,024 would leave an 8K model nothing, and a
107
+ // model under the lean-harness line has its summary written by a larger one, so only the reply has to fit.
108
+ const MIN_DEFAULT_THRESHOLD = 0.7;
109
+ /** The proactive trigger when the owner set none: 0.92 of the SERVED window, lowered to the largest ratio that still
110
+ * leaves TRIGGER_RESERVE_TOKENS free, never under 0.7. (window − 9,024) / window reaches 0.92 at 112,800 tokens and
111
+ * 0.7 at 30,080: 8,192 → 0.70 (5,734) · 32,768 → 0.72 (23,744) · 131,072 → 0.92 (120,586) · 262,144 → 0.92
112
+ * (241,172) · 1,048,576 → 0.92 (964,689). */
113
+ export function defaultThreshold(ctxWindow) {
114
+ if (ctxWindow <= 0)
115
+ return DEFAULT_THRESHOLD;
116
+ return Math.max(MIN_DEFAULT_THRESHOLD, Math.min(DEFAULT_THRESHOLD, (ctxWindow - TRIGGER_RESERVE_TOKENS) / ctxWindow));
117
+ }
118
+ const triggerRatio = (opts) => opts.threshold ?? defaultThreshold(opts.ctxWindow);
99
119
  export function needsCompaction(conversation, opts) {
100
- return usageRatio(conversation, opts) >= (opts.threshold ?? 0.7);
120
+ return usageRatio(conversation, opts) >= triggerRatio(opts);
101
121
  }
102
122
  /** The part of every request compaction can never shrink: the system prompt + tool schemas, measured on the same
103
123
  * basis as fullRequestEstimate (calibrated per endpoint when metered). 0 when neither is set. */
@@ -109,7 +129,7 @@ export function fixedRequestTokens(opts) {
109
129
  // The conversation always gets at least min(ceiling, this) tokens above the fixed part. 2026-10-30: the fixed part
110
130
  // alone (≈12.8K system + ≈18.2K for 102 tool schemas) was over the 24K interactive ceiling, so the ceiling could
111
131
  // never be met — the gate fired every round and compaction evicted to the last 4 turns, which still held every big
112
- // tool output (session 512d2b4f sat at 110-125K). The interactive default's 24K becomes the conversation's budget.
132
+ // tool output (session 512d2b4f sat at 110-125K). That old default's 24K stays the conversation's minimum budget under an owner-set ceiling.
113
133
  const MIN_CONVERSATION_TOKENS = 24_000;
114
134
  // Hysteresis: a ceiling-triggered compaction sheds down to this fraction of the conversation budget, not just under
115
135
  // the line — every compaction rewrites history and resets the server's prompt cache, so it must not run every round.
@@ -148,7 +168,7 @@ export function compactionAction(conversation, opts) {
148
168
  if (!shouldProactivelyCompact(conversation, opts))
149
169
  return "none";
150
170
  const est = fullRequestEstimate(conversation, opts);
151
- const hardLimit = opts.ctxWindow * (opts.threshold ?? 0.7);
171
+ const hardLimit = opts.ctxWindow * triggerRatio(opts);
152
172
  if (est >= hardLimit)
153
173
  return "compact";
154
174
  const target = ceilingTargetTokens(opts);
@@ -173,10 +193,10 @@ export function compactionAction(conversation, opts) {
173
193
  * possible request rather than a guaranteed-fatal one.
174
194
  * Without an explicit `targetRatio` it then sheds on to the ceiling's hysteresis target (ceilingTargetTokens) when
175
195
  * `ceilingTokens` is set — the bulk of a long interactive session lives in the kept turns, and the window ratio alone
176
- * (0.7 of 262K) never touched it. That soft pass leaves the trailing tool results alone: the model has not read
196
+ * (0.92 of 262K) never touched it. That soft pass leaves the trailing tool results alone: the model has not read
177
197
  * them yet, and they are shed on the next compaction once it has. */
178
198
  export function fitToWindow(conversation, opts, targetRatio) {
179
- const hard = opts.ctxWindow > 0 ? opts.ctxWindow * (targetRatio ?? opts.threshold ?? 0.7) : Infinity;
199
+ const hard = opts.ctxWindow > 0 ? opts.ctxWindow * (targetRatio ?? triggerRatio(opts)) : Infinity;
180
200
  const soft = targetRatio === undefined ? ceilingTargetTokens(opts) : undefined;
181
201
  const target = soft !== undefined ? Math.min(hard, soft) : hard;
182
202
  if (fullRequestEstimate(conversation, opts) < target)
@@ -435,8 +455,8 @@ export async function compact(conversation, opts) {
435
455
  try {
436
456
  summaryText = (await opts.summarize(evicted)).trim();
437
457
  }
438
- catch {
439
- opts.onSkip?.("summarizer_error");
458
+ catch (e) {
459
+ opts.onSkip?.("summarizer_error", e instanceof Error ? e.message : undefined);
440
460
  return [...conversation];
441
461
  }
442
462
  // Never destroy the evicted span behind an EMPTY summary. If the summarizer produced nothing (e.g.
@@ -18,6 +18,13 @@ const MUTATING_SHELL_RE = new RegExp([
18
18
  String.raw `\bgit\s+(?:init|add|commit|checkout|switch|apply|reset|merge|rebase|stash|mv|rm)\b`,
19
19
  String.raw `(?:^|[^<>&0-9])>{1,2}\s*(?!&|/dev/null)[^\s>]`,
20
20
  ].join("|"));
21
+ /** The call a `tool_call` wrapper stands for (deferredTools); any other call as it is. */
22
+ export function unwrapToolCall(name, args) {
23
+ if (name !== "tool_call")
24
+ return { name, args };
25
+ const inner = args.args;
26
+ return { name: String(args.name ?? ""), args: inner && typeof inner === "object" && !Array.isArray(inner) ? inner : {} };
27
+ }
21
28
  /** True when a tool call changes the workspace: a file write/edit, a mutating shell command, or a git write. */
22
29
  export function isMutatingCall(name, rawArgs) {
23
30
  if (isMutatingTool(name))
@@ -29,8 +36,10 @@ export function isMutatingCall(name, rawArgs) {
29
36
  args = JSON.parse(rawArgs || "{}");
30
37
  }
31
38
  catch { /* partial args: treat as text */ }
32
- if (name === "tool_call")
33
- return isMutatingCall(String(args.name ?? ""), JSON.stringify(args.args ?? {})); // deferredTools
39
+ if (name === "tool_call") {
40
+ const real = unwrapToolCall(name, args);
41
+ return isMutatingCall(real.name, JSON.stringify(real.args));
42
+ }
34
43
  if (name === "git_command") {
35
44
  const cmd = String(args.command ?? args.args ?? rawArgs ?? "");
36
45
  return !/^\s*(?:git\s+)?(?:status|log|diff|show|branch|remote|rev-parse|blame|ls-files)\b/.test(cmd);
@@ -76,9 +85,12 @@ export function decisionPointsEnabled(setting, env = process.env) {
76
85
  return true;
77
86
  return setting !== false;
78
87
  }
79
- /** The gate's per-turn decision: hold back this round's calls once and nudge, or let them run. */
88
+ /** The gate's per-turn decision: hold back this round's mutating calls and nudge, or let them run. The hold is
89
+ * ENFORCED, not one-shot — it KEEPS holding every mutating round (re-injecting the nudge) until the model
90
+ * actually calls ask_user (`askedThisTurn`), so a model cannot just walk past a single nudge. Bounded by
91
+ * `maxHolds` so a model that never asks still proceeds (the hold is tunable, not a trap). */
80
92
  export function shouldHoldForDecision(s) {
81
- if (!s.enabled || !s.buildTurn || s.askedThisTurn || s.nudged)
93
+ if (!s.enabled || !s.buildTurn || s.askedThisTurn || s.holds >= s.maxHolds)
82
94
  return false;
83
95
  if (s.calls.some((c) => c.name === "ask_user"))
84
96
  return false;
@@ -0,0 +1,87 @@
1
+ // A conversation keeps one llama.cpp slot (`id_slot`) per endpoint, so its live turn, its compaction summarize and
2
+ // its rolling summary read the same KV cache. Left to itself the server puts a short request that shares only the
3
+ // fixed prefix (tools + system prompt) on the slot holding a long conversation and truncates it to that prefix
4
+ // (_ai-docs/decisions/2026-11-24-a-conversation-keeps-its-slot.md).
5
+ //
6
+ // Only for a llama-server on this machine reached directly: its clients are the Operator processes here, so a claim
7
+ // is a lease file they all see. A router or gateway has clients elsewhere and leases slots itself (it is sent the
8
+ // session id instead, aurora.ts SESSION_HEADER).
9
+ //
10
+ // A claim is a lease file: `<endpoint hash>.<slot>`
11
+ // holding the claimant's pid, created exclusively. The owner's interactive session takes the lowest free slot; every
12
+ // other conversation (a headless run, a sub-agent) takes the highest, so automation meets the owner last. With none
13
+ // free the highest slot is shared. A lease whose process is gone is taken over.
14
+ import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
15
+ import { createHash } from "node:crypto";
16
+ import { join } from "node:path";
17
+ import { operatorPath } from "../config/home.js";
18
+ const held = new Set();
19
+ function alive(pid) {
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ }
24
+ catch (e) {
25
+ return e.code === "EPERM";
26
+ }
27
+ }
28
+ function take(file) {
29
+ for (let attempt = 0; attempt < 2; attempt++) {
30
+ try {
31
+ const fd = openSync(file, "wx");
32
+ try {
33
+ writeSync(fd, String(process.pid));
34
+ }
35
+ finally {
36
+ closeSync(fd);
37
+ }
38
+ return true;
39
+ }
40
+ catch (e) {
41
+ if (e.code !== "EEXIST")
42
+ throw e;
43
+ const pid = Number(readFileSync(file, "utf8")); // an empty file is a claim being written: pid 0 reads as alive
44
+ if (pid === process.pid ? held.has(file) : alive(pid))
45
+ return false;
46
+ unlinkSync(file);
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+ const leaseFile = (endpoint, slot, dir) => join(dir, `${createHash("sha1").update(endpoint).digest("hex").slice(0, 16)}.${slot}`);
52
+ /** Claim a slot on `endpoint` (one of `slots`) for a conversation's lifetime. Never throws: where the lease directory
53
+ * cannot be written the slot is the first choice, unleased. */
54
+ export function claimSlot(endpoint, slots, interactive, dir = operatorPath("runtime", "kv-slots")) {
55
+ const n = Math.max(1, Math.floor(slots) || 1);
56
+ const order = Array.from({ length: n }, (_, i) => (interactive ? i : n - 1 - i));
57
+ try {
58
+ mkdirSync(dir, { recursive: true });
59
+ for (const slot of order) {
60
+ const file = leaseFile(endpoint, slot, dir);
61
+ if (!take(file))
62
+ continue;
63
+ if (held.size === 0)
64
+ process.once("exit", () => { for (const f of held)
65
+ try {
66
+ unlinkSync(f);
67
+ }
68
+ catch { /* already gone */ } });
69
+ held.add(file);
70
+ return slot;
71
+ }
72
+ return n - 1;
73
+ }
74
+ catch {
75
+ return order[0];
76
+ }
77
+ }
78
+ /** Give a claimed slot back (a finished sub-agent, a closed session). A shared, unleased slot is a no-op. */
79
+ export function releaseSlot(endpoint, slot, dir = operatorPath("runtime", "kv-slots")) {
80
+ const file = leaseFile(endpoint, slot, dir);
81
+ if (!held.delete(file))
82
+ return;
83
+ try {
84
+ unlinkSync(file);
85
+ }
86
+ catch { /* already gone */ }
87
+ }