@nathanstephenson/flow 0.1.10-beta.2 → 0.1.10-beta.3

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 (60) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{claude-COCNALN2.mjs → claude-6L5KCQWJ.mjs} +63 -15
  3. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-QNU2YE4G.mjs} +10 -10
  4. package/build/backend-worker.mjs +42 -5
  5. package/dist/backend/claude/background-calls.js +7 -3
  6. package/dist/backend/claude/index.js +37 -5
  7. package/dist/backend/claude/subagents.js +30 -9
  8. package/dist/backend/fake/index.js +20 -5
  9. package/dist/backend/pi/index.js +1 -0
  10. package/dist/backend/pi/subagents.js +7 -3
  11. package/dist/backend/worker/entry.js +19 -5
  12. package/dist/backend/worker/index.js +21 -2
  13. package/dist/backend/worker/rpc.js +13 -0
  14. package/dist/backend/worker/sandbox-mcp.js +18 -7
  15. package/dist/build-id +1 -1
  16. package/dist/cli/bootstrap.js +1 -1
  17. package/dist/client/reduce.js +9 -3
  18. package/dist/client/subagent-tree.js +49 -0
  19. package/dist/daemon/git.js +10 -7
  20. package/dist/daemon/host.js +88 -21
  21. package/dist/daemon/runtime.js +63 -3
  22. package/dist/daemon/server.js +3 -0
  23. package/dist/daemon/store.js +2 -0
  24. package/dist/daemon/workflow-environment.js +191 -0
  25. package/dist/daemon/workflow-execution-launch.js +77 -0
  26. package/dist/daemon/workflow-execution-resources.js +76 -0
  27. package/dist/daemon/workflow-execution-values.js +128 -0
  28. package/dist/daemon/workflow-executions.js +272 -285
  29. package/dist/daemon/workflow-schedule-driver.js +247 -0
  30. package/dist/daemon/workflow-schedule-routes.js +137 -0
  31. package/dist/daemon/workflow-schedules.js +341 -0
  32. package/dist/isolation/sandbox.js +30 -14
  33. package/dist/isolation/shared-sandbox.js +3 -3
  34. package/dist/protocol/workflow-schedules.js +1 -0
  35. package/dist/tui/render.js +7 -1
  36. package/dist/workflows/calls.js +10 -7
  37. package/dist/workflows/errors.js +2 -0
  38. package/dist/workflows/executors.js +1 -1
  39. package/dist/workflows/invocations.js +8 -5
  40. package/dist/workflows/owner.js +45 -0
  41. package/dist/workflows/records.js +8 -2
  42. package/dist/workflows/schedule-errors.js +2 -0
  43. package/dist/workflows/schedule-store.js +385 -0
  44. package/dist/workflows/scheduler.js +29 -18
  45. package/dist/workflows/schedules.js +129 -0
  46. package/dist/workflows/store.js +110 -11
  47. package/package.json +2 -1
  48. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  49. package/web/dist/assets/index-Miy2nveb.js +40 -0
  50. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-Vf_fCXyE.js} +1 -1
  51. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  52. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  53. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  54. package/web/dist/index.html +4 -3
  55. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  56. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  57. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  58. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  59. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  60. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
package/README.md CHANGED
@@ -182,3 +182,21 @@ requirements, the browser update, systemd setup and the repair procedure.
182
182
  | [docs/workflow-builder-scope.md](docs/workflow-builder-scope.md) | Workflows, including direct MCP steps |
183
183
  | [docs/development.md](docs/development.md) | Build, test, web development, releases |
184
184
  | [docs/milestones.md](docs/milestones.md) | Project status and design notes from each milestone |
185
+
186
+ ### Repeating workflows
187
+
188
+ Open **Schedules** to run a saved workflow every N minutes/hours/days, or daily at a local time in
189
+ an explicitly saved IANA timezone. Enabling never runs immediately. The Session Host must remain
190
+ running; missed times are recorded without catch-up. Daily clock gaps are skipped and repeated times
191
+ run only once, at the first occurrence.
192
+
193
+ Choose fixed typed inputs, an opted-in Project, MCP connections and an overlap limit (default 3).
194
+ Shared-directory runs can conflict. Optional fresh worktrees use the current local base branch commit
195
+ without fetching or copying uncommitted changes. Each occurrence uses the latest saved root/called
196
+ workflows and retains its own snapshot. Pause or delete stops future runs, not already admitted work.
197
+
198
+ Code/MCP-only success creates no Agent Session or model summary. An actual agent step, human input
199
+ or recovery attaches one Agent Session with the normal controls. Inspect execution graphs, attempts,
200
+ activity and results in occurrence history, and follow its Agent Session link when input is needed.
201
+ Terminal history lasts seven days; active/input/recovery work and associated transcripts are not
202
+ pruned by that window. Unsafe worktree cleanup preserves dirty files and unmerged commits.
@@ -29485,8 +29485,13 @@ var Subagents = class {
29485
29485
  */
29486
29486
  tasks = /* @__PURE__ */ new Map();
29487
29487
  held;
29488
- spawn(callId, brief) {
29489
- this.open.set(callId, brief);
29488
+ /** Record a Subagent. One spawned under detached work is detached from the start, and holds nothing. */
29489
+ spawn(callId, brief, parent = "") {
29490
+ (this.isDetached(parent) ? this.detached : this.open).set(callId, { brief, parent });
29491
+ }
29492
+ /** The Subagent that spawned this one, or `""` for one the Agent Session's own model spawned. */
29493
+ parentOf(callId) {
29494
+ return this.spawned(callId)?.parent ?? "";
29490
29495
  }
29491
29496
  /**
29492
29497
  * What a still-open Subagent was called and asked to do, or undefined for a tool call that is
@@ -29494,24 +29499,34 @@ var Subagents = class {
29494
29499
  * a Subagent returns needs this back — the returning `tool_result` carries only an id.
29495
29500
  */
29496
29501
  describe(callId) {
29497
- return this.open.get(callId) ?? this.detached.get(callId);
29502
+ return this.spawned(callId)?.brief;
29498
29503
  }
29499
29504
  /**
29500
29505
  * Record that a Subagent was backgrounded, so it stops holding the turn without ending.
29501
29506
  *
29502
29507
  * Answers the same question `returned` does — the turn end now free to fire — because a launch
29503
29508
  * receipt releases a held end for exactly the reason a real one does: nothing else is waiting.
29509
+ *
29510
+ * Its open descendants are detached with it, since they now have a detached ancestor.
29504
29511
  */
29505
29512
  background(callId) {
29506
- const brief = this.open.get(callId);
29507
- if (brief === void 0) return void 0;
29513
+ const spawned = this.open.get(callId);
29514
+ if (spawned === void 0) return void 0;
29508
29515
  this.open.delete(callId);
29509
- this.detached.set(callId, brief);
29516
+ this.detached.set(callId, spawned);
29517
+ for (const [id, descendant] of this.open) {
29518
+ if (!this.isDetached(id)) continue;
29519
+ this.open.delete(id);
29520
+ this.detached.set(id, descendant);
29521
+ }
29510
29522
  return this.release();
29511
29523
  }
29512
- /** Whether this Subagent's work survives the parent turn ending. */
29524
+ /** Whether this Subagent's work survives the parent turn ending: it or an ancestor is detached. */
29513
29525
  isDetached(callId) {
29514
- return this.detached.has(callId);
29526
+ for (let at2 = callId; at2 !== ""; at2 = this.spawned(at2)?.parent ?? "") {
29527
+ if (this.detached.has(at2)) return true;
29528
+ }
29529
+ return false;
29515
29530
  }
29516
29531
  /** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
29517
29532
  noteTask(taskId, callId) {
@@ -29565,6 +29580,9 @@ var Subagents = class {
29565
29580
  this.detached.clear();
29566
29581
  this.tasks.clear();
29567
29582
  }
29583
+ spawned(callId) {
29584
+ return this.open.get(callId) ?? this.detached.get(callId);
29585
+ }
29568
29586
  release() {
29569
29587
  if (this.open.size > 0) return void 0;
29570
29588
  const held = this.held;
@@ -29656,13 +29674,16 @@ var BackgroundCalls = class {
29656
29674
  return brief;
29657
29675
  }
29658
29676
  /**
29659
- * Forget this turn's announced calls.
29677
+ * Forget this turn's announced calls, except those `keep` accepts — a call made by detached work
29678
+ * belongs to no turn.
29660
29679
  *
29661
29680
  * Open Background Calls and their task ids deliberately survive: one outlives the turn that made
29662
29681
  * it, and the snapshot closing it is emitted turns later from the brief kept here.
29663
29682
  */
29664
- clear() {
29665
- this.pending.clear();
29683
+ clear(keep = () => false) {
29684
+ for (const [callId, brief] of this.pending) {
29685
+ if (!keep(brief)) this.pending.delete(callId);
29686
+ }
29666
29687
  }
29667
29688
  /** Forget open Calls too, for a Backend Session being taken away. They are children of it. */
29668
29689
  abandon() {
@@ -29879,6 +29900,10 @@ function producerOf(sdkMessage) {
29879
29900
  function attribution(producer) {
29880
29901
  return producer === "" ? {} : { producer: { subagentId: producer } };
29881
29902
  }
29903
+ function promptOf(input) {
29904
+ const prompt = input?.prompt;
29905
+ return typeof prompt === "string" && prompt !== "" ? prompt : void 0;
29906
+ }
29882
29907
  function briefOf(input) {
29883
29908
  const fields = input ?? {};
29884
29909
  const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
@@ -29954,6 +29979,8 @@ var ClaudeSession = class {
29954
29979
  subagents = new Subagents();
29955
29980
  /** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
29956
29981
  calls = new BackgroundCalls();
29982
+ /** Each Subagent's brief, reported from its `Agent` call, so the same text echoed into its stream is not reported twice. */
29983
+ briefs = /* @__PURE__ */ new Map();
29957
29984
  enquiries = new PendingEnquiries();
29958
29985
  permissions = new PendingPermissions();
29959
29986
  /** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
@@ -30413,6 +30440,7 @@ var ClaudeSession = class {
30413
30440
  this.abandonPermissions("the session stopped");
30414
30441
  this.permissions.clearRefusals();
30415
30442
  this.subagents.abandon();
30443
+ this.briefs.clear();
30416
30444
  this.calls.abandon();
30417
30445
  this.inbox.close();
30418
30446
  try {
@@ -30499,13 +30527,18 @@ var ClaudeSession = class {
30499
30527
  this.calls.called(block.id, { tool: block.name, ...attribution(producer) });
30500
30528
  if (block.name !== SUBAGENT_TOOL) continue;
30501
30529
  const brief = briefOf(block.input);
30502
- this.subagents.spawn(block.id, brief);
30503
- this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
30530
+ this.subagents.spawn(block.id, brief, producer);
30531
+ this.emit({ type: "subagent", subagentId: block.id, ...brief, ...attribution(producer), state: "running" });
30532
+ const prompt = promptOf(block.input);
30533
+ if (prompt === void 0) continue;
30534
+ this.briefs.set(block.id, prompt);
30535
+ this.emit({ type: "subagent_instruction", id: `${block.id}:brief`, text: prompt, producer: { subagentId: block.id } });
30504
30536
  }
30505
30537
  return;
30506
30538
  }
30507
30539
  case "user": {
30508
30540
  const content = sdkMessage.message.content;
30541
+ this.instructSubagent(sdkMessage);
30509
30542
  if (typeof content === "string") return;
30510
30543
  for (const block of content) {
30511
30544
  if (block.type === "tool_result") {
@@ -30528,6 +30561,7 @@ var ClaudeSession = class {
30528
30561
  type: "subagent",
30529
30562
  subagentId: block.tool_use_id,
30530
30563
  ...brief,
30564
+ ...attribution(this.subagents.parentOf(block.tool_use_id)),
30531
30565
  state: isError ? "error" : "complete"
30532
30566
  });
30533
30567
  }
@@ -30598,6 +30632,7 @@ var ClaudeSession = class {
30598
30632
  this.endTurn(reason);
30599
30633
  }
30600
30634
  closeSubagent(callId) {
30635
+ this.briefs.delete(callId);
30601
30636
  this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
30602
30637
  this.permissions.clearRefusals((producer) => producer === callId);
30603
30638
  const released = this.subagents.returned(callId);
@@ -30645,7 +30680,7 @@ var ClaudeSession = class {
30645
30680
  if (callId === void 0) return;
30646
30681
  const brief = this.subagents.describe(callId);
30647
30682
  if (brief !== void 0) {
30648
- this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
30683
+ this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
30649
30684
  this.closeSubagent(callId);
30650
30685
  return;
30651
30686
  }
@@ -30670,6 +30705,19 @@ var ClaudeSession = class {
30670
30705
  this.turnId = randomUUID3();
30671
30706
  this.emit({ type: "turn_started", turnId: this.turnId });
30672
30707
  }
30708
+ /** Report text the spawning model sent into a Subagent. The Agent Session's own user text is the host's to record. */
30709
+ instructSubagent(sdkMessage) {
30710
+ const subagentId = producerOf(sdkMessage);
30711
+ if (subagentId === "") return;
30712
+ const content = sdkMessage.message.content;
30713
+ const text = typeof content === "string" ? content : content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
30714
+ if (text === "") return;
30715
+ if (this.briefs.get(subagentId) === text) {
30716
+ this.briefs.delete(subagentId);
30717
+ return;
30718
+ }
30719
+ this.emit({ type: "subagent_instruction", id: sdkMessage.uuid ?? randomUUID3(), text, producer: { subagentId } });
30720
+ }
30673
30721
  endTurn(reason) {
30674
30722
  const turnId = this.turnId;
30675
30723
  this.abandonEnquiries("the turn ended");
@@ -30677,7 +30725,7 @@ var ClaudeSession = class {
30677
30725
  this.abandonPermissions("the turn ended", ended);
30678
30726
  this.permissions.clearRefusals(ended);
30679
30727
  this.subagents.clear();
30680
- this.calls.clear();
30728
+ this.calls.clear((brief) => brief.producer !== void 0 && !ended(brief.producer.subagentId));
30681
30729
  this.enquiries.clear();
30682
30730
  if (!turnId) return;
30683
30731
  this.turnId = void 0;
@@ -5095,24 +5095,23 @@ var parameters2 = typebox_exports.Object({
5095
5095
  effort: typebox_exports.Optional(typebox_exports.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
5096
5096
  run_in_background: typebox_exports.Optional(typebox_exports.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." }))
5097
5097
  });
5098
- function subagentTool(work, run) {
5098
+ function subagentTool(work, run, producer) {
5099
5099
  return defineTool3({
5100
5100
  name: SUBAGENT_TOOL,
5101
5101
  label: "Subagent",
5102
5102
  description: "Delegate work to a Subagent with its own Conversation Context. Subagents run in the background by default and report back automatically. Multiple Subagents may run concurrently. They cannot ask the human or create further Subagents.",
5103
5103
  promptSnippet: "Delegate independent work to Subagents",
5104
5104
  parameters: parameters2,
5105
- execute: async (id, input, signal) => work.run(
5106
- {
5105
+ execute: async (id, input, signal) => {
5106
+ const subagentId = callIdFor(id, producer);
5107
+ return work.run({
5107
5108
  type: "subagent",
5108
- subagentId: id,
5109
+ subagentId,
5109
5110
  name: input.name ?? "Subagent",
5110
- description: input.description
5111
- },
5112
- (childSignal) => run(id, input, childSignal),
5113
- input.run_in_background !== false,
5114
- signal
5115
- )
5111
+ description: input.description,
5112
+ ...producer ? { producer } : {}
5113
+ }, (childSignal) => run(subagentId, input, childSignal), input.run_in_background !== false, signal);
5114
+ }
5116
5115
  });
5117
5116
  }
5118
5117
 
@@ -5747,6 +5746,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
5747
5746
  signal.throwIfAborted();
5748
5747
  await adapter.setEffort(effort);
5749
5748
  signal.throwIfAborted();
5749
+ emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
5750
5750
  await adapter.prompt(input.prompt);
5751
5751
  if (reason !== "complete") throw new Error(failure ?? `Subagent ${reason}`);
5752
5752
  return textResult(output || "Subagent completed without text output");
@@ -3943,6 +3943,20 @@ var McpSession = class {
3943
3943
  };
3944
3944
 
3945
3945
  // src/backend/worker/rpc.ts
3946
+ function waitForAbort(work, signal) {
3947
+ if (!signal) return work;
3948
+ return new Promise((resolve4, reject) => {
3949
+ const abort = () => {
3950
+ reject(signal.reason);
3951
+ };
3952
+ signal.addEventListener("abort", abort, { once: true });
3953
+ void work.then(resolve4, reject).finally(() => signal.removeEventListener("abort", abort));
3954
+ if (signal.aborted) {
3955
+ signal.removeEventListener("abort", abort);
3956
+ abort();
3957
+ }
3958
+ });
3959
+ }
3946
3960
  function errorText(error) {
3947
3961
  return error instanceof Error ? error.message : String(error);
3948
3962
  }
@@ -4179,6 +4193,26 @@ function runWorker() {
4179
4193
  });
4180
4194
  };
4181
4195
  const rpc = new WorkerRpc(send, async (method, args, signal) => {
4196
+ if (method === "mcp.initialize") {
4197
+ signal.throwIfAborted();
4198
+ if (creating || closing) throw new Error("Worker already initialized");
4199
+ creating = true;
4200
+ const options = args[0];
4201
+ localMcp = new McpSession(
4202
+ options.connections,
4203
+ options.scope,
4204
+ void 0,
4205
+ true,
4206
+ void 0,
4207
+ void 0,
4208
+ void 0,
4209
+ "none",
4210
+ void 0,
4211
+ (connectionId, refresh) => rpc.call("mcp.token", [connectionId, refresh])
4212
+ );
4213
+ localMcp.connectTimeoutMs = 12e4;
4214
+ return;
4215
+ }
4182
4216
  if (method === "create") {
4183
4217
  const ready = performance.now();
4184
4218
  if (creating || closing) throw new Error("Backend worker already initialized");
@@ -4224,7 +4258,7 @@ function runWorker() {
4224
4258
  let backend;
4225
4259
  const importing = performance.now();
4226
4260
  try {
4227
- backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-COCNALN2.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-HJKTV2TH.mjs")).PiBackend();
4261
+ backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-6L5KCQWJ.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-QNU2YE4G.mjs")).PiBackend();
4228
4262
  } catch (error) {
4229
4263
  throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
4230
4264
  }
@@ -4252,7 +4286,7 @@ function runWorker() {
4252
4286
  setImmediate(() => process.stdout.end(() => process.exit(0)));
4253
4287
  return;
4254
4288
  }
4255
- if (!session || closing) throw new Error("Backend worker is not running");
4289
+ if (closing || !session && (!localMcp || !method.startsWith("mcp."))) throw new Error("Worker is not running");
4256
4290
  let result;
4257
4291
  switch (method) {
4258
4292
  case "prompt":
@@ -4309,9 +4343,11 @@ function runWorker() {
4309
4343
  break;
4310
4344
  case "mcp.direct": {
4311
4345
  if (!localMcp) throw new Error("No sandbox MCP clients");
4346
+ signal.throwIfAborted();
4312
4347
  const id = args[0];
4313
- if (localMcp.status().find((state) => state.id === id)?.state !== "connected") await localMcp.retry(id).catch(() => {
4314
- });
4348
+ if (localMcp.status().find((state) => state.id === id)?.state !== "connected") await waitForAbort(localMcp.retry(id).catch(() => {
4349
+ }), signal);
4350
+ signal.throwIfAborted();
4315
4351
  result = {
4316
4352
  status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
4317
4353
  tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool)
@@ -4319,6 +4355,7 @@ function runWorker() {
4319
4355
  break;
4320
4356
  }
4321
4357
  case "mcp.callTool": {
4358
+ signal.throwIfAborted();
4322
4359
  const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
4323
4360
  if (!tool) throw new Error("Unknown MCP tool");
4324
4361
  result = await tool.call(args[1], signal, args[2]);
@@ -4349,7 +4386,7 @@ function runWorker() {
4349
4386
  default:
4350
4387
  throw new Error(`Unknown worker method: ${method}`);
4351
4388
  }
4352
- rpc.notify("snapshot", publishSnapshot());
4389
+ if (session) rpc.notify("snapshot", publishSnapshot());
4353
4390
  return result;
4354
4391
  }, () => {
4355
4392
  });
@@ -93,13 +93,17 @@ export class BackgroundCalls {
93
93
  return brief;
94
94
  }
95
95
  /**
96
- * Forget this turn's announced calls.
96
+ * Forget this turn's announced calls, except those `keep` accepts — a call made by detached work
97
+ * belongs to no turn.
97
98
  *
98
99
  * Open Background Calls and their task ids deliberately survive: one outlives the turn that made
99
100
  * it, and the snapshot closing it is emitted turns later from the brief kept here.
100
101
  */
101
- clear() {
102
- this.pending.clear();
102
+ clear(keep = () => false) {
103
+ for (const [callId, brief] of this.pending) {
104
+ if (!keep(brief))
105
+ this.pending.delete(callId);
106
+ }
103
107
  }
104
108
  /** Forget open Calls too, for a Backend Session being taken away. They are children of it. */
105
109
  abandon() {
@@ -102,6 +102,10 @@ function attribution(producer) {
102
102
  * something a transcript row can show. Falls back to the tool name so a client always has something
103
103
  * to print, which is what the protocol promises.
104
104
  */
105
+ function promptOf(input) {
106
+ const prompt = input?.prompt;
107
+ return typeof prompt === "string" && prompt !== "" ? prompt : undefined;
108
+ }
105
109
  export function briefOf(input) {
106
110
  const fields = (input ?? {});
107
111
  const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
@@ -191,6 +195,8 @@ class ClaudeSession {
191
195
  subagents = new Subagents();
192
196
  /** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
193
197
  calls = new BackgroundCalls();
198
+ /** Each Subagent's brief, reported from its `Agent` call, so the same text echoed into its stream is not reported twice. */
199
+ briefs = new Map();
194
200
  enquiries = new PendingEnquiries();
195
201
  permissions = new PendingPermissions();
196
202
  /** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
@@ -706,6 +712,7 @@ class ClaudeSession {
706
712
  // Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
707
713
  // Session Host records that from the transcript, the way it does a torn turn.
708
714
  this.subagents.abandon();
715
+ this.briefs.clear();
709
716
  // Background Calls are children of that process too, and go the same way for the same reason.
710
717
  this.calls.abandon();
711
718
  this.inbox.close();
@@ -840,13 +847,19 @@ class ClaudeSession {
840
847
  if (block.name !== SUBAGENT_TOOL)
841
848
  continue;
842
849
  const brief = briefOf(block.input);
843
- this.subagents.spawn(block.id, brief);
844
- this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
850
+ this.subagents.spawn(block.id, brief, producer);
851
+ this.emit({ type: "subagent", subagentId: block.id, ...brief, ...attribution(producer), state: "running" });
852
+ const prompt = promptOf(block.input);
853
+ if (prompt === undefined)
854
+ continue;
855
+ this.briefs.set(block.id, prompt);
856
+ this.emit({ type: "subagent_instruction", id: `${block.id}:brief`, text: prompt, producer: { subagentId: block.id } });
845
857
  }
846
858
  return;
847
859
  }
848
860
  case "user": {
849
861
  const content = sdkMessage.message.content;
862
+ this.instructSubagent(sdkMessage);
850
863
  if (typeof content === "string")
851
864
  return;
852
865
  for (const block of content) {
@@ -875,6 +888,7 @@ class ClaudeSession {
875
888
  type: "subagent",
876
889
  subagentId: block.tool_use_id,
877
890
  ...brief,
891
+ ...attribution(this.subagents.parentOf(block.tool_use_id)),
878
892
  state: isError ? "error" : "complete",
879
893
  });
880
894
  }
@@ -959,6 +973,7 @@ class ClaudeSession {
959
973
  this.endTurn(reason);
960
974
  }
961
975
  closeSubagent(callId) {
976
+ this.briefs.delete(callId);
962
977
  this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
963
978
  this.permissions.clearRefusals((producer) => producer === callId);
964
979
  const released = this.subagents.returned(callId);
@@ -1013,7 +1028,7 @@ class ClaudeSession {
1013
1028
  return;
1014
1029
  const brief = this.subagents.describe(callId);
1015
1030
  if (brief !== undefined) {
1016
- this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
1031
+ this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
1017
1032
  this.closeSubagent(callId);
1018
1033
  return;
1019
1034
  }
@@ -1040,6 +1055,23 @@ class ClaudeSession {
1040
1055
  this.turnId = randomUUID();
1041
1056
  this.emit({ type: "turn_started", turnId: this.turnId });
1042
1057
  }
1058
+ /** Report text the spawning model sent into a Subagent. The Agent Session's own user text is the host's to record. */
1059
+ instructSubagent(sdkMessage) {
1060
+ const subagentId = producerOf(sdkMessage);
1061
+ if (subagentId === "")
1062
+ return;
1063
+ const content = sdkMessage.message.content;
1064
+ const text = typeof content === "string"
1065
+ ? content
1066
+ : content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
1067
+ if (text === "")
1068
+ return;
1069
+ if (this.briefs.get(subagentId) === text) {
1070
+ this.briefs.delete(subagentId);
1071
+ return;
1072
+ }
1073
+ this.emit({ type: "subagent_instruction", id: sdkMessage.uuid ?? randomUUID(), text, producer: { subagentId } });
1074
+ }
1043
1075
  endTurn(reason) {
1044
1076
  const turnId = this.turnId;
1045
1077
  /*
@@ -1054,8 +1086,8 @@ class ClaudeSession {
1054
1086
  // Cleared whatever the outcome, so a held end cannot reach the turn after this one.
1055
1087
  this.subagents.clear();
1056
1088
  // Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
1057
- // that made it, which is the whole of ADR 0021.
1058
- this.calls.clear();
1089
+ // that made it, which is the whole of ADR 0021 — and so do calls detached work announced.
1090
+ this.calls.clear((brief) => brief.producer !== undefined && !ended(brief.producer.subagentId));
1059
1091
  this.enquiries.clear();
1060
1092
  if (!turnId)
1061
1093
  return;
@@ -6,7 +6,8 @@
6
6
  * subagent cannot be told apart from the one that ends the turn. (ADR 0016 records that CLI 2.1.247
7
7
  * emits no such result in the first place — one per parent turn and no more — so the holding below
8
8
  * is belt to the bookkeeping's braces. Kept because that is one version on the happy path, and says
9
- * nothing about a nested Subagent, an interrupt, or an error.) Ending on the first would clear
9
+ * nothing about an interrupt or an error.) A nested Subagent holds the turn like any other, unless
10
+ * an ancestor is backgrounded: work started by backgrounded work is backgrounded too. Ending on the first would clear
10
11
  * `turnInFlight` in the Session Host, and the Steering Queue would dispatch the next message into a
11
12
  * turn that is still running — two messages in one turn, which reads as the agent ignoring the first.
12
13
  *
@@ -31,8 +32,13 @@ export class Subagents {
31
32
  */
32
33
  tasks = new Map();
33
34
  held;
34
- spawn(callId, brief) {
35
- this.open.set(callId, brief);
35
+ /** Record a Subagent. One spawned under detached work is detached from the start, and holds nothing. */
36
+ spawn(callId, brief, parent = "") {
37
+ (this.isDetached(parent) ? this.detached : this.open).set(callId, { brief, parent });
38
+ }
39
+ /** The Subagent that spawned this one, or `""` for one the Agent Session's own model spawned. */
40
+ parentOf(callId) {
41
+ return this.spawned(callId)?.parent ?? "";
36
42
  }
37
43
  /**
38
44
  * What a still-open Subagent was called and asked to do, or undefined for a tool call that is
@@ -40,25 +46,37 @@ export class Subagents {
40
46
  * a Subagent returns needs this back — the returning `tool_result` carries only an id.
41
47
  */
42
48
  describe(callId) {
43
- return this.open.get(callId) ?? this.detached.get(callId);
49
+ return this.spawned(callId)?.brief;
44
50
  }
45
51
  /**
46
52
  * Record that a Subagent was backgrounded, so it stops holding the turn without ending.
47
53
  *
48
54
  * Answers the same question `returned` does — the turn end now free to fire — because a launch
49
55
  * receipt releases a held end for exactly the reason a real one does: nothing else is waiting.
56
+ *
57
+ * Its open descendants are detached with it, since they now have a detached ancestor.
50
58
  */
51
59
  background(callId) {
52
- const brief = this.open.get(callId);
53
- if (brief === undefined)
60
+ const spawned = this.open.get(callId);
61
+ if (spawned === undefined)
54
62
  return undefined;
55
63
  this.open.delete(callId);
56
- this.detached.set(callId, brief);
64
+ this.detached.set(callId, spawned);
65
+ for (const [id, descendant] of this.open) {
66
+ if (!this.isDetached(id))
67
+ continue;
68
+ this.open.delete(id);
69
+ this.detached.set(id, descendant);
70
+ }
57
71
  return this.release();
58
72
  }
59
- /** Whether this Subagent's work survives the parent turn ending. */
73
+ /** Whether this Subagent's work survives the parent turn ending: it or an ancestor is detached. */
60
74
  isDetached(callId) {
61
- return this.detached.has(callId);
75
+ for (let at = callId; at !== ""; at = this.spawned(at)?.parent ?? "") {
76
+ if (this.detached.has(at))
77
+ return true;
78
+ }
79
+ return false;
62
80
  }
63
81
  /** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
64
82
  noteTask(taskId, callId) {
@@ -116,6 +134,9 @@ export class Subagents {
116
134
  this.detached.clear();
117
135
  this.tasks.clear();
118
136
  }
137
+ spawned(callId) {
138
+ return this.open.get(callId) ?? this.detached.get(callId);
139
+ }
119
140
  release() {
120
141
  if (this.open.size > 0)
121
142
  return undefined;
@@ -323,12 +323,14 @@ export class FakeSession {
323
323
  *
324
324
  * `completeTurn` deliberately does not close an open Subagent: leaving one running is the
325
325
  * torn-Subagent fixture, and the Session Host is what has to cope with it.
326
+ *
327
+ * `producer` names the Subagent spawning this one, for a nested Subagent.
326
328
  */
327
- beginSubagent(name, description) {
329
+ beginSubagent(name, description, producer) {
328
330
  const subagentId = randomUUID();
329
- const subagent = new FakeSubagent(subagentId, name, description, this.emit);
331
+ const subagent = new FakeSubagent(subagentId, name, description, this.emit, producer);
330
332
  this.subagents.push(subagent);
331
- this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description } });
333
+ this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description }, ...(producer ? { producer } : {}) });
332
334
  subagent.snapshot({ state: "running" });
333
335
  return subagent;
334
336
  }
@@ -390,16 +392,18 @@ export class FakeSubagent {
390
392
  subagentId;
391
393
  name;
392
394
  description;
395
+ producer;
393
396
  finished = false;
394
397
  launched = false;
395
398
  emit;
396
399
  /** Bumped when a message finalises, so a partial and its finished half share one id. */
397
400
  messageIndex = 0;
398
- constructor(subagentId, name, description, emit) {
401
+ constructor(subagentId, name, description, emit, producer) {
399
402
  this.subagentId = subagentId;
400
403
  this.name = name;
401
404
  this.description = description;
402
405
  this.emit = emit;
406
+ this.producer = producer;
403
407
  }
404
408
  /**
405
409
  * Attributed assistant text. The id is stable until the message finalises, because a partial and
@@ -417,6 +421,12 @@ export class FakeSubagent {
417
421
  if (final)
418
422
  this.messageIndex += 1;
419
423
  }
424
+ /** Instructions from the model that spawned it. */
425
+ instruct(text) {
426
+ const id = randomUUID();
427
+ this.emit({ type: "subagent_instruction", id, text, producer: { subagentId: this.subagentId } });
428
+ return id;
429
+ }
420
430
  /** An attributed tool call — the subagent's Read, not the parent's. */
421
431
  useTool(name, input, result, isError = false) {
422
432
  const callId = randomUUID();
@@ -449,6 +459,7 @@ export class FakeSubagent {
449
459
  callId: this.subagentId,
450
460
  result: `${this.name} launched in the background`,
451
461
  isError: false,
462
+ ...this.attribution(),
452
463
  });
453
464
  }
454
465
  finish(reason = "complete") {
@@ -461,7 +472,7 @@ export class FakeSubagent {
461
472
  // produces.
462
473
  if (this.launched)
463
474
  return;
464
- this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error" });
475
+ this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error", ...this.attribution() });
465
476
  }
466
477
  /** @internal — used by FakeSession to emit the opening snapshot. */
467
478
  snapshot(state) {
@@ -470,9 +481,13 @@ export class FakeSubagent {
470
481
  subagentId: this.subagentId,
471
482
  name: this.name,
472
483
  ...(this.description === undefined ? {} : { description: this.description }),
484
+ ...this.attribution(),
473
485
  ...state,
474
486
  });
475
487
  }
488
+ attribution() {
489
+ return this.producer ? { producer: this.producer } : {};
490
+ }
476
491
  }
477
492
  export class FakeBackend {
478
493
  name = "fake";
@@ -617,6 +617,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
617
617
  signal.throwIfAborted();
618
618
  await adapter.setEffort(effort);
619
619
  signal.throwIfAborted();
620
+ emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
620
621
  await adapter.prompt(input.prompt);
621
622
  if (reason !== "complete")
622
623
  throw new Error(failure ?? `Subagent ${reason}`);