pacework 1.7.1 → 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-ctl.mjs +61 -12
- package/bin/pacework-runner.mjs +82 -51
- package/lib/claude-activity.mjs +202 -0
- package/lib/service.mjs +46 -0
- package/lib/version.mjs +13 -0
- package/package.json +1 -1
|
@@ -41,9 +41,12 @@ import {
|
|
|
41
41
|
installService,
|
|
42
42
|
installStableCopy,
|
|
43
43
|
installCommandLauncher,
|
|
44
|
+
installedServiceVersion,
|
|
44
45
|
isServiceInstalled,
|
|
45
46
|
isServiceRunning,
|
|
47
|
+
moveServiceTo,
|
|
46
48
|
privacyProtectedFolder,
|
|
49
|
+
serviceNeedsUpdate,
|
|
47
50
|
serviceKind,
|
|
48
51
|
startService,
|
|
49
52
|
stopService,
|
|
@@ -72,6 +75,57 @@ async function checkForUpdate() {
|
|
|
72
75
|
} catch {}
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Move the login service to this copy of the runner when it runs an older one.
|
|
80
|
+
* The service runs the stable copy `up` saved, so installing a new version or
|
|
81
|
+
* restarting used to leave it on the old runner (PWK-307). Returns true when it
|
|
82
|
+
* moved.
|
|
83
|
+
*/
|
|
84
|
+
function moveServiceToThisVersion() {
|
|
85
|
+
if (!isServiceInstalled() || !LOCAL_VERSION) return false
|
|
86
|
+
const running = installedServiceVersion()
|
|
87
|
+
if (!serviceNeedsUpdate(running, LOCAL_VERSION)) return false
|
|
88
|
+
console.log(` Moving the runner service from ${running ?? "an older copy"} to \x1b[1m${LOCAL_VERSION}\x1b[0m…`)
|
|
89
|
+
try {
|
|
90
|
+
moveServiceTo(path.resolve(__dirname, ".."), LOCAL_VERSION)
|
|
91
|
+
return true
|
|
92
|
+
} catch (err) {
|
|
93
|
+
console.error(` Could not move the runner service to ${LOCAL_VERSION}: ${err.message}`)
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `pacework update`: install the newest published version and restart the
|
|
100
|
+
* runner on it. With nothing newer on npm, still move a service that runs an
|
|
101
|
+
* older copy than this one.
|
|
102
|
+
*/
|
|
103
|
+
async function updateRunner() {
|
|
104
|
+
console.log("Checking for updates…")
|
|
105
|
+
const latest = await latestPublishedVersion().catch(() => null)
|
|
106
|
+
if (!latest) {
|
|
107
|
+
console.log("\x1b[31mCould not reach npm registry.\x1b[0m")
|
|
108
|
+
return 1
|
|
109
|
+
}
|
|
110
|
+
if (!isNewerVersion(latest, LOCAL_VERSION)) {
|
|
111
|
+
console.log(`\x1b[32m✓\x1b[0m Already on latest (\x1b[1m${LOCAL_VERSION}\x1b[0m)`)
|
|
112
|
+
if (moveServiceToThisVersion()) console.log(`\x1b[32m✓\x1b[0m Runner service now runs ${LOCAL_VERSION}`)
|
|
113
|
+
return 0
|
|
114
|
+
}
|
|
115
|
+
console.log(`Updating ${LOCAL_VERSION} → \x1b[1m${latest}\x1b[0m…`)
|
|
116
|
+
const install = spawn("npm", ["install", "-g", `${NPM_PACKAGE}@${latest}`], { stdio: "inherit" })
|
|
117
|
+
const installed = await new Promise((resolve) => install.on("exit", (code) => resolve(code === 0)))
|
|
118
|
+
if (!installed) {
|
|
119
|
+
console.log("\x1b[31mnpm install failed; the runner keeps running the current version.\x1b[0m")
|
|
120
|
+
return 1
|
|
121
|
+
}
|
|
122
|
+
// This process is still the old version: restart through the new one, whose
|
|
123
|
+
// `start` moves the service to it.
|
|
124
|
+
console.log(`Restarting the runner on ${latest}…`)
|
|
125
|
+
const restart = spawn("npx", ["-y", `${NPM_PACKAGE}@${latest}`, "start"], { stdio: "inherit", env: process.env })
|
|
126
|
+
return await new Promise((resolve) => restart.on("exit", (code) => resolve(code ?? 1)))
|
|
127
|
+
}
|
|
128
|
+
|
|
75
129
|
// ── ascii banner ──────────────────────────────────────────────────────────────
|
|
76
130
|
|
|
77
131
|
const BANNER = `\x1b[38;5;39m${BANNER_LINES.map((line) => ` ${line}`).join("\n")}\x1b[0m`
|
|
@@ -279,6 +333,7 @@ ${row("pacework doctor", "Check this machine's setup")}
|
|
|
279
333
|
${row("pacework triage [--once]", "Only triage, in the foreground")}
|
|
280
334
|
${row("pacework up --token CODE", "One-step setup from the command in pacework's Runners page; asks for the runner's name and model")}
|
|
281
335
|
${row("pacework down", "Remove the background service")}
|
|
336
|
+
${row("pacework update", "Install the newest version and restart the runner on it")}
|
|
282
337
|
|
|
283
338
|
\x1b[1mRunner flags\x1b[0m ${d("for start, connect and up")}
|
|
284
339
|
--repo-root PATH --executor TOOL --name NAME --model ID --max-parallel-runs N --sandbox --no-triage
|
|
@@ -930,6 +985,7 @@ else if (command === "start") {
|
|
|
930
985
|
|
|
931
986
|
if (isServiceInstalled()) {
|
|
932
987
|
const logOffset = (() => { try { return fs.statSync(LOG_FILE).size } catch { return 0 } })()
|
|
988
|
+
moveServiceToThisVersion()
|
|
933
989
|
if (!isServiceRunning()) {
|
|
934
990
|
try { startService() } catch (err) { console.error(`Could not start the runner service: ${err.message}`); process.exit(1) }
|
|
935
991
|
}
|
|
@@ -1044,6 +1100,10 @@ run()
|
|
|
1044
1100
|
|
|
1045
1101
|
// ── stop ─────────────────────────────────────────────────────────────────────
|
|
1046
1102
|
|
|
1103
|
+
else if (command === "update") {
|
|
1104
|
+
process.exit(await updateRunner())
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1047
1107
|
else if (command === "stop") {
|
|
1048
1108
|
// With a login service, stop it first; otherwise it restarts the runner the
|
|
1049
1109
|
// moment the process below is killed.
|
|
@@ -2547,18 +2607,7 @@ else if (command === "shell" || command === "sh") {
|
|
|
2547
2607
|
break
|
|
2548
2608
|
}
|
|
2549
2609
|
case "update": {
|
|
2550
|
-
|
|
2551
|
-
try {
|
|
2552
|
-
const latest = await latestPublishedVersion()
|
|
2553
|
-
if (!latest) throw new Error("no version")
|
|
2554
|
-
if (!isNewerVersion(latest, LOCAL_VERSION)) {
|
|
2555
|
-
console.log(`\x1b[32m✓\x1b[0m Already on latest (\x1b[1m${LOCAL_VERSION}\x1b[0m)`)
|
|
2556
|
-
} else {
|
|
2557
|
-
console.log(`Updating ${LOCAL_VERSION} → \x1b[1m${latest}\x1b[0m…`)
|
|
2558
|
-
const child = spawn("npm", ["install", "-g", `${NPM_PACKAGE}@${latest}`], { stdio: "inherit" })
|
|
2559
|
-
await new Promise(r => child.on("exit", r))
|
|
2560
|
-
}
|
|
2561
|
-
} catch { console.log("\x1b[31mCould not reach npm registry.\x1b[0m") }
|
|
2610
|
+
await updateRunner()
|
|
2562
2611
|
break
|
|
2563
2612
|
}
|
|
2564
2613
|
case "login": {
|
package/bin/pacework-runner.mjs
CHANGED
|
@@ -33,6 +33,8 @@ 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"
|
|
37
|
+
import { RUNNER_VERSION } from "../lib/version.mjs"
|
|
36
38
|
|
|
37
39
|
function parseArgs(argv) {
|
|
38
40
|
const args = {}
|
|
@@ -453,39 +455,6 @@ function truncateHead(value, max = 40000) {
|
|
|
453
455
|
return `${value.slice(0, max)}\n\n... diff excerpt truncated (${omitted} more chars omitted)`
|
|
454
456
|
}
|
|
455
457
|
|
|
456
|
-
/**
|
|
457
|
-
* Claude Code's --output-format json result: the final message and what the run
|
|
458
|
-
* cost. Null when the output is not that JSON (an older CLI, a crash).
|
|
459
|
-
*/
|
|
460
|
-
function parseClaudeJsonResult(stdout) {
|
|
461
|
-
const lines = String(stdout || "").trim().split(/\r?\n/).reverse()
|
|
462
|
-
for (const line of lines) {
|
|
463
|
-
if (!line.trim().startsWith("{")) continue
|
|
464
|
-
try {
|
|
465
|
-
const parsed = JSON.parse(line)
|
|
466
|
-
if (parsed?.type !== "result") continue
|
|
467
|
-
const usage = parsed.usage ?? {}
|
|
468
|
-
const inputTokens = [usage.input_tokens, usage.cache_creation_input_tokens, usage.cache_read_input_tokens]
|
|
469
|
-
.filter((value) => typeof value === "number")
|
|
470
|
-
return {
|
|
471
|
-
text: typeof parsed.result === "string" ? parsed.result : "",
|
|
472
|
-
isError: parsed.is_error === true,
|
|
473
|
-
// "error_max_budget_usd" when --max-budget-usd ended the run.
|
|
474
|
-
subtype: typeof parsed.subtype === "string" ? parsed.subtype : null,
|
|
475
|
-
usage: {
|
|
476
|
-
cost_usd: typeof parsed.total_cost_usd === "number" ? parsed.total_cost_usd : null,
|
|
477
|
-
input_tokens: inputTokens.length ? inputTokens.reduce((a, b) => a + b, 0) : null,
|
|
478
|
-
output_tokens: typeof usage.output_tokens === "number" ? usage.output_tokens : null,
|
|
479
|
-
num_turns: typeof parsed.num_turns === "number" ? parsed.num_turns : null,
|
|
480
|
-
},
|
|
481
|
-
}
|
|
482
|
-
} catch {
|
|
483
|
-
// not the result line
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
return null
|
|
487
|
-
}
|
|
488
|
-
|
|
489
458
|
function formatChildExitError(executor, code, output) {
|
|
490
459
|
const tail = truncate(String(output || "").trim(), 4000)
|
|
491
460
|
return `${executor} exited with code ${code}${tail ? `\n\nLast output:\n${tail}` : ""}`
|
|
@@ -966,6 +935,7 @@ async function registerRunner() {
|
|
|
966
935
|
local_executor: defaultExecutor,
|
|
967
936
|
labels,
|
|
968
937
|
max_parallel_runs: maxParallelRuns,
|
|
938
|
+
...(RUNNER_VERSION ? { version: RUNNER_VERSION } : {}),
|
|
969
939
|
...(homeTeam ? { home_team: homeTeam } : {}),
|
|
970
940
|
...(availabilityMode ? { availability_mode: availabilityMode } : {}),
|
|
971
941
|
capabilities: runnerCapabilities(),
|
|
@@ -1041,6 +1011,9 @@ async function heartbeat(state, status = "online") {
|
|
|
1041
1011
|
runner_id: state.runner_id,
|
|
1042
1012
|
status,
|
|
1043
1013
|
local_executors: installedExecutors,
|
|
1014
|
+
// Sent on every heartbeat, so the runner list shows the version a
|
|
1015
|
+
// runner is on now, not the one it registered with.
|
|
1016
|
+
...(RUNNER_VERSION ? { version: RUNNER_VERSION } : {}),
|
|
1044
1017
|
capabilities: runnerCapabilities(),
|
|
1045
1018
|
}),
|
|
1046
1019
|
})
|
|
@@ -1084,8 +1057,15 @@ function runMcpKey(run, state) {
|
|
|
1084
1057
|
return run.mcp_api_key || run.planner_api_key || state.runner_mcp_key
|
|
1085
1058
|
}
|
|
1086
1059
|
|
|
1087
|
-
|
|
1088
|
-
|
|
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`, {
|
|
1089
1069
|
method: "POST",
|
|
1090
1070
|
headers: {
|
|
1091
1071
|
"Content-Type": "application/json",
|
|
@@ -1097,8 +1077,18 @@ async function postRunLog(state, runId, logTail) {
|
|
|
1097
1077
|
run_id: runId,
|
|
1098
1078
|
log_tail: truncate(logTail, 12000),
|
|
1099
1079
|
heartbeat_at: new Date().toISOString(),
|
|
1080
|
+
...(withActivity ? activity : {}),
|
|
1100
1081
|
}),
|
|
1101
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
|
+
}
|
|
1102
1092
|
}
|
|
1103
1093
|
|
|
1104
1094
|
function omitNullishEntries(record) {
|
|
@@ -2128,23 +2118,37 @@ function claudeRunSettings(run) {
|
|
|
2128
2118
|
return Object.keys(settings).length ? JSON.stringify(settings) : null
|
|
2129
2119
|
}
|
|
2130
2120
|
|
|
2131
|
-
/**
|
|
2132
|
-
let
|
|
2133
|
-
function
|
|
2134
|
-
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) {
|
|
2135
2125
|
try {
|
|
2136
|
-
|
|
2137
|
-
claudeMaxBudgetSupport = help.includes("--max-budget-usd")
|
|
2126
|
+
claudeHelp = execFileSync(claudeCodeBin, ["--help"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15_000 })
|
|
2138
2127
|
} catch {
|
|
2139
|
-
|
|
2128
|
+
claudeHelp = ""
|
|
2140
2129
|
}
|
|
2141
2130
|
}
|
|
2142
|
-
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")
|
|
2143
2137
|
}
|
|
2144
2138
|
|
|
2145
2139
|
/**
|
|
2146
|
-
*
|
|
2147
|
-
*
|
|
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.
|
|
2148
2152
|
*/
|
|
2149
2153
|
function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, options = {}) {
|
|
2150
2154
|
const requestedModel = resolveRequestedModel(run)
|
|
@@ -2199,9 +2203,9 @@ function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, opt
|
|
|
2199
2203
|
const argsList = [
|
|
2200
2204
|
"-p",
|
|
2201
2205
|
prompt,
|
|
2202
|
-
// json: the same final message, plus what the run cost.
|
|
2203
|
-
|
|
2204
|
-
"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"]),
|
|
2205
2209
|
"--permission-mode",
|
|
2206
2210
|
"acceptEdits",
|
|
2207
2211
|
"--dangerously-skip-permissions",
|
|
@@ -2229,7 +2233,7 @@ function buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, opt
|
|
|
2229
2233
|
command: claudeCodeBin,
|
|
2230
2234
|
args: argsList,
|
|
2231
2235
|
stdin: null,
|
|
2232
|
-
summaryMode: "claude_json",
|
|
2236
|
+
summaryMode: options.streamActivity ? "claude_stream" : "claude_json",
|
|
2233
2237
|
}
|
|
2234
2238
|
}
|
|
2235
2239
|
|
|
@@ -3180,6 +3184,7 @@ async function runExecutor(run, state) {
|
|
|
3180
3184
|
].filter(Boolean).join("\n\n")
|
|
3181
3185
|
const execSpec = buildExecutorCommand(run, worktreePath, prompt, outputFile, mcpKey, {
|
|
3182
3186
|
maxCostUsd: costLimitApplies ? runLimits.maxCostUsd : null,
|
|
3187
|
+
streamActivity: activeExecutor() === "claude_code" && claudeSupportsStreamJson(),
|
|
3183
3188
|
})
|
|
3184
3189
|
// These steps run before the executor spawns; when one stalls the run sits in
|
|
3185
3190
|
// "running" with no output, so each is traced.
|
|
@@ -3202,6 +3207,21 @@ async function runExecutor(run, state) {
|
|
|
3202
3207
|
let stdioSummary = ""
|
|
3203
3208
|
// Claude Code's JSON result arrives on stdout only; stderr would break parsing.
|
|
3204
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
|
+
}
|
|
3205
3225
|
let runUsage = null
|
|
3206
3226
|
let cancelRequested = false
|
|
3207
3227
|
let childProcess = null
|
|
@@ -3232,7 +3252,9 @@ async function runExecutor(run, state) {
|
|
|
3232
3252
|
|
|
3233
3253
|
async function flushRunnerLog() {
|
|
3234
3254
|
appendHeartbeat()
|
|
3235
|
-
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)
|
|
3236
3258
|
if (runEndedOnServer(response)) {
|
|
3237
3259
|
cancelRequested = true
|
|
3238
3260
|
if (childProcess && !childProcess.killed) {
|
|
@@ -3380,6 +3402,9 @@ async function runExecutor(run, state) {
|
|
|
3380
3402
|
|
|
3381
3403
|
child.stdout.on("data", chunk => {
|
|
3382
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 }
|
|
3383
3408
|
if (execSpec.summaryMode === "claude_json") stdoutRaw = truncate(`${stdoutRaw}${text}`, 2_000_000)
|
|
3384
3409
|
appendLogTail(logState, text)
|
|
3385
3410
|
stdioSummary = truncate(`${stdioSummary}\n${text}`, 16000)
|
|
@@ -3395,7 +3420,13 @@ async function runExecutor(run, state) {
|
|
|
3395
3420
|
})
|
|
3396
3421
|
child.on("close", code => {
|
|
3397
3422
|
appendLogTail(logState, `> executor exited with code ${code}`)
|
|
3398
|
-
|
|
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) {
|
|
3399
3430
|
const result = parseClaudeJsonResult(stdoutRaw)
|
|
3400
3431
|
if (result) {
|
|
3401
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
|
+
|
package/lib/service.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import path from "node:path"
|
|
|
4
4
|
import process from "node:process"
|
|
5
5
|
import { execFileSync } from "node:child_process"
|
|
6
6
|
import { PACEWORK_DIR, LOG_FILE, USES_LEGACY_DIR } from "./control-state.mjs"
|
|
7
|
+
import { isNewerVersion } from "./version.mjs"
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Run the runner as an OS-managed login service, so it starts at login, restarts
|
|
@@ -230,6 +231,51 @@ WantedBy=default.target
|
|
|
230
231
|
return { kind, file }
|
|
231
232
|
}
|
|
232
233
|
|
|
234
|
+
/**
|
|
235
|
+
* The runner version a service file starts: the `<version>` in the stable copy's
|
|
236
|
+
* path, `.../runner-app/<version>/bin/pacework-runner-ctl.mjs`. Null when the
|
|
237
|
+
* file points somewhere else (an install from before stable copies).
|
|
238
|
+
*/
|
|
239
|
+
export function serviceVersionFromFile(text) {
|
|
240
|
+
const match = String(text || "").match(/runner-app[\\/]+([^\\/<"'\s]+)[\\/]+bin[\\/]+pacework-runner-ctl\.mjs/)
|
|
241
|
+
return match ? match[1] : null
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The runner version the installed login service runs, or null when unknown or not installed. */
|
|
245
|
+
export function installedServiceVersion() {
|
|
246
|
+
const file = serviceFilePath()
|
|
247
|
+
if (!file) return null
|
|
248
|
+
try {
|
|
249
|
+
return serviceVersionFromFile(fs.readFileSync(file, "utf8"))
|
|
250
|
+
} catch {
|
|
251
|
+
return null
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Whether the service should move to `version`. It keeps running the copy `up`
|
|
257
|
+
* saved, so updating the package or restarting left it on the old runner
|
|
258
|
+
* (PWK-307). Never moves it back to an older version: an old copy in npx's
|
|
259
|
+
* cache must not downgrade a newer service.
|
|
260
|
+
*/
|
|
261
|
+
export function serviceNeedsUpdate(installedVersion, version) {
|
|
262
|
+
if (!version) return false
|
|
263
|
+
if (!installedVersion) return true
|
|
264
|
+
return isNewerVersion(version, installedVersion)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Point the login service at a stable copy of the package in `sourceRoot` and
|
|
269
|
+
* restart it from there. Returns the new control script's path.
|
|
270
|
+
*/
|
|
271
|
+
export function moveServiceTo(sourceRoot, version) {
|
|
272
|
+
stopService()
|
|
273
|
+
const ctlPath = installStableCopy(sourceRoot, version)
|
|
274
|
+
try { installCommandLauncher(ctlPath) } catch {}
|
|
275
|
+
installService({ ctlPath })
|
|
276
|
+
return ctlPath
|
|
277
|
+
}
|
|
278
|
+
|
|
233
279
|
/** Start an installed service that was stopped. */
|
|
234
280
|
export function startService() {
|
|
235
281
|
const kind = serviceKind()
|
package/lib/version.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import fs from "node:fs"
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* The CLI's own npm package. The update check and `pacework update` both use
|
|
3
5
|
* this name: they used to ask for "pacework-runner", a name nobody owns, so no
|
|
@@ -25,3 +27,14 @@ export async function latestPublishedVersion(fetchImpl = fetch) {
|
|
|
25
27
|
const { version } = await res.json()
|
|
26
28
|
return typeof version === "string" ? version : null
|
|
27
29
|
}
|
|
30
|
+
|
|
31
|
+
/** This package's own version, from its package.json; null when it cannot be read. */
|
|
32
|
+
export const RUNNER_VERSION = (() => {
|
|
33
|
+
try {
|
|
34
|
+
const raw = fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")
|
|
35
|
+
const version = JSON.parse(raw).version
|
|
36
|
+
return typeof version === "string" ? version : null
|
|
37
|
+
} catch {
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
})()
|