@0perator/operator 0.1.61 → 0.1.153

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 (75) hide show
  1. package/CHANGELOG.md +1037 -1
  2. package/LICENSE +19 -0
  3. package/dist/acp/agent.js +103 -0
  4. package/dist/acp/run.js +23 -0
  5. package/dist/auth/client.js +4 -1
  6. package/dist/auth/login-intent.js +12 -0
  7. package/dist/autonomy/board-run.js +65 -0
  8. package/dist/autonomy/board.js +83 -0
  9. package/dist/autonomy/dream.js +71 -0
  10. package/dist/autonomy/headless.js +70 -0
  11. package/dist/autonomy/index.js +260 -0
  12. package/dist/autonomy/keepawake.js +84 -0
  13. package/dist/autonomy/loop.js +82 -0
  14. package/dist/autonomy/reporter.js +54 -0
  15. package/dist/autonomy/routine-run.js +25 -0
  16. package/dist/autonomy/routines.js +173 -0
  17. package/dist/autonomy/session-factory.js +61 -0
  18. package/dist/background/index.js +269 -20
  19. package/dist/background/worktree.js +62 -0
  20. package/dist/cli.js +535 -112
  21. package/dist/config/brand.js +81 -0
  22. package/dist/config/operator-harness.js +86 -0
  23. package/dist/config/persona.js +174 -0
  24. package/dist/config/settings.js +98 -9
  25. package/dist/engine/agent.js +447 -51
  26. package/dist/engine/aurora.js +180 -64
  27. package/dist/engine/compaction.js +97 -5
  28. package/dist/engine/grandmaster.js +69 -10
  29. package/dist/engine/router-adapter.js +3 -0
  30. package/dist/engine/selfheal.js +35 -0
  31. package/dist/engine/verify-gate.js +81 -0
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/permissions/index.js +13 -7
  34. package/dist/router/models.js +13 -4
  35. package/dist/router/router.js +46 -7
  36. package/dist/selfimprove/index.js +88 -0
  37. package/dist/services/preflight.js +42 -1
  38. package/dist/session.js +228 -21
  39. package/dist/telemetry/events.js +9 -0
  40. package/dist/tools/executor.js +48 -24
  41. package/dist/tools/git-status.js +71 -0
  42. package/dist/tools/mutating.js +9 -0
  43. package/dist/tools/registry.js +214 -11
  44. package/dist/tools/result-cap.js +23 -0
  45. package/dist/tools/searxng.js +42 -2
  46. package/dist/ui/ActivitySpinner.js +6 -5
  47. package/dist/ui/App.js +23 -5
  48. package/dist/ui/AuthScreen.js +1 -1
  49. package/dist/ui/BgPanel.js +60 -5
  50. package/dist/ui/Composer.js +135 -13
  51. package/dist/ui/Header.js +14 -6
  52. package/dist/ui/InputRule.js +2 -1
  53. package/dist/ui/Markdown.js +69 -10
  54. package/dist/ui/Masthead.js +6 -4
  55. package/dist/ui/PlanPane.js +23 -0
  56. package/dist/ui/QuestionPrompt.js +22 -8
  57. package/dist/ui/StatsCard.js +15 -0
  58. package/dist/ui/StatusRule.js +13 -4
  59. package/dist/ui/SummaryCard.js +18 -0
  60. package/dist/ui/Table.js +114 -0
  61. package/dist/ui/ThinkingSpinner.js +6 -4
  62. package/dist/ui/ToolBatch.js +12 -0
  63. package/dist/ui/ToolStep.js +12 -4
  64. package/dist/ui/Transcript.js +30 -6
  65. package/dist/ui/chart.js +34 -0
  66. package/dist/ui/editdiff.js +84 -0
  67. package/dist/ui/highlight.js +89 -0
  68. package/dist/ui/osc.js +32 -0
  69. package/dist/ui/planExit.js +26 -0
  70. package/dist/ui/term.js +16 -0
  71. package/dist/ui/theme.js +60 -0
  72. package/dist/ui/tree.js +71 -0
  73. package/dist/util/slash.js +15 -0
  74. package/dist/util/throttle.js +28 -0
  75. package/package.json +10 -1
@@ -0,0 +1,173 @@
1
+ // Routines — cron-scheduled unattended tasks. A routines.json declares {id, schedule (5-field cron),
2
+ // prompt, mode} entries; Operator can list them with their next fire time, run one now, generate a
3
+ // durable OS scheduler entry (launchd on macOS, a crontab line elsewhere), or run an internal watcher.
4
+ //
5
+ // WHY this shape: the OS already has robust, reboot-surviving schedulers. Rather than embed a cron daemon
6
+ // that must itself be supervised, Operator GENERATES launchd/cron config that re-invokes `operator run`
7
+ // on schedule — the lightest durable mechanism that fits. The internal `watch` (setTimeout-driven, same
8
+ // cron math) is the fallback for hosts without launchd/cron and for quick testing; it is not the durable
9
+ // path and says so.
10
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join, dirname } from "node:path";
13
+ export function routinesPath(settings) {
14
+ const p = settings?.autonomy?.routinesFile;
15
+ if (p)
16
+ return p.replace(/^~(?=\/|$)/, homedir());
17
+ return join(homedir(), ".axe", "operator", "routines.json");
18
+ }
19
+ export function readRoutines(file) {
20
+ try {
21
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
22
+ return Array.isArray(parsed?.routines) ? parsed.routines : [];
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ }
28
+ export function writeRoutines(file, routines) {
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ writeFileSync(file, JSON.stringify({ routines }, null, 2) + "\n", "utf8");
31
+ }
32
+ // ── Minimal 5-field cron ────────────────────────────────────────────────────
33
+ // Supports * , ranges a-b, lists a,b,c and steps */n (and a-b/n). Fields: minute(0-59) hour(0-23)
34
+ // dom(1-31) month(1-12) dow(0-6, 0=Sun). No named months/days, no @macros — deliberately small + testable.
35
+ function parseField(field, min, max) {
36
+ const out = new Set();
37
+ for (const part of field.split(",")) {
38
+ const [rangePart, stepPart] = part.split("/");
39
+ const step = stepPart ? parseInt(stepPart, 10) : 1;
40
+ if (!Number.isFinite(step) || step < 1)
41
+ throw new Error(`bad cron step in "${field}"`);
42
+ let lo = min, hi = max;
43
+ if (rangePart !== "*" && rangePart !== "") {
44
+ const [a, b] = rangePart.split("-");
45
+ lo = parseInt(a, 10);
46
+ hi = b !== undefined ? parseInt(b, 10) : lo;
47
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo < min || hi > max || lo > hi) {
48
+ throw new Error(`bad cron range "${part}" for [${min},${max}]`);
49
+ }
50
+ }
51
+ for (let n = lo; n <= hi; n += step)
52
+ out.add(n);
53
+ }
54
+ return out;
55
+ }
56
+ export function parseCron(expr) {
57
+ const f = expr.trim().split(/\s+/);
58
+ if (f.length !== 5)
59
+ throw new Error(`cron needs 5 fields, got ${f.length}: "${expr}"`);
60
+ return {
61
+ minute: parseField(f[0], 0, 59),
62
+ hour: parseField(f[1], 0, 23),
63
+ dom: parseField(f[2], 1, 31),
64
+ month: parseField(f[3], 1, 12),
65
+ dow: parseField(f[4], 0, 6),
66
+ domStar: f[2] === "*",
67
+ dowStar: f[4] === "*",
68
+ };
69
+ }
70
+ /** cron day semantics: when BOTH dom and dow are restricted, a match on EITHER fires (standard Vixie
71
+ * cron). When one is "*", the other must match. */
72
+ function dayMatches(spec, d) {
73
+ const domOk = spec.dom.has(d.getDate());
74
+ const dowOk = spec.dow.has(d.getDay());
75
+ if (spec.domStar && spec.dowStar)
76
+ return true;
77
+ if (spec.domStar)
78
+ return dowOk;
79
+ if (spec.dowStar)
80
+ return domOk;
81
+ return domOk || dowOk;
82
+ }
83
+ export function cronMatches(spec, d) {
84
+ return spec.minute.has(d.getMinutes()) && spec.hour.has(d.getHours()) && spec.month.has(d.getMonth() + 1) && dayMatches(spec, d);
85
+ }
86
+ /** Next fire strictly after `from` (local time), or null if none within ~2 years (a guard against an
87
+ * impossible spec like Feb-31). Minute-granular scan — simple and exact for a 5-field cron. */
88
+ export function nextFire(expr, from = new Date()) {
89
+ const spec = parseCron(expr);
90
+ const d = new Date(from.getTime());
91
+ d.setSeconds(0, 0);
92
+ d.setMinutes(d.getMinutes() + 1);
93
+ const limit = 366 * 2 * 24 * 60; // minutes in ~2 years
94
+ for (let i = 0; i < limit; i++) {
95
+ if (cronMatches(spec, d))
96
+ return new Date(d.getTime());
97
+ d.setMinutes(d.getMinutes() + 1);
98
+ }
99
+ return null;
100
+ }
101
+ /** Validate a cron expression — returns an error string or null. */
102
+ export function validateCron(expr) {
103
+ try {
104
+ parseCron(expr);
105
+ return null;
106
+ }
107
+ catch (e) {
108
+ return e instanceof Error ? e.message : String(e);
109
+ }
110
+ }
111
+ // ── Durable OS scheduler generation ──────────────────────────────────────────
112
+ export function launchdLabel(id) {
113
+ return `com.axe.operator.routine.${id.replace(/[^A-Za-z0-9._-]/g, "-")}`;
114
+ }
115
+ /** cron minute/hour → a launchd StartCalendarInterval. Only emits Minute/Hour/Weekday/Day when the field
116
+ * is a single value (launchd takes discrete values, not ranges); a multi-value field is left off so it
117
+ * fires on every value of it (documented in the plist comment). For anything launchd can't express, the
118
+ * caller should prefer `watch` or a crontab line. */
119
+ export function launchdPlist(routine, operatorBin, cwd) {
120
+ const f = routine.schedule.trim().split(/\s+/);
121
+ const single = (x) => (/^\d+$/.test(x) ? x : undefined);
122
+ const cal = [];
123
+ const min = single(f[0]);
124
+ if (min !== undefined)
125
+ cal.push(` <key>Minute</key><integer>${min}</integer>`);
126
+ const hr = single(f[1]);
127
+ if (hr !== undefined)
128
+ cal.push(` <key>Hour</key><integer>${hr}</integer>`);
129
+ const dom = single(f[2]);
130
+ if (dom !== undefined)
131
+ cal.push(` <key>Day</key><integer>${dom}</integer>`);
132
+ const dow = single(f[4]);
133
+ if (dow !== undefined)
134
+ cal.push(` <key>Weekday</key><integer>${dow}</integer>`);
135
+ const mode = routine.mode ?? "headless";
136
+ const args = mode === "board"
137
+ ? [operatorBin, "board", "run"]
138
+ : [operatorBin, mode === "loop" ? "loop" : "run", routine.prompt];
139
+ const argXml = args.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
140
+ const label = launchdLabel(routine.id);
141
+ return `<?xml version="1.0" encoding="UTF-8"?>
142
+ <!-- Operator routine "${escapeXml(routine.id)}" — schedule "${escapeXml(routine.schedule)}". Generated by \`operator routine install\`.
143
+ launchd expresses only single-value calendar fields; ranges/lists/steps fire on every value. For an
144
+ expression launchd can't represent exactly, use \`operator routine watch\` or a crontab line instead. -->
145
+ <plist version="1.0"><dict>
146
+ <key>Label</key><string>${label}</string>
147
+ <key>ProgramArguments</key><array>
148
+ ${argXml}
149
+ </array>
150
+ <key>WorkingDirectory</key><string>${escapeXml(cwd)}</string>
151
+ <key>StartCalendarInterval</key><dict>
152
+ ${cal.join("\n")}
153
+ </dict>
154
+ <key>RunAtLoad</key><false/>
155
+ <key>StandardOutPath</key><string>${escapeXml(join(homedir(), ".axe", "operator", "logs", `${routine.id}.out.log`))}</string>
156
+ <key>StandardErrorPath</key><string>${escapeXml(join(homedir(), ".axe", "operator", "logs", `${routine.id}.err.log`))}</string>
157
+ </dict></plist>
158
+ `;
159
+ }
160
+ /** A crontab line that re-invokes operator for this routine (the portable durable path off macOS). */
161
+ export function crontabLine(routine, operatorBin, cwd) {
162
+ const mode = routine.mode ?? "headless";
163
+ const cmd = mode === "board"
164
+ ? `${operatorBin} board run`
165
+ : `${operatorBin} ${mode === "loop" ? "loop" : "run"} ${shellQuote(routine.prompt)}`;
166
+ return `${routine.schedule} cd ${shellQuote(cwd)} && ${cmd}`;
167
+ }
168
+ function escapeXml(s) {
169
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
170
+ }
171
+ function shellQuote(s) {
172
+ return `'${s.replace(/'/g, `'\\''`)}'`;
173
+ }
@@ -0,0 +1,61 @@
1
+ // Headless Session factory for the autonomy runners. Mirrors the wiring cli.tsx does for the foreground
2
+ // session (persona + project context + handoff, the Aurora router, permissions, telemetry) but with NO
3
+ // Ink/TTY dependency, so `operator run/loop/board/dream` construct a real, tool-capable Session the same
4
+ // way the shell does. Kept deliberately small: it composes existing building blocks, it does not fork them.
5
+ import { Session } from "../session.js";
6
+ import { AuroraRouter } from "../router/router.js";
7
+ import { basePersona, loadProjectContext, loadMemories, loadHandoff } from "../config/persona.js";
8
+ import { renderHarnessContext } from "../config/operator-harness.js";
9
+ import { compactionThreshold, compactionCeilingTokens } from "../config/settings.js";
10
+ /** Build the Aurora router (primary + optional degraded failover) from settings — the headless twin of
11
+ * cli.tsx's buildRouter(). */
12
+ export function buildRouterFromSettings(settings) {
13
+ const eps = [{
14
+ name: "operator-1m",
15
+ base: settings.endpoints.aurora.base,
16
+ model: settings.endpoints.aurora.model,
17
+ ctxLimit: settings.endpoints.aurora.ctxWindow,
18
+ }];
19
+ const fo = settings.endpoints.failover;
20
+ if (fo)
21
+ eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
22
+ return new AuroraRouter(eps);
23
+ }
24
+ /** The full headless system prompt: settings.systemPrompt (or the base persona) + auto-loaded project
25
+ * context + handoff — the same composition cli.tsx uses, minus the TUI-only embodiment guide. */
26
+ export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
27
+ const base = settings.systemPrompt ?? basePersona(cwd);
28
+ return base + loadProjectContext(cwd) + loadMemories(cwd) + renderHarnessContext(cwd) + loadHandoff();
29
+ }
30
+ /** Construct a headless Session from settings. Unattended runs get NO ask_user handler (there's no owner
31
+ * to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
32
+ * MCP tool set directly. Permissions default to the owner's configured policy. */
33
+ export function createAutonomySession(settings, opts = {}) {
34
+ return new Session({
35
+ systemPrompt: buildHeadlessSystemPrompt(settings),
36
+ router: buildRouterFromSettings(settings),
37
+ mcp: settings.mcp,
38
+ maxTokens: settings.maxTokens,
39
+ maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling for unattended runs
40
+ temperature: settings.temperature,
41
+ recall: settings.memory.recall,
42
+ models: settings.models,
43
+ moa: settings.moa,
44
+ activeModel: settings.activeModel,
45
+ permissions: opts.permissions ?? settings.permissions,
46
+ telemetry: settings.telemetry,
47
+ compactionThreshold: compactionThreshold(settings),
48
+ compactionCeilingTokens: compactionCeilingTokens(settings),
49
+ ...opts.extra,
50
+ });
51
+ }
52
+ /** Dream mode's permission posture. "readonly"/"gated" ⇒ a gated policy with no approver, so safe/read
53
+ * tools run but every mutating tool asks → denies (there's no owner to approve): read-mostly by
54
+ * construction. "bypass" ⇒ the owner explicitly opted dream into full autonomy. */
55
+ export function dreamPermissions(settings) {
56
+ const posture = settings.autonomy?.dream?.permissions ?? "readonly";
57
+ const tier = settings.permissions.tier;
58
+ if (posture === "bypass")
59
+ return { mode: "bypass", tier };
60
+ return { mode: "gated", tier }; // no approve fn is wired for dream ⇒ mutations fail-safe deny
61
+ }
@@ -1,53 +1,206 @@
1
1
  import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, } from "../engine/grandmaster.js";
2
+ import { createWorktree, finalizeWorktree } from "./worktree.js";
2
3
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
3
4
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
4
5
  const THOUGHT_EMIT_MS = 700; // min gap between reasoning-driven re-renders — bounds render load during long thinks
5
6
  const IDLE_TTL_MS = 45_000; // a finished agent lingers this long (result already in the transcript) then decommissions
7
+ const MAX_FOLLOWUP_MSGS = 6; // cap on parent->child mid-run messages processed per agent (bidirectional coms; no runaway)
6
8
  // Pull the one identifying argument out of a tool call for the live line (path/file it read, the
7
9
  // command/query it ran) — the follower cares "read src/cli.tsx", not the full JSON args blob.
8
10
  function shortArg(args) {
9
11
  const v = args?.path ?? args?.file ?? args?.pattern ?? args?.query ?? args?.command ?? args?.url ?? args?.task;
10
12
  return typeof v === "string" ? v.replace(/\s+/g, " ").slice(0, 48) : undefined;
11
13
  }
14
+ // A readable label for a sub-agent in the background panel. The raw task is a 2nd-person brief that
15
+ // almost always opens "You are building/creating/…", so the old first-28-chars label chopped every
16
+ // agent to the same useless "You are building a comprehen". Strip that boilerplate and keep the actual
17
+ // objective, so the owner can tell the agents apart at a glance ("Comprehensive master plan…" vs
18
+ // "Initial project structure…").
19
+ function summarizeTask(task) {
20
+ let s = task.replace(/\s+/g, " ").trim();
21
+ s = s.replace(/^(you (are|will be|need to|should)( going to| now)?\s+(building|creating|writing|implementing|designing|responsible for|working on|tasked with)|your (task|job|objective|goal) is( to)?|please|build|create|implement|design)\s+/i, "").trim();
22
+ if (s)
23
+ s = s.charAt(0).toUpperCase() + s.slice(1);
24
+ return s.length > 56 ? s.slice(0, 55) + "…" : (s || task.replace(/\s+/g, " ").slice(0, 56));
25
+ }
12
26
  export class BackgroundAgents {
13
27
  makeSession;
14
28
  onChange;
15
29
  onDone;
16
30
  modelName;
31
+ onTaskActivity;
32
+ // session is created lazily in run() (a code-editing agent's session must be rooted at its worktree, which
33
+ // requires an async `git worktree add`); wt is its isolated worktree, or null when not isolated.
17
34
  agents = new Map();
18
35
  seq = 0;
36
+ queue = []; // ids waiting for a concurrency slot (FIFO)
37
+ // Cap concurrently-RUNNING background sub-agents. Unbounded fan-out (4 heavy aurora-code-1 sub-agents +
38
+ // Aurora serving) starved a 64GB node clean off the network — an agent must never overload its own host.
39
+ // Excess spawns QUEUE and start as slots free. KODE_BG_MAX overrides (settings.background.maxConcurrent).
40
+ maxConcurrent = Math.max(1, Number(process.env.KODE_BG_MAX) || 2);
41
+ // The queue itself must ALSO be bounded — a burst of spawn calls (model or /bg) used to enqueue without
42
+ // limit, so "how many are running" stayed capped while "how many are in flight" ballooned (seen live:
43
+ // "background (6)" with a running-cap of 4). Total in-flight (working+queued) is capped at 2x the
44
+ // concurrency cap; spawn() beyond it refuses outright instead of silently piling onto the wait list.
45
+ maxQueued = this.maxConcurrent;
46
+ // Wall-clock ceiling for a single working agent. The chat fetch layer (engine/aurora.ts) has no per-request
47
+ // timeout of its own — only an explicit interrupt() aborts it — so a stalled/hung endpoint (connection open,
48
+ // no chunks) would otherwise pin a concurrency slot forever and wedge the queue behind it. KODE_BG_TIMEOUT_MS
49
+ // overrides the 20m default; floored at 100ms just to reject 0/negative, not to second-guess an explicit
50
+ // override — a deliberately short value (e.g. a test exercising this exact watchdog) is honored as given.
51
+ // Read at CONSTRUCTION (an instance field, like maxConcurrent above), not module load — a module-level
52
+ // constant would freeze at whichever env var was set the first time anything imported this file.
53
+ stallTimeoutMs = Math.max(100, Number(process.env.KODE_BG_TIMEOUT_MS) || 20 * 60_000);
19
54
  /** @param makeSession builds a fresh Session for a bg agent (shell pins it to 1M).
20
55
  * @param onChange fired whenever any agent's status changes (shell re-renders the panel).
21
56
  * @param onDone fired when an agent finishes, with its final answer (shell posts it to the transcript).
22
- * @param modelName the model the child runs on, recorded for UI surfacing (grandmaster §5). */
23
- constructor(makeSession, onChange, onDone, modelName = "aurora-code-1") {
57
+ * @param modelName the model the child runs on, recorded for UI surfacing (grandmaster §5).
58
+ * @param onTaskActivity fired whenever a child's tool batch includes a task_* call — a child can mutate
59
+ * the SAME session-wide task list the foreground plan pane reads (registry.ts's agentTasks is a single
60
+ * module-level store), but the pane only refreshed on the foreground's OWN task_* calls, so a child could
61
+ * finish real, tracked work and the plan pane would sit frozen. Optional/back-compat: omit to keep the
62
+ * pre-existing behavior. */
63
+ constructor(makeSession, onChange, onDone, modelName = "aurora-code-1", onTaskActivity) {
24
64
  this.makeSession = makeSession;
25
65
  this.onChange = onChange;
26
66
  this.onDone = onDone;
27
67
  this.modelName = modelName;
68
+ this.onTaskActivity = onTaskActivity;
28
69
  }
29
70
  list() {
30
71
  return [...this.agents.values()].map((a) => ({ ...a.info }));
31
72
  }
32
- /** Spawn a background agent on `task`. Returns its short id (bg1, bg2, …). */
73
+ // Agents that finished/errored/stopped and were reaped from the live map — kept as a lightweight record
74
+ // so agent_status doesn't wrongly report "no sub-agents spawned this session yet" once a completed agent
75
+ // decommissions (its result is already in the conversation, but the model still asked whether it ran).
76
+ retired = [];
77
+ /** Terminal agents that already decommissioned this session (their results were posted when they finished). */
78
+ retiredList() {
79
+ return [...this.retired];
80
+ }
81
+ /** Total agents currently occupying a slot, running or waiting — the number that must never balloon. */
82
+ inFlight() {
83
+ return this.activeCount() + this.queue.length;
84
+ }
85
+ /** Human-readable capacity-exceeded message, shared by every spawn surface (spawn_agent tool, /bg
86
+ * command) so there is exactly one wording and one number to keep in sync. */
87
+ capacityLine() {
88
+ return `at capacity: ${this.maxConcurrent} running + ${this.maxQueued} queued already in flight on the single Operator endpoint — wait for one to finish (see the background panel) before spawning more`;
89
+ }
90
+ /** Spawn a background agent on `task`. Returns its short id (agent-1, agent-2, …), or "" when total
91
+ * in-flight (running + queued) is already at the hard cap — the caller must show capacityLine() and NOT
92
+ * treat "" as an id. Refusing here (rather than queuing anyway) is what makes the cap authoritative for
93
+ * every caller, including one that skips its own precheck (the model's spawn_agent tool checks
94
+ * activeCount() before calling in; the /bg command used to call straight through with no check at all).
95
+ * ids are prefixed "agent-", DISJOINT from shell_background's "bgN" job ids on purpose (0.1.111) — a
96
+ * model that got back "bg1" for a sub-agent tried to poll it with bash_output (the shell-job tool), got
97
+ * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
98
+ * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
99
+ * namespaces make that specific confusion structurally impossible, not just better-worded. */
33
100
  spawn(task) {
34
- const id = `bg${++this.seq}`;
101
+ if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
102
+ return "";
103
+ const id = `agent-${++this.seq}`;
35
104
  const type = inferType(task);
36
105
  const brief = buildBrief({ objective: task, type }, process.cwd());
37
106
  const lane = routeLane(brief, { type });
38
- const label = task.replace(/\s+/g, " ").slice(0, 28);
39
- const session = this.makeSession();
40
- const info = { id, label, status: "working", task, round: 0, tokens: 0, startedAt: Date.now(), model: this.modelName, lane };
41
- this.agents.set(id, { info, session });
107
+ const label = summarizeTask(task);
108
+ // Starts QUEUED; pump() promotes it to working when a concurrency slot is free (startedAt is stamped
109
+ // then, so the panel timer measures real run time, not queue wait). The Session is created lazily in
110
+ // run() so a code-editing agent can be rooted at its own worktree (an async setup).
111
+ const info = { id, label, status: "queued", task, round: 0, tokens: 0, model: this.modelName, lane };
112
+ this.agents.set(id, { info, brief, type });
113
+ this.queue.push(id);
42
114
  this.onChange();
43
- void this.run(id, session, info, brief, type);
115
+ this.pump();
44
116
  return id;
45
117
  }
46
- async run(id, session, info, brief, type) {
118
+ /** Start queued agents up to the concurrency cap. Called on spawn and whenever a running slot frees. */
119
+ pump() {
120
+ while (this.activeCount() < this.maxConcurrent && this.queue.length > 0) {
121
+ const id = this.queue.shift();
122
+ const entry = this.agents.get(id);
123
+ if (!entry || entry.info.status !== "queued")
124
+ continue; // stopped/removed while waiting
125
+ entry.info.status = "working";
126
+ entry.info.startedAt = Date.now();
127
+ this.onChange();
128
+ this.scheduleStallTimeout(id);
129
+ void this.run(id, entry.info, entry.brief, entry.type);
130
+ }
131
+ }
132
+ /** Watchdog for a hung child: if it's still "working" after STALL_TIMEOUT_MS, stop() it (interrupt +
133
+ * free its slot, same as an owner-initiated stop) and — unlike a deliberate stop, which the owner already
134
+ * knows about — post an explicit, unmissable reason, since nobody asked for this one. A no-op if the
135
+ * agent already finished by the time the timer fires (checked by id, so it can never fire on a reused
136
+ * slot — ids are sequential and never recycled). */
137
+ scheduleStallTimeout(id) {
138
+ const timer = setTimeout(() => {
139
+ const a = this.agents.get(id);
140
+ if (!a || a.info.status !== "working")
141
+ return; // finished/stopped already — nothing to do
142
+ const mins = Math.round(this.stallTimeoutMs / 60_000);
143
+ this.stop(id);
144
+ this.onDone(a.info, `[${id} stopped: exceeded ${mins}m wall-clock limit (stalled or a hung request) — any result above may be incomplete]`);
145
+ }, this.stallTimeoutMs);
146
+ timer.unref?.();
147
+ const entry = this.agents.get(id);
148
+ if (entry)
149
+ entry.stallTimer = timer;
150
+ }
151
+ /** Cancel a still-pending stall watchdog once the agent leaves "working" for any reason (finished,
152
+ * errored, or explicitly stopped) — otherwise it lingers (harmlessly, guarded by the status check
153
+ * above, but needlessly) for up to STALL_TIMEOUT_MS. Idempotent: clearing an already-cleared timer is
154
+ * a no-op, so every exit path can call it without coordinating who "owns" the clear. */
155
+ clearStallTimer(id) {
156
+ const a = this.agents.get(id);
157
+ if (a?.stallTimer) {
158
+ clearTimeout(a.stallTimer);
159
+ a.stallTimer = undefined;
160
+ }
161
+ }
162
+ async run(id, info, brief, type) {
163
+ // Isolation: a file-editing child gets its own git worktree so it can't touch the foreground tree; its
164
+ // Session's tools are rooted there (Executor cwd). Read-only lanes (search/review/plan) share the live
165
+ // cwd — they SHOULD see the real tree, and a snapshot copy would be stale. Best-effort: no repo → no wt.
166
+ const wt = (type === "code-edit" && process.env.KODE_BG_WORKTREE !== "0") ? await createWorktree(id, process.cwd()) : null;
167
+ const cwd = wt?.dir;
168
+ let session;
169
+ try {
170
+ session = this.makeSession(cwd);
171
+ }
172
+ catch (e) {
173
+ // makeSession is a caller-supplied factory (a real `new Session(...)`, not just an object literal) —
174
+ // never let a construction failure become an unhandled rejection (pump()'s `void this.run(...)` has no
175
+ // catch of its own) that vanishes the slot or, worse, brings down the whole process for every agent.
176
+ info.status = "stopped";
177
+ this.clearStallTimer(id);
178
+ this.scheduleReap(id);
179
+ this.onChange();
180
+ if (wt)
181
+ void finalizeWorktree(wt, info.label);
182
+ this.onDone(info, `[${id} error: failed to start — ${e instanceof Error ? e.message : String(e)}]`);
183
+ this.pump();
184
+ return;
185
+ }
186
+ const entry = this.agents.get(id);
187
+ if (entry) {
188
+ entry.session = session;
189
+ entry.wt = wt;
190
+ }
191
+ if (!entry || entry.info.status === "stopped") { // stopped while the worktree was being set up
192
+ if (wt)
193
+ void finalizeWorktree(wt, info.label);
194
+ return;
195
+ }
47
196
  let total = 0;
48
197
  let lastThoughtEmit = 0;
49
198
  const hooks = {
50
- onDelta: () => { info.tokens = (info.tokens ?? 0) + 1; },
199
+ // Authoritative live token count: the real llama.cpp per-round total for the in-flight send, added
200
+ // to what prior sends already counted. Replaces the old ≈1-per-content-delta tally, which missed
201
+ // every token generated as a tool-call argument or reasoning (most of a skill-writer's output — so
202
+ // a sub-agent that wrote thousands of tokens read as "53 tok").
203
+ onTokens: (t) => { info.tokens = total + t; this.onChange(); },
51
204
  // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
52
205
  // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
53
206
  onReasoning: (chunk) => {
@@ -73,6 +226,11 @@ export class BackgroundAgents {
73
226
  info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
74
227
  info.thought = undefined;
75
228
  this.onChange();
229
+ // This child can mutate the same session-wide task list the foreground plan pane reads (a single
230
+ // module-level store in registry.ts) — refresh the pane live instead of leaving it frozen until the
231
+ // foreground itself happens to touch a task_* tool (see the constructor's onTaskActivity doc).
232
+ if (events.some((e) => e.name.startsWith("task_")))
233
+ this.onTaskActivity?.();
76
234
  },
77
235
  };
78
236
  try {
@@ -94,9 +252,25 @@ export class BackgroundAgents {
94
252
  r = r2;
95
253
  }
96
254
  }
97
- // Mechanism 3: verify-before-done (never on the model's say-so).
255
+ // Bidirectional coms: the parent can message a RUNNING child (message_agent tool → sendToAgent).
256
+ // Drain any queued messages as follow-up turns in the child's own conversation before finishing, so
257
+ // the parent can steer it / answer its question mid-run. Bounded so a chatty parent can't loop it.
258
+ let followups = 0;
259
+ while (entry.messages && entry.messages.length > 0 && followups < MAX_FOLLOWUP_MSGS && !r.interrupted) {
260
+ const msg = entry.messages.shift();
261
+ followups++;
262
+ info.thought = undefined;
263
+ this.onChange();
264
+ r = await session.send(msg, hooks);
265
+ total += r.tokens ?? 0;
266
+ const faF = extractFinalAnswer(r.content, type);
267
+ if (faF.ok)
268
+ fa = faF;
269
+ }
270
+ // Mechanism 3: verify-before-done (never on the model's say-so). Verify runs IN the worktree, so a
271
+ // code-editing child's declared verify_command tests the files it actually changed (in isolation).
98
272
  if (fa.ok && fa.value) {
99
- const v = await verifyFinalAnswer(fa.value, type, process.cwd());
273
+ const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd());
100
274
  info.verified = v.verified;
101
275
  info.verifyDetail = v.detail;
102
276
  }
@@ -107,12 +281,19 @@ export class BackgroundAgents {
107
281
  info.thought = undefined; // no live thinking once finished
108
282
  if (info.steps)
109
283
  info.steps = info.steps.map((s) => ({ ...s, running: false }));
284
+ this.clearStallTimer(id);
110
285
  this.scheduleReap(id);
111
286
  this.onChange();
287
+ // Finalize the isolated worktree: commit its changes onto the review branch, then remove the dir.
288
+ // Runs for both the finished and interrupted paths; clearing entry.wt makes finally/dispose a no-op.
289
+ const wtStatus = await finalizeWorktree(wt, info.label);
290
+ if (entry)
291
+ entry.wt = null;
112
292
  if (r.interrupted)
113
293
  return;
114
294
  // The parent sees the structured summary when we have one, tagged with verify/lane state so it can
115
- // decide whether to trust the child (mechanism 5 is the UI surfacing the same fields).
295
+ // decide whether to trust the child (mechanism 5 is the UI surfacing the same fields), plus where the
296
+ // isolated worktree's changes landed (a review branch).
116
297
  const summary = (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
117
298
  ? fa.value.summary.trim()
118
299
  : (r.content.trim() || "(no output)");
@@ -120,17 +301,32 @@ export class BackgroundAgents {
120
301
  : info.verified === false ? ` ⚠ unverified: ${info.verifyDetail}`
121
302
  : info.verified ? " ✓ verified"
122
303
  : "";
123
- this.onDone(info, `${summary}${tag}`);
304
+ this.onDone(info, `${summary}${tag}${wtStatus}`);
124
305
  }
125
306
  catch (e) {
126
307
  info.status = "stopped";
127
308
  info.thought = undefined;
128
309
  if (info.steps)
129
310
  info.steps = info.steps.map((s) => ({ ...s, running: false }));
311
+ this.clearStallTimer(id);
130
312
  this.scheduleReap(id);
131
313
  this.onChange();
314
+ try {
315
+ const leftover = this.agents.get(id)?.wt;
316
+ if (leftover) {
317
+ await finalizeWorktree(leftover, info.label);
318
+ const e2 = this.agents.get(id);
319
+ if (e2)
320
+ e2.wt = null;
321
+ }
322
+ }
323
+ catch { /* cleanup best-effort */ }
132
324
  this.onDone(info, `[${id} error: ${e instanceof Error ? e.message : String(e)}]`);
133
325
  }
326
+ finally {
327
+ // This agent set itself idle/stopped above, freeing a slot — promote the next queued agent.
328
+ this.pump();
329
+ }
134
330
  }
135
331
  /** A finished agent's result is already posted to the transcript, so it lingers in the panel only
136
332
  * briefly (so the owner sees it complete) then decommissions — otherwise idle agents pile up for
@@ -140,20 +336,64 @@ export class BackgroundAgents {
140
336
  const a = this.agents.get(id);
141
337
  if (!a || a.reap)
142
338
  return;
143
- a.reap = setTimeout(() => { this.agents.delete(id); this.onChange(); }, IDLE_TTL_MS);
339
+ a.reap = setTimeout(() => {
340
+ const info = this.agents.get(id)?.info;
341
+ if (info)
342
+ this.retired.push({ ...info }); // remember it ran (terminal state) after it leaves the live map
343
+ this.agents.delete(id);
344
+ this.onChange();
345
+ }, IDLE_TTL_MS);
144
346
  a.reap.unref?.();
145
347
  }
348
+ /** Bidirectional coms: queue a message for a RUNNING (or still-queued) sub-agent; it's delivered as a
349
+ * follow-up turn in the child's conversation (see the drain loop in run). Returns false if the agent is
350
+ * unknown or already finished — the parent then knows the message didn't land. */
351
+ sendToAgent(id, text) {
352
+ const a = this.agents.get(id);
353
+ if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
354
+ return false;
355
+ (a.messages ??= []).push(text);
356
+ return true;
357
+ }
146
358
  /** Stop a running agent (interrupts its turn). Returns false if the id is unknown. */
147
359
  stop(id) {
148
360
  const a = this.agents.get(id);
149
361
  if (!a)
150
362
  return false;
151
- a.session.interrupt();
363
+ this.queue = this.queue.filter((q) => q !== id); // if it never started, drop it from the wait list
364
+ a.session?.interrupt(); // session is created lazily in run(); may not exist yet if still queuing/setup
152
365
  a.info.status = "stopped";
366
+ this.clearStallTimer(id);
153
367
  this.scheduleReap(id);
154
368
  this.onChange();
369
+ this.pump(); // a running agent stopping frees a slot for the next queued one
370
+ return true;
371
+ }
372
+ /** Model-facing stop (the stop_agent tool): the only way to halt a sub-agent short of the user hitting
373
+ * ESC or restarting Operator entirely (seen live 09-26: a sub-agent ran to round 18 / ~1100s with no way
374
+ * to cancel it). Interrupts a RUNNING agent or drops a QUEUED one via stop() — but unlike stop() alone
375
+ * (silent by design: a human's /bg stop already sees its own local confirmation), this ALSO posts an
376
+ * explicit "[stopped by user]" note via onDone in place of whatever the agent would have posted, so a
377
+ * cancelled agent never just vanishes from the transcript. run()'s own eventual completion (once
378
+ * interrupt() actually aborts the in-flight send) still sees r.interrupted and skips its own onDone, so
379
+ * there is never a double post. Returns false if there was nothing running/queued to stop. */
380
+ requestStop(id) {
381
+ const a = this.agents.get(id);
382
+ if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
383
+ return false;
384
+ const info = a.info;
385
+ this.stop(id);
386
+ this.onDone(info, "[stopped by user]");
155
387
  return true;
156
388
  }
389
+ /** stop_agent with no id (or "all"): stop EVERY currently running or queued sub-agent. Returns the ids
390
+ * actually stopped, in the order they were found — empty when nothing was running/queued. */
391
+ requestStopAll() {
392
+ const ids = [...this.agents.values()]
393
+ .filter((a) => a.info.status === "working" || a.info.status === "queued")
394
+ .map((a) => a.info.id);
395
+ return ids.filter((id) => this.requestStop(id));
396
+ }
157
397
  /** Number of agents still working — for the status line. */
158
398
  activeCount() {
159
399
  return [...this.agents.values()].filter((a) => a.info.status === "working").length;
@@ -161,22 +401,31 @@ export class BackgroundAgents {
161
401
  /** Tear every child down on foreground exit. A child still mid-send is awaiting a streaming
162
402
  * request to the model; without aborting it the Node event loop never drains and `operator`
163
403
  * hangs after /exit (the "pressed exit → frozen" bug). interrupt() aborts the in-flight turn;
164
- * shutdown() kills the child's own MCP subprocesses; reap timers are cleared. */
404
+ * shutdown() kills the child's own MCP subprocesses; reap + stall-watchdog timers are cleared. */
165
405
  dispose() {
166
406
  for (const a of this.agents.values()) {
167
407
  if (a.reap) {
168
408
  clearTimeout(a.reap);
169
409
  a.reap = undefined;
170
410
  }
411
+ if (a.stallTimer) {
412
+ clearTimeout(a.stallTimer);
413
+ a.stallTimer = undefined;
414
+ }
171
415
  try {
172
- a.session.interrupt();
416
+ a.session?.interrupt();
173
417
  }
174
418
  catch { /* already gone */ }
175
419
  try {
176
- a.session.shutdown();
420
+ a.session?.shutdown();
177
421
  }
178
422
  catch { /* already gone */ }
423
+ if (a.wt) {
424
+ void finalizeWorktree(a.wt, a.info.label);
425
+ a.wt = null;
426
+ } // commit to branch + remove the dir (best-effort)
179
427
  }
180
428
  this.agents.clear();
429
+ this.queue = [];
181
430
  }
182
431
  }