@zvada/agent-server 0.3.23 → 0.3.25
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/CHANGELOG.md +64 -0
- package/README.md +14 -5
- package/dist/accounts/chatgpt.js +144 -0
- package/dist/accounts/check.js +71 -0
- package/dist/accounts/claude.js +80 -0
- package/dist/accounts/endpoint.js +104 -0
- package/dist/accounts/http.js +58 -0
- package/dist/accounts/index.js +9 -0
- package/dist/client/client.js +745 -0
- package/dist/client/connection.js +338 -0
- package/dist/client/history.js +49 -0
- package/dist/client/index.js +6 -0
- package/dist/client/listeners.js +19 -0
- package/dist/client/logins.js +92 -0
- package/dist/client/rpc.js +105 -0
- package/dist/client/streams.js +432 -0
- package/dist/client/transports.js +118 -0
- package/dist/client/turns.js +122 -0
- package/dist/core/agents/acp/acp-agent.js +425 -0
- package/dist/core/agents/acp/adapter.js +231 -0
- package/dist/core/agents/acp/client.js +222 -0
- package/dist/core/agents/acp/known-agents.js +57 -0
- package/dist/core/agents/acp/mappings.js +164 -0
- package/dist/core/agents/acp/requests.js +79 -0
- package/dist/core/agents/attachments.js +14 -0
- package/dist/core/agents/base.js +64 -0
- package/dist/core/agents/claude-code/adapter.js +474 -0
- package/dist/core/agents/claude-code/approvals.js +245 -0
- package/dist/core/agents/claude-code/claude-agent.js +319 -0
- package/dist/core/agents/claude-code/credentials.js +142 -0
- package/dist/core/agents/claude-code/events.js +11 -0
- package/dist/core/agents/claude-code/login.js +217 -0
- package/dist/core/agents/claude-code/mcp.js +181 -0
- package/dist/core/agents/claude-code/models.js +74 -0
- package/dist/core/agents/claude-code/options.js +240 -0
- package/dist/core/agents/claude-code/outcome.js +204 -0
- package/dist/core/agents/claude-code/results.js +58 -0
- package/dist/core/agents/claude-code/sdk-pair.js +59 -0
- package/dist/core/agents/claude-code/session.js +593 -0
- package/dist/core/agents/claude-code/spawn.js +125 -0
- package/dist/core/agents/claude-code/spend.js +118 -0
- package/dist/core/agents/claude-code/tools.js +131 -0
- package/dist/core/agents/claude-code/turn-usage.js +121 -0
- package/dist/core/agents/claude-code/turn.js +199 -0
- package/dist/core/agents/codex-app-server/adapter.js +463 -0
- package/dist/core/agents/codex-app-server/client.js +338 -0
- package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
- package/dist/core/agents/codex-app-server/commands.js +184 -0
- package/dist/core/agents/codex-app-server/credentials.js +92 -0
- package/dist/core/agents/codex-app-server/effort.js +13 -0
- package/dist/core/agents/codex-app-server/events.js +18 -0
- package/dist/core/agents/codex-app-server/homes.js +118 -0
- package/dist/core/agents/codex-app-server/input.js +52 -0
- package/dist/core/agents/codex-app-server/items.js +307 -0
- package/dist/core/agents/codex-app-server/login.js +183 -0
- package/dist/core/agents/codex-app-server/mcp.js +323 -0
- package/dist/core/agents/codex-app-server/models.js +160 -0
- package/dist/core/agents/codex-app-server/options.js +155 -0
- package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
- package/dist/core/agents/codex-app-server/protocol.js +38 -0
- package/dist/core/agents/codex-app-server/requests.js +250 -0
- package/dist/core/agents/codex-app-server/session.js +278 -0
- package/dist/core/agents/codex-app-server/subagents.js +260 -0
- package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
- package/dist/core/agents/codex-app-server/turn-items.js +69 -0
- package/dist/core/agents/codex-app-server/turn.js +448 -0
- package/dist/core/agents/codex-app-server/user-login.js +78 -0
- package/dist/core/agents/config-fingerprint.js +10 -0
- package/dist/core/agents/credentials.js +71 -0
- package/dist/core/agents/diffs.js +27 -0
- package/dist/core/agents/elicitation.js +42 -0
- package/dist/core/agents/inherit-config.js +5 -0
- package/dist/core/agents/login.js +56 -0
- package/dist/core/agents/mcp-config.js +109 -0
- package/dist/core/agents/plan.js +6 -0
- package/dist/core/agents/process-pool.js +307 -0
- package/dist/core/agents/registry.js +49 -0
- package/dist/core/agents/scripted/adapter.js +86 -0
- package/dist/core/agents/scripted/mcp-call.js +74 -0
- package/dist/core/agents/scripted/scripted-agent.js +331 -0
- package/dist/core/agents/scripted/scripts.js +154 -0
- package/dist/core/agents/scripted/steps.js +87 -0
- package/dist/core/agents/session-agent.js +209 -0
- package/dist/core/agents/stderr-tail.js +71 -0
- package/dist/core/agents/thinking-levels.js +9 -0
- package/dist/core/agents/types.js +1 -0
- package/dist/core/diagnostics.js +23 -0
- package/dist/core/index.js +31 -0
- package/dist/core/presets.js +114 -0
- package/dist/core/processes/identity.js +92 -0
- package/dist/core/processes/lifeline.js +218 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +164 -0
- package/dist/core/provision/cache-trust.js +121 -0
- package/dist/core/provision/cache-usage.js +61 -0
- package/dist/core/provision/checksums.js +22 -0
- package/dist/core/provision/extract.js +29 -0
- package/dist/core/provision/index.js +4 -0
- package/dist/core/provision/install-build.js +99 -0
- package/dist/core/provision/npm.js +316 -0
- package/dist/core/provision/pins.js +35 -0
- package/dist/core/provision/platform.js +65 -0
- package/dist/core/provision/provisioner.js +372 -0
- package/dist/core/provision/releases.js +68 -0
- package/dist/core/provision/tools.js +279 -0
- package/dist/core/proxy/anthropic-proxy.js +163 -0
- package/dist/core/proxy/api-key-store.js +30 -0
- package/dist/core/proxy/index.js +3 -0
- package/dist/core/proxy/loopback.js +86 -0
- package/dist/core/runtime/agent-runtime.js +437 -0
- package/dist/core/runtime/event-processor.js +379 -0
- package/dist/core/runtime/event-sink.js +65 -0
- package/dist/core/runtime/harness-clis.js +83 -0
- package/dist/core/runtime/harness-logins.js +313 -0
- package/dist/core/runtime/login-reads.js +71 -0
- package/dist/core/runtime/model-lists.js +160 -0
- package/dist/core/runtime/permission-policy.js +84 -0
- package/dist/core/runtime/request-broker.js +139 -0
- package/dist/core/runtime/steering.js +79 -0
- package/dist/core/runtime/turn-outcome.js +16 -0
- package/dist/core/runtime/turn.js +339 -0
- package/dist/core/utils/bounded.js +13 -0
- package/dist/core/utils/deadline.js +57 -0
- package/dist/core/utils/errors.js +176 -0
- package/dist/core/utils/is-record.js +4 -0
- package/dist/core/utils/loopback.js +11 -0
- package/dist/index.js +4 -0
- package/dist/operator/index.js +10 -0
- package/dist/operator/mcp.js +139 -0
- package/dist/operator/operator.js +499 -0
- package/dist/operator/render.js +408 -0
- package/dist/operator/view.js +35 -0
- package/dist/protocol/account.js +96 -0
- package/dist/protocol/async-queue.js +65 -0
- package/dist/protocol/auth.js +169 -0
- package/dist/protocol/canonical.js +18 -0
- package/dist/protocol/clis.js +63 -0
- package/dist/protocol/config.js +137 -0
- package/dist/protocol/conversation.js +231 -0
- package/dist/protocol/credentials.js +142 -0
- package/dist/protocol/errors.js +190 -0
- package/dist/protocol/execution.js +28 -0
- package/dist/protocol/factories.js +231 -0
- package/dist/protocol/guards.js +71 -0
- package/dist/protocol/harness.js +93 -0
- package/dist/protocol/history.js +201 -0
- package/dist/protocol/ids.js +37 -0
- package/dist/protocol/index.js +36 -0
- package/dist/protocol/lifecycle.js +562 -0
- package/dist/protocol/meta-keys.js +17 -0
- package/dist/protocol/meta.js +13 -0
- package/dist/protocol/model-catalog.js +223 -0
- package/dist/protocol/models.js +84 -0
- package/dist/protocol/part-input.js +94 -0
- package/dist/protocol/parts.js +166 -0
- package/dist/protocol/plan.js +31 -0
- package/dist/protocol/reduce.js +484 -0
- package/dist/protocol/selectors.js +136 -0
- package/dist/protocol/seq-cursor.js +37 -0
- package/dist/protocol/stop-reasons.js +41 -0
- package/dist/protocol/thinking.js +31 -0
- package/dist/protocol/time.js +21 -0
- package/dist/protocol/tokens.js +57 -0
- package/dist/protocol/tool-closure.js +70 -0
- package/dist/protocol/tool-state.js +153 -0
- package/dist/protocol/verify.js +467 -0
- package/dist/protocol/vocabulary.js +27 -0
- package/dist/protocol/wire-api.js +94 -0
- package/dist/protocol/wire.js +669 -0
- package/dist/server/acp/binding.js +251 -0
- package/dist/server/acp/session-records.js +53 -0
- package/dist/server/acp/translate.js +401 -0
- package/dist/server/agent-server.js +338 -0
- package/dist/server/bin.js +492 -0
- package/dist/server/feedback.js +216 -0
- package/dist/server/history.js +123 -0
- package/dist/server/index.js +8 -0
- package/dist/server/install.js +171 -0
- package/dist/server/open-parts.js +87 -0
- package/dist/server/routes.js +292 -0
- package/dist/server/secrets.js +19 -0
- package/dist/server/session-gate.js +54 -0
- package/dist/server/session-log.js +66 -0
- package/dist/server/session-store.js +243 -0
- package/dist/server/subscriptions.js +189 -0
- package/dist/server/transports.js +214 -0
- package/dist/server/wire-error.js +26 -0
- package/dist/sync/event-log.js +89 -0
- package/dist/sync/fit.js +202 -0
- package/dist/sync/history-reader.js +33 -0
- package/dist/sync/history-sqlite.js +281 -0
- package/dist/sync/history.js +163 -0
- package/dist/sync/index.js +5 -0
- package/dist/sync/journal-sqlite.js +316 -0
- package/dist/sync/journal.js +10 -0
- package/dist/sync/live-tails.js +85 -0
- package/dist/sync/node-sqlite.js +27 -0
- package/dist/sync/projection.js +32 -0
- package/dist/sync/recovery.js +117 -0
- package/dist/sync/retry.js +45 -0
- package/dist/sync/schema.js +73 -0
- package/dist/sync/sql.js +94 -0
- package/dist/sync/sqlite-file.js +31 -0
- package/dist/sync/sqlite.js +18 -0
- package/dist/sync/worker.js +212 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +28 -11
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/session.d.ts +8 -0
- package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
- package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
- package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
- package/dist/types/core/agents/process-pool.d.ts +8 -0
- package/dist/types/core/agents/process-pool.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- package/dist/types/server/routes.d.ts.map +1 -1
- package/dist/types/server/transports.d.ts +2 -1
- package/dist/types/server/transports.d.ts.map +1 -1
- package/dist/types/sync/node-sqlite.d.ts +4 -1
- package/dist/types/sync/node-sqlite.d.ts.map +1 -1
- package/docs/consuming.md +56 -7
- package/docs/deploy.md +35 -0
- package/docs/harnesses.md +30 -5
- package/package.json +43 -18
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/approvals.ts +5 -1
- package/src/core/agents/claude-code/claude-agent.ts +32 -5
- package/src/core/agents/claude-code/options.ts +28 -11
- package/src/core/agents/claude-code/session.ts +13 -0
- package/src/core/agents/codex-app-server/homes.ts +11 -2
- package/src/core/agents/codex-app-server/login.ts +30 -0
- package/src/core/agents/codex-app-server/requests.ts +7 -6
- package/src/core/agents/codex-app-server/session.ts +11 -2
- package/src/core/agents/process-pool.ts +30 -4
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/presets.ts +3 -2
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/bin.ts +25 -10
- package/src/server/routes.ts +3 -2
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
import { redactSecrets } from "../stderr-tail.js";
|
|
4
|
+
/** The longest stderr tail an SDK exit error carries. */
|
|
5
|
+
const SDK_TAIL_MAX = 2048;
|
|
6
|
+
/**
|
|
7
|
+
* The CLI as the SDK sees it: the child's pipes, and its `exit` once stderr
|
|
8
|
+
* has closed too (at most 200 ms after it), as the SDK's own spawner delivers
|
|
9
|
+
* it, so the exit error it builds finds the whole tail.
|
|
10
|
+
*/
|
|
11
|
+
class SpawnedClaude {
|
|
12
|
+
native;
|
|
13
|
+
stdin;
|
|
14
|
+
stdout;
|
|
15
|
+
exits = new EventEmitter();
|
|
16
|
+
constructor(native, stdin, stdout) {
|
|
17
|
+
this.native = native;
|
|
18
|
+
this.stdin = stdin;
|
|
19
|
+
this.stdout = stdout;
|
|
20
|
+
void native.exited.then(({ code, signal }) => this.exits.emit("exit", code, signal));
|
|
21
|
+
}
|
|
22
|
+
get killed() {
|
|
23
|
+
return this.native.child.killed;
|
|
24
|
+
}
|
|
25
|
+
get exitCode() {
|
|
26
|
+
return this.native.child.exitCode;
|
|
27
|
+
}
|
|
28
|
+
get signalCode() {
|
|
29
|
+
return this.native.child.signalCode;
|
|
30
|
+
}
|
|
31
|
+
kill(signal) {
|
|
32
|
+
return this.native.child.kill(signal);
|
|
33
|
+
}
|
|
34
|
+
on(event, listener) {
|
|
35
|
+
if (event === "exit")
|
|
36
|
+
this.exits.on(event, listener);
|
|
37
|
+
else
|
|
38
|
+
this.native.child.on(event, listener);
|
|
39
|
+
}
|
|
40
|
+
once(event, listener) {
|
|
41
|
+
if (event === "exit")
|
|
42
|
+
this.exits.once(event, listener);
|
|
43
|
+
else
|
|
44
|
+
this.native.child.once(event, listener);
|
|
45
|
+
}
|
|
46
|
+
off(event, listener) {
|
|
47
|
+
if (event === "exit")
|
|
48
|
+
this.exits.off(event, listener);
|
|
49
|
+
else
|
|
50
|
+
this.native.child.off(event, listener);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// @ref LLP 0007#what-each-harness-does — the engine's own spawner, the SDK's typed seam
|
|
54
|
+
/**
|
|
55
|
+
* The SDK's `spawnClaudeCodeProcess` as the engine runs Claude: in a session
|
|
56
|
+
* and group of its own, held by the lifeline and recorded for its session.
|
|
57
|
+
* An operator's own spawner (`sdkOptions`) still wins: the engine then owns no
|
|
58
|
+
* process, and records its session's as a host's (`not_owned`). The `stderr`
|
|
59
|
+
* callback, which the SDK calls only from its own spawner, is called here.
|
|
60
|
+
*/
|
|
61
|
+
export function claudeSpawner(spawn, operator, stderr) {
|
|
62
|
+
return (options) => {
|
|
63
|
+
if (operator) {
|
|
64
|
+
const done = spawn.sessionId === undefined
|
|
65
|
+
? undefined
|
|
66
|
+
: spawn.processes.hosted({
|
|
67
|
+
sessionId: spawn.sessionId,
|
|
68
|
+
harness: "claude-code",
|
|
69
|
+
executable: options.command,
|
|
70
|
+
});
|
|
71
|
+
try {
|
|
72
|
+
const hosted = operator(options);
|
|
73
|
+
if (done)
|
|
74
|
+
hosted.once("exit", done);
|
|
75
|
+
return hosted;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
// It started nothing for the host to stop.
|
|
79
|
+
done?.();
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const native = spawn.processes.spawn({
|
|
84
|
+
command: options.command,
|
|
85
|
+
args: options.args,
|
|
86
|
+
cwd: options.cwd,
|
|
87
|
+
env: options.env,
|
|
88
|
+
harness: "claude-code",
|
|
89
|
+
signal: options.signal,
|
|
90
|
+
...(spawn.sessionId !== undefined && { sessionId: spawn.sessionId }),
|
|
91
|
+
});
|
|
92
|
+
const { stdin, stdout } = native.child;
|
|
93
|
+
if (!stdin || !stdout)
|
|
94
|
+
throw new Error("Claude Code process has no stdio");
|
|
95
|
+
if (stderr) {
|
|
96
|
+
const decoder = new StringDecoder("utf8");
|
|
97
|
+
native.child.stderr?.on("data", (chunk) => stderr(decoder.write(chunk)));
|
|
98
|
+
}
|
|
99
|
+
spawn.onSpawned?.(native);
|
|
100
|
+
return new SpawnedClaude(native, stdin, stdout);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** The SDK's bare exit error: what its own spawner would have followed with `. stderr: <tail>`. */
|
|
104
|
+
const BARE_EXIT = /^Claude Code process (?:exited with code \S+|terminated by signal \S+)$/;
|
|
105
|
+
/**
|
|
106
|
+
* Put the CLI's own words back into the SDK's exit error, as the SDK's own
|
|
107
|
+
* spawner words it ("Claude Code process exited with code 1. stderr: …"):
|
|
108
|
+
* the last 2 KB, trimmed, with its secrets redacted (the SDK redacts its own;
|
|
109
|
+
* this marks each `[REDACTED]`). The SDK builds that tail only from its own
|
|
110
|
+
* spawner. Its message alone changes, so the error keeps its class and fields.
|
|
111
|
+
*/
|
|
112
|
+
export function withStderr(error, tail) {
|
|
113
|
+
if (!(error instanceof Error) || !BARE_EXIT.test(error.message))
|
|
114
|
+
return error;
|
|
115
|
+
let kept = tail.length > SDK_TAIL_MAX ? tail.slice(-SDK_TAIL_MAX) : tail;
|
|
116
|
+
// A cut that splits a surrogate pair drops its half, as the SDK's does.
|
|
117
|
+
const first = kept.charCodeAt(0);
|
|
118
|
+
if (first >= 0xdc00 && first <= 0xdfff)
|
|
119
|
+
kept = kept.slice(1);
|
|
120
|
+
// As the SDK redacts its own tail, before it quotes it.
|
|
121
|
+
kept = redactSecrets(kept).trim();
|
|
122
|
+
if (kept)
|
|
123
|
+
error.message = `${error.message}. stderr: ${kept}`;
|
|
124
|
+
return error;
|
|
125
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** The totals a result's `modelUsage` reports; undefined when it reports none. */
|
|
2
|
+
export function claudeUsageTotals(modelUsage) {
|
|
3
|
+
const models = Object.values(modelUsage);
|
|
4
|
+
if (models.length === 0)
|
|
5
|
+
return undefined;
|
|
6
|
+
const sum = (count) => models.reduce((total, model) => total + (count(model) ?? 0), 0);
|
|
7
|
+
const recordsThinking = models.every((model) => typeof model.thinkingTokens === "number");
|
|
8
|
+
return {
|
|
9
|
+
input: sum((model) => model.inputTokens),
|
|
10
|
+
output: sum((model) => model.outputTokens),
|
|
11
|
+
cacheRead: sum((model) => model.cacheReadInputTokens),
|
|
12
|
+
cacheWrite: sum((model) => model.cacheCreationInputTokens),
|
|
13
|
+
...(recordsThinking && { thinking: sum((model) => model.thinkingTokens) }),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** What the totals grew by; undefined when any of them shrank (a reset or a zeroed crash). */
|
|
17
|
+
function grownBy(now, before) {
|
|
18
|
+
const delta = {
|
|
19
|
+
input: now.input - before.input,
|
|
20
|
+
output: now.output - before.output,
|
|
21
|
+
cacheRead: now.cacheRead - before.cacheRead,
|
|
22
|
+
cacheWrite: now.cacheWrite - before.cacheWrite,
|
|
23
|
+
...(now.thinking !== undefined &&
|
|
24
|
+
before.thinking !== undefined && { thinking: now.thinking - before.thinking }),
|
|
25
|
+
};
|
|
26
|
+
return Object.values(delta).every((value) => value >= 0) ? delta : undefined;
|
|
27
|
+
}
|
|
28
|
+
/** The 5-minute and 1-hour parts of the main loop's cache writes, as far as it reports them. */
|
|
29
|
+
export function cacheWriteDurations(usage) {
|
|
30
|
+
const creation = usage?.cache_creation;
|
|
31
|
+
return {
|
|
32
|
+
...(creation?.ephemeral_5m_input_tokens !== undefined && {
|
|
33
|
+
writeEphemeral5m: creation.ephemeral_5m_input_tokens,
|
|
34
|
+
}),
|
|
35
|
+
...(creation?.ephemeral_1h_input_tokens !== undefined && {
|
|
36
|
+
writeEphemeral1h: creation.ephemeral_1h_input_tokens,
|
|
37
|
+
}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A conversation's totals before it spent anything. */
|
|
41
|
+
const NOTHING_SPENT = {
|
|
42
|
+
input: 0,
|
|
43
|
+
output: 0,
|
|
44
|
+
cacheRead: 0,
|
|
45
|
+
cacheWrite: 0,
|
|
46
|
+
thinking: 0,
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* What a Claude conversation has spent. Claude reports cost and tokens as
|
|
50
|
+
* running totals for its native conversation (`total_cost_usd`,
|
|
51
|
+
* `modelUsage`), and a resumed conversation restores what earlier processes
|
|
52
|
+
* spent. So a query spent what the totals grew by, and an unknown baseline
|
|
53
|
+
* reports nothing: the first query of a resumed process would otherwise report
|
|
54
|
+
* the conversation's whole spend.
|
|
55
|
+
*/
|
|
56
|
+
export class ClaudeSpend {
|
|
57
|
+
cost;
|
|
58
|
+
totals;
|
|
59
|
+
constructor(cost, totals) {
|
|
60
|
+
this.cost = cost;
|
|
61
|
+
this.totals = totals;
|
|
62
|
+
}
|
|
63
|
+
/** A conversation this process starts: nothing spent yet. */
|
|
64
|
+
static fresh() {
|
|
65
|
+
return new ClaudeSpend(0, NOTHING_SPENT);
|
|
66
|
+
}
|
|
67
|
+
/** A conversation this process resumes: its totals include what earlier processes spent. */
|
|
68
|
+
static unknown() {
|
|
69
|
+
return new ClaudeSpend(undefined, undefined);
|
|
70
|
+
}
|
|
71
|
+
/** The same conversation goes on in a new process, which restores the totals the old one saved. */
|
|
72
|
+
continueFrom(previous) {
|
|
73
|
+
this.cost = previous.cost;
|
|
74
|
+
this.totals = previous.totals;
|
|
75
|
+
}
|
|
76
|
+
/** Claude cleared the conversation (`conversation_reset`): its totals start over. */
|
|
77
|
+
reset() {
|
|
78
|
+
this.cost = 0;
|
|
79
|
+
this.totals = NOTHING_SPENT;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A query's result: what it spent, and its totals as the next query's
|
|
83
|
+
* baseline. A crash can report zeroed totals; they establish nothing.
|
|
84
|
+
*/
|
|
85
|
+
charge(result) {
|
|
86
|
+
const total = result.total_cost_usd;
|
|
87
|
+
const costUsd = this.cost !== undefined && total >= this.cost ? total - this.cost : null;
|
|
88
|
+
this.cost = this.cost !== undefined && total < this.cost ? undefined : total;
|
|
89
|
+
const totals = claudeUsageTotals(result.modelUsage ?? {});
|
|
90
|
+
const grown = totals && this.totals ? grownBy(totals, this.totals) : undefined;
|
|
91
|
+
if (totals)
|
|
92
|
+
this.totals = this.totals && !grown ? undefined : totals;
|
|
93
|
+
return { costUsd, usage: grown ? queryUsage(grown, result.usage) : null };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The query's usage from the totals' growth, which counts every model call.
|
|
98
|
+
* The main loop is one of those calls: totals that grew by less than it rest
|
|
99
|
+
* on a wrong baseline (one carried over from a replaced process can sit above
|
|
100
|
+
* what the resumed CLI restored), so they give way to it.
|
|
101
|
+
*/
|
|
102
|
+
function queryUsage(grown, main) {
|
|
103
|
+
// @ref LLP 0002#tokens-count-the-turn — every model call the turn made
|
|
104
|
+
const coversMainLoop = !main ||
|
|
105
|
+
(grown.input >= (main.input_tokens ?? 0) &&
|
|
106
|
+
grown.output >= (main.output_tokens ?? 0) &&
|
|
107
|
+
grown.cacheRead >= (main.cache_read_input_tokens ?? 0) &&
|
|
108
|
+
grown.cacheWrite >= (main.cache_creation_input_tokens ?? 0));
|
|
109
|
+
if (!coversMainLoop)
|
|
110
|
+
return null;
|
|
111
|
+
return {
|
|
112
|
+
input: grown.input,
|
|
113
|
+
output: grown.output,
|
|
114
|
+
...(grown.thinking !== undefined && { reasoning: grown.thinking }),
|
|
115
|
+
// Duration buckets are the main loop's: still parts of the cache writes.
|
|
116
|
+
cache: { read: grown.cacheRead, write: grown.cacheWrite, ...cacheWriteDurations(main) },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps Claude Code's tool names onto the normalized ToolKind taxonomy and
|
|
3
|
+
* extracts touched file locations from tool inputs. Pure best-effort: unknown
|
|
4
|
+
* tools are `other` and produce no locations.
|
|
5
|
+
*/
|
|
6
|
+
// @ref LLP 0002#a-tool-call-says-what-it-acts-on — every tool the pinned CLI offers has a decided kind
|
|
7
|
+
/**
|
|
8
|
+
* Each Claude tool's kind, decided on what the tool does. A map, not an
|
|
9
|
+
* object: a tool named `constructor` is no object member's kind. The free
|
|
10
|
+
* live check (`claude-tool-kinds.live.test.ts`) fails on a tool the pinned
|
|
11
|
+
* CLI offers that is not here, so a pin bump decides it.
|
|
12
|
+
*/
|
|
13
|
+
export const CLAUDE_TOOL_KINDS = new Map([
|
|
14
|
+
// What the pinned CLI (2.1.288) offers, with the engine's options or a product's.
|
|
15
|
+
["Read", "read"],
|
|
16
|
+
["Edit", "edit"],
|
|
17
|
+
["Write", "edit"],
|
|
18
|
+
["NotebookEdit", "edit"],
|
|
19
|
+
["Bash", "execute"],
|
|
20
|
+
// Stops a background shell or sub-agent the agent started.
|
|
21
|
+
["TaskStop", "execute"],
|
|
22
|
+
// Runs a script the agent wrote, which starts sub-agents of its own.
|
|
23
|
+
["Workflow", "execute"],
|
|
24
|
+
["WebFetch", "fetch"],
|
|
25
|
+
["WebSearch", "fetch"],
|
|
26
|
+
// Loads a skill's instructions into the conversation.
|
|
27
|
+
["Skill", "read"],
|
|
28
|
+
// The sub-agent tool: `init` names it `Task`, the model `Agent`. A spawn is `task` by its subagent.
|
|
29
|
+
["Task", "think"],
|
|
30
|
+
["Agent", "think"],
|
|
31
|
+
// The agent's own task list, as `TodoWrite` was.
|
|
32
|
+
["TaskCreate", "think"],
|
|
33
|
+
["TaskGet", "think"],
|
|
34
|
+
["TaskList", "think"],
|
|
35
|
+
["TaskUpdate", "think"],
|
|
36
|
+
["TodoWrite", "think"],
|
|
37
|
+
["ExitPlanMode", "switch_mode"],
|
|
38
|
+
["EnterPlanMode", "switch_mode"],
|
|
39
|
+
// Moves the session into a git worktree and back: no mode, no file of the agent's.
|
|
40
|
+
["EnterWorktree", "other"],
|
|
41
|
+
["ExitWorktree", "other"],
|
|
42
|
+
// A question to the person, through the engine's elicitation.
|
|
43
|
+
["AskUserQuestion", "other"],
|
|
44
|
+
// Talk among agents: which there are, a message to one, the findings sent back.
|
|
45
|
+
["ListAgents", "other"],
|
|
46
|
+
["SendMessage", "other"],
|
|
47
|
+
["ReportFindings", "other"],
|
|
48
|
+
// Prompts the session schedules for later, and the agent's own wake-up.
|
|
49
|
+
["CronCreate", "other"],
|
|
50
|
+
["CronDelete", "other"],
|
|
51
|
+
["CronList", "other"],
|
|
52
|
+
["ScheduleWakeup", "other"],
|
|
53
|
+
// Names the pinned CLI no longer offers: a product may pin an older CLI
|
|
54
|
+
// (`provision.pins`), whose calls keep their kinds.
|
|
55
|
+
["NotebookRead", "read"],
|
|
56
|
+
["MultiEdit", "edit"],
|
|
57
|
+
["BashOutput", "execute"],
|
|
58
|
+
["KillShell", "execute"],
|
|
59
|
+
["Grep", "search"],
|
|
60
|
+
["Glob", "search"],
|
|
61
|
+
["LS", "search"],
|
|
62
|
+
]);
|
|
63
|
+
const PATH_INPUT_KEYS = ["file_path", "filePath", "path", "notebook_path"];
|
|
64
|
+
function toolLocationsFromInput(input) {
|
|
65
|
+
for (const key of PATH_INPUT_KEYS) {
|
|
66
|
+
const v = input[key];
|
|
67
|
+
if (typeof v === "string" && v)
|
|
68
|
+
return [{ path: v }];
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
const MCP_PREFIX = "mcp__";
|
|
73
|
+
/**
|
|
74
|
+
* A server's name as Claude Code spells it in a tool name (the pinned CLI
|
|
75
|
+
* 2.1.288, SDK 0.3.288, and 2.1.325 alike):
|
|
76
|
+
* other than letters, digits, `_` and `-` become `_`, and a claude.ai
|
|
77
|
+
* connector's runs of `_` collapse.
|
|
78
|
+
*/
|
|
79
|
+
function spelledInToolName(server) {
|
|
80
|
+
const spelled = server.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
81
|
+
return server.startsWith("claude.ai ")
|
|
82
|
+
? spelled.replace(/_+/g, "_").replace(/^_|_$/g, "")
|
|
83
|
+
: spelled;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The server and tool of a Claude MCP tool name, `mcp__<server>__<tool>`. A
|
|
87
|
+
* server's name may hold `__` itself, so the longest name the session
|
|
88
|
+
* attached that fits wins; with none, the name splits at its first `__`.
|
|
89
|
+
* Undefined for a name that is no MCP tool.
|
|
90
|
+
*/
|
|
91
|
+
export function claudeMcpTool(toolName, servers = []) {
|
|
92
|
+
if (!toolName.startsWith(MCP_PREFIX))
|
|
93
|
+
return undefined;
|
|
94
|
+
const rest = toolName.slice(MCP_PREFIX.length);
|
|
95
|
+
let known;
|
|
96
|
+
for (const server of servers) {
|
|
97
|
+
const spelled = spelledInToolName(server);
|
|
98
|
+
const fits = rest.startsWith(`${spelled}__`) && rest.length > spelled.length + 2;
|
|
99
|
+
if (fits && (!known || spelled.length > known.spelled.length))
|
|
100
|
+
known = { server, spelled };
|
|
101
|
+
}
|
|
102
|
+
if (known)
|
|
103
|
+
return { server: known.server, tool: rest.slice(known.spelled.length + 2) };
|
|
104
|
+
const split = rest.indexOf("__");
|
|
105
|
+
if (split <= 0 || split + 2 >= rest.length)
|
|
106
|
+
return undefined;
|
|
107
|
+
return { server: rest.slice(0, split), tool: rest.slice(split + 2) };
|
|
108
|
+
}
|
|
109
|
+
/** `input[key]` when it is a string with something in it. */
|
|
110
|
+
function textOf(input, key) {
|
|
111
|
+
const value = input?.[key];
|
|
112
|
+
return typeof value === "string" && value ? value : undefined;
|
|
113
|
+
}
|
|
114
|
+
// @ref LLP 0002#a-tool-call-says-what-it-acts-on — Claude's own keys, read once here
|
|
115
|
+
/**
|
|
116
|
+
* A Claude tool's kind and touched files, a `Bash` call's command and a
|
|
117
|
+
* `WebFetch` call's address; for an MCP tool, its server and tool among
|
|
118
|
+
* `servers`.
|
|
119
|
+
*/
|
|
120
|
+
export function claudeToolMeta(toolName, input, servers) {
|
|
121
|
+
const mcp = claudeMcpTool(toolName, servers);
|
|
122
|
+
const command = toolName === "Bash" ? textOf(input, "command") : undefined;
|
|
123
|
+
const url = toolName === "WebFetch" ? textOf(input, "url") : undefined;
|
|
124
|
+
return {
|
|
125
|
+
kind: CLAUDE_TOOL_KINDS.get(toolName) ?? "other",
|
|
126
|
+
...(mcp && { mcp }),
|
|
127
|
+
...(command && { command }),
|
|
128
|
+
...(url && { url }),
|
|
129
|
+
...(input ? { locations: toolLocationsFromInput(input) } : {}),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { DEFAULT_TOKEN_USAGE, addTokenUsage } from "../../../protocol/index.js";
|
|
2
|
+
import { cacheWriteDurations } from "./spend.js";
|
|
3
|
+
/** Context occupancy from an Anthropic usage block: full prompt + output. */
|
|
4
|
+
function contextTokens(usage) {
|
|
5
|
+
return ((usage.input_tokens ?? 0) +
|
|
6
|
+
(usage.cache_read_input_tokens ?? 0) +
|
|
7
|
+
(usage.cache_creation_input_tokens ?? 0) +
|
|
8
|
+
(usage.output_tokens ?? 0));
|
|
9
|
+
}
|
|
10
|
+
/** A model id as `modelUsage` keys it, without the window it asked for (`[1m]`). */
|
|
11
|
+
function withoutWindow(key) {
|
|
12
|
+
return key.replace(/\[.*\]$/, "");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A Claude turn's accounting: its tokens and cost summed over the turn's
|
|
16
|
+
* queries (a turn runs one more for each steer it got too late), the models
|
|
17
|
+
* that wrote its messages, and the context gauge (`session.usage`).
|
|
18
|
+
*/
|
|
19
|
+
export class ClaudeTurnUsage {
|
|
20
|
+
usage = { ...DEFAULT_TOKEN_USAGE };
|
|
21
|
+
/** The usage of the queries this turn finished. */
|
|
22
|
+
settled;
|
|
23
|
+
/** The context in use after the latest top-level model call (the gauge). */
|
|
24
|
+
contextUsed;
|
|
25
|
+
/** The model of that call: its window is the gauge's size. */
|
|
26
|
+
contextModel;
|
|
27
|
+
/** The model the query asked for, as `modelUsage` keys it (`claude-sonnet-5-5[1m]`). */
|
|
28
|
+
requestedModel;
|
|
29
|
+
/** A finished query's cost went unreported, so the turn's is unknown. */
|
|
30
|
+
costUnknown = false;
|
|
31
|
+
cost;
|
|
32
|
+
reportedModels = new Set();
|
|
33
|
+
/** The model the query asked for (`system/init`). */
|
|
34
|
+
requested(model) {
|
|
35
|
+
this.requestedModel = model;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A top-level model message: the model that wrote it (none for Claude
|
|
39
|
+
* Code's own), and the gauge from its usage. Every top-level message
|
|
40
|
+
* carries fresh usage; a sub-agent's context is its own and would
|
|
41
|
+
* misreport the session's.
|
|
42
|
+
*/
|
|
43
|
+
message(model, usage) {
|
|
44
|
+
if (model)
|
|
45
|
+
this.reportedModels.add(model);
|
|
46
|
+
if (!usage)
|
|
47
|
+
return [];
|
|
48
|
+
this.contextUsed = contextTokens(usage);
|
|
49
|
+
if (model)
|
|
50
|
+
this.contextModel = model;
|
|
51
|
+
return [{ kind: "usage", used: this.contextUsed }];
|
|
52
|
+
}
|
|
53
|
+
/** What the streaming model message has output so far (`message_delta`). */
|
|
54
|
+
streamed(outputTokens) {
|
|
55
|
+
this.usage.output = (this.settled?.output ?? 0) + outputTokens;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A query's result, and what the session says it spent (nothing when no
|
|
59
|
+
* session said so): the turn's usage and cost grow by the query's, and the
|
|
60
|
+
* gauge takes its final reading.
|
|
61
|
+
*/
|
|
62
|
+
settle(result, spent) {
|
|
63
|
+
const main = result.usage;
|
|
64
|
+
const query = spent?.usage ?? (main && this.mainLoop(main));
|
|
65
|
+
if (query) {
|
|
66
|
+
this.usage = this.settled ? addTokenUsage(this.settled, query) : query;
|
|
67
|
+
// A copy: the next query's streaming updates `this.usage` in place.
|
|
68
|
+
this.settled = structuredClone(this.usage);
|
|
69
|
+
}
|
|
70
|
+
if (spent?.costUsd == null)
|
|
71
|
+
this.costUnknown = true;
|
|
72
|
+
this.cost = this.costUnknown ? undefined : (this.cost ?? 0) + (spent?.costUsd ?? 0);
|
|
73
|
+
if (!main)
|
|
74
|
+
return [];
|
|
75
|
+
// Final gauge: the result knows the context-window size. Its `usage` sums
|
|
76
|
+
// every model call of the query, so the context in use stays the latest
|
|
77
|
+
// call's (a single call's sum is that call). `modelUsage` lists every
|
|
78
|
+
// model the process has used, keyed as requested (`claude-sonnet-5-5[1m]`):
|
|
79
|
+
// the size is the requested model's window, else the largest window of the
|
|
80
|
+
// latest call's model.
|
|
81
|
+
const windows = Object.entries(result.modelUsage ?? {});
|
|
82
|
+
const requested = windows.find(([key]) => key === this.requestedModel &&
|
|
83
|
+
(!this.contextModel || withoutWindow(key) === this.contextModel));
|
|
84
|
+
const used = windows.filter(([key]) => withoutWindow(key) === this.contextModel);
|
|
85
|
+
const size = (requested ? [requested] : used.length ? used : windows)
|
|
86
|
+
.map(([, model]) => model.contextWindow ?? 0)
|
|
87
|
+
.reduce((a, b) => Math.max(a, b), 0);
|
|
88
|
+
return [
|
|
89
|
+
{
|
|
90
|
+
kind: "usage",
|
|
91
|
+
used: this.contextUsed ?? contextTokens(main),
|
|
92
|
+
...(size > 0 && { size }),
|
|
93
|
+
...(this.cost !== undefined && { cost: this.cost }),
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
}
|
|
97
|
+
/** What the turn used and cost, and the models that wrote it. */
|
|
98
|
+
summary() {
|
|
99
|
+
return {
|
|
100
|
+
usage: this.usage,
|
|
101
|
+
...(this.reportedModels.size && { reportedModels: [...this.reportedModels] }),
|
|
102
|
+
cost: this.cost,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The query's usage where only the main loop's can say (a resumed
|
|
107
|
+
* process's first query): its output from the stream when the result
|
|
108
|
+
* leaves it out.
|
|
109
|
+
*/
|
|
110
|
+
mainLoop(main) {
|
|
111
|
+
return {
|
|
112
|
+
input: main.input_tokens ?? 0,
|
|
113
|
+
output: main.output_tokens ?? this.usage.output - (this.settled?.output ?? 0),
|
|
114
|
+
cache: {
|
|
115
|
+
read: main.cache_read_input_tokens ?? 0,
|
|
116
|
+
write: main.cache_creation_input_tokens ?? 0,
|
|
117
|
+
...cacheWriteDurations(main),
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|