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

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 (79) hide show
  1. package/README.md +27 -1
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
  8. package/build/backend-worker.mjs +52 -116
  9. package/dist/backend/claude/background-calls.js +7 -3
  10. package/dist/backend/claude/index.js +106 -16
  11. package/dist/backend/claude/subagents.js +41 -9
  12. package/dist/backend/fake/index.js +26 -5
  13. package/dist/backend/pi/cache-warming.js +8 -0
  14. package/dist/backend/pi/canonical-json.js +120 -0
  15. package/dist/backend/pi/compaction-model.js +3 -2
  16. package/dist/backend/pi/host-auth.js +258 -0
  17. package/dist/backend/pi/index.js +38 -12
  18. package/dist/backend/pi/model-auth.js +159 -0
  19. package/dist/backend/pi/model-catalog.js +120 -0
  20. package/dist/backend/pi/model-config.js +5 -0
  21. package/dist/backend/pi/model-selection.js +32 -0
  22. package/dist/backend/pi/subagents.js +7 -3
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-subagent.js +4 -3
  25. package/dist/backend/worker/entry.js +32 -6
  26. package/dist/backend/worker/index.js +87 -7
  27. package/dist/backend/worker/rpc.js +13 -0
  28. package/dist/backend/worker/sandbox-mcp.js +18 -7
  29. package/dist/build-id +1 -1
  30. package/dist/cli/bootstrap.js +1 -1
  31. package/dist/client/reduce.js +11 -3
  32. package/dist/client/subagent-tree.js +49 -0
  33. package/dist/client/tool-summary.js +26 -15
  34. package/dist/daemon/git.js +10 -7
  35. package/dist/daemon/host.js +100 -22
  36. package/dist/daemon/models.js +2 -2
  37. package/dist/daemon/pi-model-cache.js +44 -0
  38. package/dist/daemon/runtime.js +63 -3
  39. package/dist/daemon/server.js +3 -0
  40. package/dist/daemon/store.js +2 -0
  41. package/dist/daemon/workflow-environment.js +191 -0
  42. package/dist/daemon/workflow-execution-launch.js +77 -0
  43. package/dist/daemon/workflow-execution-resources.js +76 -0
  44. package/dist/daemon/workflow-execution-values.js +128 -0
  45. package/dist/daemon/workflow-executions.js +272 -285
  46. package/dist/daemon/workflow-schedule-driver.js +247 -0
  47. package/dist/daemon/workflow-schedule-routes.js +137 -0
  48. package/dist/daemon/workflow-schedules.js +341 -0
  49. package/dist/isolation/filesystem.js +5 -1
  50. package/dist/isolation/sandbox.js +61 -18
  51. package/dist/isolation/shared-sandbox.js +3 -3
  52. package/dist/protocol/workflow-schedules.js +1 -0
  53. package/dist/tui/render.js +7 -1
  54. package/dist/workflows/calls.js +10 -7
  55. package/dist/workflows/errors.js +2 -0
  56. package/dist/workflows/executors.js +1 -1
  57. package/dist/workflows/invocations.js +8 -5
  58. package/dist/workflows/owner.js +45 -0
  59. package/dist/workflows/records.js +8 -2
  60. package/dist/workflows/schedule-errors.js +2 -0
  61. package/dist/workflows/schedule-store.js +385 -0
  62. package/dist/workflows/scheduler.js +29 -18
  63. package/dist/workflows/schedules.js +129 -0
  64. package/dist/workflows/store.js +110 -11
  65. package/package.json +8 -5
  66. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  67. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  68. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
  69. package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
  70. package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
  71. package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
  72. package/web/dist/index.html +4 -3
  73. package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
  74. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  75. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  76. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  77. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  78. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  79. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -1,7 +1,6 @@
1
1
  import { createRequire as __flowCreateRequire } from 'node:module'; const require = __flowCreateRequire(import.meta.url);
2
2
  import {
3
3
  AjvJsonSchemaValidator,
4
- AutoPermissionUnavailable,
5
4
  CallToolResultSchema,
6
5
  CompleteResultSchema,
7
6
  CreateMessageRequestSchema,
@@ -37,7 +36,12 @@ import {
37
36
  isJSONRPCResultResponse,
38
37
  mergeCapabilities,
39
38
  safeParse
40
- } from "./backend-worker-chunks/chunk-UQDH2COY.mjs";
39
+ } from "./backend-worker-chunks/chunk-K774KOGL.mjs";
40
+ import {
41
+ WorkerRpc,
42
+ errorText,
43
+ waitForAbort
44
+ } from "./backend-worker-chunks/chunk-LAEUXDNH.mjs";
41
45
  import {
42
46
  NEVER,
43
47
  ZodIssueCode,
@@ -54,7 +58,7 @@ import {
54
58
  object,
55
59
  string,
56
60
  url
57
- } from "./backend-worker-chunks/chunk-MLOUI3ZM.mjs";
61
+ } from "./backend-worker-chunks/chunk-NZZME2I3.mjs";
58
62
 
59
63
  // node_modules/isexe/windows.js
60
64
  var require_windows = __commonJS({
@@ -1093,7 +1097,11 @@ async function prepareFilesystemIsolation(options) {
1093
1097
  }
1094
1098
  };
1095
1099
  if (options.credentials === "pi") {
1096
- for (const name of ["auth.json", "models.json", "settings.json"]) stage(join3(piDir, name), join3(env.PI_CODING_AGENT_DIR, name));
1100
+ const auth2 = join3(piDir, "auth.json");
1101
+ if (existsSync3(auth2) && (!statSync3(auth2).isFile() || realpathSync3(auth2) !== resolve2(auth2))) {
1102
+ throw new Error(`Credential must be a regular, non-symlink file: ${auth2}`);
1103
+ }
1104
+ for (const name of ["models.json", "settings.json"]) stage(join3(piDir, name), join3(env.PI_CODING_AGENT_DIR, name));
1097
1105
  if (!options.workflowBuilder) resources("Pi", piDir, env.PI_CODING_AGENT_DIR, ["AGENTS.md", "skills", "prompts", "themes", "extensions", "packages", "bin", "tools"]);
1098
1106
  } else if (options.credentials === "claude") {
1099
1107
  stage(join3(claudeAuthDir, ".credentials.json"), join3(env.CLAUDE_CONFIG_DIR, ".credentials.json"));
@@ -3942,112 +3950,6 @@ var McpSession = class {
3942
3950
  }
3943
3951
  };
3944
3952
 
3945
- // src/backend/worker/rpc.ts
3946
- function errorText(error) {
3947
- return error instanceof Error ? error.message : String(error);
3948
- }
3949
- var WorkerRpc = class {
3950
- nextId = 0;
3951
- failure;
3952
- pending = /* @__PURE__ */ new Map();
3953
- incoming = /* @__PURE__ */ new Map();
3954
- send;
3955
- dispatch;
3956
- notification;
3957
- constructor(send, dispatch, notification) {
3958
- this.send = send;
3959
- this.dispatch = dispatch;
3960
- this.notification = notification;
3961
- }
3962
- call(method, args = [], signal) {
3963
- if (this.failure) return Promise.reject(this.failure);
3964
- if (signal?.aborted) return Promise.reject(new Error("Worker call cancelled"));
3965
- const id = ++this.nextId;
3966
- return new Promise((resolve4, reject) => {
3967
- const abort = () => {
3968
- this.pending.delete(id);
3969
- try {
3970
- this.send({ kind: "cancel", id });
3971
- } catch {
3972
- }
3973
- reject(new Error("Worker call cancelled"));
3974
- };
3975
- const cleanup = () => signal?.removeEventListener("abort", abort);
3976
- this.pending.set(id, {
3977
- resolve: (value) => {
3978
- cleanup();
3979
- resolve4(value);
3980
- },
3981
- reject: (error) => {
3982
- cleanup();
3983
- reject(error);
3984
- }
3985
- });
3986
- signal?.addEventListener("abort", abort, { once: true });
3987
- try {
3988
- this.send({ kind: "call", id, method, args });
3989
- } catch (error) {
3990
- this.pending.delete(id);
3991
- cleanup();
3992
- reject(error);
3993
- }
3994
- });
3995
- }
3996
- notify(name, value) {
3997
- if (!this.failure) this.send({ kind: "notification", name, value });
3998
- }
3999
- receive(raw) {
4000
- if (this.failure || !raw || typeof raw !== "object") return;
4001
- const message = raw;
4002
- switch (message.kind) {
4003
- case "reply": {
4004
- const pending = this.pending.get(message.id);
4005
- this.pending.delete(message.id);
4006
- if (message.error !== void 0) pending?.reject(message.errorCode === "auto_permission_unavailable" ? new AutoPermissionUnavailable(message.error) : new Error(message.error));
4007
- else pending?.resolve(message.value);
4008
- break;
4009
- }
4010
- case "cancel":
4011
- this.incoming.get(message.id)?.abort();
4012
- break;
4013
- case "notification":
4014
- this.notification(message.name, message.value);
4015
- break;
4016
- case "call": {
4017
- if (!Number.isSafeInteger(message.id) || typeof message.method !== "string" || !Array.isArray(message.args) || this.incoming.has(message.id)) return;
4018
- const controller = new AbortController();
4019
- this.incoming.set(message.id, controller);
4020
- void Promise.resolve().then(() => this.dispatch(message.method, message.args, controller.signal)).then(
4021
- (value) => this.reply({ kind: "reply", id: message.id, value }),
4022
- (error) => this.reply({
4023
- kind: "reply",
4024
- id: message.id,
4025
- error: errorText(error),
4026
- ...error instanceof AutoPermissionUnavailable ? { errorCode: "auto_permission_unavailable" } : {}
4027
- })
4028
- ).finally(() => this.incoming.delete(message.id));
4029
- break;
4030
- }
4031
- }
4032
- }
4033
- reply(message) {
4034
- if (this.failure) return;
4035
- try {
4036
- this.send(message);
4037
- } catch (error) {
4038
- this.close(new Error(errorText(error)));
4039
- }
4040
- }
4041
- close(error) {
4042
- if (this.failure) return;
4043
- this.failure = error;
4044
- for (const pending of this.pending.values()) pending.reject(error);
4045
- this.pending.clear();
4046
- for (const controller of this.incoming.values()) controller.abort();
4047
- this.incoming.clear();
4048
- }
4049
- };
4050
-
4051
3953
  // src/backend/worker/protocol.ts
4052
3954
  function snapshot(session) {
4053
3955
  return {
@@ -4179,11 +4081,31 @@ function runWorker() {
4179
4081
  });
4180
4082
  };
4181
4083
  const rpc = new WorkerRpc(send, async (method, args, signal) => {
4084
+ if (method === "mcp.initialize") {
4085
+ signal.throwIfAborted();
4086
+ if (creating || closing) throw new Error("Worker already initialized");
4087
+ creating = true;
4088
+ const options = args[0];
4089
+ localMcp = new McpSession(
4090
+ options.connections,
4091
+ options.scope,
4092
+ void 0,
4093
+ true,
4094
+ void 0,
4095
+ void 0,
4096
+ void 0,
4097
+ "none",
4098
+ void 0,
4099
+ (connectionId, refresh) => rpc.call("mcp.token", [connectionId, refresh])
4100
+ );
4101
+ localMcp.connectTimeoutMs = 12e4;
4102
+ return;
4103
+ }
4182
4104
  if (method === "create") {
4183
4105
  const ready = performance.now();
4184
4106
  if (creating || closing) throw new Error("Backend worker already initialized");
4185
4107
  creating = true;
4186
- const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, sessionToolsEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
4108
+ const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, sessionToolsEnabled, workflowBuilderInstructions, piAuth, backendModule, backend: backendName = "pi", ...options } = args[0];
4187
4109
  const workflowBuilder = workflowBuilderInstructions === void 0 ? void 0 : {
4188
4110
  instructions: workflowBuilderInstructions,
4189
4111
  read: (path) => rpc.call("workflowBuilder.read", [path]),
@@ -4224,13 +4146,24 @@ function runWorker() {
4224
4146
  let backend;
4225
4147
  const importing = performance.now();
4226
4148
  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();
4149
+ backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-GY27HBAY.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-JV6MWPW7.mjs")).PiBackend();
4228
4150
  } catch (error) {
4229
4151
  throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
4230
4152
  }
4231
4153
  const imported = performance.now();
4154
+ let initialAuth = piAuth;
4232
4155
  session = await backend.create({
4233
4156
  ...options,
4157
+ ...piAuth ? { piAuth: {
4158
+ snapshot: async (signal2) => {
4159
+ signal2?.throwIfAborted();
4160
+ if (!initialAuth) return rpc.call("pi.auth.snapshot", [], signal2);
4161
+ const metadata = initialAuth;
4162
+ initialAuth = void 0;
4163
+ return metadata;
4164
+ },
4165
+ resolve: (providerId, signal2) => rpc.call("pi.auth.resolve", [providerId], signal2)
4166
+ } } : {},
4234
4167
  ...workflowBuilder ? { workflowBuilder } : {
4235
4168
  ...localMcp ? { mcp: localMcp } : mcpTools ? { mcp: { connections: (mcpConnectionIds ?? []).map((id) => ({ id })), tools: () => tools } } : {},
4236
4169
  ...workflowEnabled ? { workflow } : {},
@@ -4252,7 +4185,7 @@ function runWorker() {
4252
4185
  setImmediate(() => process.stdout.end(() => process.exit(0)));
4253
4186
  return;
4254
4187
  }
4255
- if (!session || closing) throw new Error("Backend worker is not running");
4188
+ if (closing || !session && (!localMcp || !method.startsWith("mcp."))) throw new Error("Worker is not running");
4256
4189
  let result;
4257
4190
  switch (method) {
4258
4191
  case "prompt":
@@ -4309,9 +4242,11 @@ function runWorker() {
4309
4242
  break;
4310
4243
  case "mcp.direct": {
4311
4244
  if (!localMcp) throw new Error("No sandbox MCP clients");
4245
+ signal.throwIfAborted();
4312
4246
  const id = args[0];
4313
- if (localMcp.status().find((state) => state.id === id)?.state !== "connected") await localMcp.retry(id).catch(() => {
4314
- });
4247
+ if (localMcp.status().find((state) => state.id === id)?.state !== "connected") await waitForAbort(localMcp.retry(id).catch(() => {
4248
+ }), signal);
4249
+ signal.throwIfAborted();
4315
4250
  result = {
4316
4251
  status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
4317
4252
  tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool)
@@ -4319,6 +4254,7 @@ function runWorker() {
4319
4254
  break;
4320
4255
  }
4321
4256
  case "mcp.callTool": {
4257
+ signal.throwIfAborted();
4322
4258
  const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
4323
4259
  if (!tool) throw new Error("Unknown MCP tool");
4324
4260
  result = await tool.call(args[1], signal, args[2]);
@@ -4349,7 +4285,7 @@ function runWorker() {
4349
4285
  default:
4350
4286
  throw new Error(`Unknown worker method: ${method}`);
4351
4287
  }
4352
- rpc.notify("snapshot", publishSnapshot());
4288
+ if (session) rpc.notify("snapshot", publishSnapshot());
4353
4289
  return result;
4354
4290
  }, () => {
4355
4291
  });
@@ -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() {
@@ -6,7 +6,7 @@ import { claudeAutoCompactionEnv } from "./auto-compaction.js";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { query, } from "@anthropic-ai/claude-agent-sdk";
8
8
  import { ClaudeWorkflowSubagent, spawnWorkflowProcess } from "./workflow-subagent.js";
9
- import { clampEffort } from "../effort.js";
9
+ import { clampEffort, EFFORT_ORDER } from "../effort.js";
10
10
  import { AsyncQueue } from "./async-queue.js";
11
11
  import { ASK_TOOL, PendingEnquiries, questionsOf } from "./enquiries.js";
12
12
  import { claudeMcpServers, refreshClaudeMcp } from "./mcp.js";
@@ -102,11 +102,27 @@ 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
- export function briefOf(input) {
105
+ function promptOf(input) {
106
+ const prompt = input?.prompt;
107
+ return typeof prompt === "string" && prompt !== "" ? prompt : undefined;
108
+ }
109
+ export function briefOf(input, inherited = {}, agentModels = new Map()) {
106
110
  const fields = (input ?? {});
107
111
  const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
108
112
  const description = typeof fields.description === "string" ? fields.description : undefined;
109
- return description === undefined ? { name } : { name, description };
113
+ const model = typeof fields.model === "string" ? fields.model : agentModels.get(name) ?? inherited.model;
114
+ const effort = EFFORT_ORDER.find((known) => known === fields.effort) ?? inherited.effort;
115
+ return {
116
+ name,
117
+ ...(description === undefined ? {} : { description }),
118
+ ...(model === undefined ? {} : { model }),
119
+ ...(effort === undefined ? {} : { effort }),
120
+ };
121
+ }
122
+ /** The model an `Agent` result says the Subagent ran on, as the picker names it where it can. */
123
+ export function resolvedModelOf(result, aliasOf) {
124
+ const resolved = result?.resolvedModel;
125
+ return typeof resolved === "string" ? aliasOf.get(resolved) ?? resolved : undefined;
110
126
  }
111
127
  /**
112
128
  * Whether an `Agent` tool result is a launch receipt rather than the Subagent's answer.
@@ -182,6 +198,8 @@ class ClaudeSession {
182
198
  announced;
183
199
  /** Alias (`opus[1m]`) keyed by the id the SDK reports once a model is resolved. */
184
200
  aliasOf = new Map();
201
+ /** The model each agent definition names, read once per session. `inherit` is left out. */
202
+ agentModels = new Map();
185
203
  /** What the human asked for, kept apart from what is in force so a clamp is never destructive. */
186
204
  wantedEffort;
187
205
  effort;
@@ -191,6 +209,8 @@ class ClaudeSession {
191
209
  subagents = new Subagents();
192
210
  /** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
193
211
  calls = new BackgroundCalls();
212
+ /** Each Subagent's brief, reported from its `Agent` call, so the same text echoed into its stream is not reported twice. */
213
+ briefs = new Map();
194
214
  enquiries = new PendingEnquiries();
195
215
  permissions = new PendingPermissions();
196
216
  /** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
@@ -252,17 +272,24 @@ class ClaudeSession {
252
272
  const env = claudeAutoCompactionEnv(this.workflowAutoCompaction, claudeState.env) ?? claudeState.env;
253
273
  const queryOptions = {
254
274
  cwd: options.scope,
255
- env,
275
+ env: builder ? { ...env, ENABLE_TOOL_SEARCH: "false" } : env,
256
276
  includePartialMessages: true,
257
277
  mcpServers: builder ? this.parentWorkflow : toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow, ...this.parentSessions },
258
278
  // Pre-approval and native Auto can bypass canUseTool. Hooks run before either, so even
259
279
  // read-only session tools remain parent-only when the SDK inherits MCP into Subagents.
260
- ...(!builder && !toolless && options.sessionTools ? { hooks: { PreToolUse: [{
261
- matcher: `${SESSION_TOOL_PREFIX}.*`,
262
- hooks: [async (input) => input.hook_event_name === "PreToolUse" && input.agent_id
263
- ? { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny",
264
- permissionDecisionReason: "Agent Session tools are available only to the parent Agent Session" } }
265
- : {}],
280
+ ...(!builder && !toolless ? { hooks: { PreToolUse: [...(options.sessionTools ? [{
281
+ matcher: `${SESSION_TOOL_PREFIX}.*`,
282
+ hooks: [async (input) => input.hook_event_name === "PreToolUse" && input.agent_id
283
+ ? { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny",
284
+ permissionDecisionReason: "Agent Session tools are available only to the parent Agent Session" } }
285
+ : {}],
286
+ }] : []), {
287
+ // A Subagent's own tool calls are the only place the CLI says which effort it settled on.
288
+ hooks: [async (input) => {
289
+ if (input.hook_event_name === "PreToolUse" && input.agent_id)
290
+ this.noteSubagentEffort(input.agent_id, input.effort?.level);
291
+ return {};
292
+ }],
266
293
  }] } } : {}),
267
294
  strictMcpConfig: true,
268
295
  // NOT bypassPermissions: it auto-approves before canUseTool is consulted, and the SDK warns
@@ -330,6 +357,7 @@ class ClaudeSession {
330
357
  this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
331
358
  this.pump = this.consume();
332
359
  this.modelsReady = this.loadModels();
360
+ void this.loadAgentModels();
333
361
  // A meter that only fills once a turn ends reads as "no window" when it is really just early.
334
362
  // Occupancy is already meaningful here: system prompt, tools and memory files are loaded
335
363
  // before anything is sent.
@@ -361,6 +389,25 @@ class ClaudeSession {
361
389
  this.noteBootedModel(this.bootedModel ?? this.modelId ?? defaultModel(models));
362
390
  await this.reapplyEffort();
363
391
  }
392
+ /** Without the list a Subagent's starting model falls back to the parent's, which the result corrects. */
393
+ async loadAgentModels() {
394
+ try {
395
+ const agents = await this.stream.supportedAgents();
396
+ this.agentModels = new Map(agents.flatMap((agent) => agent.model && agent.model !== "inherit" ? [[agent.name, agent.model]] : []));
397
+ }
398
+ catch {
399
+ return;
400
+ }
401
+ }
402
+ noteSubagentEffort(taskId, level) {
403
+ const callId = this.subagents.callIdOf(taskId);
404
+ const effort = EFFORT_ORDER.find((known) => known === level);
405
+ if (callId === undefined || effort === undefined)
406
+ return;
407
+ const refined = this.subagents.refine(callId, { effort });
408
+ if (refined)
409
+ this.emit({ type: "subagent", subagentId: callId, ...refined, ...attribution(this.subagents.parentOf(callId)), state: "running" });
410
+ }
364
411
  /**
365
412
  * The init message names the model in its resolved form (`claude-sonnet-...`), but the picker
366
413
  * lists aliases (`sonnet`). Report the alias so the id a client holds matches an entry it can
@@ -706,6 +753,7 @@ class ClaudeSession {
706
753
  // Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
707
754
  // Session Host records that from the transcript, the way it does a torn turn.
708
755
  this.subagents.abandon();
756
+ this.briefs.clear();
709
757
  // Background Calls are children of that process too, and go the same way for the same reason.
710
758
  this.calls.abandon();
711
759
  this.inbox.close();
@@ -749,6 +797,15 @@ class ClaudeSession {
749
797
  translate(sdkMessage) {
750
798
  switch (sdkMessage.type) {
751
799
  case "system":
800
+ if (sdkMessage.subtype === "informational") {
801
+ this.emit({ type: "notice", level: sdkMessage.level === "warning" ? "warn" : "info", text: sdkMessage.content });
802
+ return;
803
+ }
804
+ if (sdkMessage.subtype === "session_writes_lost") {
805
+ const lost = sdkMessage.lost.map(part => part === "transcript" ? "its conversation record" : "its global configuration");
806
+ this.emit({ type: "notice", level: "warn", text: `Claude Code could not save ${lost.join(" and ")} (${sdkMessage.error_code}).` });
807
+ return;
808
+ }
752
809
  if (sdkMessage.subtype === "init") {
753
810
  this.sdkSessionId = sdkMessage.session_id;
754
811
  this.noteBootedModel(sdkMessage.model);
@@ -839,14 +896,23 @@ class ClaudeSession {
839
896
  this.calls.called(block.id, { tool: block.name, ...attribution(producer) });
840
897
  if (block.name !== SUBAGENT_TOOL)
841
898
  continue;
842
- const brief = briefOf(block.input);
843
- this.subagents.spawn(block.id, brief);
844
- this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
899
+ const brief = briefOf(block.input, this.subagents.describe(producer) ?? {
900
+ ...(this.modelId === undefined ? {} : { model: this.modelId }),
901
+ ...(this.effort === undefined ? {} : { effort: this.effort }),
902
+ }, this.agentModels);
903
+ this.subagents.spawn(block.id, brief, producer);
904
+ this.emit({ type: "subagent", subagentId: block.id, ...brief, ...attribution(producer), state: "running" });
905
+ const prompt = promptOf(block.input);
906
+ if (prompt === undefined)
907
+ continue;
908
+ this.briefs.set(block.id, prompt);
909
+ this.emit({ type: "subagent_instruction", id: `${block.id}:brief`, text: prompt, producer: { subagentId: block.id } });
845
910
  }
846
911
  return;
847
912
  }
848
913
  case "user": {
849
914
  const content = sdkMessage.message.content;
915
+ this.instructSubagent(sdkMessage);
850
916
  if (typeof content === "string")
851
917
  return;
852
918
  for (const block of content) {
@@ -862,7 +928,12 @@ class ClaudeSession {
862
928
  // A launch receipt, not an answer: the Subagent is only now starting work, so it gets
863
929
  // no terminal snapshot and its card stays running. What it does give up is its hold on
864
930
  // the turn, which is what keeps the Steering Queue live while it runs (ADR 0016).
931
+ const resolved = resolvedModelOf(sdkMessage.tool_use_result, this.aliasOf);
932
+ const refined = resolved === undefined ? undefined : this.subagents.refine(block.tool_use_id, { model: resolved });
865
933
  if (isAsyncLaunch(sdkMessage.tool_use_result)) {
934
+ if (refined) {
935
+ this.emit({ type: "subagent", subagentId: block.tool_use_id, ...refined, ...attribution(this.subagents.parentOf(block.tool_use_id)), state: "running" });
936
+ }
866
937
  const released = this.subagents.background(block.tool_use_id);
867
938
  if (released)
868
939
  this.endTurn(released);
@@ -875,6 +946,7 @@ class ClaudeSession {
875
946
  type: "subagent",
876
947
  subagentId: block.tool_use_id,
877
948
  ...brief,
949
+ ...attribution(this.subagents.parentOf(block.tool_use_id)),
878
950
  state: isError ? "error" : "complete",
879
951
  });
880
952
  }
@@ -959,6 +1031,7 @@ class ClaudeSession {
959
1031
  this.endTurn(reason);
960
1032
  }
961
1033
  closeSubagent(callId) {
1034
+ this.briefs.delete(callId);
962
1035
  this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
963
1036
  this.permissions.clearRefusals((producer) => producer === callId);
964
1037
  const released = this.subagents.returned(callId);
@@ -1013,7 +1086,7 @@ class ClaudeSession {
1013
1086
  return;
1014
1087
  const brief = this.subagents.describe(callId);
1015
1088
  if (brief !== undefined) {
1016
- this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
1089
+ this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
1017
1090
  this.closeSubagent(callId);
1018
1091
  return;
1019
1092
  }
@@ -1040,6 +1113,23 @@ class ClaudeSession {
1040
1113
  this.turnId = randomUUID();
1041
1114
  this.emit({ type: "turn_started", turnId: this.turnId });
1042
1115
  }
1116
+ /** Report text the spawning model sent into a Subagent. The Agent Session's own user text is the host's to record. */
1117
+ instructSubagent(sdkMessage) {
1118
+ const subagentId = producerOf(sdkMessage);
1119
+ if (subagentId === "")
1120
+ return;
1121
+ const content = sdkMessage.message.content;
1122
+ const text = typeof content === "string"
1123
+ ? content
1124
+ : content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
1125
+ if (text === "")
1126
+ return;
1127
+ if (this.briefs.get(subagentId) === text) {
1128
+ this.briefs.delete(subagentId);
1129
+ return;
1130
+ }
1131
+ this.emit({ type: "subagent_instruction", id: sdkMessage.uuid ?? randomUUID(), text, producer: { subagentId } });
1132
+ }
1043
1133
  endTurn(reason) {
1044
1134
  const turnId = this.turnId;
1045
1135
  /*
@@ -1054,8 +1144,8 @@ class ClaudeSession {
1054
1144
  // Cleared whatever the outcome, so a held end cannot reach the turn after this one.
1055
1145
  this.subagents.clear();
1056
1146
  // 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();
1147
+ // that made it, which is the whole of ADR 0021 — and so do calls detached work announced.
1148
+ this.calls.clear((brief) => brief.producer !== undefined && !ended(brief.producer.subagentId));
1059
1149
  this.enquiries.clear();
1060
1150
  if (!turnId)
1061
1151
  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,48 @@ 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;
50
+ }
51
+ /** Correct what an open or detached Subagent runs on. Answers the new brief, or undefined when nothing changed. */
52
+ refine(callId, patch) {
53
+ const spawned = this.spawned(callId);
54
+ if (spawned === undefined)
55
+ return undefined;
56
+ const { brief } = spawned;
57
+ if ((patch.model ?? brief.model) === brief.model && (patch.effort ?? brief.effort) === brief.effort)
58
+ return undefined;
59
+ spawned.brief = { ...brief, ...patch };
60
+ return spawned.brief;
44
61
  }
45
62
  /**
46
63
  * Record that a Subagent was backgrounded, so it stops holding the turn without ending.
47
64
  *
48
65
  * Answers the same question `returned` does — the turn end now free to fire — because a launch
49
66
  * receipt releases a held end for exactly the reason a real one does: nothing else is waiting.
67
+ *
68
+ * Its open descendants are detached with it, since they now have a detached ancestor.
50
69
  */
51
70
  background(callId) {
52
- const brief = this.open.get(callId);
53
- if (brief === undefined)
71
+ const spawned = this.open.get(callId);
72
+ if (spawned === undefined)
54
73
  return undefined;
55
74
  this.open.delete(callId);
56
- this.detached.set(callId, brief);
75
+ this.detached.set(callId, spawned);
76
+ for (const [id, descendant] of this.open) {
77
+ if (!this.isDetached(id))
78
+ continue;
79
+ this.open.delete(id);
80
+ this.detached.set(id, descendant);
81
+ }
57
82
  return this.release();
58
83
  }
59
- /** Whether this Subagent's work survives the parent turn ending. */
84
+ /** Whether this Subagent's work survives the parent turn ending: it or an ancestor is detached. */
60
85
  isDetached(callId) {
61
- return this.detached.has(callId);
86
+ for (let at = callId; at !== ""; at = this.spawned(at)?.parent ?? "") {
87
+ if (this.detached.has(at))
88
+ return true;
89
+ }
90
+ return false;
62
91
  }
63
92
  /** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
64
93
  noteTask(taskId, callId) {
@@ -116,6 +145,9 @@ export class Subagents {
116
145
  this.detached.clear();
117
146
  this.tasks.clear();
118
147
  }
148
+ spawned(callId) {
149
+ return this.open.get(callId) ?? this.detached.get(callId);
150
+ }
119
151
  release() {
120
152
  if (this.open.size > 0)
121
153
  return undefined;