@nathanstephenson/flow 0.1.0
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 +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,1138 @@
|
|
|
1
|
+
import { workflowParentServer } from "./workflow-parent.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { claudeAutoCompactionEnv } from "./auto-compaction.js";
|
|
4
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
+
import { query, } from "@anthropic-ai/claude-agent-sdk";
|
|
6
|
+
import { ClaudeWorkflowSubagent, spawnWorkflowProcess } from "./workflow-subagent.js";
|
|
7
|
+
import { clampEffort } from "../effort.js";
|
|
8
|
+
import { AsyncQueue } from "./async-queue.js";
|
|
9
|
+
import { ASK_TOOL, PendingEnquiries, questionsOf } from "./enquiries.js";
|
|
10
|
+
import { claudeMcpServers, refreshClaudeMcp } from "./mcp.js";
|
|
11
|
+
import { PendingPermissions } from "./permissions.js";
|
|
12
|
+
import { StreamedMessages } from "./streamed-message.js";
|
|
13
|
+
import { Subagents } from "./subagents.js";
|
|
14
|
+
import { BackgroundCalls } from "./background-calls.js";
|
|
15
|
+
/**
|
|
16
|
+
* Locate the Claude Code CLI.
|
|
17
|
+
*
|
|
18
|
+
* The Agent SDK spawns the CLI as a child process, and a child needs a real file on disk. Normally
|
|
19
|
+
* the SDK finds it inside its own package, but a single-executable build has no node_modules to
|
|
20
|
+
* look in — so there, Claude Code is a documented prerequisite and we resolve it from PATH.
|
|
21
|
+
*/
|
|
22
|
+
export function resolveClaudeExecutable() {
|
|
23
|
+
const override = process.env["FLOW_CLAUDE_PATH"];
|
|
24
|
+
if (override)
|
|
25
|
+
return override;
|
|
26
|
+
if (!isSingleExecutable())
|
|
27
|
+
return undefined;
|
|
28
|
+
const found = spawnSync(process.platform === "win32" ? "where" : "which", ["claude"], {
|
|
29
|
+
encoding: "utf8",
|
|
30
|
+
});
|
|
31
|
+
const path = found.stdout?.split("\n")[0]?.trim();
|
|
32
|
+
if (!path) {
|
|
33
|
+
throw new Error("Claude Code was not found on PATH. A Flow binary needs it installed separately: " +
|
|
34
|
+
"npm i -g @anthropic-ai/claude-code (or set FLOW_CLAUDE_PATH).");
|
|
35
|
+
}
|
|
36
|
+
return path;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Work out what to actually execute when the SDK asks for the CLI.
|
|
40
|
+
*
|
|
41
|
+
* A JS install is run as `<node> <cli-path> ...`, using process.execPath as the interpreter. Inside
|
|
42
|
+
* a single executable, process.execPath is *this binary*, so that spawn re-invokes Flow with
|
|
43
|
+
* the CLI's arguments, argument parsing rejects them, and the exit status surfaces as "Claude Code
|
|
44
|
+
* process exited with code 1". Executing the CLI path directly sidesteps the interpreter entirely.
|
|
45
|
+
*
|
|
46
|
+
* A native install has no interpreter to get wrong: the SDK spawns the binary as the command and
|
|
47
|
+
* args[0] is a real flag. Hoisting args[0] there would execute `--output-format` as a program, and
|
|
48
|
+
* the SDK reports the resulting failure as a libc mismatch, which sends you a long way off course.
|
|
49
|
+
*/
|
|
50
|
+
export function seaSpawnTarget(options) {
|
|
51
|
+
if (options.command !== process.execPath)
|
|
52
|
+
return options;
|
|
53
|
+
const [cliPath, ...rest] = options.args;
|
|
54
|
+
if (!cliPath)
|
|
55
|
+
return options;
|
|
56
|
+
return { command: cliPath, args: rest };
|
|
57
|
+
}
|
|
58
|
+
function spawnClaudeDirectly(options) {
|
|
59
|
+
const target = seaSpawnTarget(options);
|
|
60
|
+
return spawn(target.command, target.args, {
|
|
61
|
+
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
62
|
+
env: options.env,
|
|
63
|
+
signal: options.signal,
|
|
64
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function isSingleExecutable() {
|
|
68
|
+
// getBuiltinModule works the same in ESM and in the CommonJS bundle a SEA build produces.
|
|
69
|
+
const sea = process.getBuiltinModule?.("node:sea");
|
|
70
|
+
return sea?.isSea?.() ?? false;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The tool whose call spawns a Subagent, and whose result returns it.
|
|
74
|
+
*
|
|
75
|
+
* `Agent`, not `Task`: the CLI emits `tool_use` with name `Agent`, and the subagent's own tool calls
|
|
76
|
+
* carry that call's id as their `parent_tool_use_id`.
|
|
77
|
+
*/
|
|
78
|
+
const SUBAGENT_TOOL = "Agent";
|
|
79
|
+
/**
|
|
80
|
+
* Who produced an SDK message: the callId of the spawning tool call, or `""` for the Agent Session's
|
|
81
|
+
* own model. A string rather than `string | undefined` so it can key a Map without a sentinel.
|
|
82
|
+
*/
|
|
83
|
+
function producerOf(sdkMessage) {
|
|
84
|
+
return sdkMessage.parent_tool_use_id ?? "";
|
|
85
|
+
}
|
|
86
|
+
/** Spread onto an event, so an unattributed one carries no explicit `producer: undefined`. */
|
|
87
|
+
function attribution(producer) {
|
|
88
|
+
return producer === "" ? {} : { producer: { subagentId: producer } };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* What a Subagent is called and was asked to do, read off the spawning tool call.
|
|
92
|
+
*
|
|
93
|
+
* `subagent_type` is the subagent's declared identity (`Explore`) and `description` the one-line
|
|
94
|
+
* brief; the full `prompt` is deliberately not carried, being the whole instruction rather than
|
|
95
|
+
* something a transcript row can show. Falls back to the tool name so a client always has something
|
|
96
|
+
* to print, which is what the protocol promises.
|
|
97
|
+
*/
|
|
98
|
+
export function briefOf(input) {
|
|
99
|
+
const fields = (input ?? {});
|
|
100
|
+
const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
|
|
101
|
+
const description = typeof fields.description === "string" ? fields.description : undefined;
|
|
102
|
+
return description === undefined ? { name } : { name, description };
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Whether an `Agent` tool result is a launch receipt rather than the Subagent's answer.
|
|
106
|
+
*
|
|
107
|
+
* A backgrounded agent — which the SDK documents as the default — returns its `tool_result` at
|
|
108
|
+
* once, carrying an id and an output file instead of a report. Read from `tool_use_result`, the
|
|
109
|
+
* structured `AgentOutput` the SDK asks callers to render from, rather than sniffed out of the
|
|
110
|
+
* result text, which is prose written for the model and free to change.
|
|
111
|
+
*
|
|
112
|
+
* `remote_launched` counts too: it is the same promise about a different machine.
|
|
113
|
+
*/
|
|
114
|
+
export function isAsyncLaunch(result) {
|
|
115
|
+
const status = result?.status;
|
|
116
|
+
return status === "async_launched" || status === "remote_launched";
|
|
117
|
+
}
|
|
118
|
+
/** How a settled task reports itself, in the three words a Subagent and a turn already share. */
|
|
119
|
+
function outcomeOf(status) {
|
|
120
|
+
if (status === "completed")
|
|
121
|
+
return "complete";
|
|
122
|
+
if (status === "failed")
|
|
123
|
+
return "error";
|
|
124
|
+
if (status === "stopped" || status === "killed")
|
|
125
|
+
return "aborted";
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const DEFAULT_ALLOWED_TOOLS = [
|
|
129
|
+
"Read",
|
|
130
|
+
"Write",
|
|
131
|
+
"Edit",
|
|
132
|
+
"Bash",
|
|
133
|
+
"Glob",
|
|
134
|
+
"Grep",
|
|
135
|
+
"WebFetch",
|
|
136
|
+
"WebSearch",
|
|
137
|
+
"TodoWrite",
|
|
138
|
+
"NotebookEdit",
|
|
139
|
+
// How a backgrounded Bash is read and stopped. Refused until Permission Prompts existed, which
|
|
140
|
+
// was a latent bug — the tool that *started* the job was allowed. They belong here rather than
|
|
141
|
+
// behind a prompt: a poll of a job the human already authorised is not a decision, and asking on
|
|
142
|
+
// every poll would make the most benign pair in the set the loudest.
|
|
143
|
+
"BashOutput",
|
|
144
|
+
"KillShell",
|
|
145
|
+
// Without this a session that reaches plan mode can never leave it: the deny message ends
|
|
146
|
+
// "Continue without it", so the model proceeds read-only instead of surfacing the refusal, and
|
|
147
|
+
// every edit for the rest of the session fails for a reason it cannot name.
|
|
148
|
+
"ExitPlanMode",
|
|
149
|
+
"Skill",
|
|
150
|
+
// Spawns a Subagent. A Subagent's own conversation never enters this session's Conversation
|
|
151
|
+
// Context — only the call and the summary it returns do — so the context meter stays accurate;
|
|
152
|
+
// what it cannot show is what the Subagent spent, which is a different measure.
|
|
153
|
+
"Agent",
|
|
154
|
+
];
|
|
155
|
+
class ClaudeSession {
|
|
156
|
+
capabilities = { providers: ["anthropic"], models: [], compaction: true, autoCompaction: "startup", fork: true, subagents: true, enquiries: true, permissions: true };
|
|
157
|
+
inbox = new AsyncQueue();
|
|
158
|
+
emit;
|
|
159
|
+
stream;
|
|
160
|
+
pump;
|
|
161
|
+
sdkSessionId = "";
|
|
162
|
+
turnId;
|
|
163
|
+
/** Set between asking the CLI for a compaction and the `result` that closes it. See `compact`. */
|
|
164
|
+
compacting = false;
|
|
165
|
+
disposed = false;
|
|
166
|
+
workflowSubagents = new Set();
|
|
167
|
+
parentWorkflow;
|
|
168
|
+
workflowGrants;
|
|
169
|
+
disposal;
|
|
170
|
+
modelId;
|
|
171
|
+
bootedModel;
|
|
172
|
+
/** The last model id reported to clients, so the model in force is announced exactly once. */
|
|
173
|
+
announced;
|
|
174
|
+
/** Alias (`opus[1m]`) keyed by the id the SDK reports once a model is resolved. */
|
|
175
|
+
aliasOf = new Map();
|
|
176
|
+
/** What the human asked for, kept apart from what is in force so a clamp is never destructive. */
|
|
177
|
+
wantedEffort;
|
|
178
|
+
effort;
|
|
179
|
+
/** The assistant message in flight, per producer. See StreamedMessages for why it is not one. */
|
|
180
|
+
streamed = new StreamedMessages();
|
|
181
|
+
/** Subagents open in this turn, and any turn end waiting on them. */
|
|
182
|
+
subagents = new Subagents();
|
|
183
|
+
/** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
|
|
184
|
+
calls = new BackgroundCalls();
|
|
185
|
+
enquiries = new PendingEnquiries();
|
|
186
|
+
permissions = new PendingPermissions();
|
|
187
|
+
/**
|
|
188
|
+
* What runs without being asked about: the pre-approved set, plus the Standing Authorisations this
|
|
189
|
+
* Backend Session was created with.
|
|
190
|
+
*
|
|
191
|
+
* An instance field rather than the local the callback used to close over, because an Always
|
|
192
|
+
* decision has to change what the callback consults — otherwise the grant would be persisted, the
|
|
193
|
+
* next session would honour it, and *this* one would go on asking about a tool the human had just
|
|
194
|
+
* authorised for the machine.
|
|
195
|
+
*/
|
|
196
|
+
allowed;
|
|
197
|
+
/**
|
|
198
|
+
* Everything this Agent Session has spent, across every model and every Backend Session.
|
|
199
|
+
*
|
|
200
|
+
* Seeded from what it had spent before this one opened, because `modelUsage` counts only this
|
|
201
|
+
* `query()` run: on a Revive its counters start at zero, and reporting that alone would read as
|
|
202
|
+
* the bill resetting itself.
|
|
203
|
+
*/
|
|
204
|
+
spend;
|
|
205
|
+
priorSpend;
|
|
206
|
+
options;
|
|
207
|
+
backendOptions;
|
|
208
|
+
workflowAutoCompaction;
|
|
209
|
+
constructor(options, backendOptions) {
|
|
210
|
+
this.parentWorkflow = workflowParentServer(options.tools === "none" ? undefined : options.workflow);
|
|
211
|
+
this.options = options;
|
|
212
|
+
this.backendOptions = backendOptions;
|
|
213
|
+
this.workflowAutoCompaction = structuredClone(options.autoCompaction ?? {});
|
|
214
|
+
this.emit = options.emit;
|
|
215
|
+
this.workflowGrants = new Set(options.standingAuthorisations ?? []);
|
|
216
|
+
this.modelId = options.modelId;
|
|
217
|
+
this.wantedEffort = options.effort;
|
|
218
|
+
this.priorSpend = options.priorSpend;
|
|
219
|
+
// Reported before this run has billed anything, so a Revive does not blank the meter it inherits.
|
|
220
|
+
this.spend = options.priorSpend;
|
|
221
|
+
// A one-shot text call pre-approves nothing and authorises nothing — see
|
|
222
|
+
// `BackendCreateOptions.tools`. The deny in `canUseTool` below is the half that makes it hold.
|
|
223
|
+
const toolless = options.tools === "none";
|
|
224
|
+
const preApproved = 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"] : [])];
|
|
225
|
+
this.allowed = new Set(toolless ? [] : [...preApproved, ...(options.standingAuthorisations ?? [])]);
|
|
226
|
+
// `allowedTools` is what the CLI auto-approves before the callback, and it is given only the
|
|
227
|
+
// pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
|
|
228
|
+
// `disallowedTools` — which an operator meant — still outranks a grant a human clicked.
|
|
229
|
+
const startingEffort = sdkEffort(options.effort);
|
|
230
|
+
const env = claudeAutoCompactionEnv(options.modelId ? this.workflowAutoCompaction[options.modelId] : undefined);
|
|
231
|
+
const queryOptions = {
|
|
232
|
+
cwd: options.scope,
|
|
233
|
+
...(env ? { env } : {}),
|
|
234
|
+
includePartialMessages: true,
|
|
235
|
+
mcpServers: toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
|
|
236
|
+
strictMcpConfig: true,
|
|
237
|
+
// NOT bypassPermissions: it auto-approves before canUseTool is consulted, and the SDK warns
|
|
238
|
+
// as much. "default" runs the permission flow, allowedTools auto-approves the pre-approved
|
|
239
|
+
// set, and canUseTool catches only the fall-through so nothing can stall waiting on a prompt.
|
|
240
|
+
permissionMode: "default",
|
|
241
|
+
allowedTools: preApproved,
|
|
242
|
+
...(backendOptions.disallowedTools ? { disallowedTools: backendOptions.disallowedTools } : {}),
|
|
243
|
+
...(backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {}),
|
|
244
|
+
...(options.modelId ? { model: options.modelId } : {}),
|
|
245
|
+
// Effort is also settable later, but starting with it avoids a first turn at the wrong level
|
|
246
|
+
// while the model list is still in flight. Levels Claude does not have wait for the clamp.
|
|
247
|
+
...(startingEffort ? { effort: startingEffort } : {}),
|
|
248
|
+
...(options.resume ? { resume: options.resume } : {}),
|
|
249
|
+
...(backendOptions.pathToClaudeCodeExecutable
|
|
250
|
+
? { pathToClaudeCodeExecutable: backendOptions.pathToClaudeCodeExecutable }
|
|
251
|
+
: {}),
|
|
252
|
+
...(isSingleExecutable() ? { spawnClaudeCodeProcess: spawnClaudeDirectly } : {}),
|
|
253
|
+
/*
|
|
254
|
+
* The fall-through, and the whole of how a human is asked anything.
|
|
255
|
+
*
|
|
256
|
+
* `AskUserQuestion` is deliberately absent from the pre-approved set: an allowlisted tool is
|
|
257
|
+
* approved before this runs, so putting it there would answer the model's question with
|
|
258
|
+
* silence. It reaches here instead, and so does every tool nobody has authorised.
|
|
259
|
+
*
|
|
260
|
+
* Both cases *park* the callback rather than answering it, which is the whole of what this
|
|
261
|
+
* adapter does differently from one that pre-approves everything — and the whole of its risk.
|
|
262
|
+
* What settles them is a human, through `answerEnquiry` or `answerPermission`; on every path
|
|
263
|
+
* where there will never be one, an abandonment.
|
|
264
|
+
*/
|
|
265
|
+
canUseTool: async (toolName, input, extra) => {
|
|
266
|
+
// Denied, never parked. There is no human behind a toolless session, so parking would hold
|
|
267
|
+
// the turn open until the caller gave up on it.
|
|
268
|
+
if (toolless)
|
|
269
|
+
return { behavior: "deny", message: "This session runs no tools" };
|
|
270
|
+
if (toolName === ASK_TOOL)
|
|
271
|
+
return await this.ask(extra.toolUseID, input);
|
|
272
|
+
if (this.allowed.has(toolName) || this.workflowGrants.has(toolName))
|
|
273
|
+
return { behavior: "allow", updatedInput: input };
|
|
274
|
+
return await this.authorise(extra.toolUseID, toolName, input);
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
|
|
278
|
+
this.pump = this.consume();
|
|
279
|
+
void this.loadModels();
|
|
280
|
+
// A meter that only fills once a turn ends reads as "no window" when it is really just early.
|
|
281
|
+
// Occupancy is already meaningful here: system prompt, tools and memory files are loaded
|
|
282
|
+
// before anything is sent.
|
|
283
|
+
void this.reportContextUsage();
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Ask the CLI what models this account can actually reach.
|
|
287
|
+
*
|
|
288
|
+
* The init message only names the model the session booted with, which made the picker a list of
|
|
289
|
+
* one. `supportedModels()` is a control request rather than part of the message stream, so it
|
|
290
|
+
* answers before the first prompt — the session advertises the real list from the start.
|
|
291
|
+
*/
|
|
292
|
+
async loadModels() {
|
|
293
|
+
let models;
|
|
294
|
+
try {
|
|
295
|
+
models = await this.stream.supportedModels();
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
this.emit({ type: "notice", level: "warn", text: `Could not list models: ${message(error)}` });
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (this.disposed)
|
|
302
|
+
return;
|
|
303
|
+
this.aliasOf = new Map(models.filter((model) => model.resolvedModel).map((model) => [model.resolvedModel ?? "", model.value]));
|
|
304
|
+
this.capabilities = { ...this.capabilities, models: models.map(describeModel) };
|
|
305
|
+
this.emit({ type: "capabilities_changed", capabilities: this.capabilities });
|
|
306
|
+
// Which model is in force decides which effort levels a client may offer, so say it now
|
|
307
|
+
// rather than waiting for the init message that only arrives with the first turn.
|
|
308
|
+
this.noteBootedModel(this.bootedModel ?? this.modelId ?? defaultModel(models));
|
|
309
|
+
await this.reapplyEffort();
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* The init message names the model in its resolved form (`claude-sonnet-...`), but the picker
|
|
313
|
+
* lists aliases (`sonnet`). Report the alias so the id a client holds matches an entry it can
|
|
314
|
+
* offer; before the list has arrived there is nothing to match against, and the raw id stands
|
|
315
|
+
* until loadModels comes back and corrects it.
|
|
316
|
+
*/
|
|
317
|
+
noteBootedModel(booted) {
|
|
318
|
+
if (!booted)
|
|
319
|
+
return;
|
|
320
|
+
this.bootedModel = booted;
|
|
321
|
+
// An id `capabilities.models` cannot describe costs the label *and* the Effort levels, so it must
|
|
322
|
+
// never displace one the list can describe. With nothing announced yet there is nothing to
|
|
323
|
+
// protect and the raw id still beats silence.
|
|
324
|
+
this.announceModel(modelInForce(booted, this.aliasOf, this.capabilities.models) ?? this.announced ?? booted);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* The effort the SDK says it is actually running at.
|
|
328
|
+
*
|
|
329
|
+
* This is the *only* place Claude reports it — `initializationResult()` does not carry it, and
|
|
330
|
+
* `supportedModels()` describes which levels exist rather than which is in force. So a session
|
|
331
|
+
* nobody has set an effort on stays unreported until its first turn brings this message, which is
|
|
332
|
+
* why `EffortPicker` has a placeholder to fall back to rather than a value.
|
|
333
|
+
*
|
|
334
|
+
* `null` means the model has no effort control, which is a state rather than a failure: haiku
|
|
335
|
+
* reports it, clients hide the control for such a model, and a level left on file in
|
|
336
|
+
* `wantedEffort` is restored by `reapplyEffort` on the way back to a model that has one.
|
|
337
|
+
*
|
|
338
|
+
* Announced only on a difference, so a turn that changed nothing says nothing — and taken as the
|
|
339
|
+
* truth when it disagrees with what we asked for, because the SDK clamps and this is it telling
|
|
340
|
+
* us what it settled on.
|
|
341
|
+
*/
|
|
342
|
+
noteBootedEffort(booted) {
|
|
343
|
+
if (booted === undefined || booted === null)
|
|
344
|
+
return;
|
|
345
|
+
if (booted === this.effort)
|
|
346
|
+
return;
|
|
347
|
+
this.effort = booted;
|
|
348
|
+
this.emit({ type: "effort_changed", effort: booted });
|
|
349
|
+
}
|
|
350
|
+
announceModel(modelId) {
|
|
351
|
+
if (modelId === this.announced)
|
|
352
|
+
return;
|
|
353
|
+
this.announced = modelId;
|
|
354
|
+
this.modelId = modelId;
|
|
355
|
+
this.emit({ type: "model_changed", model: this.modelInfo(modelId) });
|
|
356
|
+
}
|
|
357
|
+
resumeToken() {
|
|
358
|
+
return this.sdkSessionId || undefined;
|
|
359
|
+
}
|
|
360
|
+
async prompt(text, attachments) {
|
|
361
|
+
if (this.disposed)
|
|
362
|
+
throw new Error("Backend Session disposed");
|
|
363
|
+
this.turnId = randomUUID();
|
|
364
|
+
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
365
|
+
this.inbox.push({
|
|
366
|
+
type: "user",
|
|
367
|
+
message: { role: "user", content: userContent(text, attachments) },
|
|
368
|
+
parent_tool_use_id: null,
|
|
369
|
+
session_id: this.sdkSessionId,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* The SDK exposes no `compact()`. Slash commands are dispatched by the CLI out of the prompt
|
|
374
|
+
* channel itself — verified in `spikes/slash-dispatch.ts`, where `/compact` came back with
|
|
375
|
+
* `turns=0 input_tokens=0` and no credential ever checked — so this is the same shape as
|
|
376
|
+
* `applyEffort` above: the SDK has no method, and the wire format lives in one place.
|
|
377
|
+
*
|
|
378
|
+
* **A compaction is a turn.** It was not, on the reasoning that a local command is not billed and
|
|
379
|
+
* that a turn here would leave the Steering Queue believing the session was busy. Both halves were
|
|
380
|
+
* wrong, and one session's transcript showed it: summarising is a model call, so it billed $3.85,
|
|
381
|
+
* and it held the session for three minutes — during which the queue's belief that nothing was
|
|
382
|
+
* running was the false one. Everything downstream follows from saying so: a second compaction is
|
|
383
|
+
* refused by the guard the host already has, a message typed meanwhile is queued in order rather
|
|
384
|
+
* than pushed into this inbox ahead of the compaction, and three minutes of work becomes
|
|
385
|
+
* abortable.
|
|
386
|
+
*
|
|
387
|
+
* `compacting` is what keeps the CLI's reply out of the transcript as an assistant message, which
|
|
388
|
+
* is how it arrives — "Not enough messages to compact." would otherwise be attributed to the
|
|
389
|
+
* model. Cleared on the `result` that closes the command, in every outcome.
|
|
390
|
+
*/
|
|
391
|
+
async compact(instructions) {
|
|
392
|
+
if (this.disposed)
|
|
393
|
+
throw new Error("Backend Session disposed");
|
|
394
|
+
this.compacting = true;
|
|
395
|
+
this.turnId = randomUUID();
|
|
396
|
+
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
397
|
+
// Said before the CLI has been asked, because the whole point is that summarising takes a model
|
|
398
|
+
// call: someone who sees nothing for ten seconds asks again.
|
|
399
|
+
this.emit({ type: "compacting", active: true });
|
|
400
|
+
this.inbox.push({
|
|
401
|
+
type: "user",
|
|
402
|
+
message: { role: "user", content: instructions ? `/compact ${instructions}` : "/compact" },
|
|
403
|
+
parent_tool_use_id: null,
|
|
404
|
+
session_id: this.sdkSessionId,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* `reloadSkills` and not `supportedCommands`, though the second is the one that sounds right.
|
|
409
|
+
*
|
|
410
|
+
* `supportedCommands()` returns everything the CLI knows — 52 of them in this repo — with no field
|
|
411
|
+
* distinguishing a Skill from a built-in, so telling `/tdd` from `/heapdump` would mean a denylist
|
|
412
|
+
* of names that rots on the next CLI release. `reloadSkills()` returns the 18 that are actually
|
|
413
|
+
* Skills, which is the question being asked.
|
|
414
|
+
*
|
|
415
|
+
* That it also rescans the disk is the behaviour worth having: a human who has just written a
|
|
416
|
+
* Skill opens the menu expecting to find it.
|
|
417
|
+
*/
|
|
418
|
+
async skills() {
|
|
419
|
+
const { skills } = await this.stream.reloadSkills();
|
|
420
|
+
return skills.map((skill) => ({
|
|
421
|
+
name: skill.name,
|
|
422
|
+
description: skill.description,
|
|
423
|
+
...(skill.argumentHint ? { argumentHint: skill.argumentHint } : {}),
|
|
424
|
+
}));
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Hold the permission callback for an `AskUserQuestion` call until a human answers it.
|
|
428
|
+
*
|
|
429
|
+
* The returned promise is the turn: the SDK does not continue until it settles, so nothing here
|
|
430
|
+
* may throw and no path may drop it. `spikes/ask-user-question.ts` established that the assistant
|
|
431
|
+
* message carrying the `tool_use` block arrives *before* this does, so the `tool` Entry for
|
|
432
|
+
* `askId` is already in the Presentation Transcript by the time the snapshot below joins it.
|
|
433
|
+
*
|
|
434
|
+
* A call posing no readable Question is denied rather than parked, because a picker with nothing
|
|
435
|
+
* in it is a turn blocked on a box a human cannot answer.
|
|
436
|
+
*/
|
|
437
|
+
async ask(askId, input) {
|
|
438
|
+
const questions = questionsOf(input);
|
|
439
|
+
if (questions.length === 0) {
|
|
440
|
+
return { behavior: "deny", message: `${ASK_TOOL} was called with no question. Continue without it.` };
|
|
441
|
+
}
|
|
442
|
+
return await new Promise((resolve) => {
|
|
443
|
+
this.enquiries.hold(askId, questions, input, resolve);
|
|
444
|
+
this.emit({ type: "enquiry", askId, questions, state: "asked" });
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
async answerEnquiry(askId, answers) {
|
|
448
|
+
const questions = this.enquiries.describe(askId);
|
|
449
|
+
if (!questions || !this.enquiries.answer(askId, answers))
|
|
450
|
+
return false;
|
|
451
|
+
this.emit({ type: "enquiry", askId, questions, state: "answered", answers });
|
|
452
|
+
return true;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Settle every open Enquiry as unanswered, and say so in the transcript.
|
|
456
|
+
*
|
|
457
|
+
* Called from every path that ends a turn or a Backend Session. Denying rather than dropping is
|
|
458
|
+
* what leaves the CLI's own conversation record complete — a real `tool_result` against the right
|
|
459
|
+
* id — so a later Revive resumes onto a turn with no dangling `tool_use`.
|
|
460
|
+
*/
|
|
461
|
+
abandonEnquiries(why) {
|
|
462
|
+
for (const { askId, questions } of this.enquiries.abandonAll(why)) {
|
|
463
|
+
this.emit({ type: "enquiry", askId, questions, state: "aborted" });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Hold the permission callback for a tool nobody has authorised until a human decides.
|
|
468
|
+
*
|
|
469
|
+
* The returned promise is the turn: the SDK does not continue until it settles, so nothing here may
|
|
470
|
+
* throw and no path may drop it. Deliberately has no timeout, the rule ADR 0016 set for an Enquiry
|
|
471
|
+
* — a timer that gave up on a prompt someone was still reading would be worse than one that waits,
|
|
472
|
+
* and Abort is the escape.
|
|
473
|
+
*
|
|
474
|
+
* A tool already refused this turn is answered here rather than asked about again, with the
|
|
475
|
+
* adapter's own neutral message. That is not a shortcut: a model that wanted a tool wants it
|
|
476
|
+
* several times, and re-asking the moment someone says no pins the composer on the same question
|
|
477
|
+
* while the model rephrases around it.
|
|
478
|
+
*/
|
|
479
|
+
async authorise(callId, tool, input) {
|
|
480
|
+
if (this.permissions.isRefused(tool)) {
|
|
481
|
+
return { behavior: "deny", message: `${tool} is not enabled for this session. Continue without it.` };
|
|
482
|
+
}
|
|
483
|
+
return await new Promise((resolve) => {
|
|
484
|
+
this.permissions.hold(callId, tool, input, resolve);
|
|
485
|
+
this.emit({ type: "permission", callId, tool, state: "asked" });
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
async answerPermission(callId, decision) {
|
|
489
|
+
const tool = this.permissions.describe(callId);
|
|
490
|
+
if (tool === undefined || !this.permissions.decide(callId, decision))
|
|
491
|
+
return false;
|
|
492
|
+
// Before the snapshot, so nothing can observe a decided Always against a session still asking.
|
|
493
|
+
// The Standing Authorisation itself is the host's to persist; this is only this session honouring
|
|
494
|
+
// it, which it must do itself because the list it was created with is a snapshot.
|
|
495
|
+
if (decision === "always") {
|
|
496
|
+
this.allowed.add(tool);
|
|
497
|
+
this.workflowGrants.add(tool);
|
|
498
|
+
}
|
|
499
|
+
this.emit({ type: "permission", callId, tool, state: "decided", decision });
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Settle every open Permission Prompt as unauthorised, and say so in the transcript.
|
|
504
|
+
*
|
|
505
|
+
* Called from every path that ends a turn or a Backend Session, for the reason `abandonEnquiries`
|
|
506
|
+
* is: denying rather than dropping leaves the CLI's own conversation record complete, so a later
|
|
507
|
+
* Revive resumes onto a turn with no dangling `tool_use`.
|
|
508
|
+
*/
|
|
509
|
+
abandonPermissions(why) {
|
|
510
|
+
for (const { callId, tool } of this.permissions.abandonAll(why)) {
|
|
511
|
+
this.emit({ type: "permission", callId, tool, state: "aborted" });
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async abort() {
|
|
515
|
+
// Before the interrupt, not after: the CLI is blocked on this callback, and an interrupt that
|
|
516
|
+
// waits on the outstanding permission request would be waiting on something only this releases.
|
|
517
|
+
this.abandonEnquiries("the turn was aborted");
|
|
518
|
+
this.abandonPermissions("the turn was aborted");
|
|
519
|
+
try {
|
|
520
|
+
await this.stream.interrupt();
|
|
521
|
+
}
|
|
522
|
+
catch (error) {
|
|
523
|
+
this.emit({ type: "notice", level: "warn", text: `Interrupt failed: ${message(error)}` });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async setModel(modelId) {
|
|
527
|
+
await this.stream.setModel(modelId);
|
|
528
|
+
this.announceModel(modelId);
|
|
529
|
+
await this.reapplyEffort();
|
|
530
|
+
}
|
|
531
|
+
async setEffort(effort) {
|
|
532
|
+
this.wantedEffort = effort;
|
|
533
|
+
await this.applyEffort(effort);
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* The SDK has no setEffort(): `effortLevel` is a settings key, and applyFlagSettings is how a
|
|
537
|
+
* live session is told about one. It is the same key the CLI's own effort control writes.
|
|
538
|
+
*/
|
|
539
|
+
async applyEffort(wanted) {
|
|
540
|
+
const level = clampEffort(wanted, this.modelInfo(this.modelId).effortLevels);
|
|
541
|
+
// A model with no effort control (haiku) leaves the request on file, unapplied: clients hide
|
|
542
|
+
// the control for such a model, and switching back to one that has it restores the choice.
|
|
543
|
+
const effortLevel = sdkEffort(level);
|
|
544
|
+
if (!effortLevel) {
|
|
545
|
+
this.effort = undefined;
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
try {
|
|
549
|
+
await this.stream.applyFlagSettings({ effortLevel });
|
|
550
|
+
}
|
|
551
|
+
catch (error) {
|
|
552
|
+
this.emit({ type: "notice", level: "warn", text: `Could not set effort: ${message(error)}` });
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
this.effort = effortLevel;
|
|
556
|
+
this.emit({ type: "effort_changed", effort: effortLevel });
|
|
557
|
+
}
|
|
558
|
+
/** After a model change, only re-apply when the new model forces a different level. */
|
|
559
|
+
async reapplyEffort() {
|
|
560
|
+
if (!this.wantedEffort)
|
|
561
|
+
return;
|
|
562
|
+
if (clampEffort(this.wantedEffort, this.modelInfo(this.modelId).effortLevels) === this.effort)
|
|
563
|
+
return;
|
|
564
|
+
await this.applyEffort(this.wantedEffort);
|
|
565
|
+
}
|
|
566
|
+
modelInfo(modelId) {
|
|
567
|
+
const known = this.capabilities.models.find((model) => model.id === modelId);
|
|
568
|
+
return known ?? { id: modelId ?? "default", provider: "anthropic" };
|
|
569
|
+
}
|
|
570
|
+
async refreshMcp() {
|
|
571
|
+
await refreshClaudeMcp(this.stream, this.options.mcp, this.parentWorkflow);
|
|
572
|
+
}
|
|
573
|
+
startWorkflowSubagent(options) {
|
|
574
|
+
if (this.disposed)
|
|
575
|
+
throw new Error("Backend Session disposed");
|
|
576
|
+
if (this.options.tools === "none")
|
|
577
|
+
throw new Error("This Backend Session runs no tools");
|
|
578
|
+
const handle = new ClaudeWorkflowSubagent({ cwd: this.options.scope,
|
|
579
|
+
mcpServers: claudeMcpServers(this.options.mcp),
|
|
580
|
+
...(this.backendOptions.disallowedTools ? { disallowedTools: this.backendOptions.disallowedTools } : {}),
|
|
581
|
+
...(this.backendOptions.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: this.backendOptions.pathToClaudeCodeExecutable } : {}),
|
|
582
|
+
}, options, this.workflowGrants, {
|
|
583
|
+
...(this.backendOptions.query ? { query: this.backendOptions.query } : {}),
|
|
584
|
+
spawn: (options) => spawnWorkflowProcess(isSingleExecutable() ? { ...options, ...seaSpawnTarget(options) } : options),
|
|
585
|
+
}, this.workflowAutoCompaction);
|
|
586
|
+
this.workflowSubagents.add(handle);
|
|
587
|
+
void handle.done.finally(() => this.workflowSubagents.delete(handle)).catch(() => { });
|
|
588
|
+
return handle;
|
|
589
|
+
}
|
|
590
|
+
dispose() {
|
|
591
|
+
return this.disposal ??= this.stop();
|
|
592
|
+
}
|
|
593
|
+
async stop() {
|
|
594
|
+
this.disposed = true;
|
|
595
|
+
const workflowsStopped = Promise.all([...this.workflowSubagents].map((handle) => handle.cancel()));
|
|
596
|
+
// Before the stream closes, while there is still something to deny into. A callback dropped by
|
|
597
|
+
// the teardown leaves an unterminated tool call in the CLI's record, and the Agent Session this
|
|
598
|
+
// belongs to is going Dormant — so that record is exactly what the next Revive resumes onto.
|
|
599
|
+
this.abandonEnquiries("the session stopped");
|
|
600
|
+
this.abandonPermissions("the session stopped");
|
|
601
|
+
// Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
|
|
602
|
+
// Session Host records that from the transcript, the way it does a torn turn.
|
|
603
|
+
this.subagents.abandon();
|
|
604
|
+
// Background Calls are children of that process too, and go the same way for the same reason.
|
|
605
|
+
this.calls.abandon();
|
|
606
|
+
this.inbox.close();
|
|
607
|
+
try {
|
|
608
|
+
await this.stream.close();
|
|
609
|
+
}
|
|
610
|
+
catch {
|
|
611
|
+
// Closing a stream that already ended is not an error worth surfacing.
|
|
612
|
+
}
|
|
613
|
+
await this.pump.catch(() => undefined);
|
|
614
|
+
await workflowsStopped;
|
|
615
|
+
}
|
|
616
|
+
async consume() {
|
|
617
|
+
try {
|
|
618
|
+
for await (const sdkMessage of this.stream) {
|
|
619
|
+
this.translate(sdkMessage);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
catch (error) {
|
|
623
|
+
if (!this.disposed) {
|
|
624
|
+
// A stream that has failed will never deliver the `result` that would clear this, and a
|
|
625
|
+
// session left suppressing would silently drop every assistant message after it.
|
|
626
|
+
this.compacting = false;
|
|
627
|
+
this.emit({ type: "compacting", active: false });
|
|
628
|
+
// Same argument as the line above, for the other thing a dead stream will never deliver:
|
|
629
|
+
// nothing is coming back to answer an open Enquiry, and a picker left on screen over a
|
|
630
|
+
// session that has stopped is a question the human can answer into nothing.
|
|
631
|
+
this.abandonEnquiries("the session failed");
|
|
632
|
+
this.abandonPermissions("the session failed");
|
|
633
|
+
this.emit({ type: "notice", level: "error", text: message(error) });
|
|
634
|
+
this.endTurn("error");
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
translate(sdkMessage) {
|
|
639
|
+
switch (sdkMessage.type) {
|
|
640
|
+
case "system":
|
|
641
|
+
if (sdkMessage.subtype === "init") {
|
|
642
|
+
this.sdkSessionId = sdkMessage.session_id;
|
|
643
|
+
this.noteBootedModel(sdkMessage.model);
|
|
644
|
+
this.noteBootedEffort(sdkMessage.effort);
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (sdkMessage.subtype === "compact_boundary") {
|
|
648
|
+
this.emit(describeCompaction(sdkMessage.compact_metadata));
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
/*
|
|
652
|
+
* The only message carrying both ids, and so two things at once: the chance to learn which
|
|
653
|
+
* Subagent a later notification is about, and — for a call that is not a Subagent's — the
|
|
654
|
+
* signal that the CLI is running it in the background (ADR 0021).
|
|
655
|
+
*
|
|
656
|
+
* This is the whole of the Background Call detector, and it reads no tool-specific field.
|
|
657
|
+
* The launch receipt cannot serve: `spikes/background-call-messages.ts` captured a
|
|
658
|
+
* backgrounded `Bash` answering `{ backgroundTaskId }` and a `Monitor` answering
|
|
659
|
+
* `{ taskId }`, neither with the `status` `isAsyncLaunch` looks for, so reading the receipt
|
|
660
|
+
* would mean knowing every tool's own spelling.
|
|
661
|
+
*/
|
|
662
|
+
if (sdkMessage.subtype === "task_started") {
|
|
663
|
+
const callId = sdkMessage.tool_use_id;
|
|
664
|
+
if (!callId)
|
|
665
|
+
return;
|
|
666
|
+
// One or the other, never both, on the same predicate `settleTask` routes on — so a task
|
|
667
|
+
// id lives in exactly one map and a `task_updated` carrying nothing else cannot be
|
|
668
|
+
// routed to the wrong lifecycle.
|
|
669
|
+
if (this.subagents.describe(callId) !== undefined)
|
|
670
|
+
this.subagents.noteTask(sdkMessage.task_id, callId);
|
|
671
|
+
else
|
|
672
|
+
this.openBackgroundCall(sdkMessage.task_id, callId);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
// What actually closes a detached Subagent. `tool_use_id` where the SDK supplies it, the
|
|
676
|
+
// task map where it does not.
|
|
677
|
+
if (sdkMessage.subtype === "task_notification") {
|
|
678
|
+
this.settleTask(sdkMessage.task_id, sdkMessage.tool_use_id, outcomeOf(sdkMessage.status));
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
// A task that died without notifying still has to stop its card spinning.
|
|
682
|
+
if (sdkMessage.subtype === "task_updated") {
|
|
683
|
+
const status = sdkMessage.patch.status;
|
|
684
|
+
// No `tool_use_id` on this one, so the task map is the only way back to the Subagent.
|
|
685
|
+
if (status)
|
|
686
|
+
this.settleTask(sdkMessage.task_id, undefined, outcomeOf(status));
|
|
687
|
+
}
|
|
688
|
+
return;
|
|
689
|
+
case "stream_event":
|
|
690
|
+
// A local command's reply is not the model talking, so none of it may reach the transcript
|
|
691
|
+
// as a partial assistant message either. See `compact`.
|
|
692
|
+
if (this.compacting)
|
|
693
|
+
return;
|
|
694
|
+
this.ensureTurn(producerOf(sdkMessage));
|
|
695
|
+
this.translateStreamEvent(sdkMessage.event, producerOf(sdkMessage));
|
|
696
|
+
return;
|
|
697
|
+
case "assistant": {
|
|
698
|
+
// What the CLI says about a command it ran itself, said as Flow rather than as the
|
|
699
|
+
// model. On a compaction that landed there is a `compacted` marker beside this; on one that
|
|
700
|
+
// did not — "Not enough messages to compact." — this is the only account of it.
|
|
701
|
+
if (this.compacting) {
|
|
702
|
+
const said = textOf(sdkMessage.message.content);
|
|
703
|
+
if (said)
|
|
704
|
+
this.emit({ type: "notice", level: "info", text: said });
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
// The streamed copy and this one are the same Entry, and StreamedMessage is what guarantees
|
|
708
|
+
// it. Tool calls stay here: they have nothing to do with the partial-message state.
|
|
709
|
+
const producer = producerOf(sdkMessage);
|
|
710
|
+
this.ensureTurn(producer);
|
|
711
|
+
const finished = this.streamed.finish(producer, sdkMessage.message.id, sdkMessage.message.content);
|
|
712
|
+
for (const event of finished)
|
|
713
|
+
this.emit(event);
|
|
714
|
+
for (const block of sdkMessage.message.content) {
|
|
715
|
+
if (block.type !== "tool_use")
|
|
716
|
+
continue;
|
|
717
|
+
this.emit({
|
|
718
|
+
type: "tool_started",
|
|
719
|
+
callId: block.id,
|
|
720
|
+
name: block.name,
|
|
721
|
+
input: block.input,
|
|
722
|
+
...attribution(producer),
|
|
723
|
+
});
|
|
724
|
+
// Every call, not the ones we recognise: this block is the only place a name is knowable,
|
|
725
|
+
// and whether the CLI backgrounds the call is read off a later `task_started` rather than
|
|
726
|
+
// guessed from that name. Recording only the names we expect to background would be the
|
|
727
|
+
// tool-name allowlist ADR 0021 refuses.
|
|
728
|
+
this.calls.called(block.id, { tool: block.name, ...attribution(producer) });
|
|
729
|
+
if (block.name !== SUBAGENT_TOOL)
|
|
730
|
+
continue;
|
|
731
|
+
const brief = briefOf(block.input);
|
|
732
|
+
this.subagents.spawn(block.id, brief);
|
|
733
|
+
this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
|
|
734
|
+
}
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
case "user": {
|
|
738
|
+
const content = sdkMessage.message.content;
|
|
739
|
+
if (typeof content === "string")
|
|
740
|
+
return;
|
|
741
|
+
for (const block of content) {
|
|
742
|
+
if (block.type === "tool_result") {
|
|
743
|
+
const isError = block.is_error === true;
|
|
744
|
+
this.emit({
|
|
745
|
+
type: "tool_ended",
|
|
746
|
+
callId: block.tool_use_id,
|
|
747
|
+
result: block.content ?? "",
|
|
748
|
+
isError,
|
|
749
|
+
...attribution(producerOf(sdkMessage)),
|
|
750
|
+
});
|
|
751
|
+
// A launch receipt, not an answer: the Subagent is only now starting work, so it gets
|
|
752
|
+
// no terminal snapshot and its card stays running. What it does give up is its hold on
|
|
753
|
+
// the turn, which is what keeps the Steering Queue live while it runs (ADR 0016).
|
|
754
|
+
if (isAsyncLaunch(sdkMessage.tool_use_result)) {
|
|
755
|
+
const released = this.subagents.background(block.tool_use_id);
|
|
756
|
+
if (released)
|
|
757
|
+
this.endTurn(released);
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
// Before closeSubagent, which forgets the brief this snapshot needs.
|
|
761
|
+
const brief = this.subagents.describe(block.tool_use_id);
|
|
762
|
+
if (brief) {
|
|
763
|
+
this.emit({
|
|
764
|
+
type: "subagent",
|
|
765
|
+
subagentId: block.tool_use_id,
|
|
766
|
+
...brief,
|
|
767
|
+
state: isError ? "error" : "complete",
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
this.closeSubagent(block.tool_use_id);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
case "result": {
|
|
776
|
+
// Cleared here and only here: a local command always ends in a result, whatever it made of
|
|
777
|
+
// the request, so this is the one point that cannot leave the session suppressing forever.
|
|
778
|
+
const wasCompacting = this.compacting;
|
|
779
|
+
this.compacting = false;
|
|
780
|
+
// Whatever it made of the request. A compaction that found nothing to do still has to stop
|
|
781
|
+
// saying it is working, or the meter pulses until the session is disposed.
|
|
782
|
+
if (wasCompacting)
|
|
783
|
+
this.emit({ type: "compacting", active: false });
|
|
784
|
+
// Read before the meter is asked for, so the two land on the client as one event.
|
|
785
|
+
this.spend = addSpend(this.priorSpend, describeSpend(sdkMessage));
|
|
786
|
+
// Worth asking even for a compaction, and especially then — occupancy has just fallen, and
|
|
787
|
+
// that number is the whole reason anyone asked for one.
|
|
788
|
+
void this.reportContextUsage();
|
|
789
|
+
this.finishTurn(sdkMessage.subtype === "success" ? "complete" : "error");
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
default:
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
translateStreamEvent(event, producer) {
|
|
797
|
+
const streamed = this.streamed.for(producer);
|
|
798
|
+
if (event.type === "message_start") {
|
|
799
|
+
streamed.start(event.message.id);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
if (event.type !== "content_block_delta")
|
|
803
|
+
return;
|
|
804
|
+
const delta = event.delta;
|
|
805
|
+
if (delta.type === "text_delta")
|
|
806
|
+
this.emit(streamed.text(event.index, delta.text));
|
|
807
|
+
else if (delta.type === "thinking_delta")
|
|
808
|
+
this.emit(streamed.thinking(event.index, delta.thinking));
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Ask the CLI how much of the Conversation Context is spent.
|
|
812
|
+
*
|
|
813
|
+
* Never awaited by its callers: `translate` runs inside the message pump, so awaiting a control
|
|
814
|
+
* request there would stop us reading the stream until the CLI answered and one hung request
|
|
815
|
+
* would stall the Agent Session. The meter is chrome, so it may land just after `turn_ended`.
|
|
816
|
+
*
|
|
817
|
+
* Silent on rejection rather than emitting a `notice`. Only FLOW_CLAUDE_PATH and the SEA
|
|
818
|
+
* build's PATH lookup can reach a CLI the SDK did not ship, and `getContextUsage` is a required
|
|
819
|
+
* member of `Query` — so an older CLI rejects at runtime with no type warning, and a notice would
|
|
820
|
+
* repeat every turn to say the meter has nothing to show.
|
|
821
|
+
*/
|
|
822
|
+
async reportContextUsage() {
|
|
823
|
+
let usage;
|
|
824
|
+
try {
|
|
825
|
+
usage = await this.stream.getContextUsage();
|
|
826
|
+
}
|
|
827
|
+
catch {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (this.disposed)
|
|
831
|
+
return;
|
|
832
|
+
this.emit({
|
|
833
|
+
type: "context_usage",
|
|
834
|
+
...describeContextUsage(usage),
|
|
835
|
+
...(this.spend === undefined ? {} : { spend: this.spend }),
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* End the turn a `result` reports, unless a Subagent is still open — see Subagents for why a
|
|
840
|
+
* result cannot be attributed to one.
|
|
841
|
+
*
|
|
842
|
+
* Only this path defers. The pump's error path calls `endTurn` directly, because a stream that has
|
|
843
|
+
* failed will never deliver the `tool_result` that would release a held end.
|
|
844
|
+
*/
|
|
845
|
+
finishTurn(reason) {
|
|
846
|
+
if (this.subagents.hold(reason))
|
|
847
|
+
return;
|
|
848
|
+
this.endTurn(reason);
|
|
849
|
+
}
|
|
850
|
+
closeSubagent(callId) {
|
|
851
|
+
const released = this.subagents.returned(callId);
|
|
852
|
+
if (released)
|
|
853
|
+
this.endTurn(released);
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* A tool call the CLI is running past the turn that made it gets a card of its own (ADR 0021).
|
|
857
|
+
*
|
|
858
|
+
* Emits and nothing else: it takes no hold, releases none, and cannot end a turn. A Background
|
|
859
|
+
* Call is not occupancy, and the turn this call belongs to ends on its own `result` exactly as it
|
|
860
|
+
* did before any of this existed.
|
|
861
|
+
*/
|
|
862
|
+
openBackgroundCall(taskId, callId) {
|
|
863
|
+
const brief = this.calls.launch(callId);
|
|
864
|
+
// A call this never saw announced, or one already open because the CLI repeated itself. Either
|
|
865
|
+
// way there is nothing new to say, and a card named after a guess is worse than no card.
|
|
866
|
+
if (brief === undefined)
|
|
867
|
+
return;
|
|
868
|
+
this.calls.noteTask(taskId, callId);
|
|
869
|
+
this.emit({ type: "background_call", callId, ...brief, state: "running" });
|
|
870
|
+
}
|
|
871
|
+
closeBackgroundCall(callId, outcome) {
|
|
872
|
+
const brief = this.calls.settled(callId);
|
|
873
|
+
if (brief === undefined)
|
|
874
|
+
return;
|
|
875
|
+
this.emit({ type: "background_call", callId, ...brief, state: outcome });
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Close whatever a settled task belongs to: a Subagent's card, or a Background Call's.
|
|
879
|
+
*
|
|
880
|
+
* Routed on `Subagents.describe`, the same predicate `task_started` uses, so the two cannot
|
|
881
|
+
* disagree about which lifecycle a call has. Deliberately *not* on what `Subagents.background`
|
|
882
|
+
* returns, which answers undefined both for a call that is not a Subagent's and for one that held
|
|
883
|
+
* no turn end — the second being the common case, so routing on it would drop nearly every card.
|
|
884
|
+
*
|
|
885
|
+
* The `??` chain over the two task maps is safe for the same reason: each only ever accepted its
|
|
886
|
+
* own callIds, so a task id is in one of them or neither, never both.
|
|
887
|
+
*
|
|
888
|
+
* Both closers are idempotent, which is load-bearing rather than defensive — a task settles
|
|
889
|
+
* through `task_updated` *and* `task_notification`, both in the same tick with the same outcome
|
|
890
|
+
* (`spikes/background-call-messages.ts`), and this runs for each.
|
|
891
|
+
*
|
|
892
|
+
* Silent for a task in neither: the `Agent` a `--resume` inherited, or a call whose `task_started`
|
|
893
|
+
* we never saw. That is the silence this had before Background Calls existed, not a new hole.
|
|
894
|
+
*/
|
|
895
|
+
settleTask(taskId, toolUseId, outcome) {
|
|
896
|
+
if (outcome === undefined)
|
|
897
|
+
return;
|
|
898
|
+
const callId = toolUseId ?? this.subagents.callIdOf(taskId) ?? this.calls.callIdOf(taskId);
|
|
899
|
+
if (callId === undefined)
|
|
900
|
+
return;
|
|
901
|
+
const brief = this.subagents.describe(callId);
|
|
902
|
+
if (brief !== undefined) {
|
|
903
|
+
this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
|
|
904
|
+
this.closeSubagent(callId);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
this.closeBackgroundCall(callId, outcome);
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Open a turn for work the CLI started on its own.
|
|
911
|
+
*
|
|
912
|
+
* A backgrounded Subagent settling wakes the model without anyone prompting it: the CLI injects
|
|
913
|
+
* the notification and the model speaks again, turns after the one that spawned it. Those words
|
|
914
|
+
* are a turn — they cost money and occupy the session — and without one minted here they would
|
|
915
|
+
* reduce into whatever turn happened to be last, or into none at all.
|
|
916
|
+
*
|
|
917
|
+
* Only for the Agent Session's own model. A detached Subagent goes on streaming its own rows after
|
|
918
|
+
* the turn that launched it has ended, and minting a turn for those would occupy the session for
|
|
919
|
+
* as long as it runs — which is the blocking this decision exists to avoid. ADR 0015 keeps
|
|
920
|
+
* `producer` off `turn_started` for the same reason: a Subagent is not a turn and does not open one.
|
|
921
|
+
*/
|
|
922
|
+
ensureTurn(producer) {
|
|
923
|
+
if (producer !== "")
|
|
924
|
+
return;
|
|
925
|
+
if (this.turnId)
|
|
926
|
+
return;
|
|
927
|
+
this.turnId = randomUUID();
|
|
928
|
+
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
929
|
+
}
|
|
930
|
+
endTurn(reason) {
|
|
931
|
+
const turnId = this.turnId;
|
|
932
|
+
/*
|
|
933
|
+
* Defensive, and should be unreachable: the turn cannot end while the CLI is blocked on a
|
|
934
|
+
* permission callback, so anything still open here has already been abandoned by the path that
|
|
935
|
+
* got us here. One line against the alternative, which is a picker on screen over a turn that
|
|
936
|
+
* ended — a question with no way to answer it and no way to dismiss it.
|
|
937
|
+
*/
|
|
938
|
+
this.abandonEnquiries("the turn ended");
|
|
939
|
+
this.abandonPermissions("the turn ended");
|
|
940
|
+
// Cleared whatever the outcome, so a held end cannot reach the turn after this one. For
|
|
941
|
+
// permissions that also drops what the human refused: a no was about what was being attempted,
|
|
942
|
+
// and the next turn is a different attempt.
|
|
943
|
+
this.subagents.clear();
|
|
944
|
+
// Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
|
|
945
|
+
// that made it, which is the whole of ADR 0021.
|
|
946
|
+
this.calls.clear();
|
|
947
|
+
this.enquiries.clear();
|
|
948
|
+
this.permissions.clear();
|
|
949
|
+
if (!turnId)
|
|
950
|
+
return;
|
|
951
|
+
this.turnId = undefined;
|
|
952
|
+
this.emit({ type: "turn_ended", turnId, reason });
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
export class ClaudeBackend {
|
|
956
|
+
name = "claude";
|
|
957
|
+
options;
|
|
958
|
+
constructor(options = {}) {
|
|
959
|
+
const resolved = options.pathToClaudeCodeExecutable ?? resolveClaudeExecutable();
|
|
960
|
+
this.options = { ...options, ...(resolved ? { pathToClaudeCodeExecutable: resolved } : {}) };
|
|
961
|
+
}
|
|
962
|
+
async create(options) {
|
|
963
|
+
// Deliberately not awaiting init: in streaming-input mode the SDK emits nothing until the
|
|
964
|
+
// input stream yields, so waiting for the init message before returning would deadlock. The
|
|
965
|
+
// session starts with provisional capabilities and emits capabilities_changed once known.
|
|
966
|
+
return new ClaudeSession(options, this.options);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
/** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
|
|
970
|
+
/**
|
|
971
|
+
* Which model id to announce for the one the SDK just named.
|
|
972
|
+
*
|
|
973
|
+
* The picker lists aliases (`opus[1m]`) because that is what `supportedModels()` reports as `value`,
|
|
974
|
+
* while the init message at the start of every turn names the model in its *resolved* form
|
|
975
|
+
* (`claude-opus-5`). Announcing the resolved form is not a cosmetic problem: `effortChoices` and the
|
|
976
|
+
* picker's label both find the model by id in `capabilities.models`, so an id that is not on the list
|
|
977
|
+
* has no `effortLevels` and no `label` — the Effort control disappears entirely and the model pill
|
|
978
|
+
* falls back to printing the raw id. That happened one turn into every Agent Session.
|
|
979
|
+
*
|
|
980
|
+
* `undefined` means "nothing here worth announcing": the caller keeps what it already had rather than
|
|
981
|
+
* trading a described model for an undescribed one.
|
|
982
|
+
*/
|
|
983
|
+
export function modelInForce(named, aliasOf, models) {
|
|
984
|
+
const alias = aliasOf.get(named) ?? named;
|
|
985
|
+
// Before the list arrives there is nothing to match against, and the raw id stands until
|
|
986
|
+
// loadModels comes back and corrects it.
|
|
987
|
+
if (models.length === 0)
|
|
988
|
+
return alias;
|
|
989
|
+
return models.some((model) => model.id === alias) ? alias : undefined;
|
|
990
|
+
}
|
|
991
|
+
export function describeModel(model) {
|
|
992
|
+
return {
|
|
993
|
+
id: model.value,
|
|
994
|
+
provider: "anthropic",
|
|
995
|
+
label: model.displayName,
|
|
996
|
+
...(model.supportedEffortLevels?.length ? { effortLevels: [...model.supportedEffortLevels] } : {}),
|
|
997
|
+
// Stated rather than read: `supportedModels()` reports effort and fast mode but nothing about
|
|
998
|
+
// input modality, because every model this SDK serves can be shown an image. Hardcoded the way
|
|
999
|
+
// `providers` and `compaction` are, and for the same reason — it is a fact about this backend
|
|
1000
|
+
// rather than an answer the SDK is willing to give.
|
|
1001
|
+
acceptsImages: true,
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Everything billed for this Agent Session so far, per model.
|
|
1006
|
+
*
|
|
1007
|
+
* `modelUsage` is keyed by model and is cumulative for the session, so it is read rather than
|
|
1008
|
+
* accumulated — and because a Subagent runs under its own model entry, its spend is already in
|
|
1009
|
+
* here. That is the whole reason this exists: `getContextUsage` reports occupancy, and a
|
|
1010
|
+
* Subagent's conversation never occupies the parent's Conversation Context.
|
|
1011
|
+
*
|
|
1012
|
+
* Cache reads are counted in `tokens` and reported again in `cached`. They are billed, and on a long
|
|
1013
|
+
* session they are most of the count — so a total that omitted them would match no invoice, and a
|
|
1014
|
+
* total that hid them would overstate what the session actually cost to produce.
|
|
1015
|
+
*
|
|
1016
|
+
* Keyed by `canonicalModel` where the backend gives one, so the reading says `claude-haiku-4-5`
|
|
1017
|
+
* rather than `claude-haiku-4-5-20251001` — and so two versioned keys of one model add up.
|
|
1018
|
+
*/
|
|
1019
|
+
/**
|
|
1020
|
+
* Two readings of Spend added together, per model.
|
|
1021
|
+
*
|
|
1022
|
+
* Addition rather than replacement because each Backend Session reports only its own run: a Revive's
|
|
1023
|
+
* numbers are a continuation of the Agent Session's bill, not a correction to it.
|
|
1024
|
+
*/
|
|
1025
|
+
export function addSpend(before, after) {
|
|
1026
|
+
if (!before)
|
|
1027
|
+
return after;
|
|
1028
|
+
if (!after)
|
|
1029
|
+
return before;
|
|
1030
|
+
const byModel = new Map();
|
|
1031
|
+
for (const model of [...before.models, ...after.models]) {
|
|
1032
|
+
const running = byModel.get(model.id) ?? { id: model.id, tokens: 0, cached: 0, costUSD: 0 };
|
|
1033
|
+
running.tokens += model.tokens;
|
|
1034
|
+
running.cached += model.cached;
|
|
1035
|
+
running.costUSD += model.costUSD;
|
|
1036
|
+
byModel.set(model.id, running);
|
|
1037
|
+
}
|
|
1038
|
+
const models = [...byModel.values()].sort((a, b) => b.costUSD - a.costUSD);
|
|
1039
|
+
return {
|
|
1040
|
+
tokens: before.tokens + after.tokens,
|
|
1041
|
+
cached: before.cached + after.cached,
|
|
1042
|
+
costUSD: before.costUSD + after.costUSD,
|
|
1043
|
+
models,
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
export function describeSpend(result) {
|
|
1047
|
+
const usage = result.modelUsage;
|
|
1048
|
+
if (!usage)
|
|
1049
|
+
return undefined;
|
|
1050
|
+
const byModel = new Map();
|
|
1051
|
+
for (const [key, model] of Object.entries(usage)) {
|
|
1052
|
+
const id = model.canonicalModel ?? key;
|
|
1053
|
+
const running = byModel.get(id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
|
|
1054
|
+
running.tokens +=
|
|
1055
|
+
model.inputTokens + model.outputTokens + model.cacheReadInputTokens + model.cacheCreationInputTokens;
|
|
1056
|
+
running.cached += model.cacheReadInputTokens;
|
|
1057
|
+
running.costUSD += model.costUSD;
|
|
1058
|
+
byModel.set(id, running);
|
|
1059
|
+
}
|
|
1060
|
+
// Costliest first: the reading is about where the money went, and a Subagent on a cheap model
|
|
1061
|
+
// should not push the model that did the work down the list.
|
|
1062
|
+
const models = [...byModel.values()].sort((a, b) => b.costUSD - a.costUSD);
|
|
1063
|
+
return {
|
|
1064
|
+
tokens: models.reduce((total, model) => total + model.tokens, 0),
|
|
1065
|
+
cached: models.reduce((total, model) => total + model.cached, 0),
|
|
1066
|
+
costUSD: models.reduce((total, model) => total + model.costUSD, 0),
|
|
1067
|
+
models,
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
export function describeContextUsage(usage) {
|
|
1071
|
+
return { used: usage.totalTokens, window: usage.maxTokens };
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* The SDK's compaction boundary as the event a transcript records.
|
|
1075
|
+
*
|
|
1076
|
+
* The SDK compacts the Conversation Context on its own once the window fills, and until this
|
|
1077
|
+
* existed it did so silently — occupancy fell by two thirds between one turn and the next with
|
|
1078
|
+
* nothing to explain it. `trigger` is the SDK's own word for whether anyone asked, and it is kept
|
|
1079
|
+
* verbatim because both halves of it mean here exactly what they mean there.
|
|
1080
|
+
*
|
|
1081
|
+
* `post_tokens` is optional upstream, so `after` is omitted rather than defaulted: a compaction
|
|
1082
|
+
* reported as ending at zero tokens would read as having thrown the conversation away.
|
|
1083
|
+
*/
|
|
1084
|
+
/** The text of an assistant message, for the one case that is not the model speaking. See `compact`. */
|
|
1085
|
+
function textOf(content) {
|
|
1086
|
+
return content
|
|
1087
|
+
.filter((block) => block.type === "text")
|
|
1088
|
+
.map((block) => ("text" in block ? block.text : ""))
|
|
1089
|
+
.join("")
|
|
1090
|
+
.trim();
|
|
1091
|
+
}
|
|
1092
|
+
export function describeCompaction(
|
|
1093
|
+
// `post_tokens` is widened to accept an explicit undefined as well as an absent key, which
|
|
1094
|
+
// `exactOptionalPropertyTypes` otherwise keeps apart. A caller reading it off a message it did not
|
|
1095
|
+
// build should not have to care which of the two it has.
|
|
1096
|
+
metadata) {
|
|
1097
|
+
return {
|
|
1098
|
+
type: "compacted",
|
|
1099
|
+
trigger: metadata.trigger,
|
|
1100
|
+
before: metadata.pre_tokens,
|
|
1101
|
+
...(metadata.post_tokens === undefined ? {} : { after: metadata.post_tokens }),
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* One user turn's content: a plain string when there is nothing but text, and a block array when
|
|
1106
|
+
* there is more.
|
|
1107
|
+
*
|
|
1108
|
+
* The string is kept for the common turn rather than always sending a one-element array, because a
|
|
1109
|
+
* `content` this backend has sent as a string since it was written is not worth re-shaping for a
|
|
1110
|
+
* feature most turns do not use.
|
|
1111
|
+
*
|
|
1112
|
+
* Images lead. The docs prefer image-then-text and it costs nothing to honour here, where the text
|
|
1113
|
+
* is a question *about* what precedes it.
|
|
1114
|
+
*/
|
|
1115
|
+
export function userContent(text, attachments) {
|
|
1116
|
+
if (!attachments?.length)
|
|
1117
|
+
return text;
|
|
1118
|
+
return [
|
|
1119
|
+
...attachments.map((attachment) => ({
|
|
1120
|
+
type: "image",
|
|
1121
|
+
source: { type: "base64", media_type: attachment.mediaType, data: attachment.data },
|
|
1122
|
+
})),
|
|
1123
|
+
{ type: "text", text },
|
|
1124
|
+
];
|
|
1125
|
+
}
|
|
1126
|
+
/** Absent an override, the entry Claude itself calls the default is the model in force. */
|
|
1127
|
+
function defaultModel(models) {
|
|
1128
|
+
return (models.find((model) => model.value === "default") ?? models[0])?.value;
|
|
1129
|
+
}
|
|
1130
|
+
/** Claude has no `off` or `minimal`; those wait for the clamp rather than being mistranslated. */
|
|
1131
|
+
function sdkEffort(effort) {
|
|
1132
|
+
return effort === undefined || effort === "off" || effort === "minimal"
|
|
1133
|
+
? undefined
|
|
1134
|
+
: effort;
|
|
1135
|
+
}
|
|
1136
|
+
function message(error) {
|
|
1137
|
+
return error instanceof Error ? error.message : String(error);
|
|
1138
|
+
}
|