@0perator/operator 0.1.351 → 0.1.353

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 (92) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1073 -177
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +66 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +362 -33
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/toolchain/toolchain.py +528 -112
  46. package/dist/tools/deferred.js +28 -18
  47. package/dist/tools/executor.js +7 -3
  48. package/dist/tools/registry.js +68 -7
  49. package/dist/tools/result-cap.js +1 -1
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
package/dist/acp/agent.js CHANGED
@@ -368,12 +368,12 @@ export function acpHandlers(emit, ctx = {}) {
368
368
  });
369
369
  }
370
370
  },
371
- onToolResult: (id, result) => {
371
+ onToolResult: (id, result, _batchId, refused) => {
372
372
  ctx.calls?.settle(id);
373
373
  emit({
374
374
  sessionUpdate: "tool_call_update",
375
375
  toolCallId: id,
376
- status: resultStatus(result),
376
+ status: resultStatus(result, refused),
377
377
  content: [{ type: "content", content: { type: "text", text: capResult(result) } }],
378
378
  });
379
379
  },
@@ -37,10 +37,11 @@ export function toolLocations(args, cwd) {
37
37
  return [{ path: raw }];
38
38
  return cwd ? [{ path: resolve(cwd, raw) }] : [];
39
39
  }
40
- /** A tool result reads as failed when it is an engine error/loop-guard/interrupt sentinel, a permission/tier
41
- * refusal, or a sandbox block — the editor should paint those red instead of "completed". */
42
- export function resultStatus(result) {
43
- return isErrorResult(result) || /^(permission denied|sandbox)/i.test(result.trim()) ? "failed" : "completed";
40
+ /** A tool result reads as failed when a layer refused or cancelled the call (`refused`, the engine's report), when it
41
+ * is an engine error/interrupt or a non-zero exit, a permission/tier refusal, or a sandbox block — the editor should
42
+ * paint those red instead of "completed". */
43
+ export function resultStatus(result, refused) {
44
+ return isErrorResult(result, refused) || /^(permission denied|sandbox)/i.test(result.trim()) ? "failed" : "completed";
44
45
  }
45
46
  export const MAX_RESULT_CHARS = 50_000;
46
47
  /** One tool result is one JSON-RPC line to the editor; an uncapped `cat` of a build log would stall the pipe. */
@@ -115,6 +115,51 @@ function briefFor(task) {
115
115
  const NO_ANSWER = /^\s*(\[(stopped|paused|no reply came back from the model|declined by the provider)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
116
116
  let _seq = 0;
117
117
  const TIMED_OUT = Symbol("delegate-timeout");
118
+ const progressListeners = new Set();
119
+ export function onDelegateProgress(fn) {
120
+ progressListeners.add(fn);
121
+ return () => { progressListeners.delete(fn); };
122
+ }
123
+ function emitProgress(p) {
124
+ for (const fn of progressListeners) {
125
+ try {
126
+ fn({ ...p });
127
+ }
128
+ catch { /* a bad listener never touches the delegation */ }
129
+ }
130
+ }
131
+ const WRITE_TOOLS = new Set(["file_write", "file_edit", "multi_edit", "apply_patch", "notebook_edit"]);
132
+ const CMD_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
133
+ const READ_TOOLS = /^(file_read|read_files|list_directory|find_files|glob|grep|grep_search|search|code_search|web_search|web_fetch|browser_read|deep_research)$/;
134
+ function shortArg(args) {
135
+ const v = args?.path ?? args?.file ?? args?.pattern ?? args?.query ?? args?.command ?? args?.url;
136
+ return typeof v === "string" ? v.replace(/\s+/g, " ").slice(0, 60) : undefined;
137
+ }
138
+ /** The handlers that turn a child's events into progress snapshots. Pure wiring, exported for tests. */
139
+ export function progressHandlers(p) {
140
+ return {
141
+ onToolStart: (calls) => { const c = calls[0]; p.tool = c?.name; p.arg = c ? shortArg(c.args) : undefined; p.thinking = false; emitProgress(p); },
142
+ onToolBatch: (events) => {
143
+ p.round += 1;
144
+ for (const e of events) {
145
+ if (WRITE_TOOLS.has(e.name))
146
+ p.writes += 1;
147
+ else if (CMD_TOOLS.has(e.name))
148
+ p.commands += 1;
149
+ else if (READ_TOOLS.test(e.name))
150
+ p.reads += 1;
151
+ }
152
+ p.tool = undefined;
153
+ p.arg = undefined;
154
+ emitProgress(p);
155
+ },
156
+ onTokens: (t) => { p.tokens = t; emitProgress(p); },
157
+ onReasoning: () => { if (!p.thinking) {
158
+ p.thinking = true;
159
+ emitProgress(p);
160
+ } },
161
+ };
162
+ }
118
163
  /** Race a send against the wall-clock bound. On timeout the session is interrupted (so a cooperative turn
119
164
  * stops) AND the race resolves immediately (so a wedged one can't hold the planner). */
120
165
  function sendWithTimeout(send, ms, interrupt) {
@@ -194,7 +239,15 @@ export async function runDelegateTask(args, deps = defaultDeps) {
194
239
  return `error: delegate_task: ${bound.error ?? `could not select "${profile.id}"`}`;
195
240
  const timeoutMs = deps.timeoutMs ?? DELEGATE_TIMEOUT_MS;
196
241
  const store = await depthStore();
197
- const outcome = await sendWithTimeout(store.run(depth + 1, () => session.send(briefFor(task))), timeoutMs, () => session.interrupt());
242
+ const progress = { id, task, model: profile.id, round: 0, reads: 0, writes: 0, commands: 0, tokens: 0 };
243
+ emitProgress(progress);
244
+ let outcome;
245
+ try {
246
+ outcome = await sendWithTimeout(store.run(depth + 1, () => session.send(briefFor(task), progressHandlers(progress))), timeoutMs, () => session.interrupt());
247
+ }
248
+ finally {
249
+ emitProgress({ ...progress, done: true });
250
+ }
198
251
  if (outcome === TIMED_OUT) {
199
252
  return `error: delegate_task timed out after ${Math.round(timeoutMs / 1000)}s — the sub-agent on ${profile.id} was interrupted; narrow the subtask or pick a faster model`;
200
253
  }
@@ -18,6 +18,8 @@ function handlersFor(reporter, json, prompt = "", onDelta) {
18
18
  onServed: (s) => reporter.event("fallback", { from: s.fallbackFrom, servedBy: s.backend ?? null }), // the selected model was down; another box answered
19
19
  onAutoContinue: (round) => reporter.event("auto_continue", { round }),
20
20
  onSelfHeal: (kind, attempt) => reporter.event("self_heal", { kind, attempt }),
21
+ onLoopCompaction: (e) => reporter.event("loop_compaction", { ...e }),
22
+ onLoopRecovery: (e) => reporter.event("loop_recovery", { attempt: e.attempt, max: e.max, rounds: e.rounds, replaced: e.replaced, calls: e.repeated.length }),
21
23
  onToolBatch: (events, durationMs) => {
22
24
  reporter.event("tools", {
23
25
  count: events.length,
@@ -62,6 +62,7 @@ export function createAutonomySession(settings, opts = {}) {
62
62
  moa: settings.moa,
63
63
  classifier: { mode: resolveMode(settings), endpoint: classifierConfig(settings).endpoint },
64
64
  fastStart: settings.fastStart,
65
+ frontDoor: settings.frontDoor, // a message the gateway's front door answers (engine/front-door.ts) never runs a full turn
65
66
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
66
67
  activeModel: settings.activeModel,
67
68
  // A local Aurora loads for the first turn on it (owner, 11/03), never for the run starting: a run on moa or cortana
@@ -1,4 +1,4 @@
1
- import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
1
+ import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, partialCounts, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
2
2
  import { isEngineFinal } from "../engine/continuation.js";
3
3
  import { createWorktree, finalizeWorktree } from "./worktree.js";
4
4
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
@@ -23,6 +23,7 @@ const pathArg = (args) => {
23
23
  const THOUGHT_EMIT_MS = 700; // min gap between reasoning-driven re-renders — bounds render load during long thinks
24
24
  const IDLE_TTL_MS = 45_000; // a finished agent lingers this long (result already in the transcript) then decommissions
25
25
  const MAX_FOLLOWUP_MSGS = 6; // cap on parent->child mid-run messages processed per agent (bidirectional coms; no runaway)
26
+ const RETAINED_TRANSCRIPTS = 10; // finished agents whose conversation the owner can still open (TUI A3.4 switcher)
26
27
  // Pull the one identifying argument out of a tool call for the live line (path/file it read, the
27
28
  // command/query it ran) — the follower cares "read src/cli.tsx", not the full JSON args blob.
28
29
  function shortArg(args) {
@@ -57,6 +58,20 @@ export function progressFromReasoning(reasoning) {
57
58
  return undefined;
58
59
  return last.length > PROGRESS_MAX ? last.slice(0, PROGRESS_MAX - 1) + "…" : last;
59
60
  }
61
+ /** The first sentence of a report, for the owner's one-line view. Pure + exported for testing. */
62
+ export function firstSentence(text, max = 120) {
63
+ const t = text.replace(/\s+/g, " ").trim();
64
+ if (!t)
65
+ return undefined;
66
+ const m = /^(.+?[.!?])(\s|$)/.exec(t);
67
+ const s = (m ? m[1] : t).trim();
68
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
69
+ }
70
+ /** The engine's own stop line, as the owner reads it ("loop guard: the same bash call …"). Pure + exported. */
71
+ export function engineStopReason(content) {
72
+ const first = content.trim().split("\n")[0].replace(/^\[|\]$/g, "").replace(/^(stopped|paused|turn ended)\s*[—:-]\s*/i, "").trim();
73
+ return (first.length > 80 ? `${first.slice(0, 79)}…` : first) || "stopped by the engine";
74
+ }
60
75
  const OUTPUT_TAIL_MAX = 72; // chars of the latest tool result surfaced in the panel
61
76
  // The last non-blank line of a tool result, whitespace-collapsed and capped — a glanceable "what came back"
62
77
  // without dumping a multi-KB payload into the live frame. Pure + exported for testing.
@@ -75,6 +90,7 @@ export class BackgroundAgents {
75
90
  modelName;
76
91
  onTaskActivity;
77
92
  onStuck;
93
+ onMessageTaken;
78
94
  // session is created lazily in run() (a code-editing agent's session must be rooted at its worktree, which
79
95
  // requires an async `git worktree add`); wt is its isolated worktree, or null when not isolated.
80
96
  agents = new Map();
@@ -109,16 +125,36 @@ export class BackgroundAgents {
109
125
  constructor(makeSession, onChange, onDone, modelName = "aurora-code-1", onTaskActivity,
110
126
  /** Fired ONCE per agent when the deterministic checks first find it stuck (BgAgent.stuck says why) — the shell
111
127
  * wakes the orchestrator with the evidence so it steers, stops, or takes the step over. */
112
- onStuck) {
128
+ onStuck,
129
+ /** Fired when a child takes a message the owner or parent sent it (@Name, message_agent): at the top of its round
130
+ * `round`, or as a follow-up turn once its own turn ended — the shell confirms delivery with a measured round. */
131
+ onMessageTaken) {
113
132
  this.makeSession = makeSession;
114
133
  this.onChange = onChange;
115
134
  this.onDone = onDone;
116
135
  this.modelName = modelName;
117
136
  this.onTaskActivity = onTaskActivity;
118
137
  this.onStuck = onStuck;
138
+ this.onMessageTaken = onMessageTaken;
119
139
  }
120
140
  list() {
121
- return [...this.agents.values()].map((a) => ({ ...a.info }));
141
+ return [...this.agents.values()].map((a) => ({ ...a.info, pendingMessages: a.messages?.length || undefined }));
142
+ }
143
+ // The conversations of agents that already decommissioned, newest last — the owner can still open them (A3.4).
144
+ retiredTranscripts = new Map();
145
+ /** A sub-agent's own conversation (its brief, its replies, its tool calls and results), live or retained after it
146
+ * finished; undefined for an unknown id or one that never started a session. */
147
+ transcript(id) {
148
+ const key = this.resolve(id) ?? id;
149
+ const live = this.agents.get(key)?.session;
150
+ if (live && typeof live.snapshot === "function")
151
+ return live.snapshot();
152
+ return this.retiredTranscripts.get(key);
153
+ }
154
+ /** Cheap: whether transcript(id) has anything (a started session, or a retained one) — no snapshot copy. */
155
+ hasTranscript(id) {
156
+ const key = this.resolve(id) ?? id;
157
+ return !!this.agents.get(key)?.session || this.retiredTranscripts.has(key);
122
158
  }
123
159
  // Agents that finished/errored/stopped and were reaped from the live map — kept as a lightweight record
124
160
  // so agent_status doesn't wrongly report "no sub-agents spawned this session yet" once a completed agent
@@ -241,6 +277,8 @@ export class BackgroundAgents {
241
277
  const mins = Math.round(this.stallTimeoutMs / 60_000);
242
278
  const snap = (typeof a.session?.snapshot === "function" ? a.session.snapshot() : []);
243
279
  this.stop(id);
280
+ const quiet = this.stallTimeoutMs >= 60_000 ? `${mins}m` : `${Math.round(this.stallTimeoutMs / 1000)}s`;
281
+ Object.assign(a.info, { endKind: "stalled", endReason: `no progress for ${quiet}`, headline: partialCounts(snap) });
244
282
  this.onDone(a.info, partialReport(snap, `${id} stopped: no progress for ${mins}m (stalled or a hung request) after ${a.info.round ?? 0} rounds`));
245
283
  }, Math.max(100, delay));
246
284
  timer.unref?.();
@@ -274,13 +312,15 @@ export class BackgroundAgents {
274
312
  const cwd = wt?.dir;
275
313
  let session;
276
314
  try {
277
- session = this.makeSession(cwd, type, info.model);
315
+ session = this.makeSession(cwd, type, info.model, info.name);
278
316
  }
279
317
  catch (e) {
280
318
  // makeSession is a caller-supplied factory (a real `new Session(...)`, not just an object literal) —
281
319
  // never let a construction failure become an unhandled rejection (pump()'s `void this.run(...)` has no
282
320
  // catch of its own) that vanishes the slot or, worse, brings down the whole process for every agent.
283
321
  info.status = "stopped";
322
+ info.endKind = "failed";
323
+ info.endReason = `failed to start: ${e instanceof Error ? e.message : String(e)}`;
284
324
  this.clearStallTimer(id);
285
325
  this.scheduleReap(id);
286
326
  this.onChange();
@@ -323,8 +363,22 @@ export class BackgroundAgents {
323
363
  this.onStuck?.({ ...info });
324
364
  };
325
365
  const hooks = {
326
- // message_agent while this agent works: folded in at its next round boundary, not after the whole turn.
327
- steer: () => (entry.messages?.length ? entry.messages.shift() : undefined),
366
+ // 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) {
369
+ info.slotWaitSince = undefined;
370
+ info.slotHolder = undefined;
371
+ this.onChange();
372
+ } },
373
+ // message_agent / @Name while this agent works: folded in at its next round boundary, not after the whole turn.
374
+ steer: () => {
375
+ const m = entry.messages?.length ? entry.messages.shift() : undefined;
376
+ if (m !== undefined) {
377
+ this.onMessageTaken?.({ ...info }, (info.round ?? 0) + 1, "round");
378
+ this.onChange();
379
+ }
380
+ return m;
381
+ },
328
382
  // Authoritative live token count: the real llama.cpp per-round total for the in-flight send, added
329
383
  // to what prior sends already counted. Replaces the old ≈1-per-content-delta tally, which missed
330
384
  // every token generated as a tool-call argument or reasoning (most of a skill-writer's output — so
@@ -442,6 +496,7 @@ export class BackgroundAgents {
442
496
  while (entry.messages && entry.messages.length > 0 && followups < MAX_FOLLOWUP_MSGS && !r.interrupted && !engineStopped) {
443
497
  const msg = entry.messages.shift();
444
498
  followups++;
499
+ this.onMessageTaken?.({ ...info }, (info.round ?? 0) + 1, "followup");
445
500
  info.thought = undefined;
446
501
  this.onChange();
447
502
  r = await session.send(msg, hooks);
@@ -487,6 +542,10 @@ export class BackgroundAgents {
487
542
  : (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
488
543
  ? fa.value.summary.trim()
489
544
  : (r.content.trim() || "(no output)");
545
+ if (engineStopped)
546
+ Object.assign(info, { endKind: "engine", endReason: engineStopReason(r.content), headline: partialCounts(session.snapshot()) });
547
+ else
548
+ Object.assign(info, { endKind: "done", endReason: "done", headline: firstSentence(summary) });
490
549
  const tag = info.malformed ? " ⚠ malformed final_answer (unstructured)"
491
550
  : info.verified === false ? ` ⚠ unverified: ${info.verifyDetail}`
492
551
  : info.verified ? " ✓ verified"
@@ -495,6 +554,8 @@ export class BackgroundAgents {
495
554
  }
496
555
  catch (e) {
497
556
  info.status = "stopped";
557
+ info.endKind = "error";
558
+ info.endReason = `error: ${e instanceof Error ? e.message : String(e)}`;
498
559
  info.thought = undefined;
499
560
  info.progress = undefined;
500
561
  info.lastOutput = undefined;
@@ -535,9 +596,15 @@ export class BackgroundAgents {
535
596
  if (!a || a.reap)
536
597
  return;
537
598
  a.reap = setTimeout(() => {
538
- const info = this.agents.get(id)?.info;
599
+ const gone = this.agents.get(id);
600
+ const info = gone?.info;
539
601
  if (info)
540
602
  this.retired.push({ ...info }); // remember it ran (terminal state) after it leaves the live map
603
+ if (gone?.session && typeof gone.session.snapshot === "function") {
604
+ this.retiredTranscripts.set(id, gone.session.snapshot());
605
+ for (const k of [...this.retiredTranscripts.keys()].slice(0, Math.max(0, this.retiredTranscripts.size - RETAINED_TRANSCRIPTS)))
606
+ this.retiredTranscripts.delete(k);
607
+ }
541
608
  this.agents.delete(id);
542
609
  this.onChange();
543
610
  }, IDLE_TTL_MS);
@@ -576,7 +643,7 @@ export class BackgroundAgents {
576
643
  * cancelled agent never just vanishes from the transcript. run()'s own eventual completion (once
577
644
  * interrupt() actually aborts the in-flight send) still sees r.interrupted and skips its own onDone, so
578
645
  * there is never a double post. Returns false if there was nothing running/queued to stop. */
579
- requestStop(id) {
646
+ requestStop(id, by = "owner", byLabel) {
580
647
  id = this.resolve(id) ?? id;
581
648
  const a = this.agents.get(id);
582
649
  if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
@@ -584,16 +651,25 @@ export class BackgroundAgents {
584
651
  const info = a.info;
585
652
  const snap = (typeof a.session?.snapshot === "function" ? a.session.snapshot() : []);
586
653
  this.stop(id);
654
+ // Who stopped it is on the record: the owner (/agents stop, /bg stop) or the orchestrator's stop_agent call. Both
655
+ // used to post the same "stopped by request" and the panel read every stop as "errored".
656
+ info.endKind = "stopped";
657
+ info.endReason = by === "owner" ? "stopped by you" : `stopped by ${byLabel ?? "the orchestrator"} (stop_agent)`;
658
+ info.headline = snap.length ? partialCounts(snap) : undefined;
587
659
  this.onDone(info, snap.length ? partialReport(snap, `${id} stopped by request after ${info.round ?? 0} rounds`) : "[stopped by user]");
588
660
  return true;
589
661
  }
590
662
  /** stop_agent with no id (or "all"): stop EVERY currently running or queued sub-agent. Returns the ids
591
663
  * actually stopped, in the order they were found — empty when nothing was running/queued. */
592
- requestStopAll() {
664
+ requestStopAll(by = "owner", byLabel) {
593
665
  const ids = [...this.agents.values()]
594
666
  .filter((a) => a.info.status === "working" || a.info.status === "queued")
595
667
  .map((a) => a.info.id);
596
- return ids.filter((id) => this.requestStop(id));
668
+ return ids.filter((id) => this.requestStop(id, by, byLabel));
669
+ }
670
+ /** The concurrency caps (TUI plan #11): how many agents run at once, and how many may wait for a slot. */
671
+ limits() {
672
+ return { running: this.maxConcurrent, queued: this.maxQueued };
597
673
  }
598
674
  /** Number of agents still working — for the status line. */
599
675
  activeCount() {
@@ -6,6 +6,8 @@
6
6
  // outcome, and the turns that kept polling were the ones that worked. Side-effect-free store: the shell decides
7
7
  // when to wake; a surface without a shell never queues.
8
8
  const REPORT_CHARS = 8000; // the spawn brief asks for a ~1-2k token report; a runaway one is clipped, never dropped
9
+ // Each entry carries the model's text and a short line for the owner (TUI plan #4): the wake turn used to split every
10
+ // report on blank lines and print each paragraph — the model's instructions included — as its own "⤷" line.
9
11
  const reports = [];
10
12
  const listeners = new Set();
11
13
  const clip = (s, n) => s.length <= n ? s : s.slice(0, n) + `\n… [report clipped at ${n} chars — re-run the sub-agent with a tighter deliverable if the rest matters]`;
@@ -29,9 +31,14 @@ export function formatStuckNotice(agent) {
29
31
  `steer it (message_agent with the missing piece), or stop it (stop_agent) and do the step yourself, or stop it and re-brief ` +
30
32
  `a fresh sub-agent with a tighter brief. Waiting on it is not an option — it will not finish on its own.`;
31
33
  }
34
+ /** The owner's few words for a queued report: "Iris's report", or "Orion's partial notes" for a stopped child. */
35
+ export function ownerLine(agent, result) {
36
+ const partial = /PARTIAL findings below/.test(result) || /^\s*\[(stopped|error)/.test(result);
37
+ return `${agent.name ?? agent.id}'s ${partial ? "partial notes" : "report"}`;
38
+ }
32
39
  /** Queue a stuck notice for the next turn and wake the shell (same channel as a finished report). */
33
- export function queueAgentNotice(text) {
34
- reports.push(text);
40
+ export function queueAgentNotice(text, owner = "a sub-agent notice") {
41
+ reports.push({ text, owner });
35
42
  for (const fn of listeners) {
36
43
  try {
37
44
  fn();
@@ -41,7 +48,7 @@ export function queueAgentNotice(text) {
41
48
  }
42
49
  /** Queue a finished agent's report for the next turn and tell the shell (which wakes an idle session). */
43
50
  export function queueAgentReport(agent, result) {
44
- reports.push(formatAgentReport(agent, result));
51
+ reports.push({ text: formatAgentReport(agent, result), owner: ownerLine(agent, result) });
45
52
  for (const fn of listeners) {
46
53
  try {
47
54
  fn();
@@ -52,9 +59,14 @@ export function queueAgentReport(agent, result) {
52
59
  export function pendingAgentReports() {
53
60
  return reports.length;
54
61
  }
62
+ /** Take every queued report: the model's text (joined, byte-identical to what it always was) and the owner lines. */
63
+ export function drainAgentNotices() {
64
+ const taken = reports.splice(0);
65
+ return { text: taken.map((r) => r.text).join("\n\n"), owners: taken.map((r) => r.owner) };
66
+ }
55
67
  /** Take every queued report (joined), or "" when none. Called at the start of a turn. */
56
68
  export function drainAgentReports() {
57
- return reports.length ? reports.splice(0).join("\n\n") : "";
69
+ return drainAgentNotices().text;
58
70
  }
59
71
  export function onAgentReport(fn) {
60
72
  listeners.add(fn);