pacework 1.7.2 → 1.7.3
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/bin/pacework-runner.mjs +77 -51
- package/lib/claude-activity.mjs +202 -0
- package/package.json +1 -1
package/bin/pacework-runner.mjs
CHANGED
|
@@ -33,6 +33,7 @@ import { AVAILABILITY_MODES, describeRegistration, isRevokedError, registrationC
|
|
|
33
33
|
import { describeTriageJob, runTriageLoop, TRIAGE_EXECUTORS } from "../lib/triage-worker.mjs"
|
|
34
34
|
import { automationDenyRules, automationLimits } from "../lib/automation-limits.mjs"
|
|
35
35
|
import { truncateSummary } from "../lib/summary-text.mjs"
|
|
36
|
+
import { activityForStreamEvent, createActivityTracker, createStreamReader, helpSupportsStreamJson, parseClaudeJsonResult } from "../lib/claude-activity.mjs"
|
|
36
37
|
import { RUNNER_VERSION } from "../lib/version.mjs"
|
|
37
38
|
|
|
38
39
|
function parseArgs(argv) {
|
|
@@ -454,39 +455,6 @@ function truncateHead(value, max = 40000) {
|
|
|
454
455
|
return `${value.slice(0, max)}\n\n... diff excerpt truncated (${omitted} more chars omitted)`
|
|
455
456
|
}
|
|
456
457
|
|
|
457
|
-
/**
|
|
458
|
-
* Claude Code's --output-format json result: the final message and what the run
|
|
459
|
-
* cost. Null when the output is not that JSON (an older CLI, a crash).
|
|
460
|
-
*/
|
|
461
|
-
function parseClaudeJsonResult(stdout) {
|
|
462
|
-
const lines = String(stdout || "").trim().split(/\r?\n/).reverse()
|
|
463
|
-
for (const line of lines) {
|
|
464
|
-
if (!line.trim().startsWith("{")) continue
|
|
465
|
-
try {
|
|
466
|
-
const parsed = JSON.parse(line)
|
|
467
|
-
if (parsed?.type !== "result") continue
|
|
468
|
-
const usage = parsed.usage ?? {}
|
|
469
|
-
const inputTokens = [usage.input_tokens, usage.cache_creation_input_tokens, usage.cache_read_input_tokens]
|
|
470
|
-
.filter((value) => typeof value === "number")
|
|
471
|
-
return {
|
|
472
|
-
text: typeof parsed.result === "string" ? parsed.result : "",
|
|
473
|
-
isError: parsed.is_error === true,
|
|
474
|
-
// "error_max_budget_usd" when --max-budget-usd ended the run.
|
|
475
|
-
subtype: typeof parsed.subtype === "string" ? parsed.subtype : null,
|
|
476
|
-
usage: {
|
|
477
|
-
cost_usd: typeof parsed.total_cost_usd === "number" ? parsed.total_cost_usd : null,
|
|
478
|
-
input_tokens: inputTokens.length ? inputTokens.reduce((a, b) => a + b, 0) : null,
|
|
479
|
-
output_tokens: typeof usage.output_tokens === "number" ? usage.output_tokens : null,
|
|
480
|
-
num_turns: typeof parsed.num_turns === "number" ? parsed.num_turns : null,
|
|
481
|
-
},
|
|
482
|
-
}
|
|
483
|
-
} catch {
|
|
484
|
-
// not the result line
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
return null
|
|
488
|
-
}
|
|
489
|
-
|
|
490
458
|
function formatChildExitError(executor, code, output) {
|
|
491
459
|
const tail = truncate(String(output || "").trim(), 4000)
|
|
492
460
|
return `${executor} exited with code ${code}${tail ? `\n\nLast output:\n${tail}` : ""}`
|
|
@@ -1089,8 +1057,15 @@ function runMcpKey(run, state) {
|
|
|
1089
1057
|
return run.mcp_api_key || run.planner_api_key || state.runner_mcp_key
|
|
1090
1058
|
}
|
|
1091
1059
|
|
|
1092
|
-
|
|
1093
|
-
|
|
1060
|
+
/** False once the server refused an activity report: an older server rejects unknown fields. */
|
|
1061
|
+
let serverTakesActivity = true
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* @param {{ activity: string, activity_at: string } | null} [activity] What the agent
|
|
1065
|
+
* is doing now (PWK-317). Only the value and when it changed, never content.
|
|
1066
|
+
*/
|
|
1067
|
+
async function postRunLog(state, runId, logTail, activity = null) {
|
|
1068
|
+
const send = (withActivity) => requestJson(`${appUrl}/api/agent-runners/runs/${runId}/log`, {
|
|
1094
1069
|
method: "POST",
|
|
1095
1070
|
headers: {
|
|
1096
1071
|
"Content-Type": "application/json",
|
|
@@ -1102,8 +1077,18 @@ async function postRunLog(state, runId, logTail) {
|
|
|
1102
1077
|
run_id: runId,
|
|
1103
1078
|
log_tail: truncate(logTail, 12000),
|
|
1104
1079
|
heartbeat_at: new Date().toISOString(),
|
|
1080
|
+
...(withActivity ? activity : {}),
|
|
1105
1081
|
}),
|
|
1106
1082
|
})
|
|
1083
|
+
if (!activity || !serverTakesActivity) return send(false)
|
|
1084
|
+
try {
|
|
1085
|
+
return await send(true)
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
if (error?.status !== 400) throw error
|
|
1088
|
+
// A server without activity support: stop sending it, and still deliver the log.
|
|
1089
|
+
serverTakesActivity = false
|
|
1090
|
+
return send(false)
|
|
1091
|
+
}
|
|
1107
1092
|
}
|
|
1108
1093
|
|
|
1109
1094
|
function omitNullishEntries(record) {
|
|
@@ -2133,23 +2118,37 @@ function claudeRunSettings(run) {
|
|
|
2133
2118
|
return Object.keys(settings).length ? JSON.stringify(settings) : null
|
|
2134
2119
|
}
|
|
2135
2120
|
|
|
2136
|
-
/**
|
|
2137
|
-
let
|
|
2138
|
-
function
|
|
2139
|
-
if (
|
|
2121
|
+
/** This machine's `claude --help`, read once; empty when it cannot be read. */
|
|
2122
|
+
let claudeHelp = null
|
|
2123
|
+
function claudeHelpText() {
|
|
2124
|
+
if (claudeHelp === null) {
|
|
2140
2125
|
try {
|
|
2141
|
-
|
|
2142
|
-
claudeMaxBudgetSupport = help.includes("--max-budget-usd")
|
|
2126
|
+
claudeHelp = execFileSync(claudeCodeBin, ["--help"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15_000 })
|
|
2143
2127
|
} catch {
|
|
2144
|
-
|
|
2128
|
+
claudeHelp = ""
|
|
2145
2129
|
}
|
|
2146
2130
|
}
|
|
2147
|
-
return
|
|
2131
|
+
return claudeHelp
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
/** Whether this machine's Claude Code takes --max-budget-usd; an older one would refuse to start. */
|
|
2135
|
+
function claudeSupportsMaxBudget() {
|
|
2136
|
+
return claudeHelpText().includes("--max-budget-usd")
|
|
2148
2137
|
}
|
|
2149
2138
|
|
|
2150
2139
|
/**
|
|
2151
|
-
*
|
|
2152
|
-
*
|
|
2140
|
+
* Whether this machine's Claude Code streams events (`--output-format stream-json`
|
|
2141
|
+
* with `--verbose`), which is how a run reports what it is doing. An older one
|
|
2142
|
+
* runs with the single JSON result and reports no activity.
|
|
2143
|
+
*/
|
|
2144
|
+
function claudeSupportsStreamJson() {
|
|
2145
|
+
return helpSupportsStreamJson(claudeHelpText())
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
/**
|
|
2149
|
+
* @param {{ maxCostUsd?: number | null, streamActivity?: boolean }} [options] The run's
|
|
2150
|
+
* cost limit, for Claude Code: it ends the run itself once the limit is spent.
|
|
2151
|
+
* streamActivity: Claude Code streams events, so the run can report what it is doing.
|
|
2153
2152
|
*/
|
|
2154
2153
|
function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, options = {}) {
|
|
2155
2154
|
const requestedModel = resolveRequestedModel(run)
|
|
@@ -2204,9 +2203,9 @@ function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, opt
|
|
|
2204
2203
|
const argsList = [
|
|
2205
2204
|
"-p",
|
|
2206
2205
|
prompt,
|
|
2207
|
-
// json: the same final message, plus what the run cost.
|
|
2208
|
-
|
|
2209
|
-
"json",
|
|
2206
|
+
// json: the same final message, plus what the run cost. stream-json ends with
|
|
2207
|
+
// that same result as its last event, and shows what the agent does on the way.
|
|
2208
|
+
...(options.streamActivity ? ["--output-format", "stream-json", "--verbose"] : ["--output-format", "json"]),
|
|
2210
2209
|
"--permission-mode",
|
|
2211
2210
|
"acceptEdits",
|
|
2212
2211
|
"--dangerously-skip-permissions",
|
|
@@ -2234,7 +2233,7 @@ function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, opt
|
|
|
2234
2233
|
command: claudeCodeBin,
|
|
2235
2234
|
args: argsList,
|
|
2236
2235
|
stdin: null,
|
|
2237
|
-
summaryMode: "claude_json",
|
|
2236
|
+
summaryMode: options.streamActivity ? "claude_stream" : "claude_json",
|
|
2238
2237
|
}
|
|
2239
2238
|
}
|
|
2240
2239
|
|
|
@@ -3185,6 +3184,7 @@ async function runExecutor(run, state) {
|
|
|
3185
3184
|
].filter(Boolean).join("\n\n")
|
|
3186
3185
|
const execSpec = buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, {
|
|
3187
3186
|
maxCostUsd: costLimitApplies ? runLimits.maxCostUsd : null,
|
|
3187
|
+
streamActivity: activeExecutor() === "claude_code" && claudeSupportsStreamJson(),
|
|
3188
3188
|
})
|
|
3189
3189
|
// These steps run before the executor spawns; when one stalls the run sits in
|
|
3190
3190
|
// "running" with no output, so each is traced.
|
|
@@ -3207,6 +3207,21 @@ async function runExecutor(run, state) {
|
|
|
3207
3207
|
let stdioSummary = ""
|
|
3208
3208
|
// Claude Code's JSON result arrives on stdout only; stderr would break parsing.
|
|
3209
3209
|
let stdoutRaw = ""
|
|
3210
|
+
const claudeResultMode = execSpec.summaryMode === "claude_json" || execSpec.summaryMode === "claude_stream"
|
|
3211
|
+
/** What the agent is doing, from Claude Code's event stream (PWK-317). Null for every other executor. */
|
|
3212
|
+
let activity = null
|
|
3213
|
+
let streamReader = null
|
|
3214
|
+
if (execSpec.summaryMode === "claude_stream") {
|
|
3215
|
+
activity = createActivityTracker()
|
|
3216
|
+
streamReader = createStreamReader({
|
|
3217
|
+
onEvent: (event) => activity.observe(activityForStreamEvent(event)),
|
|
3218
|
+
// Not an event: something the CLI printed itself, kept for the log as before.
|
|
3219
|
+
onOtherLine: (line) => {
|
|
3220
|
+
appendLogTail(logState, line)
|
|
3221
|
+
stdioSummary = truncate(`${stdioSummary}\n${line}`, 16000)
|
|
3222
|
+
},
|
|
3223
|
+
})
|
|
3224
|
+
}
|
|
3210
3225
|
let runUsage = null
|
|
3211
3226
|
let cancelRequested = false
|
|
3212
3227
|
let childProcess = null
|
|
@@ -3237,7 +3252,9 @@ async function runExecutor(run, state) {
|
|
|
3237
3252
|
|
|
3238
3253
|
async function flushRunnerLog() {
|
|
3239
3254
|
appendHeartbeat()
|
|
3240
|
-
const
|
|
3255
|
+
const report = activity && childProcess && !childProcess.killed ? activity.due() : null
|
|
3256
|
+
const response = await postRunLog(state, run.id, logState.tail, report)
|
|
3257
|
+
if (report) activity.markSent(report)
|
|
3241
3258
|
if (runEndedOnServer(response)) {
|
|
3242
3259
|
cancelRequested = true
|
|
3243
3260
|
if (childProcess && !childProcess.killed) {
|
|
@@ -3385,6 +3402,9 @@ async function runExecutor(run, state) {
|
|
|
3385
3402
|
|
|
3386
3403
|
child.stdout.on("data", chunk => {
|
|
3387
3404
|
const text = chunk.toString()
|
|
3405
|
+
// The event stream stays on this machine: only the final result is kept,
|
|
3406
|
+
// and only lines that are not events reach the log.
|
|
3407
|
+
if (streamReader) { streamReader.push(text); return }
|
|
3388
3408
|
if (execSpec.summaryMode === "claude_json") stdoutRaw = truncate(`${stdoutRaw}${text}`, 2_000_000)
|
|
3389
3409
|
appendLogTail(logState, text)
|
|
3390
3410
|
stdioSummary = truncate(`${stdioSummary}\n${text}`, 16000)
|
|
@@ -3400,7 +3420,13 @@ async function runExecutor(run, state) {
|
|
|
3400
3420
|
})
|
|
3401
3421
|
child.on("close", code => {
|
|
3402
3422
|
appendLogTail(logState, `> executor exited with code ${code}`)
|
|
3403
|
-
|
|
3423
|
+
// The agent is no longer doing anything; the server clears the value when the run ends.
|
|
3424
|
+
activity = null
|
|
3425
|
+
if (streamReader) {
|
|
3426
|
+
streamReader.end()
|
|
3427
|
+
stdoutRaw = streamReader.resultText()
|
|
3428
|
+
}
|
|
3429
|
+
if (claudeResultMode) {
|
|
3404
3430
|
const result = parseClaudeJsonResult(stdoutRaw)
|
|
3405
3431
|
if (result) {
|
|
3406
3432
|
// Claude Code prices every run at Anthropic's rates; for
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a Claude Code run is doing right now (PWK-317), for the Workers office.
|
|
3
|
+
*
|
|
4
|
+
* With `--output-format stream-json --verbose`, Claude Code prints one JSON event
|
|
5
|
+
* per line while it works and ends with a `result` event that carries the same
|
|
6
|
+
* fields as the single `--output-format json` result. This module turns those
|
|
7
|
+
* events into one of five activity values and decides when to send a change.
|
|
8
|
+
*
|
|
9
|
+
* Only the value and when it changed ever leave the machine: no file names,
|
|
10
|
+
* commands, prompts or text.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const RUN_ACTIVITIES = ["writing", "reading", "running", "thinking", "waiting"]
|
|
14
|
+
|
|
15
|
+
/** At most one activity report per run in this window. */
|
|
16
|
+
export const ACTIVITY_MIN_INTERVAL_MS = 5_000
|
|
17
|
+
/**
|
|
18
|
+
* The runner sends its log every 5 seconds, and timers drift by a few milliseconds:
|
|
19
|
+
* two ticks can be 4,999 ms apart. Without this slack every other tick would be
|
|
20
|
+
* skipped and a change would take 10 seconds to show.
|
|
21
|
+
*/
|
|
22
|
+
export const ACTIVITY_TICK_SLACK_MS = 250
|
|
23
|
+
/** Silence from the agent this long, while its process is alive, reads as waiting. */
|
|
24
|
+
export const ACTIVITY_WAITING_AFTER_MS = 60_000
|
|
25
|
+
/** A single event line longer than this is not kept whole (a huge tool result, for example). */
|
|
26
|
+
const MAX_LINE_CHARS = 1_000_000
|
|
27
|
+
|
|
28
|
+
const WRITING_TOOLS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"])
|
|
29
|
+
const READING_TOOLS = new Set(["Read", "Grep", "Glob", "LS", "WebFetch", "WebSearch", "NotebookRead", "ToolSearch", "ListMcpResourcesTool", "ReadMcpResourceTool"])
|
|
30
|
+
const RUNNING_TOOLS = new Set(["Bash", "BashOutput", "KillBash", "KillShell", "Monitor"])
|
|
31
|
+
|
|
32
|
+
/** The activity for one tool name. MCP tools look things up, so they read; anything else is the agent working things out. */
|
|
33
|
+
export function activityForTool(name) {
|
|
34
|
+
const tool = String(name || "")
|
|
35
|
+
if (WRITING_TOOLS.has(tool)) return "writing"
|
|
36
|
+
if (READING_TOOLS.has(tool)) return "reading"
|
|
37
|
+
if (RUNNING_TOOLS.has(tool)) return "running"
|
|
38
|
+
if (tool.startsWith("mcp__")) return "reading"
|
|
39
|
+
return "thinking"
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The activity one stream event shows, or null when it shows nothing new (system
|
|
44
|
+
* events, rate limit notices, the final result).
|
|
45
|
+
*
|
|
46
|
+
* - An assistant message that uses a tool: that tool's activity (the last tool when it uses several).
|
|
47
|
+
* - An assistant message with text or reasoning only: thinking.
|
|
48
|
+
* - A tool result coming back: the agent is reading it and deciding what to do next, so thinking.
|
|
49
|
+
*/
|
|
50
|
+
export function activityForStreamEvent(event) {
|
|
51
|
+
if (!event || typeof event !== "object") return null
|
|
52
|
+
const content = Array.isArray(event.message?.content) ? event.message.content : []
|
|
53
|
+
if (event.type === "assistant") {
|
|
54
|
+
const tools = content.filter((block) => block?.type === "tool_use")
|
|
55
|
+
if (tools.length) return activityForTool(tools[tools.length - 1].name)
|
|
56
|
+
if (content.some((block) => block?.type === "text" || block?.type === "thinking" || block?.type === "redacted_thinking")) return "thinking"
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
if (event.type === "user" && content.some((block) => block?.type === "tool_result")) return "thinking"
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Reads Claude Code's stream line by line as chunks arrive. Holds at most one
|
|
65
|
+
* partial line and the final result line, never the whole stream.
|
|
66
|
+
*
|
|
67
|
+
* @param {{ onEvent?: (event: object) => void, onOtherLine?: (line: string) => void }} handlers
|
|
68
|
+
* onEvent gets each parsed JSON event; onOtherLine gets lines that are not JSON
|
|
69
|
+
* (an error printed by the CLI, for example), so they still reach the log.
|
|
70
|
+
*/
|
|
71
|
+
export function createStreamReader({ onEvent, onOtherLine } = {}) {
|
|
72
|
+
let partial = ""
|
|
73
|
+
let resultLine = null
|
|
74
|
+
let overflow = false
|
|
75
|
+
|
|
76
|
+
function line(raw) {
|
|
77
|
+
const text = raw.trim()
|
|
78
|
+
if (!text) return
|
|
79
|
+
if (!text.startsWith("{")) {
|
|
80
|
+
onOtherLine?.(text)
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
let event
|
|
84
|
+
try {
|
|
85
|
+
event = JSON.parse(text)
|
|
86
|
+
} catch {
|
|
87
|
+
onOtherLine?.(text)
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
if (event?.type === "result") resultLine = text
|
|
91
|
+
onEvent?.(event)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
push(chunk) {
|
|
96
|
+
const text = partial + String(chunk ?? "")
|
|
97
|
+
const lines = text.split(/\r?\n/)
|
|
98
|
+
partial = lines.pop() ?? ""
|
|
99
|
+
if (partial.length > MAX_LINE_CHARS) {
|
|
100
|
+
// Not an event we need whole; drop it rather than grow without limit.
|
|
101
|
+
partial = ""
|
|
102
|
+
overflow = true
|
|
103
|
+
}
|
|
104
|
+
for (const raw of lines) {
|
|
105
|
+
if (overflow) { overflow = false; continue }
|
|
106
|
+
line(raw)
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
end() {
|
|
110
|
+
if (partial && !overflow) line(partial)
|
|
111
|
+
partial = ""
|
|
112
|
+
overflow = false
|
|
113
|
+
},
|
|
114
|
+
/** The final result event's line, in the form parseClaudeJsonResult reads. Empty until it arrives. */
|
|
115
|
+
resultText() {
|
|
116
|
+
return resultLine ?? ""
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Tracks a run's activity and decides when to send it: only when it changed,
|
|
123
|
+
* at most once per `minIntervalMs`, and as `waiting` once the agent has been
|
|
124
|
+
* silent for `waitingAfterMs`.
|
|
125
|
+
*/
|
|
126
|
+
export function createActivityTracker({ startedAt = Date.now(), minIntervalMs = ACTIVITY_MIN_INTERVAL_MS, waitingAfterMs = ACTIVITY_WAITING_AFTER_MS } = {}) {
|
|
127
|
+
let current = null
|
|
128
|
+
let currentAt = null
|
|
129
|
+
let lastEventAt = startedAt
|
|
130
|
+
let sent = null
|
|
131
|
+
let sentAt = -Infinity
|
|
132
|
+
|
|
133
|
+
function set(activity, at) {
|
|
134
|
+
if (activity === current) return
|
|
135
|
+
current = activity
|
|
136
|
+
currentAt = at
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
/** An event arrived from the agent. `activity` is null when the event shows no activity of its own. */
|
|
141
|
+
observe(activity, at = Date.now()) {
|
|
142
|
+
lastEventAt = at
|
|
143
|
+
if (activity) set(activity, at)
|
|
144
|
+
// Any sign of life ends a wait; the agent was last seen doing what it does now.
|
|
145
|
+
else if (current === "waiting") set("thinking", at)
|
|
146
|
+
},
|
|
147
|
+
/** The value to send now, or null when nothing should be sent. Call markSent once it was sent. */
|
|
148
|
+
due(now = Date.now()) {
|
|
149
|
+
if (now - lastEventAt >= waitingAfterMs) set("waiting", lastEventAt + waitingAfterMs)
|
|
150
|
+
if (!current || current === sent) return null
|
|
151
|
+
if (now - sentAt < minIntervalMs - ACTIVITY_TICK_SLACK_MS) return null
|
|
152
|
+
return { activity: current, activity_at: new Date(currentAt).toISOString() }
|
|
153
|
+
},
|
|
154
|
+
markSent(report, now = Date.now()) {
|
|
155
|
+
sent = report.activity
|
|
156
|
+
sentAt = now
|
|
157
|
+
},
|
|
158
|
+
current() {
|
|
159
|
+
return current
|
|
160
|
+
},
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Whether this Claude Code's help text offers streaming output. */
|
|
165
|
+
export function helpSupportsStreamJson(help) {
|
|
166
|
+
return /stream-json/.test(String(help || "")) && /--verbose/.test(String(help || ""))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Claude Code's result (the --output-format json line, or the last event of
|
|
171
|
+
* stream-json): the final message and what the run
|
|
172
|
+
* cost. Null when the output is not that JSON (an older CLI, a crash).
|
|
173
|
+
*/
|
|
174
|
+
export function parseClaudeJsonResult(stdout) {
|
|
175
|
+
const lines = String(stdout || "").trim().split(/\r?\n/).reverse()
|
|
176
|
+
for (const line of lines) {
|
|
177
|
+
if (!line.trim().startsWith("{")) continue
|
|
178
|
+
try {
|
|
179
|
+
const parsed = JSON.parse(line)
|
|
180
|
+
if (parsed?.type !== "result") continue
|
|
181
|
+
const usage = parsed.usage ?? {}
|
|
182
|
+
const inputTokens = [usage.input_tokens, usage.cache_creation_input_tokens, usage.cache_read_input_tokens]
|
|
183
|
+
.filter((value) => typeof value === "number")
|
|
184
|
+
return {
|
|
185
|
+
text: typeof parsed.result === "string" ? parsed.result : "",
|
|
186
|
+
isError: parsed.is_error === true,
|
|
187
|
+
// "error_max_budget_usd" when --max-budget-usd ended the run.
|
|
188
|
+
subtype: typeof parsed.subtype === "string" ? parsed.subtype : null,
|
|
189
|
+
usage: {
|
|
190
|
+
cost_usd: typeof parsed.total_cost_usd === "number" ? parsed.total_cost_usd : null,
|
|
191
|
+
input_tokens: inputTokens.length ? inputTokens.reduce((a, b) => a + b, 0) : null,
|
|
192
|
+
output_tokens: typeof usage.output_tokens === "number" ? usage.output_tokens : null,
|
|
193
|
+
num_turns: typeof parsed.num_turns === "number" ? parsed.num_turns : null,
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
} catch {
|
|
197
|
+
// not the result line
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return null
|
|
201
|
+
}
|
|
202
|
+
|