@0perator/operator 0.2.0 → 0.2.2-next.0

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 (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. package/dist/tools/mutating.js +0 -15
@@ -1,18 +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
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";
5
11
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
6
12
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
7
13
  // The work ledger + stuck checks (10/31: a sub-agent ran 54 rounds / 33 min, wrote nothing, and nobody could tell).
8
- const WRITE_TOOLS = new Set(["file_write", "file_edit", "apply_patch", "multi_edit", "write_file", "edit_file", "notebook_edit"]);
9
- const READ_TOOLS = new Set(["file_read", "read_files", "list_directory", "find_files", "glob", "grep", "grep_search", "search",
10
- "code_search", "codebase_search", "web_search", "web_fetch", "browser", "browser_read", "deep_research", "knowledge_search"]);
11
- const CMD_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
12
14
  const WRITTEN_MAX = 8;
13
15
  const STUCK_REPEATS = 3; // the same call(s) this many batches in a row
14
16
  const STUCK_ROUNDS_NO_WRITE = 15; // a writing task with this many rounds and no file written
15
- 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
16
26
  const WRITING_TASK = /\b(write|create|draft|edit|update|build|implement|fix|add|document|save)\b/i;
17
27
  /** Default names when the planner gives none — short, distinct, easy to type in `/agents <name>`, and none of them a
18
28
  * fleet box or service (Nova, Atlas, Forge… already mean machines here). */
@@ -100,12 +110,29 @@ export class BackgroundAgents {
100
110
  // Cap concurrently-RUNNING background sub-agents. Unbounded fan-out (4 heavy aurora-code-1 sub-agents +
101
111
  // Aurora serving) starved a 64GB node clean off the network — an agent must never overload its own host.
102
112
  // Excess spawns QUEUE and start as slots free. KODE_BG_MAX overrides (settings.background.maxConcurrent).
103
- 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);
104
126
  // The queue itself must ALSO be bounded — a burst of spawn calls (model or /bg) used to enqueue without
105
127
  // limit, so "how many are running" stayed capped while "how many are in flight" ballooned (seen live:
106
128
  // "background (6)" with a running-cap of 4). Total in-flight (working+queued) is capped at 2x the
107
129
  // concurrency cap; spawn() beyond it refuses outright instead of silently piling onto the wait list.
108
- 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
+ }
109
136
  // Wall-clock ceiling for a single working agent. The chat fetch layer (engine/aurora.ts) has no per-request
110
137
  // timeout of its own — only an explicit interrupt() aborts it — so a stalled/hung endpoint (connection open,
111
138
  // no chunks) would otherwise pin a concurrency slot forever and wedge the queue behind it. KODE_BG_TIMEOUT_MS
@@ -172,7 +199,7 @@ export class BackgroundAgents {
172
199
  /** Human-readable capacity-exceeded message, shared by every spawn surface (spawn_agent tool, /bg
173
200
  * command) so there is exactly one wording and one number to keep in sync. */
174
201
  capacityLine() {
175
- 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`;
176
203
  }
177
204
  /** Spawn a background agent on `task`. Returns its short id (agent-1, agent-2, …), or "" when total
178
205
  * in-flight (running + queued) is already at the hard cap — the caller must show capacityLine() and NOT
@@ -184,8 +211,8 @@ export class BackgroundAgents {
184
211
  * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
185
212
  * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
186
213
  * namespaces make that specific confusion structurally impossible, not just better-worded. */
187
- spawn(task, role, name, resumed) {
188
- if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
214
+ spawn(task, role, name, resumed, opts = {}) {
215
+ if (this.inFlight() >= this.maxQueued * 2)
189
216
  return "";
190
217
  const id = `agent-${++this.seq}`;
191
218
  const type = role ?? roleForBrief(task);
@@ -203,8 +230,13 @@ export class BackgroundAgents {
203
230
  name: this.uniqueName(name?.trim().replace(/\s+/g, " ").slice(0, 24) || AGENT_NAMES[(this.seq - 1) % AGENT_NAMES.length]),
204
231
  title: SUBAGENT_ROLES[type]?.title ?? "assistant", role: type,
205
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()),
206
236
  };
207
237
  this.agents.set(id, { info, brief, type });
238
+ this.evidence.push(...briefRecords(info.name, task));
239
+ this.refreshEvidence();
208
240
  this.queue.push(id);
209
241
  this.onChange();
210
242
  this.pump();
@@ -230,18 +262,217 @@ export class BackgroundAgents {
230
262
  return a.info.id;
231
263
  return undefined;
232
264
  }
233
- /** 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. */
234
288
  pump() {
235
- while (this.activeCount() < this.maxConcurrent && this.queue.length > 0) {
236
- 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];
237
318
  const entry = this.agents.get(id);
238
- if (!entry || entry.info.status !== "queued")
239
- continue; // stopped/removed while waiting
240
- entry.info.status = "working";
241
- 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 };
242
370
  this.onChange();
243
- this.scheduleStallTimeout(id);
244
- 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;
245
476
  }
246
477
  }
247
478
  /** Watchdog for a HUNG child — a STALL detector, NOT an absolute cap. The clock resets on every real
@@ -326,6 +557,7 @@ export class BackgroundAgents {
326
557
  info.endKind = "failed";
327
558
  info.endReason = `failed to start: ${e instanceof Error ? e.message : String(e)}`;
328
559
  this.clearStallTimer(id);
560
+ this.dropLease(id);
329
561
  this.scheduleReap(id);
330
562
  this.onChange();
331
563
  if (wt)
@@ -354,24 +586,39 @@ export class BackgroundAgents {
354
586
  let lastThoughtEmit = 0;
355
587
  let lastSig = "";
356
588
  let repeat = 0;
357
- let lastBatchAt = Date.now();
358
589
  const writesExpected = roleCanWrite(type) && (type === "code-edit" || WRITING_TASK.test(info.task ?? ""));
359
- const markStuck = (why) => {
360
- if (info.stuck)
361
- return;
362
- info.stuck = why;
363
- this.onChange();
364
- if (entry.stuckNotified)
365
- return; // the orchestrator is woken once per agent; the panel keeps showing it
366
- entry.stuckNotified = true;
367
- 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();
368
603
  };
369
604
  const hooks = {
370
605
  // Waiting in the endpoint gate behind whoever holds its model's slot (TUI plan #7): the lane says who, and since when.
371
- onQueued: (q) => { info.slotWaitSince = Date.now(); info.slotHolder = q.holder; this.onChange(); },
372
- onSent: () => { if (info.slotWaitSince !== undefined) {
606
+ onQueued: (q) => { info.slotWaitSince = Date.now(); info.slotHolder = q.holder; phase({ type: "slotWait", holder: q.holder }); },
607
+ onSent: () => {
373
608
  info.slotWaitSince = undefined;
374
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;
375
622
  this.onChange();
376
623
  } },
377
624
  // message_agent / @Name while this agent works: folded in at its next round boundary, not after the whole turn.
@@ -390,14 +637,12 @@ export class BackgroundAgents {
390
637
  onTokens: (t) => {
391
638
  info.tokens = total + t;
392
639
  this.touchProgress(id);
393
- this.onChange();
394
- // Tokens keep the stall timer alive, so a model that talks without acting never "stalls" — catch it here.
395
- if (Date.now() - lastBatchAt > STUCK_TALK_MS)
396
- markStuck(`talking without acting for ${Math.round((Date.now() - lastBatchAt) / 60_000)} min`);
640
+ phase({ type: "tokens", total: t });
397
641
  },
398
642
  // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
399
643
  // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
400
644
  onReasoning: (chunk) => {
645
+ phase({ type: "reasoning" }, false);
401
646
  const t = ((info.thought ?? "") + chunk).replace(/\s+/g, " ");
402
647
  info.thought = t.length > THOUGHT_MAX ? "…" + t.slice(-(THOUGHT_MAX - 1)) : t;
403
648
  // Continually-updating mission line ("what I'm doing now") — persists across tool batches (unlike
@@ -415,34 +660,48 @@ export class BackgroundAgents {
415
660
  onToolStart: (calls) => {
416
661
  const running = calls.map((c) => ({ name: c.name, arg: shortArg(c.args), running: true }));
417
662
  info.steps = [...(info.steps ?? []), ...running].slice(-RECENT_STEPS);
418
- 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 });
419
665
  },
420
666
  // A batch finished — replace the in-flight rows with settled name+arg, bump the round, and drop
421
667
  // the pre-call reasoning (it belonged to choosing THIS batch; the next think starts fresh).
422
668
  onToolBatch: (events) => {
423
669
  info.round = (info.round ?? 0) + 1;
424
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
+ }
425
677
  info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
426
678
  // Keep a short tail of the latest tool's output so the owner sees the work's EFFECT, not just its name
427
679
  // — the "I have no visibility on what anyone is doing" gap. Skipped for an empty/errored result.
428
680
  const lastOut = events.length ? String(events[events.length - 1].result ?? "").trim() : "";
429
681
  info.lastOutput = lastOut ? outputTail(lastOut) : undefined;
430
682
  info.thought = undefined;
431
- lastBatchAt = Date.now();
683
+ info.phase = nextPhase(info.phase, { type: "toolsDone" }, Date.now());
684
+ entry.lastStreamAt = Date.now();
432
685
  // Work ledger: what it changed, read and ran — the owner's answer to "what has it actually done?".
433
686
  let wrote = false;
434
687
  for (const e of events) {
435
688
  const out = String(e.result ?? "").trim();
436
- if (WRITE_TOOLS.has(e.name) && !/^(error|✗)/i.test(out)) {
689
+ if (FILE_WRITE.has(e.name) && !/^(error|✗)/i.test(out)) {
437
690
  const p = pathArg(e.args);
438
691
  if (p) {
439
692
  info.written = [...(info.written ?? []).filter((x) => x !== p), p].slice(-WRITTEN_MAX);
440
693
  wrote = true;
441
694
  }
442
695
  }
443
- else if (READ_TOOLS.has(e.name))
696
+ else if (LOOKUP.has(e.name)) {
444
697
  info.reads = (info.reads ?? 0) + 1;
445
- 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))
446
705
  info.commands = (info.commands ?? 0) + 1;
447
706
  }
448
707
  if (wrote)
@@ -474,14 +733,14 @@ export class BackgroundAgents {
474
733
  let fa = extractFinalAnswer(r.content, type);
475
734
  // The engine ended the child's turn (loop guard, no progress, round cap): a repair round would hand the same loop
476
735
  // a fresh budget (10/31: round 54 against a cap of 50). Finish with what it has; the stop note says why.
477
- let engineStopped = isEngineFinal(r.content);
736
+ let engineStopped = engineEnded(r);
478
737
  if (engineStopped)
479
738
  info.malformed = true;
480
739
  // Mechanism 2: one repair round on a schema failure — feed the error back, re-run just the final step.
481
740
  if (!fa.ok && !r.interrupted && !engineStopped) {
482
741
  const r2 = await session.send(repairPrompt(fa.errors ?? [], type), hooks);
483
742
  total += r2.tokens ?? 0;
484
- engineStopped = isEngineFinal(r2.content);
743
+ engineStopped = engineEnded(r2);
485
744
  const fa2 = extractFinalAnswer(r2.content, type);
486
745
  if (fa2.ok) {
487
746
  fa = fa2;
@@ -505,7 +764,7 @@ export class BackgroundAgents {
505
764
  this.onChange();
506
765
  r = await session.send(msg, hooks);
507
766
  total += r.tokens ?? 0;
508
- engineStopped = isEngineFinal(r.content);
767
+ engineStopped = engineEnded(r);
509
768
  const faF = extractFinalAnswer(r.content, type);
510
769
  if (faF.ok)
511
770
  fa = faF;
@@ -587,6 +846,7 @@ export class BackgroundAgents {
587
846
  session.disposeShell();
588
847
  }
589
848
  catch { /* shell may never have started */ }
849
+ this.dropLease(id);
590
850
  // This agent set itself idle/stopped above, freeing a slot — promote the next queued agent.
591
851
  this.pump();
592
852
  }
@@ -634,6 +894,7 @@ export class BackgroundAgents {
634
894
  a.session?.interrupt(); // session is created lazily in run(); may not exist yet if still queuing/setup
635
895
  a.info.status = "stopped";
636
896
  this.clearStallTimer(id);
897
+ this.dropLease(id);
637
898
  this.scheduleReap(id);
638
899
  this.onChange();
639
900
  this.pump(); // a running agent stopping frees a slot for the next queued one
@@ -704,7 +965,13 @@ export class BackgroundAgents {
704
965
  * hangs after /exit (the "pressed exit → frozen" bug). interrupt() aborts the in-flight turn;
705
966
  * shutdown() kills the child's own MCP subprocesses; reap + stall-watchdog timers are cleared. */
706
967
  dispose() {
968
+ if (this.ticker) {
969
+ clearInterval(this.ticker);
970
+ this.ticker = undefined;
971
+ }
707
972
  for (const a of this.agents.values()) {
973
+ if (a.leaseId)
974
+ this.dropLease(a.info.id);
708
975
  if (a.reap) {
709
976
  clearTimeout(a.reap);
710
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
+ }