ticket-runner 0.6.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/LICENSE +21 -0
- package/README.ko.md +97 -0
- package/README.md +98 -0
- package/bin/ticket-runner.js +6 -0
- package/docs/templates/operator-skill.md +87 -0
- package/package.json +42 -0
- package/src/acceptance-criteria.ts +44 -0
- package/src/adapters/claude-agent-runner.ts +389 -0
- package/src/adapters/exec.ts +169 -0
- package/src/adapters/gh-tracker.ts +955 -0
- package/src/adapters/git-workspace.ts +951 -0
- package/src/adapters/repo-root.ts +20 -0
- package/src/adapters/version.ts +118 -0
- package/src/base-branch.ts +21 -0
- package/src/branch.ts +33 -0
- package/src/cli.ts +135 -0
- package/src/command-line.ts +190 -0
- package/src/config.ts +277 -0
- package/src/conventions.ts +118 -0
- package/src/criteria.ts +106 -0
- package/src/frontier.ts +36 -0
- package/src/guards.ts +143 -0
- package/src/handoff.ts +82 -0
- package/src/host.ts +116 -0
- package/src/init.ts +405 -0
- package/src/labels.ts +42 -0
- package/src/landing.ts +75 -0
- package/src/lifecycle.ts +34 -0
- package/src/lock.ts +215 -0
- package/src/note-schema.ts +58 -0
- package/src/notes.ts +433 -0
- package/src/operator-skill.ts +24 -0
- package/src/orchestrator.ts +1816 -0
- package/src/ports/agent-runner.ts +105 -0
- package/src/ports/tracker.ts +334 -0
- package/src/ports/workspace.ts +422 -0
- package/src/progress.ts +231 -0
- package/src/prompts.ts +288 -0
- package/src/readiness.ts +256 -0
- package/src/remove.ts +732 -0
- package/src/resume.ts +145 -0
- package/src/run-log.ts +85 -0
- package/src/run.ts +331 -0
- package/src/self-hosting.ts +33 -0
- package/src/stage-guard.ts +32 -0
- package/src/staleness.ts +101 -0
- package/src/start.ts +284 -0
- package/src/startup.ts +34 -0
- package/src/stop.ts +178 -0
- package/src/stranded.ts +136 -0
- package/src/templates.ts +596 -0
- package/src/title.ts +97 -0
- package/src/verdict.ts +88 -0
- package/src/version-number.ts +67 -0
- package/src/version-pr.ts +103 -0
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
type AgentPreflight,
|
|
5
|
+
type AgentRunner,
|
|
6
|
+
SKILLS_PLUGIN,
|
|
7
|
+
type StageFailure,
|
|
8
|
+
type StageRequest,
|
|
9
|
+
type StageResult,
|
|
10
|
+
} from "../ports/agent-runner.js";
|
|
11
|
+
import { STAGE_ENV_VAR } from "../stage-guard.js";
|
|
12
|
+
import { type Execution, type RunProcess, exec } from "./exec.js";
|
|
13
|
+
|
|
14
|
+
export interface ClaudeAgentRunnerOptions {
|
|
15
|
+
binary?: string;
|
|
16
|
+
run?: RunProcess;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* How long one preflight question may take. Generous for a CLI printing its
|
|
21
|
+
* own version, and short enough that `init` cannot hang on a binary that never
|
|
22
|
+
* answers.
|
|
23
|
+
*/
|
|
24
|
+
const PREFLIGHT_TIMEOUT_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
/** The final `result` event of a stream-json run, as far as we rely on it. */
|
|
27
|
+
interface ResultEvent {
|
|
28
|
+
type: "result";
|
|
29
|
+
subtype?: string;
|
|
30
|
+
is_error?: boolean;
|
|
31
|
+
num_turns?: number;
|
|
32
|
+
result?: unknown;
|
|
33
|
+
structured_output?: unknown;
|
|
34
|
+
/** The HTTP status of the API error that ended the session, when one did. */
|
|
35
|
+
api_error_status?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A `rate_limit_event` of a stream-json run: the CLI's own word on where the
|
|
40
|
+
* subscription stands, printed as each request's answer comes back.
|
|
41
|
+
*/
|
|
42
|
+
interface RateLimitEvent {
|
|
43
|
+
type: "rate_limit_event";
|
|
44
|
+
rate_limit_info?: { status?: string };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* One `claude -p` child process per Stage (ADR-0002).
|
|
49
|
+
*
|
|
50
|
+
* Thin on purpose: it builds the command line, saves everything the session
|
|
51
|
+
* produced, and classifies how the session ended. It makes no decisions.
|
|
52
|
+
*/
|
|
53
|
+
export class ClaudeAgentRunner implements AgentRunner {
|
|
54
|
+
private readonly binary: string;
|
|
55
|
+
private readonly runProcess: RunProcess;
|
|
56
|
+
|
|
57
|
+
constructor(options: ClaudeAgentRunnerOptions = {}) {
|
|
58
|
+
this.binary = options.binary ?? "claude";
|
|
59
|
+
this.runProcess = options.run ?? exec;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What `claude` says about itself: that it can be run at all, and that the
|
|
64
|
+
* plugin the Stages drive is installed.
|
|
65
|
+
*
|
|
66
|
+
* Every failure is an answer rather than an error — no binary, a CLI too old
|
|
67
|
+
* to list its plugins, a non-zero exit — because the whole point of asking is
|
|
68
|
+
* to put a line in the `init` report for the human who has to fix it.
|
|
69
|
+
*/
|
|
70
|
+
async preflight(): Promise<AgentPreflight> {
|
|
71
|
+
const version = await this.ask(["--version"]);
|
|
72
|
+
if (version?.exitCode !== 0) return { runs: false, plugin: false };
|
|
73
|
+
|
|
74
|
+
const plugins = await this.ask(["plugin", "list"]);
|
|
75
|
+
const listed = plugins?.exitCode === 0 && plugins.stdout.includes(SKILLS_PLUGIN);
|
|
76
|
+
return { runs: true, plugin: listed };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One preflight question, or nothing when `claude` could not be started. */
|
|
80
|
+
private async ask(args: string[]): Promise<Execution | undefined> {
|
|
81
|
+
try {
|
|
82
|
+
return await this.runProcess(this.binary, args, { timeoutMs: PREFLIGHT_TIMEOUT_MS });
|
|
83
|
+
} catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private async spawn(
|
|
89
|
+
request: StageRequest,
|
|
90
|
+
args: string[],
|
|
91
|
+
log: StageLog,
|
|
92
|
+
): Promise<Execution> {
|
|
93
|
+
try {
|
|
94
|
+
return await this.runProcess(this.binary, args, {
|
|
95
|
+
cwd: request.cwd,
|
|
96
|
+
timeoutMs: request.maxMinutes * 60_000,
|
|
97
|
+
// The Stage mark the CLI refuses on, so the session cannot nest a Run.
|
|
98
|
+
extraEnv: stageEnv(request),
|
|
99
|
+
onStdout: log.appendStdout,
|
|
100
|
+
onStderr: log.appendStderr,
|
|
101
|
+
});
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return spawnFailure(error);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async run(request: StageRequest): Promise<StageResult> {
|
|
108
|
+
const args = buildArgs(request);
|
|
109
|
+
const commandLine = quoteCommand(stageEnv(request), this.binary, args);
|
|
110
|
+
const startedAt = Date.now();
|
|
111
|
+
|
|
112
|
+
// Started before the child, so a Run killed mid-Stage still leaves the
|
|
113
|
+
// command line and everything printed so far behind.
|
|
114
|
+
const log = startStageLog(request, commandLine);
|
|
115
|
+
const execution = await this.spawn(request, args, log);
|
|
116
|
+
|
|
117
|
+
const events = parseEvents(execution.stdout);
|
|
118
|
+
log.close(execution, events);
|
|
119
|
+
|
|
120
|
+
const results = events.filter(isResultEvent);
|
|
121
|
+
const failure = classify(request, execution, events);
|
|
122
|
+
const structured = request.jsonSchema === undefined ? undefined : structuredOutput(results);
|
|
123
|
+
const turns = countTurns(results);
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
ok: failure === undefined,
|
|
127
|
+
...(failure === undefined ? {} : { failure }),
|
|
128
|
+
...(structured === undefined ? {} : { result: structured }),
|
|
129
|
+
commandLine,
|
|
130
|
+
transcriptPath: log.transcriptPath,
|
|
131
|
+
...(turns === undefined ? {} : { turns }),
|
|
132
|
+
// The clock is the runner's own. A session that woke for a background
|
|
133
|
+
// agent reports one `duration_ms` per waking, and the time it spent
|
|
134
|
+
// waiting for that agent belongs to none of them.
|
|
135
|
+
durationMs: Date.now() - startedAt,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* A session that spawns a background agent ends its main turn with a `result`
|
|
142
|
+
* event, then wakes once per finished agent and ends each waking with another.
|
|
143
|
+
* Every later event counts only its own waking, so a Stage's turns are the sum
|
|
144
|
+
* over all of them.
|
|
145
|
+
*/
|
|
146
|
+
function countTurns(results: ResultEvent[]): number | undefined {
|
|
147
|
+
const counted = results.filter((result) => result.num_turns !== undefined);
|
|
148
|
+
if (counted.length === 0) return undefined;
|
|
149
|
+
return counted.reduce((sum, result) => sum + (result.num_turns ?? 0), 0);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A session that could not even start still has to leave a trace behind. */
|
|
153
|
+
async function spawnFailure(error: unknown): Promise<Execution> {
|
|
154
|
+
const message = `ticket-runner could not start the Stage: ${(error as Error).message}\n`;
|
|
155
|
+
return { exitCode: 1, stdout: "", stderr: message, output: message, timedOut: false };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** What a Stage's shell carries beyond the environment it inherits. */
|
|
159
|
+
function stageEnv(request: StageRequest): Record<string, string> {
|
|
160
|
+
return { [STAGE_ENV_VAR]: request.stage };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function buildArgs(request: StageRequest): string[] {
|
|
164
|
+
const args = [
|
|
165
|
+
"--print",
|
|
166
|
+
request.prompt,
|
|
167
|
+
"--output-format",
|
|
168
|
+
"stream-json",
|
|
169
|
+
"--verbose",
|
|
170
|
+
// Nobody is watching, so anything that would prompt is denied instead.
|
|
171
|
+
"--permission-prompts",
|
|
172
|
+
"none",
|
|
173
|
+
"--permission-mode",
|
|
174
|
+
request.permissionMode,
|
|
175
|
+
"--model",
|
|
176
|
+
request.model,
|
|
177
|
+
// Always passed, like the model: a Stage's logged command line is what a
|
|
178
|
+
// human pastes back, so neither may be left to the host's own default.
|
|
179
|
+
"--effort",
|
|
180
|
+
request.effort,
|
|
181
|
+
"--max-turns",
|
|
182
|
+
String(request.maxTurns),
|
|
183
|
+
];
|
|
184
|
+
if (request.jsonSchema !== undefined) {
|
|
185
|
+
args.push("--json-schema", JSON.stringify(request.jsonSchema));
|
|
186
|
+
}
|
|
187
|
+
return args;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The Stage's four files, written from the moment the Stage starts. */
|
|
191
|
+
interface StageLog {
|
|
192
|
+
transcriptPath: string;
|
|
193
|
+
appendStdout: (chunk: string) => void;
|
|
194
|
+
appendStderr: (chunk: string) => void;
|
|
195
|
+
/** Reconcile the output files with the finished child, then transcribe it. */
|
|
196
|
+
close: (execution: Execution, events: unknown[]) => void;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Put the Stage's command line on disk and empty its output files, before
|
|
201
|
+
* anything is spawned. Chunks are appended as they arrive rather than saved at
|
|
202
|
+
* the end, so the files hold what the session printed even when nobody is left
|
|
203
|
+
* alive to write them (#12). The transcript is the one derivation that has to
|
|
204
|
+
* wait: it is parsed out of the stdout the session has finished printing.
|
|
205
|
+
*/
|
|
206
|
+
function startStageLog(request: StageRequest, commandLine: string): StageLog {
|
|
207
|
+
mkdirSync(request.logDir, { recursive: true });
|
|
208
|
+
const path = (suffix: string) => join(request.logDir, `${request.stage}.${suffix}`);
|
|
209
|
+
|
|
210
|
+
writeFileSync(path("command"), `${commandLine}\n`);
|
|
211
|
+
// Emptied up front, so a Stage never appends to output from an earlier one.
|
|
212
|
+
writeFileSync(path("stdout"), "");
|
|
213
|
+
writeFileSync(path("stderr"), "");
|
|
214
|
+
|
|
215
|
+
const appended = { stdout: 0, stderr: 0 };
|
|
216
|
+
// Appending happens inside the child's stream handler, where a throw would
|
|
217
|
+
// take the whole Run down. A write that fails is left to `close` to redo.
|
|
218
|
+
const append = (suffix: "stdout" | "stderr") => (chunk: string) => {
|
|
219
|
+
try {
|
|
220
|
+
appendFileSync(path(suffix), chunk);
|
|
221
|
+
appended[suffix] += chunk.length;
|
|
222
|
+
} catch {
|
|
223
|
+
// Nothing is lost: the chunk is still part of the Execution.
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
transcriptPath: path("transcript.jsonl"),
|
|
229
|
+
appendStdout: append("stdout"),
|
|
230
|
+
appendStderr: append("stderr"),
|
|
231
|
+
close: (execution, events) => {
|
|
232
|
+
// Whatever the appends missed — a failed write, or a process runner that
|
|
233
|
+
// delivered no chunks at all — is written back whole here, so a Stage
|
|
234
|
+
// that ran to the end always has its full output on disk.
|
|
235
|
+
if (appended.stdout !== execution.stdout.length) {
|
|
236
|
+
writeFileSync(path("stdout"), execution.stdout);
|
|
237
|
+
}
|
|
238
|
+
if (appended.stderr !== execution.stderr.length) {
|
|
239
|
+
writeFileSync(path("stderr"), execution.stderr);
|
|
240
|
+
}
|
|
241
|
+
writeFileSync(
|
|
242
|
+
path("transcript.jsonl"),
|
|
243
|
+
events.map((event) => JSON.stringify(event)).join("\n") + (events.length ? "\n" : ""),
|
|
244
|
+
);
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function parseEvents(stdout: string): unknown[] {
|
|
250
|
+
const events: unknown[] = [];
|
|
251
|
+
for (const line of stdout.split("\n")) {
|
|
252
|
+
const trimmed = line.trim();
|
|
253
|
+
if (trimmed === "") continue;
|
|
254
|
+
try {
|
|
255
|
+
events.push(JSON.parse(trimmed));
|
|
256
|
+
} catch {
|
|
257
|
+
// Anything the CLI printed outside the stream stays in the stdout file.
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return events;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function isResultEvent(event: unknown): event is ResultEvent {
|
|
264
|
+
return isEvent(event, "result");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function isRateLimitEvent(event: unknown): event is RateLimitEvent {
|
|
268
|
+
return isEvent(event, "rate_limit_event");
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function isEvent(event: unknown, type: string): boolean {
|
|
272
|
+
return (
|
|
273
|
+
typeof event === "object" && event !== null && (event as { type?: unknown }).type === type
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function classify(
|
|
278
|
+
request: StageRequest,
|
|
279
|
+
execution: Execution,
|
|
280
|
+
events: unknown[],
|
|
281
|
+
): StageFailure | undefined {
|
|
282
|
+
const results = events.filter(isResultEvent);
|
|
283
|
+
// How the session ended is what its last event says; see `structuredOutput`
|
|
284
|
+
// for why the last event is not where the rest of the answer is.
|
|
285
|
+
const result = results.at(-1);
|
|
286
|
+
|
|
287
|
+
if (execution.timedOut) return "timed-out";
|
|
288
|
+
|
|
289
|
+
if (result?.subtype === "error_max_turns") return "turn-capped";
|
|
290
|
+
|
|
291
|
+
// A session's failure is read from how it ended, never from what it talked
|
|
292
|
+
// about: a Ticket about rate limits mentions them hundreds of times and
|
|
293
|
+
// still succeeds.
|
|
294
|
+
const failed = execution.exitCode !== 0 || result?.is_error === true || result === undefined;
|
|
295
|
+
if (failed) {
|
|
296
|
+
if (rateLimited(execution, events, result)) return "rate-limited";
|
|
297
|
+
return "nonzero-exit";
|
|
298
|
+
}
|
|
299
|
+
// A schema the Stage answered with nothing is only a failure where the
|
|
300
|
+
// structured output was the point of the Stage; see `resultRequired`.
|
|
301
|
+
if (
|
|
302
|
+
request.jsonSchema !== undefined &&
|
|
303
|
+
request.resultRequired !== false &&
|
|
304
|
+
structuredOutput(results) === undefined
|
|
305
|
+
) {
|
|
306
|
+
return "invalid-result";
|
|
307
|
+
}
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Whether a session that failed was stopped by the subscription rate limit.
|
|
313
|
+
*
|
|
314
|
+
* The CLI says so in three places, and any one of them is enough: the `result`
|
|
315
|
+
* event carries the API's 429, a `rate_limit_event` reports the request
|
|
316
|
+
* `rejected`, or the message it printed names the limit. The message is read
|
|
317
|
+
* last because it is the least stable of the three: its wording has already
|
|
318
|
+
* moved from "usage limit" to "session limit" once, and a Run that only knew
|
|
319
|
+
* the old wording handed off every Ticket it reached instead of releasing the
|
|
320
|
+
* first. A `rate_limit_event` that merely warns is not a stop: a session near
|
|
321
|
+
* the limit prints those and finishes.
|
|
322
|
+
*/
|
|
323
|
+
function rateLimited(
|
|
324
|
+
execution: Execution,
|
|
325
|
+
events: unknown[],
|
|
326
|
+
result: ResultEvent | undefined,
|
|
327
|
+
): boolean {
|
|
328
|
+
if (result?.api_error_status === 429) return true;
|
|
329
|
+
const rejected = (event: unknown) =>
|
|
330
|
+
isRateLimitEvent(event) && event.rate_limit_info?.status === "rejected";
|
|
331
|
+
if (events.some(rejected)) return true;
|
|
332
|
+
const text = [result?.subtype ?? "", String(result?.result ?? ""), execution.stderr].join(" ");
|
|
333
|
+
return /usage limit|session limit|rate limit|rate_limit/i.test(text);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* The Stage's structured output, from the last `result` event that carries one.
|
|
338
|
+
*
|
|
339
|
+
* The session answers the schema when its main turn ends, and may answer it
|
|
340
|
+
* again from a waking for a background agent, once a review it spawned has
|
|
341
|
+
* come back. The later answer is the one it stands by: sessions repeat every
|
|
342
|
+
* Note they keep and add the ones the review turned up, so keeping the first
|
|
343
|
+
* would drop those. A waking that answers nothing ends with an event that
|
|
344
|
+
* carries no structured output, and that erases no earlier answer, which is why
|
|
345
|
+
* reading only the last event would not do either.
|
|
346
|
+
*/
|
|
347
|
+
function structuredOutput(results: ResultEvent[]): unknown {
|
|
348
|
+
for (const result of results.toReversed()) {
|
|
349
|
+
const output = structuredOutputOf(result);
|
|
350
|
+
if (output !== undefined) return output;
|
|
351
|
+
}
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* One event's structured output: the dedicated field when the CLI provides it,
|
|
357
|
+
* otherwise whatever JSON the session left in `result`.
|
|
358
|
+
*/
|
|
359
|
+
function structuredOutputOf(result: ResultEvent): unknown {
|
|
360
|
+
if (result.structured_output !== undefined && result.structured_output !== null) {
|
|
361
|
+
return result.structured_output;
|
|
362
|
+
}
|
|
363
|
+
if (typeof result.result === "object" && result.result !== null) return result.result;
|
|
364
|
+
if (typeof result.result !== "string") return undefined;
|
|
365
|
+
|
|
366
|
+
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(result.result);
|
|
367
|
+
const candidate = (fenced?.[1] ?? result.result).trim();
|
|
368
|
+
if (!candidate.startsWith("{") && !candidate.startsWith("[")) return undefined;
|
|
369
|
+
try {
|
|
370
|
+
return JSON.parse(candidate);
|
|
371
|
+
} catch {
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Shell-quote the command so a human can paste it back into a terminal, with
|
|
378
|
+
* the Stage's environment in front of it so the reproduction is exact.
|
|
379
|
+
*/
|
|
380
|
+
function quoteCommand(
|
|
381
|
+
extraEnv: Record<string, string>,
|
|
382
|
+
binary: string,
|
|
383
|
+
args: string[],
|
|
384
|
+
): string {
|
|
385
|
+
const assignments = Object.entries(extraEnv).map(([name, value]) => `${name}=${value}`);
|
|
386
|
+
return [...assignments, binary, ...args]
|
|
387
|
+
.map((part) => (/^[\w./:=-]+$/.test(part) ? part : `'${part.replaceAll("'", `'\\''`)}'`))
|
|
388
|
+
.join(" ");
|
|
389
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export interface Execution {
|
|
4
|
+
exitCode: number;
|
|
5
|
+
stdout: string;
|
|
6
|
+
stderr: string;
|
|
7
|
+
/** stdout and stderr interleaved, as a human would see them in a terminal. */
|
|
8
|
+
output: string;
|
|
9
|
+
/**
|
|
10
|
+
* Whether `timeoutMs` killed the child, which the exit code alone cannot
|
|
11
|
+
* say: 124 is what the kill is reported as, and a command is free to exit
|
|
12
|
+
* 124 on its own. Asking the run is the only honest answer.
|
|
13
|
+
*/
|
|
14
|
+
timedOut: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ExecOptions {
|
|
18
|
+
cwd?: string;
|
|
19
|
+
/** Run through the shell, for user-supplied Check commands. */
|
|
20
|
+
shell?: boolean;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
/** Variables merged over the environment the child inherits, not replacing it. */
|
|
23
|
+
extraEnv?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Called with each chunk the child prints on that stream, as it arrives, so
|
|
26
|
+
* a caller that saves the output has it before the child exits. A sink runs
|
|
27
|
+
* inside the stream's handler: one that throws takes this process down.
|
|
28
|
+
*/
|
|
29
|
+
onStdout?: (chunk: string) => void;
|
|
30
|
+
/** As `onStdout`, for what the child prints on stderr. */
|
|
31
|
+
onStderr?: (chunk: string) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* How long a child's pipes are read after the child itself is gone. A
|
|
36
|
+
* descendant that inherited them can hold them open for as long as it likes,
|
|
37
|
+
* so what the child printed has to be collected on a clock rather than waited
|
|
38
|
+
* for. Long enough that a pipe's worth of buffered output always arrives.
|
|
39
|
+
*
|
|
40
|
+
* What the clock gives up: everything the child itself wrote is complete,
|
|
41
|
+
* because its own output is in the pipe buffer by the time it exits, but a
|
|
42
|
+
* descendant's is collected only while the child lives and during this window
|
|
43
|
+
* after it. Later than that it is dropped by design, in exchange for a call
|
|
44
|
+
* that always settles.
|
|
45
|
+
*/
|
|
46
|
+
const DRAIN_MS = 100;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* How a child process is run. Adapters take one so tests can hand them
|
|
50
|
+
* recorded output instead of spawning anything.
|
|
51
|
+
*/
|
|
52
|
+
export type RunProcess = (
|
|
53
|
+
command: string,
|
|
54
|
+
args: string[],
|
|
55
|
+
options: ExecOptions,
|
|
56
|
+
) => Promise<Execution>;
|
|
57
|
+
|
|
58
|
+
/** Run a child process to completion. Never throws on a non-zero exit. */
|
|
59
|
+
export function exec(
|
|
60
|
+
command: string,
|
|
61
|
+
args: string[],
|
|
62
|
+
options: ExecOptions = {},
|
|
63
|
+
): Promise<Execution> {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const child = spawn(command, args, {
|
|
66
|
+
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
67
|
+
...(options.extraEnv === undefined
|
|
68
|
+
? {}
|
|
69
|
+
: { env: { ...process.env, ...options.extraEnv } }),
|
|
70
|
+
shell: options.shell ?? false,
|
|
71
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
let stdout = "";
|
|
75
|
+
let stderr = "";
|
|
76
|
+
let output = "";
|
|
77
|
+
let killed = false;
|
|
78
|
+
let settled = false;
|
|
79
|
+
let limit: NodeJS.Timeout | undefined;
|
|
80
|
+
let drain: NodeJS.Timeout | undefined;
|
|
81
|
+
|
|
82
|
+
/** The child itself is gone. Only a descendant can still hold its pipes. */
|
|
83
|
+
const hasExited = () =>
|
|
84
|
+
child.exitCode !== null || child.signalCode !== null;
|
|
85
|
+
|
|
86
|
+
/** Let go of the clocks, and of read ends nobody may ever close. */
|
|
87
|
+
const stopWaiting = () => {
|
|
88
|
+
settled = true;
|
|
89
|
+
clearTimeout(limit);
|
|
90
|
+
clearTimeout(drain);
|
|
91
|
+
child.stdout.destroy();
|
|
92
|
+
child.stderr.destroy();
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const finish = () => {
|
|
96
|
+
if (settled) return;
|
|
97
|
+
stopWaiting();
|
|
98
|
+
resolve({
|
|
99
|
+
exitCode: killed ? 124 : (child.exitCode ?? 1),
|
|
100
|
+
stdout,
|
|
101
|
+
stderr,
|
|
102
|
+
output,
|
|
103
|
+
timedOut: killed,
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** Keep reading for a moment, then stop waiting on the pipes for good. */
|
|
108
|
+
const drainThenFinish = () => {
|
|
109
|
+
drain ??= setTimeout(finish, DRAIN_MS);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
if (options.timeoutMs !== undefined) {
|
|
113
|
+
limit = setTimeout(() => {
|
|
114
|
+
// A child that already exited is past killing: its own exit started
|
|
115
|
+
// the drain, and its own exit code is the honest one to report.
|
|
116
|
+
if (hasExited()) return;
|
|
117
|
+
killed = true;
|
|
118
|
+
child.kill("SIGKILL");
|
|
119
|
+
}, options.timeoutMs);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
child.stdout.setEncoding("utf8");
|
|
123
|
+
child.stderr.setEncoding("utf8");
|
|
124
|
+
child.stdout.on("data", (chunk: string) => {
|
|
125
|
+
stdout += chunk;
|
|
126
|
+
output += chunk;
|
|
127
|
+
options.onStdout?.(chunk);
|
|
128
|
+
});
|
|
129
|
+
child.stderr.on("data", (chunk: string) => {
|
|
130
|
+
stderr += chunk;
|
|
131
|
+
output += chunk;
|
|
132
|
+
options.onStderr?.(chunk);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
child.on("error", (error) => {
|
|
136
|
+
if (settled) return;
|
|
137
|
+
stopWaiting();
|
|
138
|
+
reject(error);
|
|
139
|
+
});
|
|
140
|
+
// However the child ended, its pipes are read on a clock from here on.
|
|
141
|
+
child.on("exit", drainThenFinish);
|
|
142
|
+
// The usual ending, and the quicker one: nothing outlived the child, so
|
|
143
|
+
// its pipes reach EOF and there is nothing left to wait for.
|
|
144
|
+
child.on("close", finish);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Run a child process and throw when it fails. */
|
|
149
|
+
export async function execOrThrow(
|
|
150
|
+
command: string,
|
|
151
|
+
args: string[],
|
|
152
|
+
options: ExecOptions = {},
|
|
153
|
+
): Promise<Execution> {
|
|
154
|
+
return throwOnFailure(command, args, await exec(command, args, options));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Turn a non-zero exit into an error naming the command and its output. */
|
|
158
|
+
export function throwOnFailure(
|
|
159
|
+
command: string,
|
|
160
|
+
args: string[],
|
|
161
|
+
result: Execution,
|
|
162
|
+
): Execution {
|
|
163
|
+
if (result.exitCode !== 0) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
`\`${command} ${args.join(" ")}\` exited ${result.exitCode}\n${result.output.trim()}`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|