@0perator/operator 0.2.4 → 0.2.6

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 (49) hide show
  1. package/dist/autonomy/delegate-mode.js +4 -1
  2. package/dist/autonomy/delegate.js +3 -13
  3. package/dist/background/index.js +7 -10
  4. package/dist/background/notices.js +1 -1
  5. package/dist/cli.js +31 -14
  6. package/dist/config/persona.js +20 -3
  7. package/dist/engine/agent.js +62 -7
  8. package/dist/engine/aurora.js +30 -30
  9. package/dist/engine/batch-hints.js +45 -0
  10. package/dist/engine/batch-scheduler.js +23 -7
  11. package/dist/engine/decision-points.js +12 -2
  12. package/dist/engine/delegate-turn.js +24 -0
  13. package/dist/engine/grandmaster.js +28 -11
  14. package/dist/mcp/index.js +2 -2
  15. package/dist/permissions/modes.js +7 -3
  16. package/dist/session.js +65 -12
  17. package/dist/tools/classes.js +4 -0
  18. package/dist/tools/deferred.js +11 -6
  19. package/dist/tools/readonly-shell.js +92 -0
  20. package/dist/tools/registry.js +3 -3
  21. package/dist/tools/shell-session.js +56 -1
  22. package/dist/ui/ActivitySpinner.js +2 -2
  23. package/dist/ui/App.js +9 -9
  24. package/dist/ui/ApprovalPrompt.js +5 -4
  25. package/dist/ui/ArtifactPicker.js +4 -3
  26. package/dist/ui/AuthScreen.js +2 -1
  27. package/dist/ui/BgPanel.js +11 -8
  28. package/dist/ui/Composer.js +4 -3
  29. package/dist/ui/Header.js +2 -2
  30. package/dist/ui/Markdown.js +50 -77
  31. package/dist/ui/PlanPane.js +5 -5
  32. package/dist/ui/QuestionPrompt.js +2 -1
  33. package/dist/ui/SecretPrompt.js +2 -1
  34. package/dist/ui/SessionPicker.js +4 -3
  35. package/dist/ui/SkillFinder.js +3 -2
  36. package/dist/ui/StatsCard.js +2 -2
  37. package/dist/ui/StatusRule.js +2 -2
  38. package/dist/ui/SummaryCard.js +2 -2
  39. package/dist/ui/Table.js +25 -24
  40. package/dist/ui/ThinkingSpinner.js +2 -1
  41. package/dist/ui/ToolBatch.js +3 -3
  42. package/dist/ui/ToolStep.js +4 -4
  43. package/dist/ui/Transcript.js +12 -12
  44. package/dist/ui/UpdatePrompt.js +2 -1
  45. package/dist/ui/inline.js +109 -0
  46. package/dist/ui/reportLine.js +2 -0
  47. package/dist/ui/slashCommands.js +2 -2
  48. package/dist/ui/theme.js +4 -0
  49. package/package.json +1 -1
@@ -130,12 +130,14 @@ export function withDelegateGuard(inner, ctx) {
130
130
  },
131
131
  };
132
132
  }
133
- export const DELEGATE_USAGE = "/delegate · /delegate planner <model> [executor] · /delegate subagents <model> · /delegate guard on|off · /delegate push on|off · /delegate off";
133
+ export const DELEGATE_USAGE = "/delegate · /delegate on · /delegate planner <model> [executor] · /delegate subagents <model> · /delegate guard on|off · /delegate push on|off · /delegate off";
134
134
  export function parseDelegate(argText) {
135
135
  const [verb, a, b, ...rest] = argText.trim().split(/\s+/).filter(Boolean);
136
136
  const onOff = (x) => (x === "on" ? true : x === "off" ? false : undefined);
137
137
  if (!verb || verb === "status")
138
138
  return { kind: "status" };
139
+ if (verb === "on" && !a)
140
+ return { kind: "on" };
139
141
  if (verb === "off" && !a)
140
142
  return { kind: "off" };
141
143
  if (verb === "planner" && a && !rest.length)
@@ -154,6 +156,7 @@ export function delegateStatusLines(v) {
154
156
  `delegate · ${team}`,
155
157
  `sub-agents (spawn_agent, delegate_task default): ${v.subagentModel}`,
156
158
  `guard ${v.guard ? "ON" : "off"}${v.guard ? ` · push ${v.allowPush ? "allowed" : "blocked"} · deploys blocked · writes: this repo${v.repos.length ? `, ${v.repos.join(", ")}` : ""}, scratch, temp` : ""}`,
159
+ `Delegate mode ${v.mode ? "ON (/delegate off)" : "off (/delegate on, or shift+tab)"}`,
157
160
  DELEGATE_USAGE,
158
161
  ];
159
162
  }
@@ -1,17 +1,6 @@
1
- // delegate_task — the planner -> executor seam. Operator (the planner) hands ONE self-contained subtask to
2
- // a sub-agent running on a CHOSEN fleet model and gets its final answer back as the tool result: the first
3
- // step toward orchestrating our own models (Scout for the cheap/fast pass, Cortana for the hard one, ...).
4
- //
5
- // A sub-agent is not a new engine. It is a child headless Session built by the SAME createAutonomySession
6
- // factory `operator run/loop/board/cron` use, pointed at a registry model (router/models.ts) exactly the
7
- // way /model points a session at one (Session.setModel — which also resolves BYO keys + wire dialect). The
8
- // turn loop is untouched; this module only derives settings, runs one turn, and tears the session down.
9
- //
10
- // Browser-safe: reachable from the tool registry (which rides in the engine bundle's graph), so node
11
- // builtins and the node-bound session factory load lazily via the nodeImport idiom (same as autonomy/cron.ts).
12
1
  import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
2
  import { MemoryStore } from "../memory/index.js";
14
- import { delegateBrief, inferType, roleForBrief, SUBAGENT_ROLES } from "../engine/grandmaster.js";
3
+ import { delegateBrief, inferType, roleForBrief, SUBAGENT_ROLES, partialReport, beforeStopNote } from "../engine/grandmaster.js";
15
4
  import { engineEnded } from "../engine/continuation.js";
16
5
  import { suggestSkillsBlock } from "./subagent-amplifier.js";
17
6
  import { subagentModelFor, DEFAULT_SUBAGENT_MODEL } from "./subagent-model.js";
@@ -265,7 +254,8 @@ export async function runDelegateTask(args, deps = defaultDeps) {
265
254
  const text = String(outcome.content ?? "").trim();
266
255
  // The engine's own hand-back ([stopped …], [paused …], the output-limit note) is no answer: the planner must not get it as one.
267
256
  if (!text || engineEnded(outcome)) {
268
- return `error: delegate_task: the sub-agent on ${profile.id} produced no answer (${outcome.rounds} rounds, ${outcome.toolCalls} tool calls)${text ? ` — it reported: ${text.slice(0, 300)}` : ""}. Retry with a smaller, clearer subtask or a stronger model.`;
257
+ const gathered = outcome.toolCalls && session.snapshot ? `\n${partialReport(beforeStopNote(session.snapshot(), outcome), `${profile.id} was stopped`)}` : "";
258
+ return `error: delegate_task: the sub-agent on ${profile.id} produced no answer (${outcome.rounds} rounds, ${outcome.toolCalls} tool calls)${text ? ` — it reported: ${text.slice(0, 300)}` : ""}. Retry with a smaller, clearer subtask or a stronger model.${gathered}`;
269
259
  }
270
260
  if (lane.note)
271
261
  return `${lane.note}\n${text}`;
@@ -1,4 +1,4 @@
1
- import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, partialCounts, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
1
+ import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, partialCounts, beforeStopNote, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
2
2
  import { engineEnded } from "../engine/continuation.js";
3
3
  import { createWorktree, finalizeWorktree } from "./worktree.js";
4
4
  import { resumeBrief } from "./resume.js";
@@ -734,8 +734,6 @@ export class BackgroundAgents {
734
734
  // The engine ended the child's turn (loop guard, no progress, round cap): a repair round would hand the same loop
735
735
  // a fresh budget (10/31: round 54 against a cap of 50). Finish with what it has; the stop note says why.
736
736
  let engineStopped = engineEnded(r);
737
- if (engineStopped)
738
- info.malformed = true;
739
737
  // Mechanism 2: one repair round on a schema failure — feed the error back, re-run just the final step.
740
738
  if (!fa.ok && !r.interrupted && !engineStopped) {
741
739
  const r2 = await session.send(repairPrompt(fa.errors ?? [], type), hooks);
@@ -771,14 +769,15 @@ export class BackgroundAgents {
771
769
  }
772
770
  // Mechanism 3: verify-before-done (never on the model's say-so). Verify runs IN the worktree, so a
773
771
  // code-editing child's declared verify_command tests the files it actually changed (in isolation).
774
- if (engineStopped)
775
- info.malformed = true;
776
772
  if (!engineStopped && fa.ok && fa.value) {
777
773
  const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd(), { diffSha });
778
774
  info.verified = v.verified;
779
775
  info.verifyDetail = v.detail;
780
776
  }
781
- info.status = r.interrupted ? "stopped" : "idle";
777
+ const gathered = engineStopped ? beforeStopNote(session.snapshot(), r) : [];
778
+ if (engineStopped)
779
+ Object.assign(info, { endKind: "engine", endReason: r.stopKind === "length" ? "its reply hit the output limit" : engineStopReason(r.content), headline: partialCounts(gathered) });
780
+ info.status = r.interrupted || engineStopped ? "stopped" : "idle";
782
781
  if (total > 0)
783
782
  info.tokens = total; // authoritative llama.cpp count summed across sends
784
783
  info.durationMs = r.durationMs ?? (Date.now() - (info.startedAt ?? Date.now()));
@@ -801,13 +800,11 @@ export class BackgroundAgents {
801
800
  // decide whether to trust the child (mechanism 5 is the UI surfacing the same fields), plus where the
802
801
  // isolated worktree's changes landed (a review branch).
803
802
  const summary = engineStopped
804
- ? `${partialReport(session.snapshot(), `${id} was stopped by the engine after ${info.round ?? 0} rounds`)}\n${r.content.split("\n")[0]}`
803
+ ? `${partialReport(gathered, `${id} was stopped by the engine after ${info.round ?? 0} rounds`)}\n${r.content.split("\n")[0]}`
805
804
  : (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
806
805
  ? fa.value.summary.trim()
807
806
  : (r.content.trim() || "(no output)");
808
- if (engineStopped)
809
- Object.assign(info, { endKind: "engine", endReason: engineStopReason(r.content), headline: partialCounts(session.snapshot()) });
810
- else
807
+ if (!engineStopped)
811
808
  Object.assign(info, { endKind: "done", endReason: "done", headline: firstSentence(summary) });
812
809
  const tag = info.malformed ? " ⚠ malformed final_answer (unstructured)"
813
810
  : info.verified === false ? ` ⚠ unverified: ${info.verifyDetail}`
@@ -21,7 +21,7 @@ const who = (a) => `${a.name ? `${a.name} (${a.title ?? "sub-agent"}, ${a.id})`
21
21
  export function formatAgentReport(agent, result) {
22
22
  const files = agent.written?.length ? ` Files it wrote or edited: ${agent.written.join(", ")}.` : " No file writes were recorded by the tool ledger. Shell commands and untracked tools may have changed files; inspect their results.";
23
23
  return [
24
- `[system notice] ${who(agent)} finished.${files} Its report follows — a SELF-REPORT. Review it before you tell the owner: ` +
24
+ `[system notice] ${who(agent)} ${agent.endKind === "engine" ? `was stopped by the engine (${agent.endReason}) and is no longer running.` : "finished."}${files} Its report follows — a SELF-REPORT. Review it before you tell the owner: ` +
25
25
  `open what it produced, check it against the brief's Done line, fix or re-brief what is missing, update the plan, then tell ` +
26
26
  `the owner in a few lines what was done, what you checked, and what is next.`,
27
27
  clip(result.trim() || "(no output)", REPORT_CHARS),
package/dist/cli.js CHANGED
@@ -12,7 +12,7 @@ import { App } from "./ui/index.js";
12
12
  import { restKey } from "./ui/Composer.js";
13
13
  import { mastheadLines } from "./ui/Masthead.js";
14
14
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
15
- import { initialMode, modePolicy, nextMode, parseMode, planToggleTarget } from "./permissions/modes.js";
15
+ import { initialMode, MODE_NAME, modePolicy, nextMode, parseMode, planToggleTarget } from "./permissions/modes.js";
16
16
  import { createActivationFlow } from "./ui/activationFlow.js";
17
17
  import { FREE_ROW_PRESETS, PROVIDER_ROW_PRESETS, connectedAccounts, isMainModel, mainIds, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, mainPickerView, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, rereadConfirmView, wantsContextStep, wantsRereadConfirm } from "./ui/modelPicker.js";
18
18
  import { RemoteHost, toRemoteAgents } from "./remote/host.js";
@@ -69,7 +69,7 @@ import { drainAgentNotices, onAgentReport, agentReportsDue, queueAgentReport, qu
69
69
  import { delegateCapacity, liveDelegateRoute } from "./background/capacity.js";
70
70
  import { laneSummary } from "./background/lane-summary.js";
71
71
  import { missingLine, synthesisState } from "./background/synthesis.js";
72
- import { reportLine, deliveredLine } from "./ui/reportLine.js";
72
+ import { reportLine, deliveredLine, stopReasonOf } from "./ui/reportLine.js";
73
73
  import { pushCollapsed, popCollapsed, dropCollapsed } from "./ui/expand.js";
74
74
  import { ensureScratchDir } from "./config/scratch.js";
75
75
  import { caffeinateEnabled, startCaffeinate } from "./util/caffeinate.js";
@@ -353,6 +353,7 @@ const START_MODE = initialMode(settings.permissions.mode);
353
353
  const START_POLICY = modePolicyFor(START_MODE);
354
354
  const MODE_LINE = {
355
355
  auto: "◆ mode → AUTONOMOUS — no approval prompts: I put multi-step work in the task list for you to review, and a money / prod / destructive step runs only if the approved plan lists it (shift+tab to cycle)",
356
+ delegate: "⇉ mode → DELEGATE — Autonomous permissions and plan review, and I send the independent parts of each task to sub-agents (shift+tab to cycle)",
356
357
  manual: Object.keys(computerAskRules).length
357
358
  ? "◈ mode → MANUAL — I execute without asking, except computer-control actions and money / prod / destructive steps (shift+tab to cycle)"
358
359
  : "◈ mode → MANUAL — I execute without asking (shift+tab to cycle)",
@@ -519,11 +520,12 @@ function buildRouter() {
519
520
  function formatAgentLine(a) {
520
521
  const who = a.name ? `${a.name} (${a.title ?? "sub-agent"}, ${a.id}${a.model ? `, ${a.model}` : ""})` : a.id;
521
522
  const wrote = a.written?.length ? `wrote ${a.written.join(", ")}` : "no file writes recorded";
522
- return `${who} [${a.status}]${a.round ? ` round ${a.round}` : ""} · ${wrote}${a.stuck ? ` · STUCK: ${a.stuck}` : ""} ${a.label}`;
523
+ return `${who} [${(a.status === "stopped" && stopReasonOf(a)) || a.status}]${a.round ? ` round ${a.round}` : ""} · ${wrote}${a.stuck ? ` · STUCK: ${a.stuck}` : ""} ${a.label}`;
523
524
  }
525
+ const erroredOut = (a) => !a.endKind || a.endKind === "failed" || a.endKind === "error";
524
526
  const DISPLAY_STATUS = { queued: "queued", working: "running", idle: "done", stopped: "errored" };
525
527
  function formatAgentDetail(a) {
526
- const ds = a.status === "stopped" && a.endReason ? a.endReason : DISPLAY_STATUS[a.status] ?? a.status;
528
+ const ds = (a.status === "stopped" && stopReasonOf(a)) || (DISPLAY_STATUS[a.status] ?? a.status);
527
529
  const parts = [`${a.id} [${ds}]`];
528
530
  if (a.round)
529
531
  parts.push(`round ${a.round}`);
@@ -538,14 +540,14 @@ function formatAgentDetail(a) {
538
540
  parts.push(`(${metrics.join(" · ")})`);
539
541
  if (a.status === "idle")
540
542
  parts.push("— result posted");
541
- if (a.status === "stopped")
543
+ if (a.status === "stopped" && erroredOut(a))
542
544
  parts.push("— errored");
543
545
  return parts.join(" ");
544
546
  }
545
547
  // Full per-agent view for /agents <id> — everything the one-liner can't fit (task, model/lane, verify
546
548
  // outcome, live tool steps, mission line) plus the msg/stop controls for a still-running child.
547
549
  function formatAgentDeepView(a) {
548
- const ds = DISPLAY_STATUS[a.status] ?? a.status;
550
+ const ds = (a.status === "stopped" && stopReasonOf(a)) || (DISPLAY_STATUS[a.status] ?? a.status);
549
551
  const lines = [];
550
552
  lines.push(`── ${a.id} [${ds}] ──`);
551
553
  lines.push(` label: ${a.label}`);
@@ -621,7 +623,7 @@ const HELP = [
621
623
  " /artifacts browse + attach your artifacts: search · attach · copy url · delete",
622
624
  " /sessions [query] search Operator's and other agents' sessions (providers in agents.md) and pick one up",
623
625
  " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
624
- " /mode [auto|manual|plan|gated] set operating mode (autonomous · manual · plan · gated); Shift+Tab cycles the first three",
626
+ " /mode [auto|delegate|manual|plan|gated] set operating mode (autonomous · delegate · manual · plan · gated); Shift+Tab cycles all but gated",
625
627
  " /voice [on|off|status] voice mode: ctrl+t to talk (again to send), the answer is spoken back, esc stops it",
626
628
  " /think [level] extended reasoning: Operator thinks before answering (/think again = off); a level sets this model's reasoning effort",
627
629
  " /ultrathink deep, exhaustive reasoning for hard problems (/ultrathink again = off)",
@@ -629,6 +631,7 @@ const HELP = [
629
631
  " /remember <note> store a note to recall in future sessions",
630
632
  " /memory [query] show remembered notes (all, or matching query)",
631
633
  " /allow <tool:args> auto-allow a tool+args glob pattern in gated mode (e.g. bash:npm test*)",
634
+ " /delegate on|off Delegate mode: Autonomous permissions, and each task's independent parts go to sub-agents",
632
635
  " /delegate any /model id as the MoA planner or the sub-agents, plus a guard (no push, deploys or writes outside this repo)",
633
636
  " /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
634
637
  " /<skill> [message] any installed skill is its own command; the rest of the line is your first message",
@@ -741,6 +744,7 @@ function Root() {
741
744
  // selector must light up the instant it changes, before React flushes the setOpMode state update).
742
745
  const opModeRef = useRef(opMode);
743
746
  const beforePlanRef = useRef(opMode === "plan" ? "gated" : opMode); // the mode /plan off returns to
747
+ const beforeDelegateRef = useRef(opMode); // the mode /delegate off returns to
744
748
  const [thinkMode, setThinkMode] = useState(settings.ui?.reasoning ?? "think"); // /think, /ultrathink badge; default "think" so the model's thoughts stream dim above the answer (settings.ui.reasoning / /think to change)
745
749
  const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
746
750
  const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
@@ -886,7 +890,7 @@ function Root() {
886
890
  // sub-agent can't spawn more (no fork bombs). BackgroundAgents itself is the single source of truth
887
891
  // for the cap (running + queued) — it refuses ("") past it, so there's exactly one number to keep in
888
892
  // sync, not a second constant here that can drift from the manager's own.
889
- spawnSlots: () => (sessionRef.current?.currentModel() === "moa" ? bgRef.current?.freeLanes() : undefined), // a planner fan-out is sized to the free lanes
893
+ spawnSlots: () => (sessionRef.current?.currentModel() === "moa" || opModeRef.current === "delegate" ? bgRef.current?.freeLanes() : undefined), // a planner or Delegate mode fan-out is sized to the free lanes
890
894
  spawnAgent: (task, role, name, opts) => {
891
895
  const mgr = bgRef.current;
892
896
  if (!mgr)
@@ -942,7 +946,7 @@ function Root() {
942
946
  // misleading "none spawned" (live 09-27: two errored agents decommissioned, then agent_status wrongly
943
947
  // said none were ever spawned). Their results are already in the conversation.
944
948
  if (retired.length) {
945
- return `no sub-agents are currently active. ${retired.length} ran earlier this session and decommissioned (${retired.map((r) => `${r.id}: ${r.status}`).join(", ")}) — their results were posted to the conversation when they finished.`;
949
+ return `no sub-agents are currently active. ${retired.length} ran earlier this session and decommissioned (${retired.map((r) => `${r.id}: ${(r.status === "stopped" && stopReasonOf(r)) || r.status}`).join(", ")}) — their results were posted to the conversation when they finished.`;
946
950
  }
947
951
  return "no sub-agents spawned this session yet.";
948
952
  },
@@ -2226,6 +2230,8 @@ function Root() {
2226
2230
  // lockstep. Factored out of applyMode so the plan-exit picker below can perform it from a resolve
2227
2231
  // callback without re-entering (and re-gating) applyMode itself.
2228
2232
  const performModeSwitch = useCallback((next, quiet) => {
2233
+ if (next === "delegate" && opModeRef.current !== "delegate" && opModeRef.current !== "plan")
2234
+ beforeDelegateRef.current = opModeRef.current;
2229
2235
  if (next === "plan" && opModeRef.current !== "plan")
2230
2236
  beforePlanRef.current = opModeRef.current;
2231
2237
  if (next === "plan") {
@@ -3076,12 +3082,22 @@ function Root() {
3076
3082
  const status = () => {
3077
3083
  const team = s.moaTeam();
3078
3084
  const d = settings.delegate ?? {};
3079
- return delegateStatusLines({ activeModel: s.currentModel(), plannerModel: settings.moa?.plannerModel?.trim() ? team?.planner.id : undefined, specialist: team?.specialist, subagentModel: subagentModel(), guard: delegateGuardOn(process.env, d), allowPush: !!d.allowPush, repos: d.repos ?? [] }).join("\n");
3085
+ return delegateStatusLines({ mode: opModeRef.current === "delegate", activeModel: s.currentModel(), plannerModel: settings.moa?.plannerModel?.trim() ? team?.planner.id : undefined, specialist: team?.specialist, subagentModel: subagentModel(), guard: delegateGuardOn(process.env, d), allowPush: !!d.allowPush, repos: d.repos ?? [] }).join("\n");
3080
3086
  };
3081
3087
  if (a.kind === "error") {
3082
3088
  sys(a.message);
3083
3089
  break;
3084
3090
  }
3091
+ if (a.kind === "on") {
3092
+ applyMode("delegate");
3093
+ break;
3094
+ }
3095
+ // In Delegate mode, off leaves the mode and nothing else: the guard and planner the owner set stay as they are.
3096
+ if (a.kind === "off" && opModeRef.current === "delegate") {
3097
+ applyMode(beforeDelegateRef.current);
3098
+ sys("delegate · mode off. Guard and planner unchanged; /delegate off again clears them.");
3099
+ break;
3100
+ }
3085
3101
  if (a.kind === "planner") {
3086
3102
  const executor = a.executor ?? (settings.moa?.specialist?.id ? undefined : subagentModelFor({ autonomy: settings.autonomy }));
3087
3103
  const r = s.setMoaPlanner(a.model, executor);
@@ -3152,7 +3168,7 @@ function Root() {
3152
3168
  if (!gated)
3153
3169
  sys(on
3154
3170
  ? "◔ plan mode ON — I'll research read-only and propose a plan; writes/edits/shell mutations are blocked. /plan again to approve + execute."
3155
- : `plan mode OFF — back to ${next === "auto" ? "Autonomous" : next === "manual" ? "Manual" : "Gated"}.`);
3171
+ : `plan mode OFF — back to ${MODE_NAME[next]}.`);
3156
3172
  break;
3157
3173
  }
3158
3174
  case "mode": {
@@ -3160,7 +3176,7 @@ function Root() {
3160
3176
  // addressable, plus gated, which is outside the cycle. No arg → report current.
3161
3177
  const target = parseMode(arg);
3162
3178
  if (!target) {
3163
- sys(`mode is ${opModeRef.current === "auto" ? "AUTONOMOUS" : opModeRef.current.toUpperCase()} — usage: /mode autonomous | manual | plan | gated`);
3179
+ sys(`mode is ${MODE_NAME[opModeRef.current].toUpperCase()} — usage: /mode autonomous | delegate | manual | plan | gated`);
3164
3180
  break;
3165
3181
  }
3166
3182
  applyMode(target);
@@ -3365,8 +3381,9 @@ function Root() {
3365
3381
  const running = l.filter((a) => a.status === "working").length;
3366
3382
  const queued = l.filter((a) => a.status === "queued").length;
3367
3383
  const done = l.filter((a) => a.status === "idle").length;
3368
- const errored = l.filter((a) => a.status === "stopped").length;
3369
- const counts = [running ? `${running} running` : "", queued ? `${queued} queued` : "", done ? `${done} done` : "", errored ? `${errored} errored` : ""].filter(Boolean).join(" · ");
3384
+ const errored = l.filter((a) => a.status === "stopped" && erroredOut(a)).length;
3385
+ const stopped = l.filter((a) => a.status === "stopped").length - errored;
3386
+ const counts = [running ? `${running} running` : "", queued ? `${queued} queued` : "", done ? `${done} done` : "", stopped ? `${stopped} stopped` : "", errored ? `${errored} errored` : ""].filter(Boolean).join(" · ");
3370
3387
  sys(`sub-agents (${counts}):\n` + l.map((a) => ` ${formatAgentDetail(a)}${a.resumed ? " · resumed" : ""}`).join("\n") + pausedLines);
3371
3388
  break;
3372
3389
  }
@@ -371,6 +371,8 @@ export function basePersona(_cwd = process.cwd(), opts = {}) {
371
371
  `\nScratch dir (also \`$OPERATOR_SCRATCH\` in every shell) — temporary scripts, probe ` +
372
372
  `output, downloads to inspect, intermediate files: ALWAYS here, never /tmp and never the repo root. It is ` +
373
373
  `git-ignored and swept after a week, so nothing you keep belongs in it; name files \`<subject>-<thing>\`.` +
374
+ (typeof process !== "undefined" && process.platform === "darwin"
375
+ ? `\nmacOS: BSD tools (no \`grep -P\`); Mac ssh is zsh: quote globs.` : "") +
374
376
  ctxLine +
375
377
  `\n## Talking about yourself\nYou are Operator, AXE's agent, whichever model is serving you — the model underneath can change between sessions (or mid-session with /model) and you are still Operator. Asked what you are, say you are Operator; give ` +
376
378
  `the context window above if asked. What you may say about the model underneath is set by the "Active model" section at the end ` +
@@ -440,14 +442,14 @@ export function basePersona(_cwd = process.cwd(), opts = {}) {
440
442
  `intent; a failed step is cancelled and replaced by a revised one. The owner watches the list live, so never ` +
441
443
  `restate the numbered plan in prose round after round — narrate only what you are doing now.`) +
442
444
  `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT, issue them as multiple tool calls in a ` +
443
- `SINGLE message so they run in parallel — independent bash commands included (they overlap for real). ` +
445
+ `SINGLE message so they run together — independent bash commands included. ` +
444
446
  `Serialize only when one call's output feeds the next. Read several files with ONE read_files call.` +
445
447
  `\n## Long-running commands\nBuilds, servers, watchers, test suites and batches go to shell_background from ` +
446
448
  `the start; a finished job announces itself at your next turn, so do NOT poll bash_output in a loop.` +
447
449
  `\n## Downloading files\nUse download_file (on demand), never curl/wget, and NEVER say a file is downloaded until its ` +
448
450
  `completion notice says so; a 0-byte file, an HTML page with an .iso/.zip name or a failed hash is a FAILURE ` +
449
451
  `to report and fix, not to retry blindly.` +
450
- `\n## Finding things\nContent: the search tool scoped to a directory — never bash \`grep -r\` / \`rg\` / ` +
452
+ `\n## Finding things\nContent: the search tool scoped to a directory, then file_read, not cat/sed. Never bash \`grep -r\` / \`rg\` / ` +
451
453
  `\`find ~/ | grep\` over $HOME or / (it refuses those roots because they wedge the TUI for minutes). Check the ` +
452
454
  `2-3 most likely directories first, batched in ONE message.\nA FLEET HOST / server name (acropolis, jl1, jla, …): ` +
453
455
  `\`~/.ssh/config\` + \`ssh <name> 'hostname; uptime'\`, then \`gh repo view axetechnologies/<name>\`, then fleet ` +
@@ -496,7 +498,8 @@ export function harnessRules(cwd = process.cwd(), opts = {}) {
496
498
  // (10/31: on JL2 Cortana never saw the rule). Static per session — cache-safe.
497
499
  function subagentsSection(opts) {
498
500
  return opts.interactive
499
- ? `\n## Sub-agents — you stay the lead\nWhen work splits into independent parts, call spawn_agent in the SAME round ` +
501
+ ? `\n## Sub-agents — you stay the lead\nDelegate to finish sooner: when work splits into independent parts, ` +
502
+ `call spawn_agent in the SAME round ` +
500
503
  `you decide to (never announce it without the call; its description carries the brief format and rules) and ` +
501
504
  `tell the owner who you are sending and why. While they run, do what does not depend on them and never redo a ` +
502
505
  `step an agent is still working on. When a report or a STUCK notice arrives, check what the agent produced ` +
@@ -552,6 +555,20 @@ export const AUTONOMOUS_MODE_ON = `Autonomous mode is on: the owner reviews plan
552
555
  `unless it has a risky step.`;
553
556
  export const AUTONOMOUS_MODE_OFF = `Autonomous mode is off: stop following its plan-review rules. The Decision points rules apply again, and a step ` +
554
557
  `that needs approval asks the owner when you make it.`;
558
+ /** Delegate mode (permissions/modes.ts) runs with Autonomous's permissions and plan reviews, and adds this. It rides each
559
+ * owner message that asks for work (engine/delegate-turn.ts), after the owner's words, never the system prompt.
560
+ * `free` is the sub-agent route's free lanes when the router reports them. */
561
+ export function delegateModeOn(free) {
562
+ const head = `Delegate mode is on: you lead, sub-agents cover ground. `;
563
+ if (free === 0)
564
+ return `${head}No sub-agent lane is free right now: do this turn's work yourself.`;
565
+ return `${head}For a message that asks for work, split off the independent parts and send them with spawn_agent in your ` +
566
+ `FIRST tool round${free === undefined ? "" : ` (${free} sub-agent lane${free === 1 ? "" : "s"} free now)`}; keep the ` +
567
+ `rest, check each report against its brief, and answer the owner yourself. Plan reviews still apply: research, ` +
568
+ `search, review and plan agents (set role) may go first; on a build, other agents wait for the plan review. ` +
569
+ `A greeting or a one-line question: answer it directly. If nothing can usefully be split off, say why in one line.`;
570
+ }
571
+ export const DELEGATE_MODE_OFF = `Delegate mode is off: delegate only when it helps.`;
555
572
  // Embodiment guidance, appended only to an interactive session with computer control on. It steers the
556
573
  // model to READ the screen with chauffeur's textual accessibility tree instead of hand-rolling osascript —
557
574
  // the exact loop that failed on Slack (AppleScript can't read Electron UIs). `chauffeurReady` = chauffeur is
@@ -32,10 +32,12 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
32
32
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
33
33
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
34
34
  import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision, unwrapToolCall } from "./decision-points.js";
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
+ import { DISPATCH, 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
36
36
  /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
37
37
  * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
38
38
  export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
39
+ import { batchHints } from "./batch-hints.js";
40
+ import { DELEGATE_FINAL_NOTE, DELEGATE_ROUNDS, DELEGATE_ROUNDS_NOTE } from "./delegate-turn.js";
39
41
  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";
40
42
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
41
43
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
@@ -122,6 +124,9 @@ const LOOP_ADMISSION_RE = /\bI(?:['’]ve| have) been stuck\b|\bI(?:['’]ve| ha
122
124
  // still gets its one soft nudge first. Paired with turn-continuation (continuation.ts): keep going on real work,
123
125
  // stop on circles.
124
126
  const NO_CONVERGE_LIMIT = 25;
127
+ const REPORT_RUNWAY = 3; // rounds left before a cap when an agent that cannot write is told to report
128
+ const REPORT_NOW = "This run is about to hit its round limit. Stop calling tools and report your findings now, in the form your brief asks " +
129
+ "for: what you checked, what you found (with path:line), and what you did not get to.";
125
130
  const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
126
131
  // Think-spiral latch: with /think ON, a reasoning model can spend round after round in heavy reasoning that
127
132
  // keeps acting (a poll/read tool) but never edits a file or answers. The churn lives in the reasoning
@@ -711,7 +716,7 @@ export async function runTurn(userInput, conversation, opts) {
711
716
  const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
712
717
  const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
713
718
  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 — mode-gated hard stop (FIX 2); the attended read-only-loop backstop is the LoopGuard terminal (FIX 1)
719
+ const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite && opts.canWrite !== false) : undefined; // investigate-loop detector — mode-gated hard stop (FIX 2); the attended read-only-loop backstop is the LoopGuard terminal (FIX 1)
715
720
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
716
721
  // Loop reset (loop-guard.ts "Loop evidence"): every loop-family nudge is counted; the Nth one the model has seen and
717
722
  // answered with no landed write since, while the turn repeats itself (a warning ignored), is not injected — before
@@ -742,6 +747,7 @@ export async function runTurn(userInput, conversation, opts) {
742
747
  let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
743
748
  let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
744
749
  let delegationNudged = false; // the delegation-by-prose nudge (continuation.ts) fires at most once per turn
750
+ let reportAsked = false; // a reader was told to report before a cap ends the turn
745
751
  let budgetWarned = false; // the one-time "near the time budget, converge" warning fires before the hard wall-clock stop
746
752
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
747
753
  let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
@@ -795,7 +801,15 @@ export async function runTurn(userInput, conversation, opts) {
795
801
  // Delegation-by-prose guard applies only where spawn_agent is actually offered (interactive foreground; a bg
796
802
  // sub-agent has no spawn tool and must not be told to call one).
797
803
  const hasSpawnTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "spawn_agent");
804
+ const widen = opts.batchHints ? batchHints(hasSpawnTool) : undefined;
798
805
  let announceNudges = 0;
806
+ let delegateAsked = false; // Delegate mode's one note per turn
807
+ let delegated = false; // spawn_agent was called, whether or not a lane took it
808
+ let blindRounds = 0; // tool rounds with no spawn_agent
809
+ let answeredBeforeDelegateNote;
810
+ let keptAnswer = ""; // that answer, when the note sent the model back to work: the turn's result keeps it
811
+ // `display` stays the new text alone: the kept answer is already on screen above the calls that followed it.
812
+ const withKept = (r) => keptAnswer ? { ...r, content: `${keptAnswer}\n\n${r.content}`, display: r.display ?? r.content } : r;
799
813
  let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
800
814
  let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
801
815
  let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
@@ -827,10 +841,28 @@ export async function runTurn(userInput, conversation, opts) {
827
841
  // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
828
842
  let convergeStreak = 0;
829
843
  const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
844
+ const delegateDue = () => !!opts.delegate && hasSpawnTool && !opts.background && !opts.unattended &&
845
+ !delegateAsked && !delegated && ownerActStage === 0 && opts.delegate.freeLanes?.() !== 0;
846
+ const delegateRound = (calls) => {
847
+ if (answeredBeforeDelegateNote)
848
+ keptAnswer = answeredBeforeDelegateNote.content; // it went on working
849
+ answeredBeforeDelegateNote = undefined;
850
+ delegated ||= calls.some((c) => {
851
+ const name = c.function?.name ?? "";
852
+ if (name !== "tool_call")
853
+ return DISPATCH.has(name);
854
+ const a = parseToolArgs(c.function.arguments ?? "");
855
+ return DISPATCH.has(unwrapToolCall(name, a.ok ? a.args : {}).name);
856
+ });
857
+ if (++blindRounds >= DELEGATE_ROUNDS && delegateDue()) {
858
+ delegateAsked = true;
859
+ engineUser(DELEGATE_ROUNDS_NOTE);
860
+ }
861
+ };
830
862
  const stopTurn = (note, kind, roundsRun, stopReason) => {
831
863
  const text = closeStopNote(note, opts.preservedState?.(), kind); // never a bare stop: the open items + how to steer
832
864
  conversation.assistant(text);
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() };
865
+ return withKept({ 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() });
834
866
  };
835
867
  // Never silent (11/04): a router's legs are each tried once per round. When all of them fail, or the model keeps
836
868
  // finishing with nothing in its reply, the model's fallback (TurnModel) takes the rest of THIS turn; a turn nothing
@@ -1141,6 +1173,10 @@ export async function runTurn(userInput, conversation, opts) {
1141
1173
  `The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
1142
1174
  return stopTurn(note, "paused", rounds);
1143
1175
  }
1176
+ if (opts.canWrite === false && !reportAsked && (rounds >= absCeiling - REPORT_RUNWAY || convergeStreak >= NO_CONVERGE_LIMIT - REPORT_RUNWAY)) {
1177
+ reportAsked = true;
1178
+ engineUser(REPORT_NOW);
1179
+ }
1144
1180
  if (rounds === softRounds)
1145
1181
  opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
1146
1182
  // Progress-aware stop: past the soft budget, end the turn only on a GENUINE stall (N consecutive
@@ -1703,7 +1739,7 @@ export async function runTurn(userInput, conversation, opts) {
1703
1739
  // Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
1704
1740
  // gets a plan + options (ask_user), or in Autonomous mode a plan review, instead of a silently picked approach.
1705
1741
  // This round's calls are not dispatched.
1706
- 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 })) })) {
1742
+ if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, holds: decisionHolds, maxHolds: decisionMaxHolds, writerSpawns: opts.decisionPoints?.writerSpawns, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1707
1743
  decisionHolds++;
1708
1744
  if (response.content.trim())
1709
1745
  conversation.assistant(cleanAssistantProse(response.content));
@@ -1778,6 +1814,7 @@ export async function runTurn(userInput, conversation, opts) {
1778
1814
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1779
1815
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1780
1816
  trackTouchedFiles(response.toolCalls, touchedFiles);
1817
+ delegateRound(response.toolCalls);
1781
1818
  if (response.toolCalls.some((c) => c.function?.name === "ask_user")) {
1782
1819
  repliesSinceOwner = -1;
1783
1820
  askedThisTurn = true;
@@ -1796,8 +1833,9 @@ export async function runTurn(userInput, conversation, opts) {
1796
1833
  // Delegation-by-prose guard: the round's narration said "spawn sub-agents / delegate" but none of its calls
1797
1834
  // delegated. Nudge ONCE per turn to make the call (tasks[] for parallel work) or stop announcing it — a
1798
1835
  // nudge, never a stop; the model may legitimately decide the work is sequential after all.
1799
- if (!delegationNudged && hasSpawnTool && detectAnnouncedDelegation(response.content, response.toolCalls.map((c) => c.function?.name ?? ""))) {
1836
+ if (!delegationNudged && !delegateAsked && hasSpawnTool && detectAnnouncedDelegation(response.content, response.toolCalls.map((c) => c.function?.name ?? ""))) {
1800
1837
  delegationNudged = true;
1838
+ delegateAsked ||= !!opts.delegate;
1801
1839
  engineUser(DELEGATION_NUDGE);
1802
1840
  }
1803
1841
  // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
@@ -1831,6 +1869,9 @@ export async function runTurn(userInput, conversation, opts) {
1831
1869
  }
1832
1870
  if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
1833
1871
  return stopTurn(notConvergingNote(response.toolCalls), "stopped", rounds + 1);
1872
+ const hint = widen?.(response.toolCalls);
1873
+ if (hint)
1874
+ engineUser(hint);
1834
1875
  continue;
1835
1876
  }
1836
1877
  // No structured tool_calls — check for text-encoded ones before treating this as final.
@@ -1842,7 +1883,7 @@ export async function runTurn(userInput, conversation, opts) {
1842
1883
  if (fromReasoning.calls.length > 0)
1843
1884
  recovered = { ...recovered, calls: fromReasoning.calls };
1844
1885
  }
1845
- 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 })) })) {
1886
+ if (recovered.calls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, holds: decisionHolds, maxHolds: decisionMaxHolds, writerSpawns: opts.decisionPoints?.writerSpawns, calls: recovered.calls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1846
1887
  decisionHolds++;
1847
1888
  if (recovered.cleanedContent.trim())
1848
1889
  conversation.assistant(recovered.cleanedContent);
@@ -1907,6 +1948,7 @@ export async function runTurn(userInput, conversation, opts) {
1907
1948
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1908
1949
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1909
1950
  trackTouchedFiles(recovered.calls, touchedFiles);
1951
+ delegateRound(recovered.calls);
1910
1952
  if (recovered.calls.some((c) => c.function?.name === "ask_user")) {
1911
1953
  repliesSinceOwner = -1;
1912
1954
  askedThisTurn = true;
@@ -1960,6 +2002,12 @@ export async function runTurn(userInput, conversation, opts) {
1960
2002
  engineUser("Your last tool call was malformed (a tag was missing or the call was cut off), so NOTHING ran. Call the tool again now as a proper tool call, with the complete arguments. If the content is long, split it into smaller calls.");
1961
2003
  continue;
1962
2004
  }
2005
+ // The reply to Delegate mode's closing note, with no call in it: the answer already given stands, whatever this says.
2006
+ if (answeredBeforeDelegateNote) {
2007
+ if (final)
2008
+ conversation.assistant(final);
2009
+ return { ...answeredBeforeDelegateNote, content: [answeredBeforeDelegateNote.content, final].filter(Boolean).join("\n\n"), rounds: rounds + 1, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
2010
+ }
1963
2011
  // Empty round — two very different causes, handled differently so we never (a) inject a user-role
1964
2012
  // directive that renders as the user speaking and gets answered as the request, nor (b) treat a
1965
2013
  // budget-truncated turn as a "dud".
@@ -2115,7 +2163,14 @@ export async function runTurn(userInput, conversation, opts) {
2115
2163
  // Nothing in the reply or its reasoning: `answer` is the engine's output-limit note, said plainly on screen.
2116
2164
  const cutOff = !final && !stripScratchpad(response.reasoningContent ?? "") && !stripScratchpad(lastReasoning);
2117
2165
  const display = cutOff ? stopQuestion("length", opts.preservedState?.()) : undefined;
2118
- 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() };
2166
+ const result = { 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() };
2167
+ if (final && !declined && response.stopReason !== "length" && rounds + 1 < absCeiling && delegateDue()) {
2168
+ delegateAsked = true;
2169
+ answeredBeforeDelegateNote = result;
2170
+ engineUser(DELEGATE_FINAL_NOTE);
2171
+ continue;
2172
+ }
2173
+ return withKept(result);
2119
2174
  }
2120
2175
  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]`;
2121
2176
  return stopTurn(timeoutMsg, "rounds", rounds);
@@ -210,7 +210,8 @@ const HEAD_MAX = 65_536; // a non-SSE body is read whole up to this: a JSON erro
210
210
  // here before; this replaces that whole idea with a clean stream stop + prefix trim.
211
211
  // ---------------------------------------------------------------------------
212
212
  const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets, "OK")
213
- const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
213
+ const LOOP_LINE_REPEATS = 6; // a substantial line or phrase seen this many times counts as repeated
214
+ const LOOP_COVERAGE = 0.5; // …and repeats must make up this much of the scanned tail to be a loop
214
215
  const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
215
216
  const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
216
217
  const LOOP_SCAN_TAIL = 4000; // repeats are counted in this much of the tail: a loop piles up there, while a long
@@ -237,38 +238,37 @@ export function isDegenerate(text) {
237
238
  if (text.length > RUNAWAY_CHARS)
238
239
  return true;
239
240
  const recent = text.slice(-LOOP_SCAN_TAIL);
240
- // (a) a substantial line repeated many times in the recent tail — counted both exact and fuzzy-normalized.
241
- const exact = new Map();
242
- const norm = new Map();
243
- for (const raw of recent.split("\n")) {
244
- const line = raw.trim();
245
- if (line.length < LOOP_MIN_LINE_LEN || !hasAlpha(line))
246
- continue;
247
- const ne = (exact.get(line) ?? 0) + 1;
248
- if (ne >= LOOP_LINE_REPEATS)
249
- return true;
250
- exact.set(line, ne);
251
- const nl = normLoop(line);
252
- if (nl.length >= LOOP_MIN_LINE_LEN) {
253
- const nn = (norm.get(nl) ?? 0) + 1;
254
- if (nn >= LOOP_LINE_REPEATS)
255
- return true;
256
- norm.set(nl, nn);
257
- }
258
- }
259
- // (c) a normalized word n-gram repeated many times in the recent tail — catches a run-together / garbled loop
260
- // that is one long line with trailing junk, so it's neither line- nor cycle-aligned.
241
+ // (a) substantial lines repeated many times in the recent tail, exact or fuzzy-normalized, that together make up
242
+ // most of it. A report repeats a field line (`"severity": "med",`) once per finding between distinct text.
243
+ const lines = recent.split("\n").map((l) => l.trim()).filter(Boolean);
244
+ const keys = (line) => (line.length < LOOP_MIN_LINE_LEN || !hasAlpha(line) ? [] : [line, normLoop(line)].filter((k) => k.length >= LOOP_MIN_LINE_LEN));
245
+ const counts = [new Map(), new Map()];
246
+ for (const line of lines)
247
+ keys(line).forEach((k, i) => counts[i].set(k, (counts[i].get(k) ?? 0) + 1));
248
+ const repeated = lines.filter((line) => keys(line).some((k, i) => (counts[i].get(k) ?? 0) >= LOOP_LINE_REPEATS));
249
+ const chars = (xs) => xs.reduce((n, x) => n + x.length, 0);
250
+ if (repeated.length && chars(repeated) >= chars(lines) * LOOP_COVERAGE)
251
+ return true;
252
+ // (c) normalized word n-grams repeated many times that cover most of the recent tail — catches a run-together /
253
+ // garbled loop that is one long line with trailing junk, so it's neither line- nor cycle-aligned. Findings that
254
+ // cite one long directory share a phrase, not most of their words.
261
255
  const words = normLoop(recent).split(" ").filter(Boolean);
262
256
  const N = 8;
263
257
  if (words.length >= N * LOOP_LINE_REPEATS) {
264
- const grams = new Map();
265
- for (let i = 0; i + N <= words.length; i++) {
266
- const g = words.slice(i, i + N).join(" ");
267
- const c = (grams.get(g) ?? 0) + 1;
268
- if (c >= LOOP_LINE_REPEATS)
269
- return true;
270
- grams.set(g, c);
271
- }
258
+ const grams = words.slice(0, words.length - N + 1).map((_, i) => words.slice(i, i + N).join(" "));
259
+ const seen = new Map();
260
+ for (const g of grams)
261
+ seen.set(g, (seen.get(g) ?? 0) + 1);
262
+ let covered = 0;
263
+ let end = 0;
264
+ grams.forEach((g, i) => {
265
+ if ((seen.get(g) ?? 0) < LOOP_LINE_REPEATS)
266
+ return;
267
+ covered += i + N - Math.max(i, end);
268
+ end = i + N;
269
+ });
270
+ if (covered >= words.length * LOOP_COVERAGE)
271
+ return true;
272
272
  }
273
273
  // (b) the tail is one short cycle repeated back-to-back — check raw tail (token loop, no newlines) AND
274
274
  // the normalized tail (garbled/interleaved repeat that isn't byte-exact).