@0perator/operator 0.1.360-next.2 → 0.2.1

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 (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
@@ -8,6 +8,7 @@ import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
9
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, effectiveCeilingTokens, fullRequestEstimate, compactionAction, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
+ import { imageRejected, withoutImages } from "./native-vision.js";
11
12
  import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
13
  import { hostOf } from "./net-error.js";
13
14
  import { TaskVerification, VERIFY_REMINDER, backgroundCheckReminder, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder, pendingVerifyCriterion, failedCheckReminder, failedCheckBanner } from "./verify-gate.js";
@@ -31,20 +32,18 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
31
32
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
32
33
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
33
34
  import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision, unwrapToolCall } from "./decision-points.js";
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
+ import { FILE_WRITE as MUTATING_TOOLS, POLLERS as LOOP_GUARD_EXEMPT, STATUS_TOOLS, mutationLanded } from "../tools/classes.js"; // a LANDED workspace edit ⇒ prior identical-call counts are stale
35
36
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
36
37
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
37
38
  export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
38
- import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, needsDeliverFindings, DELIVER_FINDINGS_NUDGE, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
39
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, needsDeliverFindings, DELIVER_FINDINGS_NUDGE, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stripEngineEcho } from "./continuation.js";
39
40
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
40
41
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
41
- const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
42
42
  // Status/introspection tools return the SAME facts for the whole turn and are never progress when repeated.
43
43
  // A weak model can fixate on one and poll it instead of answering — seen live on belmont-30b calling
44
44
  // self_status 5–9× every turn until a human interrupted, because LOOP_GUARD_LIMIT only short-circuits and the
45
45
  // hard stop sits at 10. Cap them tight and interactive-safe: the 2nd identical call is refused, a 3rd ends the
46
46
  // turn and hands back. No intervening-edit reset — a status fact does not change because a file was written.
47
- const STATUS_TOOLS = new Set(["self_status"]);
48
47
  const STATUS_TOOL_REFUSE = 2; // identical calls before the status tool is refused for the rest of the turn
49
48
  const STATUS_TOOL_HARD = 3; // …before the turn ends and hands back to the user
50
49
  // Hard backstop: after this many identical (name+args) calls in a turn with NO intervening edit, the model is
@@ -828,10 +827,10 @@ export async function runTurn(userInput, conversation, opts) {
828
827
  // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
829
828
  let convergeStreak = 0;
830
829
  const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
831
- const stopTurn = (note, roundsRun, stopReason) => {
832
- const text = closeStopNote(note, opts.preservedState?.()); // never a bare stop: the open items + how to steer
830
+ const stopTurn = (note, kind, roundsRun, stopReason) => {
831
+ const text = closeStopNote(note, opts.preservedState?.(), kind); // never a bare stop: the open items + how to steer
833
832
  conversation.assistant(text);
834
- return { content: text, display: stopQuestion(note, opts.preservedState?.()), stopKind: stopKind(note), rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
833
+ return { content: text, display: stopQuestion(kind, opts.preservedState?.()), stopKind: kind, rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
835
834
  };
836
835
  // Never silent (11/04): a router's legs are each tried once per round. When all of them fail, or the model keeps
837
836
  // finishing with nothing in its reply, the model's fallback (TurnModel) takes the rest of THIS turn; a turn nothing
@@ -962,7 +961,7 @@ export async function runTurn(userInput, conversation, opts) {
962
961
  return true;
963
962
  }
964
963
  if (ladder.switchesUsed > 0)
965
- return stopTurn(methodLadderStopNote(d, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
964
+ return stopTurn(methodLadderStopNote(d, ladder.switchesUsed), "stopped", rounds + 1); // budget of distinct methods spent → partial-with-blocker
966
965
  }
967
966
  else {
968
967
  const dir = recovery.directive(d);
@@ -974,7 +973,7 @@ export async function runTurn(userInput, conversation, opts) {
974
973
  }
975
974
  }
976
975
  }
977
- return stopTurn(loopStopNote({ ...d, message: d.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
976
+ return stopTurn(loopStopNote({ ...d, message: d.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), "stopped", rounds + 1);
978
977
  }
979
978
  guard?.resume(); // this batch's halt (a hard limit, a re-worded completed action) is what the recovery answers
980
979
  guard?.forgetResults(); // the results it compares against leave the context: a later duplicate is no stub pointing at them
@@ -1020,7 +1019,7 @@ export async function runTurn(userInput, conversation, opts) {
1020
1019
  conversation.assistant(cleanAssistantProse(content), calls);
1021
1020
  for (const c of calls)
1022
1021
  conversation.tool(c.id, OWNER_ACT_REFUSED);
1023
- return stopTurn(OWNER_ACT_STOP, rounds + 1);
1022
+ return stopTurn(OWNER_ACT_STOP, "owner", rounds + 1);
1024
1023
  };
1025
1024
  /** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
1026
1025
  const stalledNotConverging = (calls, toolMsgs, content) => {
@@ -1041,7 +1040,7 @@ export async function runTurn(userInput, conversation, opts) {
1041
1040
  `tell me how you'd like to proceed, or ask me to continue and I'll pick up from here with a different approach.]`;
1042
1041
  };
1043
1042
  const thinkingNow = () => (typeof opts.thinking === "function" ? opts.thinking() : opts.thinking === true);
1044
- conversation.user(userInput);
1043
+ conversation.user(userInput, opts.images);
1045
1044
  /** Every mid-turn message the engine injects rides in the user role; the marker is what lets the model tell it from
1046
1045
  * the owner (continuation.ts, owner-facing turns). */
1047
1046
  const engineUser = (text) => conversation.user(engineNote(text));
@@ -1114,7 +1113,7 @@ export async function runTurn(userInput, conversation, opts) {
1114
1113
  const note = `[paused — this turn reached its token budget (${spent} ≥ ${opts.maxTurnTokens} tokens). ` +
1115
1114
  `The work so far is above; continue with a fresh, focused request, or raise the budget ` +
1116
1115
  `(settings.maxTurnTokens).]`;
1117
- return stopTurn(note, rounds);
1116
+ return stopTurn(note, "paused", rounds);
1118
1117
  }
1119
1118
  // Opt-in per-turn WALL-CLOCK ceiling: the only bound on TIME. Round/token budgets don't stop a turn whose
1120
1119
  // decode has crawled (RAM pressure from a big model on the serving box, or very high context) to ~1 tok/s —
@@ -1140,7 +1139,7 @@ export async function runTurn(userInput, conversation, opts) {
1140
1139
  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.` : "";
1141
1140
  const note = `[paused — this turn hit its ${capMin}-min wall-clock budget (ran ${ranMin} min, ${spent} tokens).${crawl} ` +
1142
1141
  `The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
1143
- return stopTurn(note, rounds);
1142
+ return stopTurn(note, "paused", rounds);
1144
1143
  }
1145
1144
  if (rounds === softRounds)
1146
1145
  opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
@@ -1250,7 +1249,7 @@ export async function runTurn(userInput, conversation, opts) {
1250
1249
  const stuck = `[stopped — the context is over this model's window and compaction can't free enough space ` +
1251
1250
  `(${compactionFailStreak} rounds running; the summarizer may be failing). Start a fresh session, or ask me ` +
1252
1251
  `again with a shorter request — nothing was lost.]`;
1253
- return stopTurn(stuck, rounds + 1);
1252
+ return stopTurn(stuck, "window", rounds + 1);
1254
1253
  }
1255
1254
  }
1256
1255
  else {
@@ -1335,11 +1334,19 @@ export async function runTurn(userInput, conversation, opts) {
1335
1334
  // retry or continue-nudge could re-seed it. The partial is dropped; history keeps only the marker.
1336
1335
  if (watch.tripped && !opts.signal?.aborted)
1337
1336
  return watch.tripReason === "budget"
1338
- ? stopTurn(REASONING_BUDGET_INTERRUPTED, rounds + 1, "reasoning_budget")
1339
- : stopTurn(REPETITION_INTERRUPTED, rounds + 1, "repetition");
1337
+ ? stopTurn(REASONING_BUDGET_INTERRUPTED, "reasoning_budget", rounds + 1, "reasoning_budget")
1338
+ : stopTurn(REPETITION_INTERRUPTED, "repetition", rounds + 1, "repetition");
1340
1339
  if (isAbort(err, opts.signal))
1341
1340
  throw new TurnAbortedError(); // never self-heal an interrupt
1342
1341
  const recovery = classifyFailure(err);
1342
+ // An image the model cannot take: the server answers 4xx naming it. Take the images off the conversation, point
1343
+ // the owner's message at the files for image_analyze, and run this round again (once per set of images).
1344
+ if (conversation.all.some((m) => m.images?.length) && imageRejected(err)) {
1345
+ const { messages: plain, removed } = withoutImages(conversation.all);
1346
+ conversation.replaceAll(plain);
1347
+ opts.onImagesRejected?.({ base: endpoint.base, model: endpoint.model }, removed);
1348
+ continue;
1349
+ }
1343
1350
  // Truncated tool-call JSON (the model's own over-long file write cut off at the token limit): the
1344
1351
  // server can't parse the unterminated arguments (aurora /v1 500). Failing over is futile — the next
1345
1352
  // endpoint truncates the same write — so DON'T burn the failover budget or switch routes. Nudge the
@@ -1383,7 +1390,7 @@ export async function runTurn(userInput, conversation, opts) {
1383
1390
  await sleep(opts.loadingBackoffMs ?? DEFAULT_LOADING_BACKOFF_MS, opts.signal, () => new TurnAbortedError());
1384
1391
  continue;
1385
1392
  }
1386
- // The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — QwenCloud's "Range of
1393
+ // The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — one vendor's "Range of
1387
1394
  // max_tokens should be [1, 131072]"): learn it for this endpoint, so every later clamp honours it, and
1388
1395
  // retry this round ONCE. Not a context problem (compaction/failover can't help) and no self-heal
1389
1396
  // budget spent. A ceiling no lower than what we sent, or a second hit this round, is surfaced as-is.
@@ -1593,7 +1600,7 @@ export async function runTurn(userInput, conversation, opts) {
1593
1600
  // the continue-nudge below (it would stitch the loop into history and re-seed it) nor be recorded verbatim.
1594
1601
  // Runs BEFORE every nudge; the looped text is dropped and the turn tells the user plainly.
1595
1602
  if (guardCfg.enabled && guardCfg.repetition && response.toolCalls.length === 0 && isDegenerateReply(response.content, response.stopReason)) {
1596
- return stopTurn(REPETITION_INTERRUPTED, rounds + 1, "repetition");
1603
+ return stopTurn(REPETITION_INTERRUPTED, "repetition", rounds + 1, "repetition");
1597
1604
  }
1598
1605
  // Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
1599
1606
  // actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
@@ -1641,7 +1648,7 @@ export async function runTurn(userInput, conversation, opts) {
1641
1648
  const stuck = `[stopped — I repeated the same step ${seen}× and self-correction (${forcedRedirects} ` +
1642
1649
  `forced redirects) didn't break it, which usually means a tool isn't doing what I expect. Where I'm ` +
1643
1650
  `stuck: ${gist}\nTell me how you'd like to proceed.]`;
1644
- return stopTurn(stuck, rounds + 1);
1651
+ return stopTurn(stuck, "stopped", rounds + 1);
1645
1652
  }
1646
1653
  }
1647
1654
  }
@@ -1682,7 +1689,7 @@ export async function runTurn(userInput, conversation, opts) {
1682
1689
  const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
1683
1690
  `the loop, so I'm handing back rather than burning more time. Where I am: ${gist}\nTell me how you'd like ` +
1684
1691
  `to proceed — a different angle, or I can apply the fix I've been circling if you confirm it.]`;
1685
- return stopTurn(stuck, rounds + 1);
1692
+ return stopTurn(stuck, "stopped", rounds + 1);
1686
1693
  }
1687
1694
  opts.onSelfHeal?.("server_error", Math.max(1, selfLoopStreak)); // footer ↻ — breaking a self-declared loop
1688
1695
  loopNudge("self_loop", SELF_LOOP_NUDGE);
@@ -1745,7 +1752,7 @@ export async function runTurn(userInput, conversation, opts) {
1745
1752
  continue;
1746
1753
  }
1747
1754
  if (ladder.switchesUsed > 0)
1748
- return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
1755
+ return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), "stopped", rounds + 1); // budget of distinct methods spent → partial-with-blocker
1749
1756
  }
1750
1757
  else {
1751
1758
  const dir = recovery.directive(guard.halt);
@@ -1756,7 +1763,7 @@ export async function runTurn(userInput, conversation, opts) {
1756
1763
  }
1757
1764
  }
1758
1765
  }
1759
- return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
1766
+ return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), "stopped", rounds + 1);
1760
1767
  }
1761
1768
  guard.resume();
1762
1769
  engineUser(note);
@@ -1796,7 +1803,7 @@ export async function runTurn(userInput, conversation, opts) {
1796
1803
  if (pollSpin) {
1797
1804
  const ps = pollSpin.observe(response.toolCalls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""), response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")));
1798
1805
  if (ps.action === "halt")
1799
- return stopTurn(ps.message, rounds + 1);
1806
+ return stopTurn(ps.message, "yield", rounds + 1);
1800
1807
  if (ps.action === "nudge") {
1801
1808
  engineUser(ps.message);
1802
1809
  continue;
@@ -1805,7 +1812,7 @@ export async function runTurn(userInput, conversation, opts) {
1805
1812
  if (yieldGuard) {
1806
1813
  const yg = yieldGuard.observe(response.toolCalls.map((c) => c.function.name), response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")), endpointSlots(endpoint.base), (opts.slotSharers?.() ?? 1) > 0);
1807
1814
  if (yg.action === "halt")
1808
- return stopTurn(yg.message, rounds + 1);
1815
+ return stopTurn(yg.message, "yield", rounds + 1);
1809
1816
  if (yg.action === "nudge") {
1810
1817
  engineUser(yg.message);
1811
1818
  continue;
@@ -1814,13 +1821,13 @@ export async function runTurn(userInput, conversation, opts) {
1814
1821
  if (noWriteProgress) {
1815
1822
  const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
1816
1823
  if (nwp.action === "halt")
1817
- return stopTurn(nwp.message, rounds + 1);
1824
+ return stopTurn(nwp.message, "stopped", rounds + 1);
1818
1825
  if (nwp.action === "warn") {
1819
1826
  loopNudge("no_write_progress", nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
1820
1827
  }
1821
1828
  }
1822
1829
  if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
1823
- return stopTurn(notConvergingNote(response.toolCalls), rounds + 1);
1830
+ return stopTurn(notConvergingNote(response.toolCalls), "stopped", rounds + 1);
1824
1831
  continue;
1825
1832
  }
1826
1833
  // No structured tool_calls — check for text-encoded ones before treating this as final.
@@ -1874,7 +1881,7 @@ export async function runTurn(userInput, conversation, opts) {
1874
1881
  continue;
1875
1882
  }
1876
1883
  if (ladder.switchesUsed > 0)
1877
- return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), rounds + 1); // budget of distinct methods spent → partial-with-blocker
1884
+ return stopTurn(methodLadderStopNote(guard.halt, ladder.switchesUsed), "stopped", rounds + 1); // budget of distinct methods spent → partial-with-blocker
1878
1885
  }
1879
1886
  else {
1880
1887
  const dir = recovery.directive(guard.halt);
@@ -1885,7 +1892,7 @@ export async function runTurn(userInput, conversation, opts) {
1885
1892
  }
1886
1893
  }
1887
1894
  }
1888
- return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
1895
+ return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), "stopped", rounds + 1);
1889
1896
  }
1890
1897
  guard.resume();
1891
1898
  engineUser(note);
@@ -1913,7 +1920,7 @@ export async function runTurn(userInput, conversation, opts) {
1913
1920
  if (pollSpin) {
1914
1921
  const ps = pollSpin.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""), recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")));
1915
1922
  if (ps.action === "halt")
1916
- return stopTurn(ps.message, rounds + 1);
1923
+ return stopTurn(ps.message, "yield", rounds + 1);
1917
1924
  if (ps.action === "nudge") {
1918
1925
  engineUser(ps.message);
1919
1926
  continue;
@@ -1922,7 +1929,7 @@ export async function runTurn(userInput, conversation, opts) {
1922
1929
  if (yieldGuard) {
1923
1930
  const yg = yieldGuard.observe(recovered.calls.map((c) => c.function.name), recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")), endpointSlots(endpoint.base), (opts.slotSharers?.() ?? 1) > 0);
1924
1931
  if (yg.action === "halt")
1925
- return stopTurn(yg.message, rounds + 1);
1932
+ return stopTurn(yg.message, "yield", rounds + 1);
1926
1933
  if (yg.action === "nudge") {
1927
1934
  engineUser(yg.message);
1928
1935
  continue;
@@ -1931,14 +1938,14 @@ export async function runTurn(userInput, conversation, opts) {
1931
1938
  if (noWriteProgress) {
1932
1939
  const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
1933
1940
  if (nwp.action === "halt")
1934
- return stopTurn(nwp.message, rounds + 1);
1941
+ return stopTurn(nwp.message, "stopped", rounds + 1);
1935
1942
  if (nwp.action === "warn") {
1936
1943
  loopNudge("no_write_progress", nwp.message);
1937
1944
  continue;
1938
1945
  }
1939
1946
  }
1940
1947
  if (stalledNotConverging(recovered.calls, toolMsgs, recovered.cleanedContent))
1941
- return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
1948
+ return stopTurn(notConvergingNote(recovered.calls), "stopped", rounds + 1);
1942
1949
  continue;
1943
1950
  }
1944
1951
  const final = stripEngineEcho(stripScratchpad(recovered.cleanedContent)); // a model that echoes the marker must not show it to the owner
@@ -2042,7 +2049,9 @@ export async function runTurn(userInput, conversation, opts) {
2042
2049
  // an allowlisted-but-empty command (`npm ls`) can't clear it. Unattended loops back up to verifyMaxNudges (a
2043
2050
  // hard precondition); attended is the one-shot advisory nudge. Either way bounded → never hangs.
2044
2051
  const changedNotVerified = verifyHard ? verify.gateStrong() : verify.gate();
2045
- if (verifyEnabled && final && !isEngineFinal(final) && changedNotVerified && verifyNudges < verifyMaxNudges) {
2052
+ // `final` is the model's own text, except a reply the provider declined: its content is the engine's refusal note.
2053
+ const declined = response.stopReason === "content_filter";
2054
+ if (verifyEnabled && final && !declined && changedNotVerified && verifyNudges < verifyMaxNudges) {
2046
2055
  verifyNudges++;
2047
2056
  conversation.assistant(final);
2048
2057
  const jobId = verify.backgroundCheck();
@@ -2054,7 +2063,7 @@ export async function runTurn(userInput, conversation, opts) {
2054
2063
  // Attended: only a turn that CHANGED files owes its reported checks (a read-only turn quoting CI/logs is fine).
2055
2064
  // Unattended (FIX 3): extended to read-only turns that ASSERT a check — a headless run that claims "tests pass"
2056
2065
  // 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);
2066
+ const unrunGateApplies = verifyEnabled && final && !declined && toolCallTotal > 0 && (verify.changedFiles() || verifyHard);
2058
2067
  const unrunChecks = unrunGateApplies ? verify.unrun(final) : [];
2059
2068
  if (unrunChecks.length && unrunNudges < verifyMaxNudges) {
2060
2069
  unrunNudges++;
@@ -2064,7 +2073,7 @@ export async function runTurn(userInput, conversation, opts) {
2064
2073
  }
2065
2074
  // Failed-check gate: a check whose latest run this turn failed, and an answer that never says so or explains it away
2066
2075
  // ("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) : [];
2076
+ const failedChecks = verifyEnabled && final && !declined ? verify.unreportedFailures(final) : [];
2068
2077
  if (failedChecks.length && failedNudges < verifyMaxNudges) {
2069
2078
  failedNudges++;
2070
2079
  conversation.assistant(final);
@@ -2073,7 +2082,7 @@ export async function runTurn(userInput, conversation, opts) {
2073
2082
  }
2074
2083
  // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
2075
2084
  // one nudge to continue or to close with a status line per item and ONE steering question.
2076
- if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
2085
+ if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !declined && needsClosingSteer(final, !!opts.preservedState?.())) {
2077
2086
  closingNudged = true;
2078
2087
  conversation.assistant(final);
2079
2088
  engineUser(opts.unattended ? CLOSING_NUDGE_UNATTENDED : CLOSING_NUDGE);
@@ -2084,7 +2093,7 @@ export async function runTurn(userInput, conversation, opts) {
2084
2093
  // holding the review back instead of delivering it (v0.1.358: found 31 repos + a 404 caveat, then "Which direction
2085
2094
  // — A/B/C?"). ONE nudge to deliver now. Conservative: never on a build/edit task (answerFirst), never a pre-work
2086
2095
  // clarifier or a blocker with nothing found (producedFindings), at most once; background sub-agents are never nudged.
2087
- if (final && response.stopReason !== "length" && !deliverFindingsNudged && !opts.background && !isEngineFinal(final) && needsDeliverFindings(final, { answerFirst, hasFindings: producedFindings })) {
2096
+ if (final && response.stopReason !== "length" && !deliverFindingsNudged && !opts.background && !declined && needsDeliverFindings(final, { answerFirst, hasFindings: producedFindings })) {
2088
2097
  deliverFindingsNudged = true;
2089
2098
  conversation.assistant(final);
2090
2099
  engineUser(DELIVER_FINDINGS_NUDGE);
@@ -2098,11 +2107,13 @@ export async function runTurn(userInput, conversation, opts) {
2098
2107
  conversation.assistant(answer);
2099
2108
  // a recovered loop moved on to an answer: reported here, where the answer is final — an announcement the continuation
2100
2109
  // check sent back, or a closing the nudge rewrote, never became the step that moved the turn on
2101
- if (final && !isEngineFinal(final))
2110
+ if (final && !declined)
2102
2111
  proceeded([], final);
2103
- const display = final ? undefined : stopQuestion(answer, opts.preservedState?.()); // the engine's own empty/length status, said plainly
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() };
2112
+ // Nothing in the reply or its reasoning: `answer` is the engine's output-limit note, said plainly on screen.
2113
+ const cutOff = !final && !stripScratchpad(response.reasoningContent ?? "") && !stripScratchpad(lastReasoning);
2114
+ const display = cutOff ? stopQuestion("length", opts.preservedState?.()) : undefined;
2115
+ return { content: answer, display, stopKind: cutOff ? "length" : 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() };
2105
2116
  }
2106
2117
  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]`;
2107
- return stopTurn(timeoutMsg, rounds);
2118
+ return stopTurn(timeoutMsg, "rounds", rounds);
2108
2119
  }
@@ -68,6 +68,22 @@ export function releaseEndpoint(base, model, owner) {
68
68
  g.holders.push(next.owner);
69
69
  next.resolve();
70
70
  }
71
+ // Capacity reservations (background/capacity.ts): a sub-agent lane that holds one owns a unit the router set aside for
72
+ // it, so its requests skip this in-process gate (the router bounds them) and carry the reservation to the reserved leg.
73
+ // Keyed by the gate's owner label (the lane's unique name) and matched on base, so a fallback endpoint is gated as before.
74
+ export const CAPACITY_LEASE_HEADER = "x-0perator-capacity-lease";
75
+ const _capacityLeases = new Map();
76
+ const bareBase = (b) => b.replace(/\/v1\/?$/, "").replace(/\/+$/, "");
77
+ export function setCapacityLease(owner, lease) {
78
+ if (lease)
79
+ _capacityLeases.set(owner, { id: lease.id, base: bareBase(lease.base) });
80
+ else
81
+ _capacityLeases.delete(owner);
82
+ }
83
+ export function capacityLeaseFor(o) {
84
+ const l = o.owner ? _capacityLeases.get(o.owner) : undefined;
85
+ return l && l.base === bareBase(o.base) ? l.id : undefined;
86
+ }
71
87
  /** Snapshot of every endpoint gate (for tests + a live status surface): who holds each slot, and who waits. */
72
88
  export function endpointGateStatus() {
73
89
  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) }));
@@ -79,7 +95,7 @@ export function isRemoteBase(base) {
79
95
  return !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(base);
80
96
  }
81
97
  // Owner-trusted fallback scope for the OPERATOR bearer: AXE's own hosts (api.axe.onl gateway) and
82
- // private/LAN fleet nodes. A third-party BYO host (qwencloudapi.com, …) must NEVER receive the operator
98
+ // private/LAN fleet nodes. A third-party BYO host (api.openai.com, …) must NEVER receive the operator
83
99
  // token — a BYO profile carries its own vendor key via Endpoint.token (AuroraOpts.token), and an
84
100
  // endpoint with no explicit token gets NO auth on a public third-party host. This scope rule is the
85
101
  // credential-leak guard for the BYO era.
@@ -295,7 +311,7 @@ export function requestBody(messages, o, stream) {
295
311
  // Transport dialect: llama.cpp-only fields ship to Aurora/fleet (default "llama") AND to our OWN
296
312
  // vendor gateway (*.axe.onl — LiteLLM terminating at our llama.cpp, so the wire is OpenAI but the
297
313
  // BACKEND understands the knobs; measured live 2026-10-11: extras pass api.axe.onl with no 400 and
298
- // no fallback trip). A genuine third-party "openai" BYO (qwencloudapi.com, …) still gets standard
314
+ // no fallback trip). A genuine third-party "openai" BYO (api.openai.com, …) still gets standard
299
315
  // fields only — third-party gateways can 400 on unknown keys, and silence on extras is not a
300
316
  // contract we should bank on.
301
317
  const llama = o.transport !== "openai";
@@ -324,7 +340,7 @@ export function requestBody(messages, o, stream) {
324
340
  // fed through a long cold prefill instead of looking wedged. A server that ignores the field is harmless.
325
341
  ...(stream && llama ? { return_progress: true } : {}),
326
342
  // GW-26 (2026-11-25): no per-request speculative field by default, tool rounds included — the server's
327
- // --spec-type decides. ngram-mod drafts are verified by the target model, so the output is exact (Qwen3.8-27B,
343
+ // --spec-type decides. ngram-mod drafts are verified by the target model, so the output is exact (the 27B dense model,
328
344
  // 6 prompts: identical sha256 with and without it; a code edit 11.1 → 52-56 tok/s). The old tool-round
329
345
  // disable (sent on the belief that drafts fight the tool-call grammar) starved every agent round of that
330
346
  // speed-up. Opt out with settings.speculation:false / KODE_SPECULATION=0 (setSpeculation), or per call with
@@ -351,19 +367,23 @@ export function chatUrl(base, chatPath) {
351
367
  return `${base}${chatPath ?? "/v1/chat/completions"}`;
352
368
  }
353
369
  /** Who answered an HTTP error, for the owner: the profile id + provider box when the turn loop passed them
354
- * ("qwen3.8-flash (QwenCloud)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
370
+ * ("gemini-flash (Google)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
355
371
  export function httpErrorLabel(o) {
356
372
  if (!o.label)
357
373
  return "aurora /v1";
358
374
  return o.provider ? `${o.label} (${o.provider})` : o.label;
359
375
  }
376
+ function leaseHeader(o) {
377
+ const id = capacityLeaseFor(o);
378
+ return id ? { [CAPACITY_LEASE_HEADER]: id } : {};
379
+ }
360
380
  async function fetchChat(o, body) {
361
381
  let lastErr;
362
382
  for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
363
383
  try {
364
384
  return await fetch(chatUrl(o.base, o.chatPath), {
365
385
  method: "POST",
366
- headers: { "Content-Type": "application/json", ...authHeaders(o), ...(o.session ? { [SESSION_HEADER]: o.session, ...(o.sessionRole ? { [SESSION_ROLE_HEADER]: o.sessionRole } : {}) } : {}) },
386
+ headers: { "Content-Type": "application/json", ...authHeaders(o), ...(o.session ? { [SESSION_HEADER]: o.session, ...(o.sessionRole ? { [SESSION_ROLE_HEADER]: o.sessionRole } : {}) } : {}), ...leaseHeader(o) },
367
387
  body,
368
388
  signal: o.signal, // SPEC §9 interrupt handling: tears down the in-flight stream on abort, not at the next loop boundary
369
389
  });
@@ -431,6 +451,16 @@ export function createDecodeMonitor(floorTps = DECODE_FLOOR_TPS, windowTokens =
431
451
  },
432
452
  };
433
453
  }
454
+ /** Attached images become image_url parts here, at the last moment; a request with none passes through untouched.
455
+ * The encoder is node-only (it reads the files), so it loads only when a message carries an image, through a
456
+ * variable specifier so the browser bundle never follows it. */
457
+ const nodeImport = (m) => import(m);
458
+ async function wireMessages(messages) {
459
+ if (!messages.some((m) => m.images?.length))
460
+ return messages;
461
+ const [{ toWireMessages }, { encodeImage }] = await Promise.all([import("./native-vision.js"), nodeImport("./native-vision-node.js")]);
462
+ return toWireMessages(messages, encodeImage);
463
+ }
434
464
  /** Shared SSE parse loop. Yields each `data:` line's `choices[0].delta`, raw. */
435
465
  async function* streamDeltas(messages, o) {
436
466
  // Hold this endpoint's slot for the WHOLE request+stream lifetime — the one decode slot is busy the entire
@@ -438,8 +468,10 @@ async function* streamDeltas(messages, o) {
438
468
  // Interactive turns preempt the queue ahead of background sub-agents (see acquireEndpoint). A single call is
439
469
  // never re-entrant, so acquire/release balance exactly once.
440
470
  const owner = o.owner ?? (o.background ? "sub-agent" : "main");
441
- await acquireEndpoint(o.base, o.background === true, o.model, { owner, onQueued: o.onQueued });
442
- let _slotReleased = false;
471
+ const leased = capacityLeaseFor({ owner, base: o.base }) !== undefined;
472
+ if (!leased)
473
+ await acquireEndpoint(o.base, o.background === true, o.model, { owner, onQueued: o.onQueued });
474
+ let _slotReleased = leased;
443
475
  const _releaseSlot = () => { if (!_slotReleased) {
444
476
  _slotReleased = true;
445
477
  releaseEndpoint(o.base, o.model, owner);
@@ -449,7 +481,7 @@ async function* streamDeltas(messages, o) {
449
481
  o.onSent?.();
450
482
  }
451
483
  catch { /* a UI callback never breaks the request */ }
452
- const res = await fetchChat(o, requestBody(messages, o, true));
484
+ const res = await fetchChat(o, requestBody(await wireMessages(messages), o, true));
453
485
  if (!res.ok || !res.body) {
454
486
  let detail = "";
455
487
  try {
@@ -22,6 +22,7 @@
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
+ import { SCHED_BARRIER, SHELL_FOREGROUND } from "../tools/classes.js";
25
26
  /** The report runBatch hands each runOne — and a hand-rolled batch loop builds the same way: `started` fires `onStart`
26
27
  * once, `why` holds the refusal. */
27
28
  export function callReport(onStart, signal) {
@@ -42,24 +43,14 @@ export function callReport(onStart, signal) {
42
43
  return r;
43
44
  }
44
45
  export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
45
- /** Foreground shells that may run concurrently within one model round (matches Cursor). */
46
- const SHELL_EXACT = new Set(["bash", "shell_exec"]);
47
- const BARRIER_EXACT = new Set([
48
- "shell_background", "bash_kill",
49
- "git_command", "checkpoint", "tool_call",
50
- "delegate_task", // a whole sub-agent session with the full tool set: it can touch anything, so it runs alone
51
- "delegate_to_agent", // spawns an external autonomous CLI agent with write + shell access: runs alone
52
- "spawn_cloud_agent", // launches a whole autonomous agent in a remote container (clone→run→PR): runs alone
53
- "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot",
54
- ]);
55
46
  const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_vault included: it drives the same browser device
56
- // NOTE: "shell" prefix still matches shell_background / shell_*; SHELL_EXACT is checked FIRST so
47
+ // NOTE: "shell" prefix still matches shell_background / shell_*; SHELL_FOREGROUND is checked FIRST so
57
48
  // bash/shell_exec become "shell" (parallelizable) instead of falling through to barrier.
58
49
  export function defaultClassify(_unused, isSafe) {
59
50
  return (n) => {
60
- if (SHELL_EXACT.has(n))
51
+ if (SHELL_FOREGROUND.has(n))
61
52
  return "shell";
62
- if (BARRIER_EXACT.has(n))
53
+ if (SCHED_BARRIER.has(n))
63
54
  return "barrier";
64
55
  for (const p of BARRIER_PREFIX)
65
56
  if (n.startsWith(p) || n.includes("__" + p))
@@ -218,7 +218,7 @@ function shedToolOutputs(out, opts, targetTokens, protectTail) {
218
218
  return out;
219
219
  const limit = out.length - protectTail;
220
220
  // Tool messages, largest content first — shed the worst offenders until it fits. GW-10-COMPLETE:
221
- // error-ish results go LAST (Manus doctrine — a failed tool trace in context suppresses repeat
221
+ // error-ish results go LAST (context-engineering practice — a failed tool trace in context suppresses repeat
222
222
  // mistakes; a success's bytes are re-fetchable from the spill file, the failure's lesson is not).
223
223
  const byLargest = out
224
224
  .map((m, i) => ({ i, len: m.role === "tool" && i < limit && !isShedStub(m.content) ? m.content.length : 0, err: /^(error[:\s]|\(no output; exit)/i.test(m.content) }))
@@ -413,7 +413,7 @@ export function applyAnchorVerification(summaryMsg, evicted, outAll) {
413
413
  }
414
414
  /** Verbatim user-voice: the FIRST user message (the original mission — the thing most often lost and
415
415
  * most catastrophic to lose: instruction drift is how long autonomous runs go off rails, this week's
416
- * 76-min Pando marathon is the cautionary tale) PLUS the last k user messages (current intent). Middle
416
+ * 76-min autonomous marathon is the cautionary tale) PLUS the last k user messages (current intent). Middle
417
417
  * follow-ups are NOT duplicated here — the summarizer's FACTS/STATE already carries them; head+tail is
418
418
  * exactly the shape frontier compaction uses (objective pinned at head, recency at tail) and keeps the
419
419
  * block bounded regardless of span depth. */