@0perator/operator 0.2.5 → 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.
@@ -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
  }
@@ -555,6 +555,20 @@ export const AUTONOMOUS_MODE_ON = `Autonomous mode is on: the owner reviews plan
555
555
  `unless it has a risky step.`;
556
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 ` +
557
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.`;
558
572
  // Embodiment guidance, appended only to an interactive session with computer control on. It steers the
559
573
  // model to READ the screen with chauffeur's textual accessibility tree instead of hand-rolling osascript —
560
574
  // the exact loop that failed on Slack (AppleScript can't read Electron UIs). `chauffeurReady` = chauffeur is
@@ -32,11 +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
39
  import { batchHints } from "./batch-hints.js";
40
+ import { DELEGATE_FINAL_NOTE, DELEGATE_ROUNDS, DELEGATE_ROUNDS_NOTE } from "./delegate-turn.js";
40
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";
41
42
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
42
43
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
@@ -123,6 +124,9 @@ const LOOP_ADMISSION_RE = /\bI(?:['’]ve| have) been stuck\b|\bI(?:['’]ve| ha
123
124
  // still gets its one soft nudge first. Paired with turn-continuation (continuation.ts): keep going on real work,
124
125
  // stop on circles.
125
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.";
126
130
  const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
127
131
  // Think-spiral latch: with /think ON, a reasoning model can spend round after round in heavy reasoning that
128
132
  // keeps acting (a poll/read tool) but never edits a file or answers. The churn lives in the reasoning
@@ -712,7 +716,7 @@ export async function runTurn(userInput, conversation, opts) {
712
716
  const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
713
717
  const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
714
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
715
- const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite) : undefined; // investigate-loop detector — mode-gated hard stop (FIX 2); the attended read-only-loop backstop is the LoopGuard terminal (FIX 1)
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)
716
720
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
717
721
  // Loop reset (loop-guard.ts "Loop evidence"): every loop-family nudge is counted; the Nth one the model has seen and
718
722
  // answered with no landed write since, while the turn repeats itself (a warning ignored), is not injected — before
@@ -743,6 +747,7 @@ export async function runTurn(userInput, conversation, opts) {
743
747
  let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
744
748
  let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
745
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
746
751
  let budgetWarned = false; // the one-time "near the time budget, converge" warning fires before the hard wall-clock stop
747
752
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
748
753
  let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
@@ -798,6 +803,13 @@ export async function runTurn(userInput, conversation, opts) {
798
803
  const hasSpawnTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "spawn_agent");
799
804
  const widen = opts.batchHints ? batchHints(hasSpawnTool) : undefined;
800
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;
801
813
  let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
802
814
  let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
803
815
  let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
@@ -829,10 +841,28 @@ export async function runTurn(userInput, conversation, opts) {
829
841
  // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
830
842
  let convergeStreak = 0;
831
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
+ };
832
862
  const stopTurn = (note, kind, roundsRun, stopReason) => {
833
863
  const text = closeStopNote(note, opts.preservedState?.(), kind); // never a bare stop: the open items + how to steer
834
864
  conversation.assistant(text);
835
- 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() });
836
866
  };
837
867
  // Never silent (11/04): a router's legs are each tried once per round. When all of them fail, or the model keeps
838
868
  // finishing with nothing in its reply, the model's fallback (TurnModel) takes the rest of THIS turn; a turn nothing
@@ -1143,6 +1173,10 @@ export async function runTurn(userInput, conversation, opts) {
1143
1173
  `The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
1144
1174
  return stopTurn(note, "paused", rounds);
1145
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
+ }
1146
1180
  if (rounds === softRounds)
1147
1181
  opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
1148
1182
  // Progress-aware stop: past the soft budget, end the turn only on a GENUINE stall (N consecutive
@@ -1705,7 +1739,7 @@ export async function runTurn(userInput, conversation, opts) {
1705
1739
  // Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
1706
1740
  // gets a plan + options (ask_user), or in Autonomous mode a plan review, instead of a silently picked approach.
1707
1741
  // This round's calls are not dispatched.
1708
- 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 })) })) {
1709
1743
  decisionHolds++;
1710
1744
  if (response.content.trim())
1711
1745
  conversation.assistant(cleanAssistantProse(response.content));
@@ -1780,6 +1814,7 @@ export async function runTurn(userInput, conversation, opts) {
1780
1814
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1781
1815
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1782
1816
  trackTouchedFiles(response.toolCalls, touchedFiles);
1817
+ delegateRound(response.toolCalls);
1783
1818
  if (response.toolCalls.some((c) => c.function?.name === "ask_user")) {
1784
1819
  repliesSinceOwner = -1;
1785
1820
  askedThisTurn = true;
@@ -1798,8 +1833,9 @@ export async function runTurn(userInput, conversation, opts) {
1798
1833
  // Delegation-by-prose guard: the round's narration said "spawn sub-agents / delegate" but none of its calls
1799
1834
  // delegated. Nudge ONCE per turn to make the call (tasks[] for parallel work) or stop announcing it — a
1800
1835
  // nudge, never a stop; the model may legitimately decide the work is sequential after all.
1801
- 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 ?? ""))) {
1802
1837
  delegationNudged = true;
1838
+ delegateAsked ||= !!opts.delegate;
1803
1839
  engineUser(DELEGATION_NUDGE);
1804
1840
  }
1805
1841
  // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
@@ -1847,7 +1883,7 @@ export async function runTurn(userInput, conversation, opts) {
1847
1883
  if (fromReasoning.calls.length > 0)
1848
1884
  recovered = { ...recovered, calls: fromReasoning.calls };
1849
1885
  }
1850
- 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 })) })) {
1851
1887
  decisionHolds++;
1852
1888
  if (recovered.cleanedContent.trim())
1853
1889
  conversation.assistant(recovered.cleanedContent);
@@ -1912,6 +1948,7 @@ export async function runTurn(userInput, conversation, opts) {
1912
1948
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1913
1949
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1914
1950
  trackTouchedFiles(recovered.calls, touchedFiles);
1951
+ delegateRound(recovered.calls);
1915
1952
  if (recovered.calls.some((c) => c.function?.name === "ask_user")) {
1916
1953
  repliesSinceOwner = -1;
1917
1954
  askedThisTurn = true;
@@ -1965,6 +2002,12 @@ export async function runTurn(userInput, conversation, opts) {
1965
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.");
1966
2003
  continue;
1967
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
+ }
1968
2011
  // Empty round — two very different causes, handled differently so we never (a) inject a user-role
1969
2012
  // directive that renders as the user speaking and gets answered as the request, nor (b) treat a
1970
2013
  // budget-truncated turn as a "dud".
@@ -2120,7 +2163,14 @@ export async function runTurn(userInput, conversation, opts) {
2120
2163
  // Nothing in the reply or its reasoning: `answer` is the engine's output-limit note, said plainly on screen.
2121
2164
  const cutOff = !final && !stripScratchpad(response.reasoningContent ?? "") && !stripScratchpad(lastReasoning);
2122
2165
  const display = cutOff ? stopQuestion("length", opts.preservedState?.()) : undefined;
2123
- 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);
2124
2174
  }
2125
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]`;
2126
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).
@@ -5,7 +5,7 @@
5
5
  // owner turn, the FIRST mutating call before any ask_user is held back once and the model is told to offer a
6
6
  // plan + options first — or, in Autonomous mode, to put the plan up for review. Pure and dependency-free so the
7
7
  // gate's trigger logic is unit-testable.
8
- import { SHELL_ANY, isMutatingTool } from "../tools/classes.js";
8
+ import { DISPATCH, SHELL_ANY, isMutatingTool } from "../tools/classes.js";
9
9
  // Shell commands that change the workspace or the machine. Read-only probes (ls, cat, grep, git status, a test
10
10
  // run) are NOT here — the gate must never hold back investigation, only the first change.
11
11
  const MUTATING_SHELL_RE = new RegExp([
@@ -84,6 +84,16 @@ export function decisionPointsEnabled(setting, env = process.env) {
84
84
  return true;
85
85
  return setting !== false;
86
86
  }
87
+ /** A spawn_agent call whose sub-agents may change files: any role but the four that cannot write, or none given. */
88
+ function isWriterSpawn(name, rawArgs) {
89
+ let args = {};
90
+ try {
91
+ args = JSON.parse(rawArgs || "{}");
92
+ }
93
+ catch { /* partial args: a writer */ }
94
+ const real = unwrapToolCall(name ?? "", args);
95
+ return DISPATCH.has(real.name) && !/^(?:research|search|review|plan)$/.test(String(real.args.role ?? ""));
96
+ }
87
97
  /** The gate's per-turn decision: hold back this round's mutating calls and nudge, or let them run. The hold is
88
98
  * ENFORCED, not one-shot — it KEEPS holding every mutating round (re-injecting the nudge) until the model
89
99
  * actually calls ask_user (`askedThisTurn`), so a model cannot just walk past a single nudge. Bounded by
@@ -93,5 +103,5 @@ export function shouldHoldForDecision(s) {
93
103
  return false;
94
104
  if (s.calls.some((c) => c.name === "ask_user"))
95
105
  return false;
96
- return s.calls.some((c) => isMutatingCall(c.name, c.args));
106
+ return s.calls.some((c) => isMutatingCall(c.name, c.args) || (!!s.writerSpawns && isWriterSpawn(c.name, c.args)));
97
107
  }
@@ -0,0 +1,24 @@
1
+ // Delegate mode's turn rules (permissions/modes.ts): which owner messages are asked to fan out, and the one note a turn
2
+ // that did not gets. Pure and dependency-free (agent.ts is also bundled for the browser). Not the delegate GUARD
3
+ // (autonomy/delegate-mode.ts, `/delegate guard`), which fences what delegated work may do.
4
+ import { isStatusAsk } from "./continuation.js";
5
+ /** Tool rounds without a spawn_agent call before the mid-turn note. */
6
+ export const DELEGATE_ROUNDS = 3;
7
+ const SOCIAL = /^(?:(?:hi|hey|hello|yo|howdy|gm|good (?:morning|afternoon|evening|night)|thanks|thank you|thx|ty|cheers|cool|nice|great|awesome|perfect|ok|okay|got it|sounds good|well done|bye|goodbye|there|operator|all|so much|man)[\s,.!:)-]*)+$/i;
8
+ const REQUEST = /^(?:please\b|(?:can|could|would|will) (?:you|we)\b(?!\s+(?:tell|explain)\b))/i;
9
+ const QUESTION = /^(?:what|why|how|where|when|who|which|is|are|am|was|were|does|do|did|can|could|would|will|should|has|have)\b/i;
10
+ /** Whether the owner's message asks for work. A greeting, thanks, a status ask or a one-line question does not. */
11
+ export function isWorkAsk(text) {
12
+ const t = text.trim();
13
+ if (!t || t.startsWith("[engine note") || SOCIAL.test(t) || isStatusAsk(t))
14
+ return false;
15
+ if (t.includes("\n") || t.length > 200 || REQUEST.test(t))
16
+ return true;
17
+ const oneSentence = !/[.!?]\s+\S/.test(t);
18
+ return !(oneSentence && t.endsWith("?") && (QUESTION.test(t) || t.split(/\s+/).length <= 12));
19
+ }
20
+ export const DELEGATE_ROUNDS_NOTE = "Delegate mode: several tool rounds and no spawn_agent call. Hand the independent parts that remain to sub-agents " +
21
+ "with spawn_agent now, or say in one line why not, and carry on.";
22
+ export const DELEGATE_FINAL_NOTE = "Delegate mode: this turn made no spawn_agent call. Your answer above stands and the owner has it. Either call " +
23
+ "spawn_agent now for independent parts still worth covering, or reply with ONE line saying why you did not " +
24
+ "delegate. Do not repeat the answer.";
@@ -11,6 +11,7 @@
11
11
  // mechanical children don't pin the single 1M slot.
12
12
  // Pure + framework-agnostic; node builtins (fs/child_process for verify) load lazily so the neutral bundle
13
13
  // is unaffected. The verify predicate (isVerifyCmd/ranButFailed) is shared with the main-loop verify gate.
14
+ import { FILE_READ, LOCAL_SEARCH, WEB_SEARCH } from "../tools/classes.js";
14
15
  import { isVerifyCmd, ranButFailed } from "./verify-gate.js";
15
16
  import { applySRFTMask } from "../flywheel/srft.js"; // PURE half — node-free, neutral-graph safe
16
17
  // runMutationCheck needs node:fs/child_process — resolved lazily via nodeImport() inside verifyMutation.
@@ -365,8 +366,9 @@ export function routeLane(brief, hint) {
365
366
  * searches it ran, and short excerpts of the last pages. Pure: the caller passes session.snapshot(). */
366
367
  function partialFindings(msgs) {
367
368
  const urls = [];
369
+ const files = [];
368
370
  const queries = [];
369
- const fetchIds = new Set();
371
+ const readIds = new Set();
370
372
  for (const m of msgs) {
371
373
  if (m.role !== "assistant" || !m.tool_calls)
372
374
  continue;
@@ -378,35 +380,50 @@ function partialFindings(msgs) {
378
380
  catch { /* unparseable args: skip */ }
379
381
  if ((c.function.name === "web_fetch" || c.function.name === "browser_read") && typeof a.url === "string") {
380
382
  urls.push(a.url);
381
- fetchIds.add(c.id);
383
+ readIds.add(c.id);
382
384
  }
383
- if ((c.function.name === "web_search" || c.function.name === "deep_research") && typeof (a.query ?? a.question) === "string")
384
- queries.push(String(a.query ?? a.question));
385
+ if (FILE_READ.has(c.function.name)) {
386
+ for (const p of Array.isArray(a.paths) ? a.paths : [a.path])
387
+ if (typeof p === "string") {
388
+ files.push(p);
389
+ readIds.add(c.id);
390
+ }
391
+ }
392
+ const q = a.query ?? a.question ?? a.pattern;
393
+ if ((WEB_SEARCH.has(c.function.name) || LOCAL_SEARCH.has(c.function.name)) && typeof q === "string")
394
+ queries.push(q);
385
395
  }
386
396
  }
387
397
  const notes = [...msgs].reverse().find((m) => m.role === "assistant" && m.content.trim() && !m.content.startsWith("[engine note"))?.content.trim() ?? "";
388
- return { urls, queries, fetchIds, notes };
398
+ return { urls, files, queries, readIds, notes };
389
399
  }
390
400
  /** What a stopped child had gathered, as counts for the owner's one-line report ("partial: 3 sources · 2 searches"). */
391
401
  export function partialCounts(msgs) {
392
- const { urls, queries, notes } = partialFindings(msgs);
402
+ const { urls, files, queries, notes } = partialFindings(msgs);
393
403
  const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
394
- const sources = new Set(urls).size, searches = new Set(queries).size;
395
- const parts = [sources ? n(sources, "source", "sources") : "", searches ? n(searches, "search", "searches") : "", notes ? "notes" : ""].filter(Boolean);
404
+ const sources = new Set(urls).size, read = new Set(files).size, searches = new Set(queries).size;
405
+ const parts = [sources ? n(sources, "source", "sources") : "", read ? n(read, "file", "files") : "", searches ? n(searches, "search", "searches") : "", notes ? "notes" : ""].filter(Boolean);
396
406
  return parts.length ? `partial: ${parts.join(" · ")}` : "partial: nothing gathered yet";
397
407
  }
408
+ /** A stopped child's conversation without the stop line the engine wrote as its last reply, which is not one of its
409
+ * notes. A reply cut at the output limit is the child's own words and stays. */
410
+ export function beforeStopNote(msgs, r) {
411
+ return r.stopKind !== "length" && msgs.at(-1)?.content === r.content ? msgs.slice(0, -1) : msgs;
412
+ }
398
413
  export function partialReport(msgs, why) {
399
- const { urls, queries, fetchIds, notes } = partialFindings(msgs);
400
- const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && fetchIds.has(m.tool_call_id) && m.content.trim())
414
+ const { urls, files, queries, readIds, notes } = partialFindings(msgs);
415
+ const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && readIds.has(m.tool_call_id) && m.content.trim())
401
416
  .slice(-2).map((m) => m.content.replace(/\s+/g, " ").trim().slice(0, 600));
402
417
  const uniq = (xs) => [...new Set(xs)];
403
418
  const parts = [`[${why} — PARTIAL findings below, gathered before it ended; verify before relying on them]`];
404
419
  parts.push(notes ? `Notes so far:\n${notes.slice(0, 3000)}` : "Notes so far: (none written yet)");
405
420
  if (urls.length)
406
421
  parts.push(`Sources read (${uniq(urls).length}):\n${uniq(urls).slice(0, 15).map((u) => `- ${u}`).join("\n")}`);
422
+ if (files.length)
423
+ parts.push(`Files read (${uniq(files).length}):\n${uniq(files).slice(-25).map((p) => `- ${p}`).join("\n")}`);
407
424
  if (queries.length)
408
425
  parts.push(`Searches run: ${uniq(queries).slice(0, 8).map((q) => `"${q}"`).join(" · ")}`);
409
426
  if (excerpts.length)
410
- parts.push(`Last pages read (excerpts):\n${excerpts.map((e) => `> ${e}`).join("\n")}`);
427
+ parts.push(`Last reads (excerpts):\n${excerpts.map((e) => `> ${e}`).join("\n")}`);
411
428
  return parts.join("\n\n");
412
429
  }
@@ -1,4 +1,5 @@
1
- export const MODE_CYCLE = ["auto", "manual", "plan"];
1
+ export const MODE_CYCLE = ["auto", "delegate", "manual", "plan"];
2
+ export const MODE_NAME = { auto: "Autonomous", delegate: "Delegate", manual: "Manual", plan: "Plan", gated: "Gated" };
2
3
  /** The mode a session starts in: gated when the settings say so, else Autonomous. */
3
4
  export function initialMode(configured) {
4
5
  return configured === "gated" ? "gated" : "auto";
@@ -16,6 +17,8 @@ export function parseMode(arg) {
16
17
  return "plan";
17
18
  if (a === "manual")
18
19
  return "manual";
20
+ if (a === "delegate")
21
+ return "delegate";
19
22
  if (a === "gated")
20
23
  return "gated";
21
24
  if (a === "auto" || a === "autonomous" || a === "bypass")
@@ -35,8 +38,9 @@ export function planToggleTarget(current, beforePlan) {
35
38
  * computer control is off). An "audit" seat keeps recording in every mode. */
36
39
  export function modePolicy(mode, base, computerAsk) {
37
40
  const unprompted = base.mode === "audit" ? "audit" : "bypass";
38
- if (mode === "auto")
39
- return { permissions: { ...base, mode: unprompted, rules: { ...base.rules } }, planReview: true };
41
+ if (mode === "auto" || mode === "delegate") {
42
+ return { permissions: { ...base, mode: unprompted, rules: { ...base.rules } }, planReview: true, ...(mode === "delegate" ? { delegate: true } : {}) };
43
+ }
40
44
  const rules = { ...base.rules, ...computerAsk };
41
45
  return { permissions: { ...base, mode: mode === "gated" ? "gated" : unprompted, rules }, planReview: false };
42
46
  }
package/dist/session.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Headless session controller — owns the conversation + engine wiring for ONE interactive session,
2
2
  // with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
3
3
  // that maps these callbacks onto React state; a test can drive the same `send()` directly.
4
- import { DELEGATION } from "./tools/classes.js";
4
+ import { DELEGATION, CAN_WRITE } from "./tools/classes.js";
5
5
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
6
6
  import { recordTruncation } from "./observability/blackbox.js";
7
7
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
@@ -29,6 +29,7 @@ import { operatorPath } from "./config/home.js";
29
29
  import { moaTeam, plannerBrief } from "./engine/moa.js";
30
30
  import { WATERFALL_MODEL_ID, WATERFALL_SEATS, waterfallTeam, waterfallTier } from "./engine/waterfall.js";
31
31
  import { routeTurn } from "./classifier/route.js";
32
+ import { isWorkAsk } from "./engine/delegate-turn.js";
32
33
  import { engineNote, isStatusAsk, STATUS_FIRST_NOTE } from "./engine/continuation.js";
33
34
  import { withDelegateDefault } from "./autonomy/delegate.js";
34
35
  import { withDelegateGuard } from "./autonomy/delegate-mode.js";
@@ -54,7 +55,7 @@ import { McpHub, withMcp } from "./mcp/index.js";
54
55
  import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
55
56
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
56
57
  import { PlanApproval, planReviewOptions, planReviewReply, riskClasses } from "./permissions/plan-review.js";
57
- import { AUTONOMOUS_MODE_ON, AUTONOMOUS_MODE_OFF } from "./config/persona.js";
58
+ import { AUTONOMOUS_MODE_ON, AUTONOMOUS_MODE_OFF, DELEGATE_MODE_OFF, delegateModeOn } from "./config/persona.js";
58
59
  import { withHooks } from "./hooks/index.js";
59
60
  import { servedTask } from "./engine/loop-guard.js";
60
61
  import { Telemetry } from "./observability/index.js";
@@ -493,6 +494,10 @@ export class Session {
493
494
  decisionPoints;
494
495
  planReview = false; // Autonomous mode: plan reviews instead of per-command prompts (setOperatingMode)
495
496
  planReviewTold = false; // what the conversation last told the model about Autonomous mode (modeCarry)
497
+ delegateMode = false; // Delegate mode: work turns are asked to fan out (delegateCarry)
498
+ delegateTold = false; // the conversation carries a Delegate mode note not yet withdrawn
499
+ spawnLanes;
500
+ canSpawn;
496
501
  planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
497
502
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
498
503
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
@@ -658,6 +663,8 @@ export class Session {
658
663
  if (this.hub)
659
664
  this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: offload huge MCP results too
660
665
  this.planReview = cfg.planReview === true;
666
+ this.canSpawn = !!cfg.spawnAgent;
667
+ this.spawnLanes = cfg.spawnSlots;
661
668
  this.permissionCfg = this.underReview(cfg.permissions ?? { mode: "bypass" });
662
669
  this.policy = new PermissionPolicy(this.permissionCfg);
663
670
  this.approve = cfg.approve;
@@ -828,6 +835,7 @@ export class Session {
828
835
  * ends when the plan changes. */
829
836
  setOperatingMode(m) {
830
837
  this.planReview = m.planReview;
838
+ this.delegateMode = m.delegate === true;
831
839
  // keep what /allow added this session: the mode's config is built from the startup settings, which lack it
832
840
  const allow = [...new Set([...(m.permissions.allow ?? []), ...(this.permissionCfg.allow ?? [])])];
833
841
  this.permissionCfg = this.underReview(allow.length ? { ...m.permissions, allow } : m.permissions);
@@ -843,10 +851,27 @@ export class Session {
843
851
  const on = this.planReview && !this.planMode;
844
852
  return { note: on === this.planReviewTold ? "" : engineNote(on ? AUTONOMOUS_MODE_ON : AUTONOMOUS_MODE_OFF), on };
845
853
  }
846
- /** What a compaction summary must keep: the active skill, and Autonomous mode's rules while they apply. */
854
+ inDelegateMode() {
855
+ return this.delegateMode;
856
+ }
857
+ /** Delegate mode's note for this message. While on, each owner message that asks for work carries the rules, and
858
+ * `fanOut` has the engine check the turn delegated; a wake turn, a greeting or a one-line question carries nothing.
859
+ * Sessions without spawn_agent (headless, sub-agents) are never asked. */
860
+ delegateCarry(ownerText) {
861
+ const on = this.delegateMode && !this.planMode;
862
+ if (!on)
863
+ return { note: this.delegateTold ? engineNote(DELEGATE_MODE_OFF) : "", on, fanOut: false };
864
+ const work = this.canSpawn && !this.background && !this.unattended && !this.wakeTurn && isWorkAsk(ownerText);
865
+ if (!work)
866
+ return { note: "", on, fanOut: false };
867
+ const free = this.spawnLanes?.();
868
+ return { note: engineNote(delegateModeOn(free)), on, fanOut: free !== 0 };
869
+ }
870
+ /** What a compaction summary must keep: the active skill, and Autonomous and Delegate mode's rules while they apply. */
847
871
  pinned() {
848
872
  const mode = this.planReview && !this.planMode ? engineNote(AUTONOMOUS_MODE_ON) : "";
849
- return [this.activeSkillBlock, mode].filter(Boolean).join("\n\n") || undefined;
873
+ const fan = this.delegateMode && !this.planMode ? engineNote(delegateModeOn()) : "";
874
+ return [this.activeSkillBlock, mode, fan].filter(Boolean).join("\n\n") || undefined;
850
875
  }
851
876
  /** `cfg` with this session's plan approval attached while plan review is on, and detached otherwise. */
852
877
  underReview(cfg) {
@@ -1152,6 +1177,7 @@ export class Session {
1152
1177
  this.rollingSummarizer.clear(); // clear the rolling summary on new session
1153
1178
  this.planApproval.clear(); // a fresh conversation has no reviewed plan
1154
1179
  this.planReviewTold = false; // …and has not been told the mode
1180
+ this.delegateTold = false;
1155
1181
  }
1156
1182
  /** Sleep-time consolidation — trigger memory reorganization. Returns the result. */
1157
1183
  async consolidate() {
@@ -1352,6 +1378,7 @@ export class Session {
1352
1378
  this.convo.replaceAll(msgs);
1353
1379
  this.planApproval.clear(); // another conversation: its plan was never reviewed here
1354
1380
  this.planReviewTold = false; // …and it has not been told the mode
1381
+ this.delegateTold = false;
1355
1382
  return true;
1356
1383
  }
1357
1384
  /** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
@@ -2112,6 +2139,9 @@ export class Session {
2112
2139
  if (this.memoryNote)
2113
2140
  text = `${text}\n\n${this.memoryNote}`; // after the owner's words: a leading note would mark the message as the engine's
2114
2141
  this.memoryNote = "";
2142
+ const fan = this.delegateCarry(ownerText);
2143
+ if (fan.note)
2144
+ text = `${text}\n\n${fan.note}`; // after the owner's words too: it rides every work message
2115
2145
  const turn = { text, task, convoStart, t0: _t0 };
2116
2146
  this.inflight = turn;
2117
2147
  const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
@@ -2131,6 +2161,7 @@ export class Session {
2131
2161
  onTurnState: (read) => { turn.read = read; }, // an interrupted turn is recorded from it (interruptedRecord)
2132
2162
  pinnedContext: () => this.pinned(), // a summary is a rewrite anyway: the skill and Autonomous mode's rules ride it
2133
2163
  preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
2164
+ canWrite: this.localSchemas.some((t) => CAN_WRITE.has(t.function.name)),
2134
2165
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
2135
2166
  affinity: this.affinity,
2136
2167
  liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
@@ -2170,6 +2201,7 @@ export class Session {
2170
2201
  h.onToolBatch?.(events, durationMs);
2171
2202
  },
2172
2203
  batchHints: !this.background,
2204
+ delegate: fan.fanOut ? { freeLanes: this.spawnLanes } : undefined,
2173
2205
  onAutoContinue: h.onAutoContinue,
2174
2206
  onCacheStats: h.onCacheStats,
2175
2207
  onServed: h.onServed,
@@ -2219,11 +2251,13 @@ export class Session {
2219
2251
  // Decision points: a build turn's first change waits for the owner's choice of direction (ask_user) — in
2220
2252
  // Autonomous mode, for a plan review. Off in plan mode (the plan + exit picker IS the decision) and inert where
2221
2253
  // ask_user isn't registered (headless).
2222
- decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview },
2254
+ decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview, writerSpawns: fan.on },
2223
2255
  });
2224
2256
  // The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
2225
2257
  if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
2226
2258
  this.planReviewTold = mode.on;
2259
+ if (fan.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(fan.note)))
2260
+ this.delegateTold = fan.on;
2227
2261
  this.telemetry.record({ type: "turn", ...shape, model: turnModelId, rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2228
2262
  // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
2229
2263
  // by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
@@ -62,6 +62,8 @@ export const FAILURE_TOLERANT = set("bash", "shell_exec", "shell_background", "b
62
62
  /** Write-progress for the investigate-loop detector. Narrower than PROGRESS: a grep inside bash is the pattern that
63
63
  * detector exists for, so shells and git_command are out. */
64
64
  export const WRITE_PROGRESS = set(FILE_WRITE, "checkpoint", PLAN_WRITE, "memory_store", DELEGATION, "cronjob");
65
+ /** An agent holding none of these cannot write, so it is never stopped for not writing (agent.ts). */
66
+ export const CAN_WRITE = set(WRITE_PROGRESS, SHELL_ANY, "git_command");
65
67
  // ── Scheduling ────────────────────────────────────────────────────────────────────────────────────────────
66
68
  /** Calls that run alone in a batch: each can touch anything. delegate_task is a whole sub-agent session with the full
67
69
  * tool set, delegate_to_agent an external CLI agent with write and shell access, spawn_cloud_agent a whole agent in a
package/dist/ui/App.js CHANGED
@@ -38,7 +38,7 @@ import { cellWidth } from "./StatusRule.js";
38
38
  import { ACT_NOW_NARROW, actNowLine } from "./actNow.js";
39
39
  import { fitSegments, seg } from "./fit.js";
40
40
  // The footer's mode badge. Gated is outside the shift+tab cycle (permissions/modes.ts); shift+tab leaves it.
41
- const MODE_BADGE = { auto: "⎈ Autonomous", manual: "⊙ Manual", plan: "◑ Plan", gated: "⊘ Gated" };
41
+ const MODE_BADGE = { auto: "⎈ Autonomous", delegate: "⇉ Delegate", manual: "⊙ Manual", plan: "◑ Plan", gated: "⊘ Gated" };
42
42
  // Cap on live rows shown at once for a parallel tool batch — keeps the dynamic (non-Static) frame
43
43
  // bounded (same render-collapse concern liveTail guards in Transcript.tsx: Ink corrupts the frame once
44
44
  // the non-Static portion approaches the terminal height). A batch rarely runs more than a handful of
@@ -1,4 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Background sub-agents list: working / idle / stopped (SPEC §7). idle never means dead —
3
+ // spawn_background keeps full state and just stops burning rounds.
4
+ import { stopReasonOf } from "./reportLine.js";
2
5
  import { Box, Text } from "ink";
3
6
  import { OrbitGlyph } from "./ActivitySpinner.js";
4
7
  import { theme, secondary } from "./theme.js";
@@ -86,7 +89,7 @@ export function detailLine(a) {
86
89
  if (a.status === "idle")
87
90
  return { text: "result posted — scroll up or /agents to review", tone: "dim" };
88
91
  if (a.status === "stopped")
89
- return { text: a.endReason ?? "errored — check transcript for details", tone: "dim" };
92
+ return { text: stopReasonOf(a) ?? "errored — check transcript for details", tone: "dim" };
90
93
  if (a.status === "queued")
91
94
  return { text: a.queueReason ? `waiting: ${a.queueReason}` : "waiting for a free slot", tone: "dim" };
92
95
  const steps = a.steps ?? [];
@@ -180,7 +183,7 @@ export function agentLaneOf(a, now, ctx = {}) {
180
183
  return { ...base, tone: "done", mission: join("done", a.verified === true ? "✓ verified" : a.verified === false ? "✗ unverified" : undefined, a.written?.length ? `wrote ${a.written.slice(-1).map((p) => p.split("/").pop()).join("")}` : undefined, "report delivered") };
181
184
  if (a.status === "stopped") {
182
185
  const err = a.endKind === "failed" || a.endKind === "error" || !a.endKind;
183
- return { ...base, tone: err ? "error" : "stopped", mission: join(a.endReason ?? "errored", a.headline?.startsWith("partial:") ? "partial notes delivered" : undefined) };
186
+ return { ...base, tone: err ? "error" : "stopped", mission: join(stopReasonOf(a) ?? "errored", a.headline?.startsWith("partial:") ? "partial notes delivered" : undefined) };
184
187
  }
185
188
  if (a.stuck)
186
189
  return { ...base, tone: "stuck", mission: `stuck: ${a.stuck} · /agents ${(a.name ?? a.id).toLowerCase()} msg | stop` };
@@ -18,6 +18,8 @@ const GLYPH = { done: "⤷", stopped: "■", error: "✗" };
18
18
  export function reportCommand(a) {
19
19
  return `/agents ${(a.name ?? a.id).toLowerCase()} report`;
20
20
  }
21
+ /** Why a stopped sub-agent stopped, for the panel and agent_status. */
22
+ export const stopReasonOf = (a) => a.endKind === "engine" ? `stopped by the engine: ${a.endReason ?? "no progress"}` : a.endReason;
21
23
  function outcome(a) {
22
24
  const dur = a.durationMs != null ? fmtElapsed(a.durationMs) : undefined;
23
25
  const rounds = a.round ? ` after ${a.round} round${a.round === 1 ? "" : "s"}` : "";
@@ -16,10 +16,10 @@ export const SLASH_COMMANDS = [
16
16
  { name: "remote", description: "remote control: let a follower attach and drive this session", args: "[on|off]" },
17
17
  { name: "pair", description: "pair a phone to drive this session — shows a QR for the Operator app (end-to-end encrypted)" },
18
18
  { name: "plan", description: "plan mode: read-only research + propose a plan (/plan again executes)" },
19
- { name: "mode", description: "set operating mode: autonomous · manual · plan · gated", args: "[auto|manual|plan|gated]" },
19
+ { name: "mode", description: "set operating mode: autonomous · delegate · manual · plan · gated", args: "[auto|delegate|manual|plan|gated]" },
20
20
  { name: "think", description: "toggle extended reasoning (think before answering)" },
21
21
  { name: "ultrathink", description: "toggle deep, exhaustive reasoning for hard problems" },
22
- { name: "delegate", description: "any /model id as the MoA planner or the sub-agents; guard: no push, deploys or writes outside this repo", args: "[planner <model> [executor]|subagents <model>|guard on|off|push on|off|off]" },
22
+ { name: "delegate", description: "Delegate mode on|off; any /model id as the MoA planner or sub-agents; guard: no push, deploys or outside writes", args: "[on|off|planner <model> [executor]|subagents <model>|guard on|off|push on|off]" },
23
23
  { name: "agents", description: "detailed sub-agent status: running/queued/done/errored + metrics" },
24
24
  { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
25
25
  { name: "jobs", description: "background shell jobs: list, or stop one (ctrl+b moves a running command here)", args: "[stop id]" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",