@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

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 (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  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-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,11 +1,13 @@
1
1
  import { workflowParentServer } from "./workflow-parent.js";
2
+ import { sessionToolsServer, claudeSessionReadTools, SESSION_TOOL_PREFIX } from "./session-tools.js";
2
3
  import { workflowBuilderServer, claudeWorkflowBuilderToolNames } from "./workflow-builder.js";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { claudeAutoCompactionEnv } from "./auto-compaction.js";
5
6
  import { spawn, spawnSync } from "node:child_process";
6
7
  import { query, } from "@anthropic-ai/claude-agent-sdk";
8
+ import { anthropicPlanLimits } from "../plan-limits.js";
7
9
  import { ClaudeWorkflowSubagent, spawnWorkflowProcess } from "./workflow-subagent.js";
8
- import { clampEffort } from "../effort.js";
10
+ import { clampEffort, EFFORT_ORDER } from "../effort.js";
9
11
  import { AsyncQueue } from "./async-queue.js";
10
12
  import { ASK_TOOL, PendingEnquiries, questionsOf } from "./enquiries.js";
11
13
  import { claudeMcpServers, refreshClaudeMcp } from "./mcp.js";
@@ -13,8 +15,12 @@ import { PendingPermissions } from "./permissions.js";
13
15
  import { StreamedMessages } from "./streamed-message.js";
14
16
  import { Subagents } from "./subagents.js";
15
17
  import { BackgroundCalls } from "./background-calls.js";
16
- import { prepareClaudeState } from "../worker/claude-state.js";
18
+ import { TODO_TOOLS, TodoList } from "./todo-list.js";
19
+ import { prepareClaudeState, projectKey } from "../worker/claude-state.js";
20
+ import { existsSync, readFileSync } from "node:fs";
21
+ import { join } from "node:path";
17
22
  import { AutoPermissionUnavailable } from "../permission-errors.js";
23
+ import { DIFF_EXCERPT_INSTRUCTIONS } from "../diff-excerpt-instructions.js";
18
24
  export { AutoPermissionUnavailable } from "../permission-errors.js";
19
25
  /**
20
26
  * Locate the Claude Code CLI.
@@ -99,11 +105,27 @@ function attribution(producer) {
99
105
  * something a transcript row can show. Falls back to the tool name so a client always has something
100
106
  * to print, which is what the protocol promises.
101
107
  */
102
- export function briefOf(input) {
108
+ function promptOf(input) {
109
+ const prompt = input?.prompt;
110
+ return typeof prompt === "string" && prompt !== "" ? prompt : undefined;
111
+ }
112
+ export function briefOf(input, inherited = {}, agentModels = new Map()) {
103
113
  const fields = (input ?? {});
104
114
  const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
105
115
  const description = typeof fields.description === "string" ? fields.description : undefined;
106
- return description === undefined ? { name } : { name, description };
116
+ const model = typeof fields.model === "string" ? fields.model : agentModels.get(name) ?? inherited.model;
117
+ const effort = EFFORT_ORDER.find((known) => known === fields.effort) ?? inherited.effort;
118
+ return {
119
+ name,
120
+ ...(description === undefined ? {} : { description }),
121
+ ...(model === undefined ? {} : { model }),
122
+ ...(effort === undefined ? {} : { effort }),
123
+ };
124
+ }
125
+ /** The model an `Agent` result says the Subagent ran on, as the picker names it where it can. */
126
+ export function resolvedModelOf(result, aliasOf) {
127
+ const resolved = result?.resolvedModel;
128
+ return typeof resolved === "string" ? aliasOf.get(resolved) ?? resolved : undefined;
107
129
  }
108
130
  /**
109
131
  * Whether an `Agent` tool result is a launch receipt rather than the Subagent's answer.
@@ -139,6 +161,12 @@ const DEFAULT_ALLOWED_TOOLS = [
139
161
  "WebFetch",
140
162
  "WebSearch",
141
163
  "TodoWrite",
164
+ // TodoWrite's successors, behind CLAUDE_CODE_ENABLE_TASKS. Like it, they keep the agent's own
165
+ // checklist and touch nothing outside the session, so asking about one would be noise.
166
+ "TaskCreate",
167
+ "TaskUpdate",
168
+ "TaskList",
169
+ "TaskGet",
142
170
  "NotebookEdit",
143
171
  // How a backgrounded Bash is read and stopped. Refused until Permission Prompts existed, which
144
172
  // was a latent bug — the tool that *started* the job was allowed. They belong here rather than
@@ -156,8 +184,13 @@ const DEFAULT_ALLOWED_TOOLS = [
156
184
  // what it cannot show is what the Subagent spent, which is a different measure.
157
185
  "Agent",
158
186
  ];
187
+ function readOnlyDeniedTools(readOnly) {
188
+ if (!readOnly)
189
+ return [];
190
+ return ["Write", "Edit", "NotebookEdit", ...(readOnly === "tools" ? ["Bash", "mcp__workflow__bash"] : [])];
191
+ }
159
192
  class ClaudeSession {
160
- capabilities = { providers: ["anthropic"], models: [], compaction: true, autoCompaction: "startup", fork: true, subagents: true, enquiries: true, permissions: true };
193
+ capabilities = { providers: ["anthropic"], models: [], compaction: true, autoCompaction: "startup", fork: true, rewind: true, rewindFiles: true, subagents: true, enquiries: true, permissions: true };
161
194
  inbox = new AsyncQueue();
162
195
  emit;
163
196
  stream;
@@ -170,6 +203,7 @@ class ClaudeSession {
170
203
  disposed = false;
171
204
  workflowSubagents = new Set();
172
205
  parentWorkflow;
206
+ parentSessions;
173
207
  workflowGrants;
174
208
  disposal;
175
209
  modelId;
@@ -178,6 +212,8 @@ class ClaudeSession {
178
212
  announced;
179
213
  /** Alias (`opus[1m]`) keyed by the id the SDK reports once a model is resolved. */
180
214
  aliasOf = new Map();
215
+ /** The model each agent definition names, read once per session. `inherit` is left out. */
216
+ agentModels = new Map();
181
217
  /** What the human asked for, kept apart from what is in force so a clamp is never destructive. */
182
218
  wantedEffort;
183
219
  effort;
@@ -187,6 +223,11 @@ class ClaudeSession {
187
223
  subagents = new Subagents();
188
224
  /** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
189
225
  calls = new BackgroundCalls();
226
+ /** Each Subagent's brief, reported from its `Agent` call, so the same text echoed into its stream is not reported twice. */
227
+ briefs = new Map();
228
+ /** The Agent Session's own Todo List, and the inputs of its todo calls still waiting on a result. */
229
+ todoList = new TodoList();
230
+ todoCalls = new Map();
190
231
  enquiries = new PendingEnquiries();
191
232
  permissions = new PendingPermissions();
192
233
  /** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
@@ -213,14 +254,19 @@ class ClaudeSession {
213
254
  priorSpend;
214
255
  options;
215
256
  backendOptions;
257
+ disallowedTools;
216
258
  workflowAutoCompaction;
217
259
  claudeState;
218
- constructor(options, backendOptions, claudeState) {
260
+ constructor(options, backendOptions, claudeState, resumeAt) {
219
261
  this.claudeState = claudeState;
220
262
  this.parentWorkflow = options.workflowBuilder ? workflowBuilderServer(options.workflowBuilder)
221
263
  : workflowParentServer(options.tools === "none" ? undefined : options.workflow);
264
+ this.parentSessions = sessionToolsServer(options.workflowBuilder || options.tools === "none" ? undefined : options.sessionTools);
222
265
  if (options.workflowBuilder)
223
266
  this.capabilities = { ...this.capabilities, subagents: false, enquiries: false, permissions: false };
267
+ if (options.readOnly)
268
+ this.capabilities = { ...this.capabilities, rewindFiles: false };
269
+ this.disallowedTools = [...backendOptions.disallowedTools ?? [], ...readOnlyDeniedTools(options.readOnly)];
224
270
  this.options = options;
225
271
  this.permissionMode = options.permissionMode ?? "ask";
226
272
  this.backendOptions = backendOptions;
@@ -236,7 +282,9 @@ class ClaudeSession {
236
282
  // `BackendCreateOptions.tools`. The deny in `canUseTool` below is the half that makes it hold.
237
283
  const builder = options.workflowBuilder;
238
284
  const toolless = !builder && options.tools === "none";
239
- const preApproved = builder ? claudeWorkflowBuilderToolNames : toolless ? [] : [...(backendOptions.allowedTools ?? DEFAULT_ALLOWED_TOOLS), ...(options.workflow ? ["mcp__flow_workflow__workflow_inspect", "mcp__flow_workflow__workflow_recover", "mcp__flow_workflow__workflow_relay_enquiry", "mcp__flow_workflow__workflow_relay_permission"] : [])];
285
+ const preApproved = builder ? claudeWorkflowBuilderToolNames : toolless ? [] : [...(backendOptions.allowedTools ?? DEFAULT_ALLOWED_TOOLS).filter((tool) => !this.disallowedTools.includes(tool)), ...(options.workflow ? ["mcp__flow_workflow__workflow_inspect", "mcp__flow_workflow__workflow_recover", "mcp__flow_workflow__workflow_relay_enquiry", "mcp__flow_workflow__workflow_relay_permission"] : [])];
286
+ if (!builder && !toolless && options.sessionTools)
287
+ preApproved.push(...claudeSessionReadTools);
240
288
  this.allowed = new Set(toolless ? [] : [...preApproved, ...(options.standingAuthorisations ?? [])]);
241
289
  // `allowedTools` is what the CLI auto-approves before the callback, and it is given only the
242
290
  // pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
@@ -245,27 +293,45 @@ class ClaudeSession {
245
293
  const env = claudeAutoCompactionEnv(this.workflowAutoCompaction, claudeState.env) ?? claudeState.env;
246
294
  const queryOptions = {
247
295
  cwd: options.scope,
248
- env,
296
+ env: builder ? { ...env, ENABLE_TOOL_SEARCH: "false" } : env,
249
297
  includePartialMessages: true,
250
- mcpServers: builder ? this.parentWorkflow : toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
298
+ mcpServers: builder ? this.parentWorkflow : toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow, ...this.parentSessions },
299
+ // Pre-approval and native Auto can bypass canUseTool. Hooks run before either, so even
300
+ // read-only session tools remain parent-only when the SDK inherits MCP into Subagents.
301
+ ...(!builder && !toolless ? { hooks: { PreToolUse: [...(options.sessionTools ? [{
302
+ matcher: `${SESSION_TOOL_PREFIX}.*`,
303
+ hooks: [async (input) => input.hook_event_name === "PreToolUse" && input.agent_id
304
+ ? { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny",
305
+ permissionDecisionReason: "Agent Session tools are available only to the parent Agent Session" } }
306
+ : {}],
307
+ }] : []), {
308
+ // A Subagent's own tool calls are the only place the CLI says which effort it settled on.
309
+ hooks: [async (input) => {
310
+ if (input.hook_event_name === "PreToolUse" && input.agent_id)
311
+ this.noteSubagentEffort(input.agent_id, input.effort?.level);
312
+ return {};
313
+ }],
314
+ }] } } : {}),
251
315
  strictMcpConfig: true,
252
316
  // NOT bypassPermissions: it auto-approves before canUseTool is consulted, and the SDK warns
253
317
  // as much. "default" runs the permission flow, allowedTools auto-approves the pre-approved
254
318
  // set, and canUseTool catches only the fall-through so nothing can stall waiting on a prompt.
255
319
  permissionMode: "default",
256
320
  allowedTools: preApproved,
257
- ...(backendOptions.disallowedTools ? { disallowedTools: backendOptions.disallowedTools } : {}),
321
+ ...(this.disallowedTools.length ? { disallowedTools: this.disallowedTools } : {}),
258
322
  ...(builder ? {
259
323
  tools: [], settingSources: [], skills: [], plugins: [], agents: {},
260
324
  settings: { disableAllHooks: true, enabledPlugins: {}, syncClaudeAiSkills: false, syncClaudeAiPlugins: false,
261
325
  disableClaudeAiConnectors: true, disableBundledSkills: true },
262
326
  systemPrompt: builder.instructions,
263
- } : backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {}),
327
+ } : { extraArgs: { "append-system-prompt": DIFF_EXCERPT_INSTRUCTIONS }, ...backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {} }),
264
328
  ...(options.modelId ? { model: options.modelId } : {}),
265
329
  // Effort is also settable later, but starting with it avoids a first turn at the wrong level
266
330
  // while the model list is still in flight. Levels Claude does not have wait for the clamp.
267
331
  ...(startingEffort ? { effort: startingEffort } : {}),
268
332
  ...(options.resume ? { resume: options.resume } : {}),
333
+ ...(resumeAt ? { resumeSessionAt: resumeAt } : {}),
334
+ ...(builder || toolless || options.readOnly ? {} : { enableFileCheckpointing: true }),
269
335
  ...(backendOptions.pathToClaudeCodeExecutable
270
336
  ? { pathToClaudeCodeExecutable: backendOptions.pathToClaudeCodeExecutable }
271
337
  : {}),
@@ -294,6 +360,11 @@ class ClaudeSession {
294
360
  return claudeWorkflowBuilderToolNames.includes(toolName)
295
361
  ? { behavior: "allow", updatedInput: input }
296
362
  : { behavior: "deny", message: "This workflow builder tool is not enabled" };
363
+ if (extra.agentID && toolName.startsWith(SESSION_TOOL_PREFIX))
364
+ return { behavior: "deny",
365
+ message: "Agent Session tools are available only to the parent Agent Session" };
366
+ if (this.disallowedTools.includes(toolName))
367
+ return { behavior: "deny", message: `${toolName} is disabled for this session` };
297
368
  if (toolName === ASK_TOOL)
298
369
  return await this.ask(extra.toolUseID, input);
299
370
  if (this.permissionMode === "always" || this.allowed.has(toolName) || this.workflowGrants.has(toolName))
@@ -309,6 +380,7 @@ class ClaudeSession {
309
380
  this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
310
381
  this.pump = this.consume();
311
382
  this.modelsReady = this.loadModels();
383
+ void this.loadAgentModels();
312
384
  // A meter that only fills once a turn ends reads as "no window" when it is really just early.
313
385
  // Occupancy is already meaningful here: system prompt, tools and memory files are loaded
314
386
  // before anything is sent.
@@ -340,6 +412,25 @@ class ClaudeSession {
340
412
  this.noteBootedModel(this.bootedModel ?? this.modelId ?? defaultModel(models));
341
413
  await this.reapplyEffort();
342
414
  }
415
+ /** Without the list a Subagent's starting model falls back to the parent's, which the result corrects. */
416
+ async loadAgentModels() {
417
+ try {
418
+ const agents = await this.stream.supportedAgents();
419
+ this.agentModels = new Map(agents.flatMap((agent) => agent.model && agent.model !== "inherit" ? [[agent.name, agent.model]] : []));
420
+ }
421
+ catch {
422
+ return;
423
+ }
424
+ }
425
+ noteSubagentEffort(taskId, level) {
426
+ const callId = this.subagents.callIdOf(taskId);
427
+ const effort = EFFORT_ORDER.find((known) => known === level);
428
+ if (callId === undefined || effort === undefined)
429
+ return;
430
+ const refined = this.subagents.refine(callId, { effort });
431
+ if (refined)
432
+ this.emit({ type: "subagent", subagentId: callId, ...refined, ...attribution(this.subagents.parentOf(callId)), state: "running" });
433
+ }
343
434
  /**
344
435
  * The init message names the model in its resolved form (`claude-sonnet-...`), but the picker
345
436
  * lists aliases (`sonnet`). Report the alias so the id a client holds matches an entry it can
@@ -389,7 +480,15 @@ class ClaudeSession {
389
480
  resumeToken() {
390
481
  return this.sdkSessionId || undefined;
391
482
  }
392
- async prompt(text, attachments) {
483
+ async rewindFiles(messageId) {
484
+ const preview = await this.stream.rewindFiles(messageId, { dryRun: true });
485
+ if (!preview.canRewind)
486
+ throw new Error(preview.error ?? "No file checkpoint exists for this message");
487
+ const result = await this.stream.rewindFiles(messageId);
488
+ if (!result.canRewind)
489
+ throw new Error(result.error ?? "Files could not be rewound");
490
+ }
491
+ async prompt(text, attachments, messageId) {
393
492
  if (this.disposed)
394
493
  throw new Error("Backend Session disposed");
395
494
  this.turnId = randomUUID();
@@ -399,6 +498,7 @@ class ClaudeSession {
399
498
  message: { role: "user", content: userContent(text, attachments) },
400
499
  parent_tool_use_id: null,
401
500
  session_id: this.sdkSessionId,
501
+ ...(messageId ? { uuid: messageId } : {}),
402
502
  });
403
503
  }
404
504
  /**
@@ -447,6 +547,11 @@ class ClaudeSession {
447
547
  * That it also rescans the disk is the behaviour worth having: a human who has just written a
448
548
  * Skill opens the menu expecting to find it.
449
549
  */
550
+ async planLimits() {
551
+ const { rate_limits } = await this.stream.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
552
+ const limits = anthropicPlanLimits(rate_limits);
553
+ return limits ? [limits] : [];
554
+ }
450
555
  async skills() {
451
556
  if (this.options.workflowBuilder)
452
557
  return [];
@@ -634,7 +739,7 @@ class ClaudeSession {
634
739
  async refreshMcp() {
635
740
  if (this.options.workflowBuilder)
636
741
  return;
637
- await refreshClaudeMcp(this.stream, this.options.mcp, this.parentWorkflow);
742
+ await refreshClaudeMcp(this.stream, this.options.mcp, { ...this.parentWorkflow, ...this.parentSessions });
638
743
  }
639
744
  startWorkflowSubagent(options) {
640
745
  if (this.disposed)
@@ -645,7 +750,7 @@ class ClaudeSession {
645
750
  throw new Error("This Backend Session runs no tools");
646
751
  const handle = new ClaudeWorkflowSubagent({ cwd: this.options.scope,
647
752
  mcpServers: claudeMcpServers(this.options.mcp),
648
- ...(this.backendOptions.disallowedTools ? { disallowedTools: this.backendOptions.disallowedTools } : {}),
753
+ ...(this.disallowedTools.length ? { disallowedTools: this.disallowedTools } : {}),
649
754
  ...(this.backendOptions.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: this.backendOptions.pathToClaudeCodeExecutable } : {}),
650
755
  }, options, this.workflowGrants, {
651
756
  ...(this.backendOptions.query ? { query: this.backendOptions.query } : {}),
@@ -676,6 +781,8 @@ class ClaudeSession {
676
781
  // Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
677
782
  // Session Host records that from the transcript, the way it does a torn turn.
678
783
  this.subagents.abandon();
784
+ this.briefs.clear();
785
+ this.todoCalls.clear();
679
786
  // Background Calls are children of that process too, and go the same way for the same reason.
680
787
  this.calls.abandon();
681
788
  this.inbox.close();
@@ -719,6 +826,15 @@ class ClaudeSession {
719
826
  translate(sdkMessage) {
720
827
  switch (sdkMessage.type) {
721
828
  case "system":
829
+ if (sdkMessage.subtype === "informational") {
830
+ this.emit({ type: "notice", level: sdkMessage.level === "warning" ? "warn" : "info", text: sdkMessage.content });
831
+ return;
832
+ }
833
+ if (sdkMessage.subtype === "session_writes_lost") {
834
+ const lost = sdkMessage.lost.map(part => part === "transcript" ? "its conversation record" : "its global configuration");
835
+ this.emit({ type: "notice", level: "warn", text: `Claude Code could not save ${lost.join(" and ")} (${sdkMessage.error_code}).` });
836
+ return;
837
+ }
722
838
  if (sdkMessage.subtype === "init") {
723
839
  this.sdkSessionId = sdkMessage.session_id;
724
840
  this.noteBootedModel(sdkMessage.model);
@@ -807,16 +923,28 @@ class ClaudeSession {
807
923
  // guessed from that name. Recording only the names we expect to background would be the
808
924
  // tool-name allowlist ADR 0021 refuses.
809
925
  this.calls.called(block.id, { tool: block.name, ...attribution(producer) });
926
+ // A Subagent's checklist is its own, and stays an ordinary tool row.
927
+ if (producer === "" && TODO_TOOLS.has(block.name))
928
+ this.todoCalls.set(block.id, { name: block.name, input: block.input });
810
929
  if (block.name !== SUBAGENT_TOOL)
811
930
  continue;
812
- const brief = briefOf(block.input);
813
- this.subagents.spawn(block.id, brief);
814
- this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
931
+ const brief = briefOf(block.input, this.subagents.describe(producer) ?? {
932
+ ...(this.modelId === undefined ? {} : { model: this.modelId }),
933
+ ...(this.effort === undefined ? {} : { effort: this.effort }),
934
+ }, this.agentModels);
935
+ this.subagents.spawn(block.id, brief, producer);
936
+ this.emit({ type: "subagent", subagentId: block.id, ...brief, ...attribution(producer), state: "running" });
937
+ const prompt = promptOf(block.input);
938
+ if (prompt === undefined)
939
+ continue;
940
+ this.briefs.set(block.id, prompt);
941
+ this.emit({ type: "subagent_instruction", id: `${block.id}:brief`, text: prompt, producer: { subagentId: block.id } });
815
942
  }
816
943
  return;
817
944
  }
818
945
  case "user": {
819
946
  const content = sdkMessage.message.content;
947
+ this.instructSubagent(sdkMessage);
820
948
  if (typeof content === "string")
821
949
  return;
822
950
  for (const block of content) {
@@ -829,10 +957,16 @@ class ClaudeSession {
829
957
  isError,
830
958
  ...attribution(producerOf(sdkMessage)),
831
959
  });
960
+ this.settleTodo(block.tool_use_id, sdkMessage.tool_use_result, isError);
832
961
  // A launch receipt, not an answer: the Subagent is only now starting work, so it gets
833
962
  // no terminal snapshot and its card stays running. What it does give up is its hold on
834
963
  // the turn, which is what keeps the Steering Queue live while it runs (ADR 0016).
964
+ const resolved = resolvedModelOf(sdkMessage.tool_use_result, this.aliasOf);
965
+ const refined = resolved === undefined ? undefined : this.subagents.refine(block.tool_use_id, { model: resolved });
835
966
  if (isAsyncLaunch(sdkMessage.tool_use_result)) {
967
+ if (refined) {
968
+ this.emit({ type: "subagent", subagentId: block.tool_use_id, ...refined, ...attribution(this.subagents.parentOf(block.tool_use_id)), state: "running" });
969
+ }
836
970
  const released = this.subagents.background(block.tool_use_id);
837
971
  if (released)
838
972
  this.endTurn(released);
@@ -845,6 +979,7 @@ class ClaudeSession {
845
979
  type: "subagent",
846
980
  subagentId: block.tool_use_id,
847
981
  ...brief,
982
+ ...attribution(this.subagents.parentOf(block.tool_use_id)),
848
983
  state: isError ? "error" : "complete",
849
984
  });
850
985
  }
@@ -928,7 +1063,18 @@ class ClaudeSession {
928
1063
  return;
929
1064
  this.endTurn(reason);
930
1065
  }
1066
+ /** Report the Todo List after a todo call of the Agent Session's own model settles, if it changed. */
1067
+ settleTodo(callId, result, isError) {
1068
+ const call = this.todoCalls.get(callId);
1069
+ if (call === undefined)
1070
+ return;
1071
+ this.todoCalls.delete(callId);
1072
+ const entries = this.todoList.settle(call.name, call.input, result, isError);
1073
+ if (entries)
1074
+ this.emit({ type: "plan", entries, callId });
1075
+ }
931
1076
  closeSubagent(callId) {
1077
+ this.briefs.delete(callId);
932
1078
  this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
933
1079
  this.permissions.clearRefusals((producer) => producer === callId);
934
1080
  const released = this.subagents.returned(callId);
@@ -983,7 +1129,7 @@ class ClaudeSession {
983
1129
  return;
984
1130
  const brief = this.subagents.describe(callId);
985
1131
  if (brief !== undefined) {
986
- this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
1132
+ this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
987
1133
  this.closeSubagent(callId);
988
1134
  return;
989
1135
  }
@@ -1010,6 +1156,23 @@ class ClaudeSession {
1010
1156
  this.turnId = randomUUID();
1011
1157
  this.emit({ type: "turn_started", turnId: this.turnId });
1012
1158
  }
1159
+ /** Report text the spawning model sent into a Subagent. The Agent Session's own user text is the host's to record. */
1160
+ instructSubagent(sdkMessage) {
1161
+ const subagentId = producerOf(sdkMessage);
1162
+ if (subagentId === "")
1163
+ return;
1164
+ const content = sdkMessage.message.content;
1165
+ const text = typeof content === "string"
1166
+ ? content
1167
+ : content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
1168
+ if (text === "")
1169
+ return;
1170
+ if (this.briefs.get(subagentId) === text) {
1171
+ this.briefs.delete(subagentId);
1172
+ return;
1173
+ }
1174
+ this.emit({ type: "subagent_instruction", id: sdkMessage.uuid ?? randomUUID(), text, producer: { subagentId } });
1175
+ }
1013
1176
  endTurn(reason) {
1014
1177
  const turnId = this.turnId;
1015
1178
  /*
@@ -1024,8 +1187,8 @@ class ClaudeSession {
1024
1187
  // Cleared whatever the outcome, so a held end cannot reach the turn after this one.
1025
1188
  this.subagents.clear();
1026
1189
  // Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
1027
- // that made it, which is the whole of ADR 0021.
1028
- this.calls.clear();
1190
+ // that made it, which is the whole of ADR 0021 — and so do calls detached work announced.
1191
+ this.calls.clear((brief) => brief.producer !== undefined && !ended(brief.producer.subagentId));
1029
1192
  this.enquiries.clear();
1030
1193
  if (!turnId)
1031
1194
  return;
@@ -1047,7 +1210,11 @@ export class ClaudeBackend {
1047
1210
  const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope, options.resume);
1048
1211
  let session;
1049
1212
  try {
1050
- session = new ClaudeSession(options, this.options, claudeState);
1213
+ const resumeAt = options.resume && options.resumeBefore ? resumePoint(claudeState.env, options.scope, options.resume, options.resumeBefore) : undefined;
1214
+ // A Rewind to the first message keeps nothing, so it starts a new conversation.
1215
+ const { resume: _discarded, ...fresh } = options;
1216
+ session = resumeAt === null ? new ClaudeSession(fresh, this.options, claudeState)
1217
+ : new ClaudeSession(options, this.options, claudeState, resumeAt);
1051
1218
  }
1052
1219
  catch (error) {
1053
1220
  claudeState.cleanup();
@@ -1084,6 +1251,19 @@ export class ClaudeBackend {
1084
1251
  }
1085
1252
  }
1086
1253
  }
1254
+ /** The chain entry just before user message `before`, or null when `before` starts the conversation. */
1255
+ function resumePoint(env, scope, resume, before) {
1256
+ const record = join(env.CLAUDE_CONFIG_DIR ?? "", "projects", projectKey(scope), `${resume}.jsonl`);
1257
+ const lines = existsSync(record) ? readFileSync(record, "utf8").split("\n") : [];
1258
+ for (const line of lines) {
1259
+ if (!line.includes(before))
1260
+ continue;
1261
+ const entry = JSON.parse(line);
1262
+ if (entry.uuid === before)
1263
+ return entry.parentUuid ?? null;
1264
+ }
1265
+ throw new Error("This message cannot be rewound: Claude has no record of it");
1266
+ }
1087
1267
  /** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
1088
1268
  /**
1089
1269
  * Which model id to announce for the one the SDK just named.
@@ -0,0 +1,14 @@
1
+ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
2
+ import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput, sessionListDescription, sessionInspectDescription, sessionCreateDescription, sessionSendDescription, } from "../session-tools.js";
3
+ export const SESSION_TOOL_PREFIX = "mcp__flow_sessions__";
4
+ export const claudeSessionReadTools = ["session_list", "session_inspect"].map(name => `${SESSION_TOOL_PREFIX}${name}`);
5
+ export function sessionToolsServer(sessions) {
6
+ if (!sessions)
7
+ return {};
8
+ return { flow_sessions: createSdkMcpServer({ name: "flow_sessions", alwaysLoad: true, tools: [
9
+ tool("session_list", sessionListDescription, sessionListInput.shape, async (input) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.list(input)) }] })),
10
+ tool("session_inspect", sessionInspectDescription, sessionInspectInput.shape, async (input) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.inspect(input)) }] })),
11
+ tool("session_create", sessionCreateDescription, sessionCreateInput.shape, async (input, extra) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.create(input, extra?.signal)) }] })),
12
+ tool("session_send", sessionSendDescription, sessionSendInput.shape, async (input, extra) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.send(input, extra?.signal)) }] })),
13
+ ] }) };
14
+ }
@@ -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;