@nathanstephenson/flow 0.1.10-beta.1 → 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.
- package/README.md +52 -22
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
- package/build/backend-worker.mjs +69 -122
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +188 -25
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +118 -20
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +1 -1
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +42 -8
- package/dist/backend/worker/index.js +131 -15
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +940 -119
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +12 -9
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +400 -311
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +127 -11
- package/dist/workflows/recovery.js +38 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +367 -96
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-api-BfExddae.js +0 -6
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
- /package/dist/protocol/{publish.js → imports.js} +0 -0
|
@@ -5,8 +5,9 @@ import { randomUUID } from "node:crypto";
|
|
|
5
5
|
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
|
+
import { anthropicPlanLimits } from "../plan-limits.js";
|
|
8
9
|
import { ClaudeWorkflowSubagent, spawnWorkflowProcess } from "./workflow-subagent.js";
|
|
9
|
-
import { clampEffort } from "../effort.js";
|
|
10
|
+
import { clampEffort, EFFORT_ORDER } from "../effort.js";
|
|
10
11
|
import { AsyncQueue } from "./async-queue.js";
|
|
11
12
|
import { ASK_TOOL, PendingEnquiries, questionsOf } from "./enquiries.js";
|
|
12
13
|
import { claudeMcpServers, refreshClaudeMcp } from "./mcp.js";
|
|
@@ -14,8 +15,12 @@ import { PendingPermissions } from "./permissions.js";
|
|
|
14
15
|
import { StreamedMessages } from "./streamed-message.js";
|
|
15
16
|
import { Subagents } from "./subagents.js";
|
|
16
17
|
import { BackgroundCalls } from "./background-calls.js";
|
|
17
|
-
import {
|
|
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";
|
|
18
22
|
import { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
23
|
+
import { DIFF_EXCERPT_INSTRUCTIONS } from "../diff-excerpt-instructions.js";
|
|
19
24
|
export { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
20
25
|
/**
|
|
21
26
|
* Locate the Claude Code CLI.
|
|
@@ -100,11 +105,27 @@ function attribution(producer) {
|
|
|
100
105
|
* something a transcript row can show. Falls back to the tool name so a client always has something
|
|
101
106
|
* to print, which is what the protocol promises.
|
|
102
107
|
*/
|
|
103
|
-
|
|
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()) {
|
|
104
113
|
const fields = (input ?? {});
|
|
105
114
|
const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
|
|
106
115
|
const description = typeof fields.description === "string" ? fields.description : undefined;
|
|
107
|
-
|
|
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;
|
|
108
129
|
}
|
|
109
130
|
/**
|
|
110
131
|
* Whether an `Agent` tool result is a launch receipt rather than the Subagent's answer.
|
|
@@ -140,6 +161,12 @@ const DEFAULT_ALLOWED_TOOLS = [
|
|
|
140
161
|
"WebFetch",
|
|
141
162
|
"WebSearch",
|
|
142
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",
|
|
143
170
|
"NotebookEdit",
|
|
144
171
|
// How a backgrounded Bash is read and stopped. Refused until Permission Prompts existed, which
|
|
145
172
|
// was a latent bug — the tool that *started* the job was allowed. They belong here rather than
|
|
@@ -157,8 +184,13 @@ const DEFAULT_ALLOWED_TOOLS = [
|
|
|
157
184
|
// what it cannot show is what the Subagent spent, which is a different measure.
|
|
158
185
|
"Agent",
|
|
159
186
|
];
|
|
187
|
+
function readOnlyDeniedTools(readOnly) {
|
|
188
|
+
if (!readOnly)
|
|
189
|
+
return [];
|
|
190
|
+
return ["Write", "Edit", "NotebookEdit", ...(readOnly === "tools" ? ["Bash", "mcp__workflow__bash"] : [])];
|
|
191
|
+
}
|
|
160
192
|
class ClaudeSession {
|
|
161
|
-
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 };
|
|
162
194
|
inbox = new AsyncQueue();
|
|
163
195
|
emit;
|
|
164
196
|
stream;
|
|
@@ -180,6 +212,8 @@ class ClaudeSession {
|
|
|
180
212
|
announced;
|
|
181
213
|
/** Alias (`opus[1m]`) keyed by the id the SDK reports once a model is resolved. */
|
|
182
214
|
aliasOf = new Map();
|
|
215
|
+
/** The model each agent definition names, read once per session. `inherit` is left out. */
|
|
216
|
+
agentModels = new Map();
|
|
183
217
|
/** What the human asked for, kept apart from what is in force so a clamp is never destructive. */
|
|
184
218
|
wantedEffort;
|
|
185
219
|
effort;
|
|
@@ -189,6 +223,11 @@ class ClaudeSession {
|
|
|
189
223
|
subagents = new Subagents();
|
|
190
224
|
/** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
|
|
191
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();
|
|
192
231
|
enquiries = new PendingEnquiries();
|
|
193
232
|
permissions = new PendingPermissions();
|
|
194
233
|
/** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
|
|
@@ -215,15 +254,19 @@ class ClaudeSession {
|
|
|
215
254
|
priorSpend;
|
|
216
255
|
options;
|
|
217
256
|
backendOptions;
|
|
257
|
+
disallowedTools;
|
|
218
258
|
workflowAutoCompaction;
|
|
219
259
|
claudeState;
|
|
220
|
-
constructor(options, backendOptions, claudeState) {
|
|
260
|
+
constructor(options, backendOptions, claudeState, resumeAt) {
|
|
221
261
|
this.claudeState = claudeState;
|
|
222
262
|
this.parentWorkflow = options.workflowBuilder ? workflowBuilderServer(options.workflowBuilder)
|
|
223
263
|
: workflowParentServer(options.tools === "none" ? undefined : options.workflow);
|
|
224
264
|
this.parentSessions = sessionToolsServer(options.workflowBuilder || options.tools === "none" ? undefined : options.sessionTools);
|
|
225
265
|
if (options.workflowBuilder)
|
|
226
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)];
|
|
227
270
|
this.options = options;
|
|
228
271
|
this.permissionMode = options.permissionMode ?? "ask";
|
|
229
272
|
this.backendOptions = backendOptions;
|
|
@@ -239,7 +282,7 @@ class ClaudeSession {
|
|
|
239
282
|
// `BackendCreateOptions.tools`. The deny in `canUseTool` below is the half that makes it hold.
|
|
240
283
|
const builder = options.workflowBuilder;
|
|
241
284
|
const toolless = !builder && options.tools === "none";
|
|
242
|
-
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"] : [])];
|
|
243
286
|
if (!builder && !toolless && options.sessionTools)
|
|
244
287
|
preApproved.push(...claudeSessionReadTools);
|
|
245
288
|
this.allowed = new Set(toolless ? [] : [...preApproved, ...(options.standingAuthorisations ?? [])]);
|
|
@@ -250,17 +293,24 @@ class ClaudeSession {
|
|
|
250
293
|
const env = claudeAutoCompactionEnv(this.workflowAutoCompaction, claudeState.env) ?? claudeState.env;
|
|
251
294
|
const queryOptions = {
|
|
252
295
|
cwd: options.scope,
|
|
253
|
-
env,
|
|
296
|
+
env: builder ? { ...env, ENABLE_TOOL_SEARCH: "false" } : env,
|
|
254
297
|
includePartialMessages: true,
|
|
255
298
|
mcpServers: builder ? this.parentWorkflow : toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow, ...this.parentSessions },
|
|
256
299
|
// Pre-approval and native Auto can bypass canUseTool. Hooks run before either, so even
|
|
257
300
|
// read-only session tools remain parent-only when the SDK inherits MCP into Subagents.
|
|
258
|
-
...(!builder && !toolless
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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
|
+
}],
|
|
264
314
|
}] } } : {}),
|
|
265
315
|
strictMcpConfig: true,
|
|
266
316
|
// NOT bypassPermissions: it auto-approves before canUseTool is consulted, and the SDK warns
|
|
@@ -268,18 +318,20 @@ class ClaudeSession {
|
|
|
268
318
|
// set, and canUseTool catches only the fall-through so nothing can stall waiting on a prompt.
|
|
269
319
|
permissionMode: "default",
|
|
270
320
|
allowedTools: preApproved,
|
|
271
|
-
...(
|
|
321
|
+
...(this.disallowedTools.length ? { disallowedTools: this.disallowedTools } : {}),
|
|
272
322
|
...(builder ? {
|
|
273
323
|
tools: [], settingSources: [], skills: [], plugins: [], agents: {},
|
|
274
324
|
settings: { disableAllHooks: true, enabledPlugins: {}, syncClaudeAiSkills: false, syncClaudeAiPlugins: false,
|
|
275
325
|
disableClaudeAiConnectors: true, disableBundledSkills: true },
|
|
276
326
|
systemPrompt: builder.instructions,
|
|
277
|
-
} : backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {}),
|
|
327
|
+
} : { extraArgs: { "append-system-prompt": DIFF_EXCERPT_INSTRUCTIONS }, ...backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {} }),
|
|
278
328
|
...(options.modelId ? { model: options.modelId } : {}),
|
|
279
329
|
// Effort is also settable later, but starting with it avoids a first turn at the wrong level
|
|
280
330
|
// while the model list is still in flight. Levels Claude does not have wait for the clamp.
|
|
281
331
|
...(startingEffort ? { effort: startingEffort } : {}),
|
|
282
332
|
...(options.resume ? { resume: options.resume } : {}),
|
|
333
|
+
...(resumeAt ? { resumeSessionAt: resumeAt } : {}),
|
|
334
|
+
...(builder || toolless || options.readOnly ? {} : { enableFileCheckpointing: true }),
|
|
283
335
|
...(backendOptions.pathToClaudeCodeExecutable
|
|
284
336
|
? { pathToClaudeCodeExecutable: backendOptions.pathToClaudeCodeExecutable }
|
|
285
337
|
: {}),
|
|
@@ -311,6 +363,8 @@ class ClaudeSession {
|
|
|
311
363
|
if (extra.agentID && toolName.startsWith(SESSION_TOOL_PREFIX))
|
|
312
364
|
return { behavior: "deny",
|
|
313
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` };
|
|
314
368
|
if (toolName === ASK_TOOL)
|
|
315
369
|
return await this.ask(extra.toolUseID, input);
|
|
316
370
|
if (this.permissionMode === "always" || this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
@@ -326,6 +380,7 @@ class ClaudeSession {
|
|
|
326
380
|
this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
|
|
327
381
|
this.pump = this.consume();
|
|
328
382
|
this.modelsReady = this.loadModels();
|
|
383
|
+
void this.loadAgentModels();
|
|
329
384
|
// A meter that only fills once a turn ends reads as "no window" when it is really just early.
|
|
330
385
|
// Occupancy is already meaningful here: system prompt, tools and memory files are loaded
|
|
331
386
|
// before anything is sent.
|
|
@@ -357,6 +412,25 @@ class ClaudeSession {
|
|
|
357
412
|
this.noteBootedModel(this.bootedModel ?? this.modelId ?? defaultModel(models));
|
|
358
413
|
await this.reapplyEffort();
|
|
359
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
|
+
}
|
|
360
434
|
/**
|
|
361
435
|
* The init message names the model in its resolved form (`claude-sonnet-...`), but the picker
|
|
362
436
|
* lists aliases (`sonnet`). Report the alias so the id a client holds matches an entry it can
|
|
@@ -406,7 +480,15 @@ class ClaudeSession {
|
|
|
406
480
|
resumeToken() {
|
|
407
481
|
return this.sdkSessionId || undefined;
|
|
408
482
|
}
|
|
409
|
-
async
|
|
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) {
|
|
410
492
|
if (this.disposed)
|
|
411
493
|
throw new Error("Backend Session disposed");
|
|
412
494
|
this.turnId = randomUUID();
|
|
@@ -416,6 +498,7 @@ class ClaudeSession {
|
|
|
416
498
|
message: { role: "user", content: userContent(text, attachments) },
|
|
417
499
|
parent_tool_use_id: null,
|
|
418
500
|
session_id: this.sdkSessionId,
|
|
501
|
+
...(messageId ? { uuid: messageId } : {}),
|
|
419
502
|
});
|
|
420
503
|
}
|
|
421
504
|
/**
|
|
@@ -464,6 +547,11 @@ class ClaudeSession {
|
|
|
464
547
|
* That it also rescans the disk is the behaviour worth having: a human who has just written a
|
|
465
548
|
* Skill opens the menu expecting to find it.
|
|
466
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
|
+
}
|
|
467
555
|
async skills() {
|
|
468
556
|
if (this.options.workflowBuilder)
|
|
469
557
|
return [];
|
|
@@ -662,7 +750,7 @@ class ClaudeSession {
|
|
|
662
750
|
throw new Error("This Backend Session runs no tools");
|
|
663
751
|
const handle = new ClaudeWorkflowSubagent({ cwd: this.options.scope,
|
|
664
752
|
mcpServers: claudeMcpServers(this.options.mcp),
|
|
665
|
-
...(this.
|
|
753
|
+
...(this.disallowedTools.length ? { disallowedTools: this.disallowedTools } : {}),
|
|
666
754
|
...(this.backendOptions.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: this.backendOptions.pathToClaudeCodeExecutable } : {}),
|
|
667
755
|
}, options, this.workflowGrants, {
|
|
668
756
|
...(this.backendOptions.query ? { query: this.backendOptions.query } : {}),
|
|
@@ -693,6 +781,8 @@ class ClaudeSession {
|
|
|
693
781
|
// Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
|
|
694
782
|
// Session Host records that from the transcript, the way it does a torn turn.
|
|
695
783
|
this.subagents.abandon();
|
|
784
|
+
this.briefs.clear();
|
|
785
|
+
this.todoCalls.clear();
|
|
696
786
|
// Background Calls are children of that process too, and go the same way for the same reason.
|
|
697
787
|
this.calls.abandon();
|
|
698
788
|
this.inbox.close();
|
|
@@ -736,6 +826,15 @@ class ClaudeSession {
|
|
|
736
826
|
translate(sdkMessage) {
|
|
737
827
|
switch (sdkMessage.type) {
|
|
738
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
|
+
}
|
|
739
838
|
if (sdkMessage.subtype === "init") {
|
|
740
839
|
this.sdkSessionId = sdkMessage.session_id;
|
|
741
840
|
this.noteBootedModel(sdkMessage.model);
|
|
@@ -824,16 +923,28 @@ class ClaudeSession {
|
|
|
824
923
|
// guessed from that name. Recording only the names we expect to background would be the
|
|
825
924
|
// tool-name allowlist ADR 0021 refuses.
|
|
826
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 });
|
|
827
929
|
if (block.name !== SUBAGENT_TOOL)
|
|
828
930
|
continue;
|
|
829
|
-
const brief = briefOf(block.input)
|
|
830
|
-
|
|
831
|
-
|
|
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 } });
|
|
832
942
|
}
|
|
833
943
|
return;
|
|
834
944
|
}
|
|
835
945
|
case "user": {
|
|
836
946
|
const content = sdkMessage.message.content;
|
|
947
|
+
this.instructSubagent(sdkMessage);
|
|
837
948
|
if (typeof content === "string")
|
|
838
949
|
return;
|
|
839
950
|
for (const block of content) {
|
|
@@ -846,10 +957,16 @@ class ClaudeSession {
|
|
|
846
957
|
isError,
|
|
847
958
|
...attribution(producerOf(sdkMessage)),
|
|
848
959
|
});
|
|
960
|
+
this.settleTodo(block.tool_use_id, sdkMessage.tool_use_result, isError);
|
|
849
961
|
// A launch receipt, not an answer: the Subagent is only now starting work, so it gets
|
|
850
962
|
// no terminal snapshot and its card stays running. What it does give up is its hold on
|
|
851
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 });
|
|
852
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
|
+
}
|
|
853
970
|
const released = this.subagents.background(block.tool_use_id);
|
|
854
971
|
if (released)
|
|
855
972
|
this.endTurn(released);
|
|
@@ -862,6 +979,7 @@ class ClaudeSession {
|
|
|
862
979
|
type: "subagent",
|
|
863
980
|
subagentId: block.tool_use_id,
|
|
864
981
|
...brief,
|
|
982
|
+
...attribution(this.subagents.parentOf(block.tool_use_id)),
|
|
865
983
|
state: isError ? "error" : "complete",
|
|
866
984
|
});
|
|
867
985
|
}
|
|
@@ -945,7 +1063,18 @@ class ClaudeSession {
|
|
|
945
1063
|
return;
|
|
946
1064
|
this.endTurn(reason);
|
|
947
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
|
+
}
|
|
948
1076
|
closeSubagent(callId) {
|
|
1077
|
+
this.briefs.delete(callId);
|
|
949
1078
|
this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
|
|
950
1079
|
this.permissions.clearRefusals((producer) => producer === callId);
|
|
951
1080
|
const released = this.subagents.returned(callId);
|
|
@@ -1000,7 +1129,7 @@ class ClaudeSession {
|
|
|
1000
1129
|
return;
|
|
1001
1130
|
const brief = this.subagents.describe(callId);
|
|
1002
1131
|
if (brief !== undefined) {
|
|
1003
|
-
this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
|
|
1132
|
+
this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
|
|
1004
1133
|
this.closeSubagent(callId);
|
|
1005
1134
|
return;
|
|
1006
1135
|
}
|
|
@@ -1027,6 +1156,23 @@ class ClaudeSession {
|
|
|
1027
1156
|
this.turnId = randomUUID();
|
|
1028
1157
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
1029
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
|
+
}
|
|
1030
1176
|
endTurn(reason) {
|
|
1031
1177
|
const turnId = this.turnId;
|
|
1032
1178
|
/*
|
|
@@ -1041,8 +1187,8 @@ class ClaudeSession {
|
|
|
1041
1187
|
// Cleared whatever the outcome, so a held end cannot reach the turn after this one.
|
|
1042
1188
|
this.subagents.clear();
|
|
1043
1189
|
// Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
|
|
1044
|
-
// that made it, which is the whole of ADR 0021.
|
|
1045
|
-
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));
|
|
1046
1192
|
this.enquiries.clear();
|
|
1047
1193
|
if (!turnId)
|
|
1048
1194
|
return;
|
|
@@ -1064,7 +1210,11 @@ export class ClaudeBackend {
|
|
|
1064
1210
|
const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope, options.resume);
|
|
1065
1211
|
let session;
|
|
1066
1212
|
try {
|
|
1067
|
-
|
|
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);
|
|
1068
1218
|
}
|
|
1069
1219
|
catch (error) {
|
|
1070
1220
|
claudeState.cleanup();
|
|
@@ -1101,6 +1251,19 @@ export class ClaudeBackend {
|
|
|
1101
1251
|
}
|
|
1102
1252
|
}
|
|
1103
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
|
+
}
|
|
1104
1267
|
/** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
|
|
1105
1268
|
/**
|
|
1106
1269
|
* Which model id to announce for the one the SDK just named.
|
|
@@ -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
|
|
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
|
-
|
|
35
|
-
|
|
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.
|
|
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
|
|
53
|
-
if (
|
|
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,
|
|
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
|
-
|
|
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;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Agent Session's Todo List, as Claude's todo tools build it.
|
|
3
|
+
*
|
|
4
|
+
* Claude has two ways to keep one. `TodoWrite` hands over the whole list every time, so its input is
|
|
5
|
+
* already the snapshot. The `Task*` tools edit one task at a time, so their effect is folded into a
|
|
6
|
+
* list here and the whole list reported — the protocol's `plan` event is a snapshot, never a delta.
|
|
7
|
+
*
|
|
8
|
+
* Fed only the Agent Session's own model's calls, and only settled ones: a denied or failed call
|
|
9
|
+
* changed nothing, so it reports nothing. The live adapter and Import both drive this, so an imported
|
|
10
|
+
* conversation reconstructs the same list a live one showed.
|
|
11
|
+
*
|
|
12
|
+
* Deliberately free of the SDK: Import reads Claude Code's records without opening a session.
|
|
13
|
+
*/
|
|
14
|
+
/** The todo tools this reads. `TaskGet` is one too, but reading a task changes nothing. */
|
|
15
|
+
export const TODO_TOOLS = new Set(["TodoWrite", "TaskCreate", "TaskUpdate", "TaskList"]);
|
|
16
|
+
const STATUSES = new Set(["pending", "in_progress", "completed"]);
|
|
17
|
+
function statusOf(value) {
|
|
18
|
+
return typeof value === "string" && STATUSES.has(value) ? value : undefined;
|
|
19
|
+
}
|
|
20
|
+
function recordOf(value) {
|
|
21
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
22
|
+
}
|
|
23
|
+
function idOf(value) {
|
|
24
|
+
if (typeof value === "string" && value !== "")
|
|
25
|
+
return value;
|
|
26
|
+
if (typeof value === "number")
|
|
27
|
+
return String(value);
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
export class TodoList {
|
|
31
|
+
items = [];
|
|
32
|
+
/**
|
|
33
|
+
* Fold one settled todo call into the list.
|
|
34
|
+
*
|
|
35
|
+
* `input` is the call's own input and `result` the SDK's structured `tool_use_result`. Returns
|
|
36
|
+
* the whole new list when the call changed it, and undefined when it did not — including for a
|
|
37
|
+
* call that is not a todo call at all, so a caller can hand over every result it sees.
|
|
38
|
+
*/
|
|
39
|
+
settle(name, input, result, isError) {
|
|
40
|
+
if (isError || !TODO_TOOLS.has(name))
|
|
41
|
+
return undefined;
|
|
42
|
+
const next = this.apply(name, recordOf(input), recordOf(result));
|
|
43
|
+
if (next === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
const changed = !sameItems(this.items, next);
|
|
46
|
+
// Kept even when the list reads the same: a `TaskList` can bring back the ids a `TodoWrite` list
|
|
47
|
+
// never had, and the next `TaskUpdate` needs them.
|
|
48
|
+
this.items = next;
|
|
49
|
+
return changed ? this.snapshot() : undefined;
|
|
50
|
+
}
|
|
51
|
+
snapshot() {
|
|
52
|
+
return this.items.map(({ item }) => ({ ...item }));
|
|
53
|
+
}
|
|
54
|
+
apply(name, input, result) {
|
|
55
|
+
switch (name) {
|
|
56
|
+
case "TodoWrite": {
|
|
57
|
+
if (!Array.isArray(input["todos"]))
|
|
58
|
+
return undefined;
|
|
59
|
+
return input["todos"].flatMap((raw) => {
|
|
60
|
+
const todo = recordOf(raw);
|
|
61
|
+
const status = statusOf(todo["status"]);
|
|
62
|
+
// `activeForm` is the spinner's wording, not the item's; the list shows what the item is.
|
|
63
|
+
return typeof todo["content"] === "string" && status ? [{ item: { content: todo["content"], status } }] : [];
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
case "TaskCreate": {
|
|
67
|
+
const task = recordOf(result["task"]);
|
|
68
|
+
const id = idOf(task["id"]);
|
|
69
|
+
const subject = typeof task["subject"] === "string" ? task["subject"] : input["subject"];
|
|
70
|
+
if (id === undefined || typeof subject !== "string")
|
|
71
|
+
return undefined;
|
|
72
|
+
const created = { id, item: { content: subject, status: "pending" } };
|
|
73
|
+
const at = this.items.findIndex((item) => item.id === id);
|
|
74
|
+
return at < 0 ? [...this.items, created] : this.items.map((item, index) => index === at ? created : item);
|
|
75
|
+
}
|
|
76
|
+
case "TaskUpdate": {
|
|
77
|
+
if (result["success"] === false)
|
|
78
|
+
return undefined;
|
|
79
|
+
const id = idOf(input["taskId"]) ?? idOf(result["taskId"]);
|
|
80
|
+
const at = this.items.findIndex((item) => item.id !== undefined && item.id === id);
|
|
81
|
+
// A task this list never saw created — most often one from before a Revive, which a
|
|
82
|
+
// `TaskList` will bring back. Guessing where it belongs would be worse than leaving it out.
|
|
83
|
+
if (at < 0)
|
|
84
|
+
return undefined;
|
|
85
|
+
if (input["status"] === "deleted")
|
|
86
|
+
return this.items.filter((_, index) => index !== at);
|
|
87
|
+
const existing = this.items[at];
|
|
88
|
+
const status = statusOf(input["status"]) ?? existing.item.status;
|
|
89
|
+
const content = typeof input["subject"] === "string" ? input["subject"] : existing.item.content;
|
|
90
|
+
return this.items.map((item, index) => index === at ? { ...item, item: { ...item.item, content, status } } : item);
|
|
91
|
+
}
|
|
92
|
+
case "TaskList": {
|
|
93
|
+
if (!Array.isArray(result["tasks"]))
|
|
94
|
+
return undefined;
|
|
95
|
+
return result["tasks"].flatMap((raw) => {
|
|
96
|
+
const task = recordOf(raw);
|
|
97
|
+
const id = idOf(task["id"]);
|
|
98
|
+
const status = statusOf(task["status"]);
|
|
99
|
+
return id !== undefined && typeof task["subject"] === "string" && status
|
|
100
|
+
? [{ id, item: { content: task["subject"], status } }] : [];
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
default:
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** Whether two lists read the same to a human. Ids are bookkeeping, not part of the snapshot. */
|
|
109
|
+
function sameItems(left, right) {
|
|
110
|
+
return left.length === right.length && left.every(({ item }, index) => {
|
|
111
|
+
const other = right[index].item;
|
|
112
|
+
return item.content === other.content && item.status === other.status && item.priority === other.priority;
|
|
113
|
+
});
|
|
114
|
+
}
|