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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
@@ -1,17 +1,28 @@
1
1
  import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, partialCounts, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
2
- import { isEngineFinal } from "../engine/continuation.js";
2
+ import { engineEnded } from "../engine/continuation.js";
3
3
  import { createWorktree, finalizeWorktree } from "./worktree.js";
4
+ import { resumeBrief } from "./resume.js";
5
+ import { CapacityUnavailable, laneBudget, laneCeiling, poolLine } from "./capacity.js";
6
+ import { isStreamEvent, nextPhase } from "./lane-phase.js";
7
+ import { briefRecords, evidenceOverlap, overlapLine, readRecord } from "./evidence.js";
8
+ import { planStepFrom, toolSummary } from "./lane-summary.js";
9
+ import { setCapacityLease } from "../engine/aurora.js";
10
+ import { FILE_WRITE, LOOKUP, SHELL_ANY } from "../tools/classes.js";
4
11
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
5
12
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
6
13
  // The work ledger + stuck checks (10/31: a sub-agent ran 54 rounds / 33 min, wrote nothing, and nobody could tell).
7
- const WRITE_TOOLS = new Set(["file_write", "file_edit", "apply_patch", "multi_edit", "write_file", "edit_file", "notebook_edit"]);
8
- const READ_TOOLS = new Set(["file_read", "read_files", "list_directory", "find_files", "glob", "grep", "grep_search", "search",
9
- "code_search", "codebase_search", "web_search", "web_fetch", "browser", "browser_read", "deep_research", "knowledge_search"]);
10
- const CMD_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
11
14
  const WRITTEN_MAX = 8;
12
15
  const STUCK_REPEATS = 3; // the same call(s) this many batches in a row
13
16
  const STUCK_ROUNDS_NO_WRITE = 15; // a writing task with this many rounds and no file written
14
- const STUCK_TALK_MS = 8 * 60_000; // tokens flowing but no tool call for this long (the announce loop; one big file write on a slow model can take 5)
17
+ // No stream activity (prefill progress, reasoning, content, token counts) and no tool for this long. A lane inside a live
18
+ // stream is never stuck: 11/27 a lane was flagged "talking without acting" 11 min into one long prefill.
19
+ const STUCK_SILENT_MS = 8 * 60_000;
20
+ const TICK_MS = 2_000; // live lane refresh + the silent check
21
+ const CAPACITY_LOOK_MS = 5_000; // how often a queued lane asks the router again (a backend that came up grows the pool)
22
+ const RENEW_MS = 40_000; // reservations renew well inside their TTL (capacity.ts RESERVATION_TTL_MS)
23
+ const STATIC_RETRY_MS = 60_000; // after the capacity API failed, the static cap holds this long before another look
24
+ const TRANSIENT_RETRY_MS = 2_000; // a busy router: look again this soon, still in live mode
25
+ const TRANSIENT_LIMIT = 3; // consecutive timeouts before the static cap takes over anyway
15
26
  const WRITING_TASK = /\b(write|create|draft|edit|update|build|implement|fix|add|document|save)\b/i;
16
27
  /** Default names when the planner gives none — short, distinct, easy to type in `/agents <name>`, and none of them a
17
28
  * fleet box or service (Nova, Atlas, Forge… already mean machines here). */
@@ -99,12 +110,29 @@ export class BackgroundAgents {
99
110
  // Cap concurrently-RUNNING background sub-agents. Unbounded fan-out (4 heavy aurora-code-1 sub-agents +
100
111
  // Aurora serving) starved a 64GB node clean off the network — an agent must never overload its own host.
101
112
  // Excess spawns QUEUE and start as slots free. KODE_BG_MAX overrides (settings.background.maxConcurrent).
102
- maxConcurrent = Math.max(1, Number(process.env.KODE_BG_MAX) || 2);
113
+ // With a capacity source (setCapacity) this is only the fallback for an endpoint without the router's capacity API.
114
+ staticLanes = Math.max(1, Number(process.env.KODE_BG_MAX) || 2);
115
+ capacity;
116
+ slots = { kind: "static", lanes: this.staticLanes, why: "no capacity source", retryAt: Infinity };
117
+ transientFailures = 0;
118
+ ceiling = laneCeiling();
119
+ pumping = false;
120
+ pumpAgain = false;
121
+ ticker;
122
+ lastLook = 0;
123
+ lastRenew = 0;
124
+ evidence = [];
125
+ runTag = Math.random().toString(36).slice(2, 10);
103
126
  // The queue itself must ALSO be bounded — a burst of spawn calls (model or /bg) used to enqueue without
104
127
  // limit, so "how many are running" stayed capped while "how many are in flight" ballooned (seen live:
105
128
  // "background (6)" with a running-cap of 4). Total in-flight (working+queued) is capped at 2x the
106
129
  // concurrency cap; spawn() beyond it refuses outright instead of silently piling onto the wait list.
107
- maxQueued = this.maxConcurrent;
130
+ get maxConcurrent() {
131
+ return this.capacity ? laneBudget(this.slots, this.activeCount(), this.ceiling) : this.staticLanes;
132
+ }
133
+ get maxQueued() {
134
+ return this.capacity && this.slots.kind === "live" ? this.ceiling : this.staticLanes;
135
+ }
108
136
  // Wall-clock ceiling for a single working agent. The chat fetch layer (engine/aurora.ts) has no per-request
109
137
  // timeout of its own — only an explicit interrupt() aborts it — so a stalled/hung endpoint (connection open,
110
138
  // no chunks) would otherwise pin a concurrency slot forever and wedge the queue behind it. KODE_BG_TIMEOUT_MS
@@ -171,7 +199,7 @@ export class BackgroundAgents {
171
199
  /** Human-readable capacity-exceeded message, shared by every spawn surface (spawn_agent tool, /bg
172
200
  * command) so there is exactly one wording and one number to keep in sync. */
173
201
  capacityLine() {
174
- 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`;
202
+ return `at capacity: ${this.activeCount()} running + ${this.queue.length} queued already in flight${this.slots.kind === "live" && this.slots.reason ? ` (${this.slots.reason})` : ""} — wait for one to finish (see the background panel) before spawning more`;
175
203
  }
176
204
  /** Spawn a background agent on `task`. Returns its short id (agent-1, agent-2, …), or "" when total
177
205
  * in-flight (running + queued) is already at the hard cap — the caller must show capacityLine() and NOT
@@ -183,12 +211,14 @@ export class BackgroundAgents {
183
211
  * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
184
212
  * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
185
213
  * namespaces make that specific confusion structurally impossible, not just better-worded. */
186
- spawn(task, role, name) {
187
- if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
214
+ spawn(task, role, name, resumed, opts = {}) {
215
+ if (this.inFlight() >= this.maxQueued * 2)
188
216
  return "";
189
217
  const id = `agent-${++this.seq}`;
190
218
  const type = role ?? roleForBrief(task);
191
- const brief = buildBrief({ objective: task, type }, process.cwd());
219
+ // A resumed agent runs on its original brief plus the engine's progress note; info.task stays the original, so a
220
+ // second quit saves the brief again rather than a note inside a note.
221
+ const brief = buildBrief({ objective: resumed ? resumeBrief(resumed) : task, type }, process.cwd());
192
222
  const lane = routeLane(brief, { type });
193
223
  const label = summarizeTask(task);
194
224
  // Starts QUEUED; pump() promotes it to working when a concurrency slot is free (startedAt is stamped
@@ -199,8 +229,14 @@ export class BackgroundAgents {
199
229
  id, label, status: "queued", task, round: 0, tokens: 0, model, lane,
200
230
  name: this.uniqueName(name?.trim().replace(/\s+/g, " ").slice(0, 24) || AGENT_NAMES[(this.seq - 1) % AGENT_NAMES.length]),
201
231
  title: SUBAGENT_ROLES[type]?.title ?? "assistant", role: type,
232
+ ...(resumed ? { resumed: true } : {}),
233
+ ...(opts.optional ? { optional: true } : {}),
234
+ ...(opts.deadlineMs && opts.deadlineMs > 0 ? { deadlineAt: Date.now() + opts.deadlineMs } : {}),
235
+ phase: nextPhase(undefined, { type: "queued" }, Date.now()),
202
236
  };
203
237
  this.agents.set(id, { info, brief, type });
238
+ this.evidence.push(...briefRecords(info.name, task));
239
+ this.refreshEvidence();
204
240
  this.queue.push(id);
205
241
  this.onChange();
206
242
  this.pump();
@@ -226,18 +262,217 @@ export class BackgroundAgents {
226
262
  return a.info.id;
227
263
  return undefined;
228
264
  }
229
- /** Start queued agents up to the concurrency cap. Called on spawn and whenever a running slot frees. */
265
+ /** Use the router's live capacity for the delegate route (smart slots). Undefined = the static cap only. */
266
+ setCapacity(source) {
267
+ this.capacity = source;
268
+ this.slots = source ? { kind: "live" } : { kind: "static", lanes: this.staticLanes, why: "no capacity source", retryAt: Infinity };
269
+ this.pump();
270
+ }
271
+ /** Where the lane count comes from, for the panel: the pool line when live, else the static cap and why. */
272
+ slotState() {
273
+ if (this.slots.kind === "live")
274
+ return { live: true, line: this.slots.snapshot ? poolLine(this.slots.snapshot) : undefined, lanes: this.maxConcurrent };
275
+ return { live: false, lanes: this.maxConcurrent, ...(this.capacity ? { line: `static ${this.staticLanes} lanes (${this.slots.why})` } : {}) };
276
+ }
277
+ /** Lanes a new spawn would start on now: the router's last free count, less what already waits, within the ceiling.
278
+ * Undefined without a live, bounded snapshot (static cap, unbounded leg, or not looked yet). */
279
+ freeLanes() {
280
+ const s = this.slots.kind === "live" ? this.slots.snapshot : undefined;
281
+ if (!s || s.unbounded)
282
+ return undefined;
283
+ return Math.max(0, Math.min(s.free, this.ceiling - this.activeCount()) - this.queue.length);
284
+ }
285
+ /** Start queued agents up to the lane budget. Called on spawn, whenever a lane frees, and on the live tick. With a
286
+ * capacity source a lane starts only once the router has reserved a unit for it; without one (or while its API is
287
+ * unreachable) the static cap applies, synchronously, as it always did. */
230
288
  pump() {
231
- while (this.activeCount() < this.maxConcurrent && this.queue.length > 0) {
232
- const id = this.queue.shift();
289
+ if (this.capacity && this.slots.kind === "static" && Date.now() >= this.slots.retryAt)
290
+ this.slots = { kind: "live" };
291
+ if (!this.capacity || this.slots.kind === "static") {
292
+ while (this.activeCount() < this.maxConcurrent && this.queue.length > 0) {
293
+ const id = this.queue.shift();
294
+ const entry = this.agents.get(id);
295
+ if (!entry || entry.info.status !== "queued")
296
+ continue; // stopped/removed while waiting
297
+ this.start(id);
298
+ }
299
+ this.markQueued(`${this.activeCount()} of ${this.maxConcurrent} agent slots busy`);
300
+ this.syncTicker();
301
+ return;
302
+ }
303
+ if (this.pumping) {
304
+ this.pumpAgain = true;
305
+ return;
306
+ }
307
+ this.pumping = true;
308
+ void this.pumpLive().finally(() => { this.pumping = false; this.syncTicker(); if (this.pumpAgain) {
309
+ this.pumpAgain = false;
310
+ this.pump();
311
+ } });
312
+ }
313
+ async pumpLive() {
314
+ const cap = this.capacity;
315
+ this.lastLook = Date.now();
316
+ while (this.queue.length > 0 && this.activeCount() < this.ceiling) {
317
+ const id = this.queue[0];
233
318
  const entry = this.agents.get(id);
234
- if (!entry || entry.info.status !== "queued")
235
- continue; // stopped/removed while waiting
236
- entry.info.status = "working";
237
- entry.info.startedAt = Date.now();
319
+ if (!entry || entry.info.status !== "queued") {
320
+ this.queue.shift();
321
+ continue;
322
+ }
323
+ let got;
324
+ try {
325
+ got = await cap.reserve(`${this.runTag}:${id}`);
326
+ }
327
+ catch (e) {
328
+ if (e instanceof CapacityUnavailable && e.transient && ++this.transientFailures < TRANSIENT_LIMIT) {
329
+ // Busy, not absent: dropping to the static cap here ran a whole fan-out one lane at a time.
330
+ this.markQueued(`waiting on the router (${e.message}); retrying`);
331
+ setTimeout(() => this.pump(), TRANSIENT_RETRY_MS).unref?.();
332
+ return;
333
+ }
334
+ this.transientFailures = 0;
335
+ this.slots = { kind: "static", lanes: this.staticLanes, why: e instanceof CapacityUnavailable ? e.message : String(e), retryAt: Date.now() + STATIC_RETRY_MS };
336
+ this.pumpAgain = true; // the static path takes over at once
337
+ return;
338
+ }
339
+ this.transientFailures = 0;
340
+ if (!got.ok) {
341
+ this.slots = { kind: "live", snapshot: got.snapshot ?? (this.slots.kind === "live" ? this.slots.snapshot : undefined), reason: got.reason };
342
+ this.markQueued(got.reason);
343
+ return;
344
+ }
345
+ if (this.queue[0] !== id || entry.info.status !== "queued") {
346
+ void cap.release(got.leaseId);
347
+ continue;
348
+ } // stopped while reserving
349
+ this.queue.shift();
350
+ entry.leaseId = got.leaseId;
351
+ entry.info.leg = got.leg;
352
+ if (entry.info.name)
353
+ setCapacityLease(entry.info.name, { id: got.leaseId, base: cap.base });
354
+ if (this.slots.kind === "live")
355
+ this.slots = { ...this.slots, reason: undefined };
356
+ this.start(id);
357
+ }
358
+ if (this.queue.length)
359
+ this.markQueued(`${this.activeCount()} lanes running: the ${this.ceiling}-lane ceiling`);
360
+ void this.look();
361
+ }
362
+ /** Refresh the pool snapshot the header shows. */
363
+ async look() {
364
+ if (!this.capacity || this.slots.kind !== "live")
365
+ return;
366
+ try {
367
+ const snapshot = await this.capacity.snapshot();
368
+ if (this.slots.kind === "live")
369
+ this.slots = { ...this.slots, snapshot };
238
370
  this.onChange();
239
- this.scheduleStallTimeout(id);
240
- void this.run(id, entry.info, entry.brief, entry.type);
371
+ }
372
+ catch { /* the next reserve decides */ }
373
+ }
374
+ markQueued(reason) {
375
+ let changed = false;
376
+ for (const id of this.queue) {
377
+ const a = this.agents.get(id)?.info;
378
+ if (!a || a.status !== "queued" || a.queueReason === reason)
379
+ continue;
380
+ a.queueReason = reason;
381
+ a.phase = nextPhase(a.phase, { type: "queued", reason }, Date.now());
382
+ changed = true;
383
+ }
384
+ if (changed)
385
+ this.onChange();
386
+ }
387
+ start(id) {
388
+ const entry = this.agents.get(id);
389
+ entry.info.status = "working";
390
+ entry.info.startedAt = Date.now();
391
+ entry.info.queueReason = undefined;
392
+ entry.info.phase = { kind: "between", since: Date.now() };
393
+ entry.lastStreamAt = Date.now();
394
+ this.onChange();
395
+ this.scheduleStallTimeout(id);
396
+ void this.run(id, entry.info, entry.brief, entry.type);
397
+ }
398
+ /** Give a lane's reservation back (finish, stop, crash): idempotent. */
399
+ dropLease(id) {
400
+ const entry = this.agents.get(id);
401
+ if (!entry?.leaseId)
402
+ return;
403
+ const leaseId = entry.leaseId;
404
+ entry.leaseId = undefined;
405
+ if (entry.info.name)
406
+ setCapacityLease(entry.info.name);
407
+ void this.capacity?.release(leaseId);
408
+ }
409
+ /** One timer while any lane is live: refreshes the lanes (elapsed, phase), runs the silent check, asks the router
410
+ * again for queued lanes, and renews reservations. Stops when nothing is working or queued. */
411
+ syncTicker() {
412
+ const live = [...this.agents.values()].some((a) => a.info.status === "working" || a.info.status === "queued");
413
+ if (live && !this.ticker) {
414
+ this.ticker = setInterval(() => this.tick(), TICK_MS);
415
+ this.ticker.unref?.();
416
+ }
417
+ else if (!live && this.ticker) {
418
+ clearInterval(this.ticker);
419
+ this.ticker = undefined;
420
+ }
421
+ }
422
+ tick(now = Date.now()) {
423
+ for (const entry of this.agents.values()) {
424
+ if (entry.info.status !== "working")
425
+ continue;
426
+ const silent = this.silentFor(entry, now);
427
+ if (silent !== undefined && silent >= STUCK_SILENT_MS)
428
+ this.flagStuck(entry, `no stream and no tool for ${Math.round(silent / 60_000)} min`);
429
+ }
430
+ if (this.queue.length && now - this.lastLook >= CAPACITY_LOOK_MS)
431
+ this.pump();
432
+ else if (this.slots.kind === "live" && now - this.lastLook >= CAPACITY_LOOK_MS) {
433
+ this.lastLook = now;
434
+ void this.look();
435
+ }
436
+ if (this.capacity && now - this.lastRenew >= RENEW_MS) {
437
+ this.lastRenew = now;
438
+ for (const e of this.agents.values())
439
+ if (e.leaseId)
440
+ void this.capacity.renew(e.leaseId);
441
+ }
442
+ this.onChange();
443
+ this.syncTicker();
444
+ }
445
+ /** How long a working lane has had neither stream activity nor a tool; undefined while a tool runs or it waits for a
446
+ * slot (neither is the model going quiet). */
447
+ silentFor(entry, now) {
448
+ const k = entry.info.phase?.kind;
449
+ if (k === "tool" || k === "slot" || k === "queued")
450
+ return undefined;
451
+ return now - (entry.lastStreamAt ?? entry.info.startedAt ?? now);
452
+ }
453
+ flagStuck(entry, why) {
454
+ if (entry.info.stuck)
455
+ return;
456
+ entry.info.stuck = why;
457
+ this.onChange();
458
+ if (entry.stuckNotified)
459
+ return; // the orchestrator is woken once per agent; the panel keeps showing it
460
+ entry.stuckNotified = true;
461
+ this.onStuck?.({ ...entry.info });
462
+ }
463
+ /** Test hook: run one live tick at `now`. */
464
+ tickForTest(now) { this.tick(now); }
465
+ /** The evidence-size guard's current warnings (siblings sharing one large input), newest grouping. */
466
+ evidenceWarnings() {
467
+ return evidenceOverlap(this.evidence).map(overlapLine);
468
+ }
469
+ refreshEvidence() {
470
+ const live = new Set([...this.agents.values()].map((a) => a.info.name));
471
+ this.evidence = this.evidence.filter((r) => live.has(r.agent));
472
+ const overlaps = evidenceOverlap(this.evidence);
473
+ for (const a of this.agents.values()) {
474
+ const o = overlaps.find((x) => a.info.name !== undefined && x.agents.includes(a.info.name));
475
+ a.info.evidence = o ? overlapLine(o) : undefined;
241
476
  }
242
477
  }
243
478
  /** Watchdog for a HUNG child — a STALL detector, NOT an absolute cap. The clock resets on every real
@@ -322,6 +557,7 @@ export class BackgroundAgents {
322
557
  info.endKind = "failed";
323
558
  info.endReason = `failed to start: ${e instanceof Error ? e.message : String(e)}`;
324
559
  this.clearStallTimer(id);
560
+ this.dropLease(id);
325
561
  this.scheduleReap(id);
326
562
  this.onChange();
327
563
  if (wt)
@@ -350,24 +586,39 @@ export class BackgroundAgents {
350
586
  let lastThoughtEmit = 0;
351
587
  let lastSig = "";
352
588
  let repeat = 0;
353
- let lastBatchAt = Date.now();
354
589
  const writesExpected = roleCanWrite(type) && (type === "code-edit" || WRITING_TASK.test(info.task ?? ""));
355
- const markStuck = (why) => {
356
- if (info.stuck)
357
- return;
358
- info.stuck = why;
359
- this.onChange();
360
- if (entry.stuckNotified)
361
- return; // the orchestrator is woken once per agent; the panel keeps showing it
362
- entry.stuckNotified = true;
363
- this.onStuck?.({ ...info });
590
+ const markStuck = (why) => this.flagStuck(entry, why);
591
+ // Every live signal moves the lane's phase; stream signals also prove the model is alive (the silent check) and
592
+ // clear a silence flag the moment bytes flow again.
593
+ const phase = (e, render = true) => {
594
+ const now = Date.now();
595
+ info.phase = nextPhase(info.phase, e, now);
596
+ if (isStreamEvent(e)) {
597
+ entry.lastStreamAt = now;
598
+ if (info.stuck?.startsWith("no stream"))
599
+ info.stuck = undefined;
600
+ }
601
+ if (render)
602
+ this.onChange();
364
603
  };
365
604
  const hooks = {
366
605
  // Waiting in the endpoint gate behind whoever holds its model's slot (TUI plan #7): the lane says who, and since when.
367
- onQueued: (q) => { info.slotWaitSince = Date.now(); info.slotHolder = q.holder; this.onChange(); },
368
- onSent: () => { if (info.slotWaitSince !== undefined) {
606
+ onQueued: (q) => { info.slotWaitSince = Date.now(); info.slotHolder = q.holder; phase({ type: "slotWait", holder: q.holder }); },
607
+ onSent: () => {
369
608
  info.slotWaitSince = undefined;
370
609
  info.slotHolder = undefined;
610
+ entry.lastStreamAt = Date.now(); // the request just went out: silence is measured from here
611
+ phase({ type: "sent", ctxPct: typeof session.ctxPct === "function" ? session.ctxPct() : undefined });
612
+ },
613
+ onPromptProgress: (p) => { this.touchProgress(id); phase({ type: "prompt", processed: p.processed, total: p.total, cached: p.cached }, false); },
614
+ onDelta: () => phase({ type: "content" }, false),
615
+ onToolDraft: () => phase({ type: "content" }, false),
616
+ onServed: (s) => { if (s.backend && s.backend !== info.leg) {
617
+ info.leg = s.backend;
618
+ this.onChange();
619
+ } },
620
+ onPrimaryRestored: (backend) => { if (backend !== info.leg) {
621
+ info.leg = backend;
371
622
  this.onChange();
372
623
  } },
373
624
  // message_agent / @Name while this agent works: folded in at its next round boundary, not after the whole turn.
@@ -386,14 +637,12 @@ export class BackgroundAgents {
386
637
  onTokens: (t) => {
387
638
  info.tokens = total + t;
388
639
  this.touchProgress(id);
389
- this.onChange();
390
- // Tokens keep the stall timer alive, so a model that talks without acting never "stalls" — catch it here.
391
- if (Date.now() - lastBatchAt > STUCK_TALK_MS)
392
- markStuck(`talking without acting for ${Math.round((Date.now() - lastBatchAt) / 60_000)} min`);
640
+ phase({ type: "tokens", total: t });
393
641
  },
394
642
  // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
395
643
  // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
396
644
  onReasoning: (chunk) => {
645
+ phase({ type: "reasoning" }, false);
397
646
  const t = ((info.thought ?? "") + chunk).replace(/\s+/g, " ");
398
647
  info.thought = t.length > THOUGHT_MAX ? "…" + t.slice(-(THOUGHT_MAX - 1)) : t;
399
648
  // Continually-updating mission line ("what I'm doing now") — persists across tool batches (unlike
@@ -411,34 +660,48 @@ export class BackgroundAgents {
411
660
  onToolStart: (calls) => {
412
661
  const running = calls.map((c) => ({ name: c.name, arg: shortArg(c.args), running: true }));
413
662
  info.steps = [...(info.steps ?? []), ...running].slice(-RECENT_STEPS);
414
- this.onChange();
663
+ info.doing = calls[0] ? toolSummary(calls[0].name, calls[0].args) : undefined;
664
+ phase({ type: "toolStart", name: calls[0]?.name ?? "tool", arg: shortArg(calls[0]?.args ?? {}), count: calls.length });
415
665
  },
416
666
  // A batch finished — replace the in-flight rows with settled name+arg, bump the round, and drop
417
667
  // the pre-call reasoning (it belonged to choosing THIS batch; the next think starts fresh).
418
668
  onToolBatch: (events) => {
419
669
  info.round = (info.round ?? 0) + 1;
420
670
  const settled = events.map((e) => ({ name: e.name, arg: shortArg(e.args), running: false }));
671
+ for (const e of events) {
672
+ if (e.name !== "task_update")
673
+ continue;
674
+ const st = e.args?.status;
675
+ info.planStep = st === "in_progress" ? planStepFrom(e.args ?? {}, String(e.result ?? "")) ?? info.planStep : st === "done" || st === "cancelled" ? undefined : info.planStep;
676
+ }
421
677
  info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
422
678
  // Keep a short tail of the latest tool's output so the owner sees the work's EFFECT, not just its name
423
679
  // — the "I have no visibility on what anyone is doing" gap. Skipped for an empty/errored result.
424
680
  const lastOut = events.length ? String(events[events.length - 1].result ?? "").trim() : "";
425
681
  info.lastOutput = lastOut ? outputTail(lastOut) : undefined;
426
682
  info.thought = undefined;
427
- lastBatchAt = Date.now();
683
+ info.phase = nextPhase(info.phase, { type: "toolsDone" }, Date.now());
684
+ entry.lastStreamAt = Date.now();
428
685
  // Work ledger: what it changed, read and ran — the owner's answer to "what has it actually done?".
429
686
  let wrote = false;
430
687
  for (const e of events) {
431
688
  const out = String(e.result ?? "").trim();
432
- if (WRITE_TOOLS.has(e.name) && !/^(error|✗)/i.test(out)) {
689
+ if (FILE_WRITE.has(e.name) && !/^(error|✗)/i.test(out)) {
433
690
  const p = pathArg(e.args);
434
691
  if (p) {
435
692
  info.written = [...(info.written ?? []).filter((x) => x !== p), p].slice(-WRITTEN_MAX);
436
693
  wrote = true;
437
694
  }
438
695
  }
439
- else if (READ_TOOLS.has(e.name))
696
+ else if (LOOKUP.has(e.name)) {
440
697
  info.reads = (info.reads ?? 0) + 1;
441
- else if (CMD_TOOLS.has(e.name))
698
+ const p = pathArg(e.args);
699
+ if (p && info.name && out.length) {
700
+ this.evidence.push(readRecord(info.name, p, out.length));
701
+ this.refreshEvidence();
702
+ }
703
+ }
704
+ else if (SHELL_ANY.has(e.name))
442
705
  info.commands = (info.commands ?? 0) + 1;
443
706
  }
444
707
  if (wrote)
@@ -470,14 +733,14 @@ export class BackgroundAgents {
470
733
  let fa = extractFinalAnswer(r.content, type);
471
734
  // The engine ended the child's turn (loop guard, no progress, round cap): a repair round would hand the same loop
472
735
  // a fresh budget (10/31: round 54 against a cap of 50). Finish with what it has; the stop note says why.
473
- let engineStopped = isEngineFinal(r.content);
736
+ let engineStopped = engineEnded(r);
474
737
  if (engineStopped)
475
738
  info.malformed = true;
476
739
  // Mechanism 2: one repair round on a schema failure — feed the error back, re-run just the final step.
477
740
  if (!fa.ok && !r.interrupted && !engineStopped) {
478
741
  const r2 = await session.send(repairPrompt(fa.errors ?? [], type), hooks);
479
742
  total += r2.tokens ?? 0;
480
- engineStopped = isEngineFinal(r2.content);
743
+ engineStopped = engineEnded(r2);
481
744
  const fa2 = extractFinalAnswer(r2.content, type);
482
745
  if (fa2.ok) {
483
746
  fa = fa2;
@@ -501,7 +764,7 @@ export class BackgroundAgents {
501
764
  this.onChange();
502
765
  r = await session.send(msg, hooks);
503
766
  total += r.tokens ?? 0;
504
- engineStopped = isEngineFinal(r.content);
767
+ engineStopped = engineEnded(r);
505
768
  const faF = extractFinalAnswer(r.content, type);
506
769
  if (faF.ok)
507
770
  fa = faF;
@@ -583,6 +846,7 @@ export class BackgroundAgents {
583
846
  session.disposeShell();
584
847
  }
585
848
  catch { /* shell may never have started */ }
849
+ this.dropLease(id);
586
850
  // This agent set itself idle/stopped above, freeing a slot — promote the next queued agent.
587
851
  this.pump();
588
852
  }
@@ -630,6 +894,7 @@ export class BackgroundAgents {
630
894
  a.session?.interrupt(); // session is created lazily in run(); may not exist yet if still queuing/setup
631
895
  a.info.status = "stopped";
632
896
  this.clearStallTimer(id);
897
+ this.dropLease(id);
633
898
  this.scheduleReap(id);
634
899
  this.onChange();
635
900
  this.pump(); // a running agent stopping frees a slot for the next queued one
@@ -667,6 +932,26 @@ export class BackgroundAgents {
667
932
  .map((a) => a.info.id);
668
933
  return ids.filter((id) => this.requestStop(id, by, byLabel));
669
934
  }
935
+ /** Every agent still working or queued, as a record the next session in `cwd` can resume (background/resume.ts).
936
+ * Finished, stopped and failed agents are left out: they are never resumed. `tasks` is the session's open task list. */
937
+ resumable(cwd, tasks = []) {
938
+ return [...this.agents.values()]
939
+ .filter((a) => a.info.status === "working" || a.info.status === "queued")
940
+ .map(({ info, session }) => {
941
+ const snap = typeof session?.snapshot === "function" ? session.snapshot() : [];
942
+ const progress = [
943
+ snap.length ? partialReport(snap, `${info.name ?? info.id} was cut off when Operator closed after ${info.round ?? 0} rounds`) : "",
944
+ info.progress ? `Last step in progress: ${info.progress}` : "",
945
+ ].filter(Boolean).join("\n\n");
946
+ return {
947
+ id: info.id, name: info.name ?? info.id, label: info.label, role: info.role ?? "generic", model: info.model,
948
+ task: info.task ?? info.label, cwd,
949
+ tasks: tasks.filter((t) => t.status === "pending" || t.status === "in_progress").map((t) => ({ ...t })),
950
+ progress, written: [...(info.written ?? [])], rounds: info.round ?? 0, startedAt: info.startedAt,
951
+ status: info.status,
952
+ };
953
+ });
954
+ }
670
955
  /** The concurrency caps (TUI plan #11): how many agents run at once, and how many may wait for a slot. */
671
956
  limits() {
672
957
  return { running: this.maxConcurrent, queued: this.maxQueued };
@@ -680,7 +965,13 @@ export class BackgroundAgents {
680
965
  * hangs after /exit (the "pressed exit → frozen" bug). interrupt() aborts the in-flight turn;
681
966
  * shutdown() kills the child's own MCP subprocesses; reap + stall-watchdog timers are cleared. */
682
967
  dispose() {
968
+ if (this.ticker) {
969
+ clearInterval(this.ticker);
970
+ this.ticker = undefined;
971
+ }
683
972
  for (const a of this.agents.values()) {
973
+ if (a.leaseId)
974
+ this.dropLease(a.info.id);
684
975
  if (a.reap) {
685
976
  clearTimeout(a.reap);
686
977
  a.reap = undefined;
@@ -0,0 +1,60 @@
1
+ // What a sub-agent lane is doing right now, set only by real events (the endpoint gate, the stream, the tool loop) — the
2
+ // lane used to show the last tool and reasoning snippet, which froze for the whole of a long model call (11/27: Vex read
3
+ // "r4 · Let me check total lines" for 16 minutes while the server prefilled a 210 KB digest). Pure: the manager feeds
4
+ // events in, the lane reads phaseText out.
5
+ import { fmtElapsed, fmtTok } from "../ui/format.js";
6
+ /** True for the events that prove the model stream is alive (the stuck check's "stream activity"). */
7
+ export const isStreamEvent = (e) => e.type === "prompt" || e.type === "reasoning" || e.type === "content" || e.type === "tokens";
8
+ export function nextPhase(p, e, now) {
9
+ switch (e.type) {
10
+ case "queued": return { kind: "queued", since: p?.kind === "queued" ? p.since : now, reason: e.reason };
11
+ case "slotWait": return { kind: "slot", since: p?.kind === "slot" ? p.since : now, holder: e.holder };
12
+ case "sent": return { kind: "sent", since: now, ctxPct: e.ctxPct };
13
+ case "prompt": return { kind: "reading", since: p?.kind === "reading" ? p.since : now, processed: e.processed, total: e.total, cached: e.cached };
14
+ case "reasoning":
15
+ case "content": {
16
+ const kind = e.type === "reasoning" ? "thinking" : "writing";
17
+ if (p?.kind === kind)
18
+ return p;
19
+ const tokens = p?.kind === "thinking" || p?.kind === "writing" ? p.tokens : 0;
20
+ return { kind, since: now, tokens, startTokens: tokens };
21
+ }
22
+ case "tokens":
23
+ if (p?.kind === "thinking" || p?.kind === "writing")
24
+ return { ...p, tokens: e.total };
25
+ return { kind: "writing", since: now, tokens: e.total, startTokens: e.total };
26
+ case "toolStart": return { kind: "tool", since: now, name: e.name, arg: e.arg, count: e.count };
27
+ case "toolsDone": return { kind: "between", since: now };
28
+ }
29
+ }
30
+ /** Decode rate over the phase so far, once a second of it has passed. */
31
+ export function tokPerSec(p, now) {
32
+ if (p.kind !== "thinking" && p.kind !== "writing")
33
+ return undefined;
34
+ const secs = (now - p.since) / 1000;
35
+ return secs >= 1 && p.tokens > p.startTokens ? (p.tokens - p.startTokens) / secs : undefined;
36
+ }
37
+ /** The phase in a few words with its live numbers: "reading 120k/210k tok (57%) 3m 2s", "writing 1.2k tok @ 38 tok/s". */
38
+ export function phaseText(p, now) {
39
+ if (!p)
40
+ return undefined;
41
+ const t = fmtElapsed(now - p.since);
42
+ switch (p.kind) {
43
+ case "queued": return p.reason ? `queued ${t}: ${p.reason}` : `queued ${t}`;
44
+ case "slot": return `waiting for a slot ${t}${p.holder ? ` (held by ${p.holder})` : ""}`;
45
+ case "sent": return `request sent ${t}, nothing back yet${p.ctxPct ? ` · prompt ${Math.round(p.ctxPct)}% of window` : ""}`;
46
+ case "reading": {
47
+ const fresh = Math.max(1, p.total - p.cached);
48
+ const done = Math.max(0, p.processed - p.cached);
49
+ return `reading ${fmtTok(done)}/${fmtTok(fresh)} tok (${Math.min(100, Math.round((done / fresh) * 100))}%) ${t}${p.cached ? ` · ${fmtTok(p.cached)} cached` : ""}`;
50
+ }
51
+ case "thinking":
52
+ case "writing": {
53
+ const tps = tokPerSec(p, now);
54
+ const n = p.tokens - p.startTokens;
55
+ return `${p.kind} ${n > 0 ? `${fmtTok(n)} tok` : t}${tps ? ` @ ${tps.toFixed(tps < 10 ? 1 : 0)} tok/s` : ""}`;
56
+ }
57
+ case "tool": return `tool ${p.name}${p.arg ? ` ${p.arg}` : ""}${p.count > 1 ? ` +${p.count - 1}` : ""} ${t}`;
58
+ case "between": return `between rounds ${t}`;
59
+ }
60
+ }