@rob-c/pi-managed-tools 0.0.0-stage → 0.23.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/src/jobs.ts ADDED
@@ -0,0 +1,1052 @@
1
+ /*
2
+ * pi-managed-tools — keep a set of developer binaries at their latest upstream release.
3
+ * Copyright (C) 2026 Robert Currie
4
+ *
5
+ * This program is free software; you can redistribute it and/or modify it under
6
+ * the terms of the GNU General Public License as published by the Free Software
7
+ * Foundation; version 2 of the License only.
8
+ *
9
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY
10
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
11
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU General Public License along with this
14
+ * program; if not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.
15
+ */
16
+ /**
17
+ * Background jobs for the model: a command that has to outlive one tool call.
18
+ *
19
+ * pi's bash tool has no background mode. A dev server started with a normal bash call
20
+ * runs into the deadline and comes back as a TIMEOUT; one started with `&` keeps running
21
+ * and its output is gone. `busybox_job` starts the command under its own `busybox run`,
22
+ * detached from the call that started it, and reads the run's capture files — which `run`
23
+ * appends to as the bytes arrive — whenever the model asks.
24
+ *
25
+ * What was measured against the packaged binary, and what this module therefore relies on:
26
+ *
27
+ * - `<root>/R1/stdout` and `<root>/R1/stderr` grow live, an unterminated line included;
28
+ * - `<root>/R1/meta` exists from the first moment as a *placeholder* (`exit_code=0`,
29
+ * `duration_ms=0`, `pgid=0`) and is rewritten in place when the run ends. Its presence
30
+ * says nothing, and its `exit_code=0` while running is not a result: only a meta with a
31
+ * process group in it is final;
32
+ * - `<root>/R1/timeline` is written once, when the run ends, so it cannot serve a live
33
+ * view. The two stream files are read instead, which costs the exact order *between*
34
+ * the streams (it is as fine as the polling interval) and nothing else;
35
+ * - `--pgid` prints at exit too, so the child's process group is not known while it runs;
36
+ * - SIGTERM to `run` makes it stop the child's process group (TERM, then KILL after its
37
+ * two-second grace) and record `cancelled=1`; its own deadline records `timed_out=1`;
38
+ * - a multi-line command is written into `meta` verbatim after `cmd=`, so a line of the
39
+ * command can look like a field. The real fields follow it: the last one wins.
40
+ *
41
+ * The pure parts — the unread buffer, the labelled view, the literal watch, the meta
42
+ * parser and the sentences — are exported so they can be tested without a binary.
43
+ */
44
+ import { type ChildProcess, execFileSync, spawn } from "node:child_process";
45
+ import { closeSync, existsSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync } from "node:fs";
46
+ import { tmpdir } from "node:os";
47
+ import { join } from "node:path";
48
+ import { StringDecoder } from "node:string_decoder";
49
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
50
+ import { Type } from "typebox";
51
+ import { busyboxAvailable, busyboxBinaryPath } from "./agenttools.ts";
52
+ import { blockReason, detectTailMerge, guardEnabled, hasOverride } from "./guard.ts";
53
+ import { UNBUFFERED_ENV } from "./wrap.ts";
54
+
55
+ /** How many jobs may be running at once. */
56
+ export const JOB_LIMIT = 8;
57
+ /** The byte budget of one returned view, unless `max_bytes` says otherwise. */
58
+ export const DEFAULT_VIEW_BYTES = 6000;
59
+ /** The largest `wait_s`: under pi's own two-minute deadline for a tool call. */
60
+ export const MAX_WAIT_SECONDS = 110;
61
+ /** How long `start` waits for a first sign of life, unless told otherwise. */
62
+ export const DEFAULT_START_WAIT_SECONDS = 5;
63
+ /** A job nobody stopped ends after this long. */
64
+ export const DEFAULT_MAX_RUNTIME_SECONDS = 3600;
65
+ /** How long `stop` gives `run` to end the command itself before the fallback. */
66
+ export const STOP_GRACE_MS = 5_000;
67
+ /** Output nobody has asked for yet is kept in memory up to this size; the files keep all of it. */
68
+ export const UNREAD_LIMIT_BYTES = 1024 * 1024;
69
+ /** How often a job's capture files are read, in ms: the granularity of the order between streams. */
70
+ const POLL_MS = 100;
71
+ /** Ended jobs stay listed so a late `status` gets an answer; beyond this the oldest are forgotten. */
72
+ const REMEMBERED_JOBS = 24;
73
+ const MIN_VIEW_BYTES = 200;
74
+ const MAX_VIEW_BYTES = 200_000;
75
+
76
+ export type StreamName = "out" | "err";
77
+
78
+ /** A run of output from one stream, in the order it was read. */
79
+ export interface Segment {
80
+ stream: StreamName;
81
+ text: string;
82
+ }
83
+
84
+ /**
85
+ * The output of a job that has not been returned to the model yet.
86
+ *
87
+ * Adjacent pieces of one stream are joined, so a line that arrived in two reads is one
88
+ * line again. Past the limit the oldest bytes are dropped and counted: a job nobody
89
+ * polls for an hour must not grow without bound, and the view says how much is missing.
90
+ */
91
+ export class UnreadOutput {
92
+ private segments: Segment[] = [];
93
+ private bytes = 0;
94
+ private dropped = 0;
95
+ private readonly limit: number;
96
+
97
+ constructor(limit: number = UNREAD_LIMIT_BYTES) {
98
+ this.limit = limit;
99
+ }
100
+
101
+ push(stream: StreamName, text: string): void {
102
+ if (text === "") return;
103
+ const last = this.segments[this.segments.length - 1];
104
+ if (last && last.stream === stream) last.text += text;
105
+ else this.segments.push({ stream, text });
106
+ this.bytes += Buffer.byteLength(text);
107
+ while (this.bytes > this.limit) {
108
+ const head = this.segments[0] as Segment;
109
+ const over = this.bytes - this.limit;
110
+ const size = Buffer.byteLength(head.text);
111
+ if (size <= over) {
112
+ this.segments.shift();
113
+ this.bytes -= size;
114
+ this.dropped += size;
115
+ continue;
116
+ }
117
+ // A character is at least a byte, so `over` characters cover the excess; a
118
+ // surrogate pair is not cut in half.
119
+ let cut = Math.min(over, head.text.length);
120
+ const code = head.text.charCodeAt(cut);
121
+ if (code >= 0xdc00 && code <= 0xdfff) cut += 1;
122
+ const gone = Buffer.byteLength(head.text.slice(0, cut));
123
+ head.text = head.text.slice(cut);
124
+ this.bytes -= gone;
125
+ this.dropped += gone;
126
+ }
127
+ }
128
+
129
+ /** What is waiting, without taking it. */
130
+ peek(): readonly Segment[] {
131
+ return this.segments;
132
+ }
133
+
134
+ /** Take everything: the next call starts from here. */
135
+ take(): { segments: Segment[]; droppedBytes: number } {
136
+ const taken = { segments: this.segments, droppedBytes: this.dropped };
137
+ this.segments = [];
138
+ this.bytes = 0;
139
+ this.dropped = 0;
140
+ return taken;
141
+ }
142
+ }
143
+
144
+ /** One line of the view, with the stream it came from. */
145
+ export interface ViewLine {
146
+ stream: StreamName;
147
+ text: string;
148
+ /** Bytes of the job's output this line stands for, its newline included. */
149
+ rawBytes: number;
150
+ }
151
+
152
+ /**
153
+ * Cut the segments into lines, each belonging to one stream.
154
+ *
155
+ * A line left unfinished by one stream and followed by the other stream ends there: the
156
+ * view is labelled per line, and a line that mixed both streams could carry no label.
157
+ */
158
+ export function toLines(segments: readonly Segment[]): ViewLine[] {
159
+ const lines: ViewLine[] = [];
160
+ let open: ViewLine | undefined;
161
+ for (const segment of segments) {
162
+ const parts = segment.text.split("\n");
163
+ for (let index = 0; index < parts.length; index++) {
164
+ const part = parts[index] as string;
165
+ const isTerminated = index < parts.length - 1;
166
+ if (!open || open.stream !== segment.stream) {
167
+ // What follows the last newline of a segment is empty: not a line.
168
+ if (part === "" && !isTerminated) continue;
169
+ open = { stream: segment.stream, text: "", rawBytes: 0 };
170
+ lines.push(open);
171
+ }
172
+ open.text += part;
173
+ open.rawBytes += Buffer.byteLength(part) + (isTerminated ? 1 : 0);
174
+ if (isTerminated) open = undefined;
175
+ }
176
+ }
177
+ return lines;
178
+ }
179
+
180
+ /** What marks a stderr line in the view. stdout lines carry nothing. */
181
+ export const STDERR_LABEL = "err| ";
182
+
183
+ export interface View {
184
+ /** The labelled lines, joined by newlines; empty when there is nothing to show. */
185
+ text: string;
186
+ lines: number;
187
+ /** Bytes of the job's own output that are shown. */
188
+ shownBytes: number;
189
+ /** Bytes of the job's own output that are not: the start, when it was over budget. */
190
+ droppedBytes: number;
191
+ }
192
+
193
+ /**
194
+ * Render output for the model: stderr lines labelled, the end kept when over budget.
195
+ *
196
+ * The end, because what a server printed last is what says whether it is up. The number
197
+ * of bytes left out is exact, in the job's own bytes, so the view never passes for whole.
198
+ */
199
+ export function renderView(segments: readonly Segment[], maxBytes: number = DEFAULT_VIEW_BYTES): View {
200
+ const lines = toLines(segments);
201
+ const total = lines.reduce((sum, line) => sum + line.rawBytes, 0);
202
+ const shown: string[] = [];
203
+ let used = 0;
204
+ let shownBytes = 0;
205
+ for (let index = lines.length - 1; index >= 0; index--) {
206
+ const line = lines[index] as ViewLine;
207
+ const label = line.stream === "err" ? STDERR_LABEL : "";
208
+ const cost = Buffer.byteLength(label) + Buffer.byteLength(line.text) + (shown.length > 0 ? 1 : 0);
209
+ if (used + cost <= maxBytes) {
210
+ shown.unshift(label + line.text);
211
+ used += cost;
212
+ shownBytes += line.rawBytes;
213
+ continue;
214
+ }
215
+ // Not even the last line fits: its end is shown, cut on a character boundary.
216
+ if (shown.length === 0) {
217
+ const room = Math.max(0, maxBytes - Buffer.byteLength(label) - Buffer.byteLength("…"));
218
+ const bytes = Buffer.from(line.text);
219
+ let from = Math.max(0, bytes.length - room);
220
+ while (from < bytes.length && ((bytes[from] as number) & 0xc0) === 0x80) from += 1;
221
+ const tail = bytes.subarray(from);
222
+ shown.unshift(`${label}…${tail.toString("utf8")}`);
223
+ shownBytes += tail.length + (line.rawBytes - bytes.length);
224
+ }
225
+ break;
226
+ }
227
+ return { text: shown.join("\n"), lines: shown.length, shownBytes, droppedBytes: total - shownBytes };
228
+ }
229
+
230
+ export interface LiteralWatch {
231
+ /** Feed the next piece of a stream; true once the literal has been seen. */
232
+ feed(stream: StreamName, text: string): boolean;
233
+ readonly seen: boolean;
234
+ }
235
+
236
+ /**
237
+ * Watch for a literal string in output that arrives in pieces.
238
+ *
239
+ * The files are read in whatever chunks the job wrote, so `listening on` can arrive as
240
+ * `listen` and `ing on`. Each stream keeps the last few characters it saw — one fewer
241
+ * than the literal is long — which is exactly enough to find a match across the join,
242
+ * and the two streams are kept apart: a match is never made of both.
243
+ */
244
+ export function watchLiteral(literal: string): LiteralWatch {
245
+ const carry: Record<StreamName, string> = { out: "", err: "" };
246
+ let isSeen = false;
247
+ return {
248
+ feed(stream, text) {
249
+ if (isSeen || literal === "") return isSeen;
250
+ const hay = carry[stream] + text;
251
+ if (hay.includes(literal)) isSeen = true;
252
+ else carry[stream] = literal.length > 1 ? hay.slice(-(literal.length - 1)) : "";
253
+ return isSeen;
254
+ },
255
+ get seen() {
256
+ return isSeen;
257
+ },
258
+ };
259
+ }
260
+
261
+ /** What `run` recorded about a run, as far as a job reads it. */
262
+ export interface JobMeta {
263
+ /** The command's status; -1 when a signal ended it. */
264
+ exitCode: number;
265
+ signal: number;
266
+ timedOut: boolean;
267
+ cancelled: boolean;
268
+ durationMs: number;
269
+ /**
270
+ * False for the placeholder `run` writes when it starts (no process group yet): its
271
+ * `exit_code=0` is not a result.
272
+ */
273
+ isFinal: boolean;
274
+ }
275
+
276
+ /**
277
+ * Read a run's `meta` (key=value lines).
278
+ *
279
+ * The last value of a key wins: the command comes first, verbatim, and a line of a
280
+ * multi-line command may look like a field. Undefined when there is no `exit_code` at all.
281
+ */
282
+ export function parseMeta(text: string): JobMeta | undefined {
283
+ const fields = new Map<string, string>();
284
+ for (const line of text.split("\n")) {
285
+ const at = line.indexOf("=");
286
+ if (at > 0) fields.set(line.slice(0, at), line.slice(at + 1));
287
+ }
288
+ if (!fields.has("exit_code")) return undefined;
289
+ const number = (key: string) => {
290
+ const value = Number.parseInt(fields.get(key) ?? "", 10);
291
+ return Number.isFinite(value) ? value : 0;
292
+ };
293
+ const flag = (key: string) => {
294
+ const raw = (fields.get(key) ?? "").trim();
295
+ return raw === "1" || raw === "true";
296
+ };
297
+ return {
298
+ exitCode: number("exit_code"),
299
+ signal: number("signal"),
300
+ timedOut: flag("timed_out"),
301
+ cancelled: flag("cancelled"),
302
+ durationMs: number("duration_ms"),
303
+ isFinal: number("pgid") > 0,
304
+ };
305
+ }
306
+
307
+ export type EndingKind = "exited" | "signalled" | "runtime-limit" | "stopped" | "cancelled" | "unknown" | "not-started";
308
+
309
+ /** How a job ended, as a kind for the details and words for the text. */
310
+ export interface Ending {
311
+ kind: EndingKind;
312
+ /** Reads after the job id: "exited with code 0". */
313
+ text: string;
314
+ /** What else is known, or what the ending must not be mistaken for. */
315
+ note?: string;
316
+ /** The command's own status, when it had one. */
317
+ exitCode?: number;
318
+ }
319
+
320
+ const SIGNAL_NAMES: Record<number, string> = { 1: "SIGHUP", 2: "SIGINT", 6: "SIGABRT", 9: "SIGKILL", 11: "SIGSEGV", 13: "SIGPIPE", 15: "SIGTERM" };
321
+
322
+ const signalName = (signal: number): string => SIGNAL_NAMES[signal] ?? `signal ${signal}`;
323
+
324
+ /**
325
+ * Say how a job ended, from what is known and no more.
326
+ *
327
+ * The three things a nonzero-looking end can be are kept apart, because the model acts
328
+ * differently on each: the command failed, the runtime limit stopped it, or `stop` did.
329
+ * When `run` itself was killed before it could record anything, the status is unknown
330
+ * and is called that — the placeholder's `exit_code=0` is never repeated as a result.
331
+ */
332
+ export function describeEnding(options: {
333
+ meta?: JobMeta;
334
+ /** Whether a run directory ever appeared. */
335
+ started: boolean;
336
+ stopRequested: boolean;
337
+ maxRuntimeS: number;
338
+ /** How the `run` process itself ended, as Node reported it. */
339
+ wrapperCode?: number | null;
340
+ wrapperSignal?: string | null;
341
+ spawnError?: string;
342
+ }): Ending {
343
+ const { meta } = options;
344
+ if (options.spawnError !== undefined) return { kind: "not-started", text: "could not be started", note: options.spawnError };
345
+ if (!options.started && !options.stopRequested) {
346
+ return {
347
+ kind: "not-started",
348
+ text: "could not be started",
349
+ note: `\`busybox run\` exited with code ${options.wrapperCode ?? "unknown"} before running the command`,
350
+ };
351
+ }
352
+ if (!meta || !meta.isFinal) {
353
+ const how = options.wrapperSignal ? `\`busybox run\` was killed by ${options.wrapperSignal}` : "`busybox run` ended without recording a result";
354
+ return options.stopRequested
355
+ ? { kind: "stopped", text: "stopped", note: `${how}; the command's exit status is unknown` }
356
+ : { kind: "unknown", text: "ended with an unknown status", note: how };
357
+ }
358
+ if (meta.timedOut) {
359
+ return {
360
+ kind: "runtime-limit",
361
+ text: `killed at the runtime limit (max_runtime_s=${options.maxRuntimeS})`,
362
+ note: "the limit, not a failure of the command",
363
+ };
364
+ }
365
+ const own =
366
+ meta.exitCode >= 0
367
+ ? `the command exited with code ${meta.exitCode}`
368
+ : meta.signal > 0
369
+ ? `the command was ended by ${signalName(meta.signal)}`
370
+ : "the command's exit status is unknown";
371
+ if (meta.cancelled) {
372
+ return options.stopRequested
373
+ ? { kind: "stopped", text: "stopped", note: own, ...(meta.exitCode >= 0 ? { exitCode: meta.exitCode } : {}) }
374
+ : { kind: "cancelled", text: "cancelled from outside this tool", note: `\`busybox run\` was signalled; ${own}` };
375
+ }
376
+ if (meta.exitCode >= 0) return { kind: "exited", text: `exited with code ${meta.exitCode}`, exitCode: meta.exitCode };
377
+ if (meta.signal > 0) return { kind: "signalled", text: `killed by ${signalName(meta.signal)}` };
378
+ return { kind: "unknown", text: "ended with an unknown status" };
379
+ }
380
+
381
+ /** The argv of the `run` that carries a job. */
382
+ export function jobArgs(options: { root: string; shell: string; cwd?: string; maxRuntimeS: number }): string[] {
383
+ return [
384
+ "run",
385
+ "--timestamps",
386
+ "--stamp-ns",
387
+ "--pty-split",
388
+ "--dir",
389
+ options.root,
390
+ "--timeout",
391
+ String(options.maxRuntimeS),
392
+ ...(options.cwd ? ["--cwd", options.cwd] : []),
393
+ "--",
394
+ "/bin/bash",
395
+ "-c",
396
+ options.shell,
397
+ ];
398
+ }
399
+
400
+ /** The refusal for one job too many, or undefined when there is room. */
401
+ export function limitRefusal(running: number, limit: number = JOB_LIMIT): string | undefined {
402
+ if (running < limit) return undefined;
403
+ return (
404
+ `Not started: ${running} jobs are already running and the limit is ${limit}. ` +
405
+ "See them with busybox_job action=list and end one with busybox_job action=stop job=<id> first."
406
+ );
407
+ }
408
+
409
+ /**
410
+ * The refusal for a command ending in a stream merge, the same one bash calls get.
411
+ *
412
+ * A job's output is returned by stream; `2>&1` would hand all of it back as stdout.
413
+ */
414
+ export function mergeRefusal(shell: string, env: NodeJS.ProcessEnv = process.env): { text: string; label: string } | undefined {
415
+ if (!guardEnabled(env)) return undefined;
416
+ const merge = detectTailMerge(shell);
417
+ if (!merge || hasOverride(shell)) return undefined;
418
+ return { text: blockReason(merge), label: merge.label };
419
+ }
420
+
421
+ /** `1.2s`, `45s`, `3m 05s`, `1h 02m`: an age short enough for a list. */
422
+ export function describeAge(ms: number): string {
423
+ const seconds = Math.max(0, ms) / 1000;
424
+ if (seconds < 10) return `${seconds.toFixed(1)}s`;
425
+ const whole = Math.round(seconds);
426
+ if (whole < 60) return `${whole}s`;
427
+ const minutes = Math.floor(whole / 60);
428
+ if (minutes < 60) return `${minutes}m ${String(whole % 60).padStart(2, "0")}s`;
429
+ return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
430
+ }
431
+
432
+ /** A command as one short line. */
433
+ export function oneLine(command: string, limit = 120): string {
434
+ const flat = command.replace(/\s+/g, " ").trim();
435
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
436
+ }
437
+
438
+ /** Why a wait ended. */
439
+ export type WaitKind = "matched" | "exited" | "elapsed" | "cancelled";
440
+
441
+ export interface WaitOutcome {
442
+ kind: WaitKind;
443
+ /** How long the call waited, in ms. */
444
+ ms: number;
445
+ }
446
+
447
+ /**
448
+ * The sentence for how a wait ended, or undefined when there is nothing to add.
449
+ *
450
+ * With `wait_for` it always says one of four things plainly — appeared, not seen in time,
451
+ * the job exited first, the call was cancelled — because "no match" alone would leave the
452
+ * model guessing which.
453
+ */
454
+ export function describeWaitOutcome(outcome: WaitOutcome, options: { literal?: string; waitS: number }): string | undefined {
455
+ const took = `${(outcome.ms / 1000).toFixed(1)}s`;
456
+ if (options.literal === undefined) {
457
+ if (outcome.kind === "cancelled") return `this call was cancelled after ${took}; the job is still running.`;
458
+ if (outcome.kind === "elapsed" && options.waitS > 0) return `waited ${options.waitS}s; the job is still running.`;
459
+ return undefined;
460
+ }
461
+ const quoted = `\`${oneLine(options.literal, 80)}\``;
462
+ switch (outcome.kind) {
463
+ case "matched":
464
+ return `wait_for: ${quoted} appeared after ${took}.`;
465
+ case "exited":
466
+ return `wait_for: ${quoted} not seen: the job exited before it appeared.`;
467
+ case "cancelled":
468
+ return `wait_for: ${quoted} not seen: this call was cancelled after ${took}; the job is still running.`;
469
+ default:
470
+ return options.waitS > 0
471
+ ? `wait_for: ${quoted} not seen after ${options.waitS}s; the job is still running.`
472
+ : `wait_for: ${quoted} is not in the new output, and this call did not wait (wait_s=0); the job is still running.`;
473
+ }
474
+ }
475
+
476
+ /**
477
+ * The output section of a result.
478
+ *
479
+ * Says once how the streams are told apart, says "no new output" when there is none, and
480
+ * says how many bytes were left out and where they still are.
481
+ */
482
+ export function formatOutput(options: {
483
+ view: View;
484
+ maxBytes: number;
485
+ /** `since the last call` for status, `so far` for start. */
486
+ since: string;
487
+ /** Where the whole capture can still be read, when it can. */
488
+ captureNote?: string;
489
+ }): string {
490
+ const { view } = options;
491
+ if (view.shownBytes === 0 && view.droppedBytes === 0) return `no new output ${options.since}.`;
492
+ const parts = [
493
+ `--- new output ${options.since}: ${view.lines} line${view.lines === 1 ? "" : "s"}, ${view.shownBytes} bytes ` +
494
+ `(stdout lines are bare, stderr lines start with \`${STDERR_LABEL}\`; the order between the two streams is approximate) ---`,
495
+ ];
496
+ if (view.droppedBytes > 0) {
497
+ parts.push(
498
+ `[${view.droppedBytes} earlier bytes are not shown: only the end fits max_bytes=${options.maxBytes}.${options.captureNote ? ` ${options.captureNote}` : ""}]`,
499
+ );
500
+ }
501
+ parts.push(view.text, "--- end of new output ---");
502
+ return parts.join("\n");
503
+ }
504
+
505
+ interface StreamFollower {
506
+ poll(): void;
507
+ started(): boolean;
508
+ runDir(): string | undefined;
509
+ close(): void;
510
+ }
511
+
512
+ /**
513
+ * Follow the one run under `root`, saying which stream each piece came from.
514
+ *
515
+ * `followRun` in userstdin.ts does the same reading for a person watching, where the two
516
+ * streams go to one screen; its callback does not carry the stream, and a job's view is
517
+ * labelled by it. So the loop is repeated here with the name passed along.
518
+ */
519
+ function followStreams(root: string, onData: (stream: StreamName, data: Buffer) => void): StreamFollower {
520
+ let runDir: string | undefined;
521
+ const streams = [
522
+ { name: "out" as StreamName, file: "stdout", fd: undefined as number | undefined, offset: 0 },
523
+ { name: "err" as StreamName, file: "stderr", fd: undefined as number | undefined, offset: 0 },
524
+ ];
525
+ const chunk = Buffer.allocUnsafe(64 * 1024);
526
+ return {
527
+ poll() {
528
+ if (!runDir) {
529
+ try {
530
+ const found = readdirSync(root).find((name) => /^R\d+$/.test(name));
531
+ if (found) runDir = join(root, found);
532
+ } catch {
533
+ // Nothing to read until `run` has made its folder.
534
+ }
535
+ if (!runDir) return;
536
+ }
537
+ for (const stream of streams) {
538
+ if (stream.fd === undefined) {
539
+ try {
540
+ stream.fd = openSync(join(runDir, stream.file), "r");
541
+ } catch {
542
+ continue;
543
+ }
544
+ }
545
+ for (;;) {
546
+ let read = 0;
547
+ try {
548
+ read = readSync(stream.fd, chunk, 0, chunk.length, stream.offset);
549
+ } catch {
550
+ break;
551
+ }
552
+ if (read <= 0) break;
553
+ stream.offset += read;
554
+ // A copy: the buffer is reused for the next read.
555
+ onData(stream.name, Buffer.from(chunk.subarray(0, read)));
556
+ }
557
+ }
558
+ },
559
+ started: () => runDir !== undefined,
560
+ runDir: () => runDir,
561
+ close() {
562
+ for (const stream of streams) {
563
+ if (stream.fd === undefined) continue;
564
+ try {
565
+ closeSync(stream.fd);
566
+ } catch {
567
+ // Already closed.
568
+ }
569
+ stream.fd = undefined;
570
+ }
571
+ },
572
+ };
573
+ }
574
+
575
+ interface Job {
576
+ id: string;
577
+ command: string;
578
+ /** The private artifact root; undefined once it has been removed. */
579
+ root: string | undefined;
580
+ child: ChildProcess;
581
+ startedAt: number;
582
+ endedAt?: number;
583
+ maxRuntimeS: number;
584
+ follower: StreamFollower;
585
+ decoders: Record<StreamName, StringDecoder>;
586
+ unread: UnreadOutput;
587
+ watchers: Set<LiteralWatch>;
588
+ timer: ReturnType<typeof setInterval> | undefined;
589
+ ending?: Ending;
590
+ isStopRequested: boolean;
591
+ /** The final output and the ending have been returned once. */
592
+ isReported: boolean;
593
+ }
594
+
595
+ /** Every job of this process, by id. Ended ones stay until they are forgotten. */
596
+ const jobs = new Map<string, Job>();
597
+ let lastJobNumber = 0;
598
+
599
+ const runningJobs = () => [...jobs.values()].filter((job) => job.ending === undefined);
600
+
601
+ /** How many jobs are running now. */
602
+ export function runningJobCount(): number {
603
+ return runningJobs().length;
604
+ }
605
+
606
+ function send(pid: number | undefined, signal: NodeJS.Signals): void {
607
+ if (pid === undefined || pid === 0) return;
608
+ try {
609
+ process.kill(pid, signal);
610
+ } catch {
611
+ // Gone already, which is what the signal was for.
612
+ }
613
+ }
614
+
615
+ function removeRoot(job: Job): void {
616
+ job.follower.close();
617
+ if (job.root === undefined) return;
618
+ try {
619
+ // `run` may still be writing its last files when a shutdown removes the folder.
620
+ rmSync(job.root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
621
+ } catch {
622
+ // A folder in the temp directory that could not be removed is not worth failing for.
623
+ }
624
+ job.root = undefined;
625
+ }
626
+
627
+ function pollJob(job: Job): void {
628
+ if (job.root === undefined) return;
629
+ job.follower.poll();
630
+ }
631
+
632
+ /** The `run` process has exited (or never started): take the last output and the verdict. */
633
+ function finishJob(job: Job, exit: { code?: number | null; signal?: string | null; spawnError?: string }): void {
634
+ if (job.ending !== undefined) return;
635
+ if (job.timer) clearInterval(job.timer);
636
+ job.timer = undefined;
637
+ job.endedAt = Date.now();
638
+ // The files are complete now: one last read, and whatever half a character was held back.
639
+ pollJob(job);
640
+ for (const stream of ["out", "err"] as const) {
641
+ const rest = job.decoders[stream].end();
642
+ if (rest) deliver(job, stream, rest);
643
+ }
644
+ let meta: JobMeta | undefined;
645
+ const runDir = job.follower.runDir();
646
+ if (runDir) {
647
+ try {
648
+ meta = parseMeta(readFileSync(join(runDir, "meta"), "utf8"));
649
+ } catch {
650
+ // No meta: the ending is described as unknown.
651
+ }
652
+ }
653
+ job.follower.close();
654
+ job.ending = describeEnding({
655
+ meta,
656
+ started: job.follower.started(),
657
+ stopRequested: job.isStopRequested,
658
+ maxRuntimeS: job.maxRuntimeS,
659
+ wrapperCode: exit.code,
660
+ wrapperSignal: exit.signal,
661
+ spawnError: exit.spawnError,
662
+ });
663
+ }
664
+
665
+ function deliver(job: Job, stream: StreamName, text: string): void {
666
+ if (text === "") return;
667
+ job.unread.push(stream, text);
668
+ for (const watch of job.watchers) watch.feed(stream, text);
669
+ }
670
+
671
+ function startJob(options: { binary: string; shell: string; cwd?: string; maxRuntimeS: number }): Job {
672
+ const root = mkdtempSync(join(tmpdir(), "pi-job-"));
673
+ const env: NodeJS.ProcessEnv = { ...process.env };
674
+ // The same quiet, unbuffered environment a bash call gets: under the pty a dev server
675
+ // would otherwise colour its log, and the view would be escape codes.
676
+ for (const [name, value] of UNBUFFERED_ENV) env[name] = value;
677
+ let child: ChildProcess;
678
+ try {
679
+ // Detached: its own process group, so a Ctrl-C in pi's terminal does not reach it and
680
+ // it does not hold pi open. Nothing is read from its pipes — the files are the output.
681
+ child = spawn(options.binary, jobArgs({ root, ...options }), { detached: true, stdio: "ignore", env });
682
+ } catch (error) {
683
+ rmSync(root, { recursive: true, force: true });
684
+ throw error;
685
+ }
686
+ child.unref();
687
+ lastJobNumber += 1;
688
+ const job: Job = {
689
+ id: `J${lastJobNumber}`,
690
+ command: options.shell,
691
+ root,
692
+ child,
693
+ startedAt: Date.now(),
694
+ maxRuntimeS: options.maxRuntimeS,
695
+ follower: followStreams(root, (stream, data) => deliver(job, stream, job.decoders[stream].write(data))),
696
+ decoders: { out: new StringDecoder("utf8"), err: new StringDecoder("utf8") },
697
+ unread: new UnreadOutput(),
698
+ watchers: new Set(),
699
+ timer: undefined,
700
+ isStopRequested: false,
701
+ isReported: false,
702
+ };
703
+ child.once("error", (error) => finishJob(job, { spawnError: error.message }));
704
+ child.once("exit", (code, signal) => finishJob(job, { code, signal }));
705
+ // Read between calls too: it keeps the order between the streams as fine as the
706
+ // interval, and keeps a chatty job's backlog from being read in one go.
707
+ job.timer = setInterval(() => pollJob(job), POLL_MS);
708
+ job.timer.unref();
709
+ jobs.set(job.id, job);
710
+ forgetOldJobs();
711
+ return job;
712
+ }
713
+
714
+ function forgetOldJobs(): void {
715
+ for (const job of [...jobs.values()]) {
716
+ if (jobs.size <= REMEMBERED_JOBS) return;
717
+ if (job.ending === undefined) continue;
718
+ removeRoot(job);
719
+ jobs.delete(job.id);
720
+ }
721
+ }
722
+
723
+ function pause(ms: number, signal: AbortSignal | undefined): Promise<void> {
724
+ return new Promise((resolve) => {
725
+ if (signal?.aborted) return resolve();
726
+ const done = () => {
727
+ clearTimeout(timer);
728
+ signal?.removeEventListener("abort", done);
729
+ resolve();
730
+ };
731
+ const timer = setTimeout(done, ms);
732
+ signal?.addEventListener("abort", done, { once: true });
733
+ });
734
+ }
735
+
736
+ /**
737
+ * Wait on a job: for the literal, for its exit, for the time to pass or for the call to
738
+ * be cancelled — whichever is first, and the answer says which.
739
+ */
740
+ async function waitOnJob(job: Job, options: { literal?: string; waitMs: number; signal?: AbortSignal }): Promise<WaitOutcome> {
741
+ const from = Date.now();
742
+ const watch = options.literal !== undefined ? watchLiteral(options.literal) : undefined;
743
+ if (watch) {
744
+ // What has arrived and not been returned yet counts: it is new to the model.
745
+ for (const segment of job.unread.peek()) watch.feed(segment.stream, segment.text);
746
+ job.watchers.add(watch);
747
+ }
748
+ try {
749
+ for (;;) {
750
+ pollJob(job);
751
+ const ms = Date.now() - from;
752
+ if (watch?.seen) return { kind: "matched", ms };
753
+ if (job.ending !== undefined) return { kind: "exited", ms };
754
+ if (options.signal?.aborted) return { kind: "cancelled", ms };
755
+ if (ms >= options.waitMs) return { kind: "elapsed", ms };
756
+ await pause(Math.min(POLL_MS, options.waitMs - ms), options.signal);
757
+ }
758
+ } finally {
759
+ if (watch) job.watchers.delete(watch);
760
+ }
761
+ }
762
+
763
+ /** The process groups `run` started: its children lead their own (measured: pgid = pid). */
764
+ function childPids(pid: number): number[] {
765
+ try {
766
+ const out = execFileSync("pgrep", ["-P", String(pid)], { encoding: "utf8", timeout: 1_000, stdio: ["ignore", "pipe", "ignore"] });
767
+ return out
768
+ .split("\n")
769
+ .map((line) => Number.parseInt(line, 10))
770
+ .filter((child) => Number.isInteger(child) && child > 1);
771
+ } catch {
772
+ // No children, or no pgrep: only the wrapper's own group can be reached.
773
+ return [];
774
+ }
775
+ }
776
+
777
+ /**
778
+ * The fallback when `run` did not end the command itself: SIGKILL, to the command's
779
+ * process group first (it would outlive a killed wrapper if it ignores the hangup) and
780
+ * then to the detached wrapper's.
781
+ */
782
+ function killHard(job: Job): void {
783
+ const pid = job.child.pid;
784
+ if (pid === undefined) return;
785
+ for (const child of childPids(pid)) {
786
+ send(-child, "SIGKILL");
787
+ send(child, "SIGKILL");
788
+ }
789
+ send(-pid, "SIGKILL");
790
+ send(pid, "SIGKILL");
791
+ }
792
+
793
+ async function waitForEnd(job: Job, ms: number, signal?: AbortSignal): Promise<void> {
794
+ const until = Date.now() + ms;
795
+ while (job.ending === undefined && Date.now() < until && !signal?.aborted) await pause(25, undefined);
796
+ }
797
+
798
+ /**
799
+ * Stop a job: SIGTERM to `run`, which stops the command's process group itself (it owns
800
+ * that group, and escalates to SIGKILL after its own grace); SIGKILL from here only when
801
+ * that has not happened in time.
802
+ */
803
+ async function stopJob(job: Job, options: { graceMs?: number; signal?: AbortSignal } = {}): Promise<void> {
804
+ if (job.ending !== undefined) return;
805
+ job.isStopRequested = true;
806
+ send(job.child.pid, "SIGTERM");
807
+ await waitForEnd(job, options.graceMs ?? STOP_GRACE_MS, options.signal);
808
+ if (job.ending !== undefined) return;
809
+ killHard(job);
810
+ await waitForEnd(job, 1_000);
811
+ // Not even SIGKILL was confirmed: say so rather than wait for ever.
812
+ if (job.ending === undefined) finishJob(job, { signal: "SIGKILL" });
813
+ }
814
+
815
+ /** Whether `run` has written its final record: the only sign of its exit that can be read without the event loop. */
816
+ function hasFinalRecord(job: Job): boolean {
817
+ if (job.root === undefined) return true;
818
+ try {
819
+ const runDir = join(job.root, "R1");
820
+ return existsSync(join(runDir, "timeline")) && parseMeta(readFileSync(join(runDir, "meta"), "utf8"))?.isFinal === true;
821
+ } catch {
822
+ return false;
823
+ }
824
+ }
825
+
826
+ function sleepSync(ms: number): void {
827
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
828
+ }
829
+
830
+ /**
831
+ * Stop every job and remove every job folder, for `session_shutdown`.
832
+ *
833
+ * Synchronous, so it works from a handler that is not awaited: SIGTERM to each `run`, up
834
+ * to `graceMs` (a second) for them to finish in total, SIGKILL to whatever is left, then
835
+ * the folders. Returns how many jobs were still running.
836
+ */
837
+ export function stopAllJobs(graceMs = 1_000): number {
838
+ const running = runningJobs();
839
+ for (const job of running) {
840
+ job.isStopRequested = true;
841
+ send(job.child.pid, "SIGTERM");
842
+ }
843
+ const until = Date.now() + graceMs;
844
+ // The exit events cannot arrive while this function runs, so the files are asked.
845
+ while (Date.now() < until && running.some((job) => !hasFinalRecord(job))) sleepSync(20);
846
+ for (const job of running) {
847
+ if (!hasFinalRecord(job)) killHard(job);
848
+ }
849
+ for (const job of jobs.values()) {
850
+ if (job.timer) clearInterval(job.timer);
851
+ job.timer = undefined;
852
+ // A late exit event finds the job already ended and does nothing.
853
+ job.ending ??= { kind: "stopped", text: "stopped at session shutdown" };
854
+ job.endedAt ??= Date.now();
855
+ removeRoot(job);
856
+ }
857
+ jobs.clear();
858
+ return running.length;
859
+ }
860
+
861
+ /** One result shape, as in agenttools.ts. */
862
+ interface ToolOutcome {
863
+ content: { type: "text"; text: string }[];
864
+ details: Record<string, unknown> | undefined;
865
+ isError?: boolean;
866
+ }
867
+
868
+ const refuse = (text: string, details?: Record<string, unknown>): ToolOutcome => ({ content: [{ type: "text", text }], details, isError: true });
869
+
870
+ function clamp(value: number | undefined, fallback: number, low: number, high: number): number {
871
+ if (value === undefined || !Number.isFinite(value)) return fallback;
872
+ return Math.min(high, Math.max(low, value));
873
+ }
874
+
875
+ /** One line for a job: its id, how it stands, for how long, and the command. */
876
+ export function headline(job: { id: string; command: string; startedAt: number; endedAt?: number; ending?: Ending }, now: number = Date.now()): string {
877
+ const command = oneLine(job.command);
878
+ if (job.ending === undefined) return `${job.id} running for ${describeAge(now - job.startedAt)} — ${command}`;
879
+ const ran = job.ending.kind === "not-started" ? "" : ` after ${describeAge((job.endedAt ?? now) - job.startedAt)}`;
880
+ return `${job.id} ${job.ending.text}${ran}${job.ending.note ? ` (${job.ending.note})` : ""} — ${command}`;
881
+ }
882
+
883
+ /**
884
+ * Take a job's unread output and build the result around it.
885
+ *
886
+ * Once an ended job's last output has been returned its folder is removed — unless that
887
+ * view was cut, in which case the files are the only place the rest can be read and they
888
+ * stay until `stop` or the end of the session.
889
+ */
890
+ function report(job: Job, options: { maxBytes: number; since: string; wait?: string; removing?: boolean; hint?: string }): ToolOutcome {
891
+ pollJob(job);
892
+ const wasReported = job.isReported;
893
+ const taken = job.unread.take();
894
+ const view = renderView(taken.segments, options.maxBytes);
895
+ view.droppedBytes += taken.droppedBytes;
896
+ const hasEnded = job.ending !== undefined;
897
+ const runDir = job.follower.runDir();
898
+ const willRemove = options.removing === true || (hasEnded && view.droppedBytes === 0);
899
+ let captureNote: string | undefined;
900
+ if (view.droppedBytes > 0 && runDir && job.root !== undefined) {
901
+ captureNote = willRemove
902
+ ? "The capture was removed with the job."
903
+ : `The whole capture is in ${join(runDir, "stdout")} and ${join(runDir, "stderr")} until busybox_job action=stop job=${job.id}${hasEnded ? " or the end of the session" : ""}.`;
904
+ }
905
+ const lines = [headline(job)];
906
+ // A second question about an ended job gets the same answer, marked as not news.
907
+ if (hasEnded && wasReported) lines.push("(this ending and the job's last output were reported before)");
908
+ if (options.wait) lines.push(options.wait);
909
+ lines.push(formatOutput({ view, maxBytes: options.maxBytes, since: options.since, captureNote }));
910
+ if (options.hint) lines.push(options.hint);
911
+ if (hasEnded) job.isReported = true;
912
+ if (willRemove) removeRoot(job);
913
+ return {
914
+ content: [{ type: "text", text: lines.join("\n") }],
915
+ details: {
916
+ job: job.id,
917
+ state: hasEnded ? "ended" : "running",
918
+ ...(job.ending ? { ending: job.ending.kind } : {}),
919
+ ...(job.ending?.exitCode !== undefined ? { exit_code: job.ending.exitCode } : {}),
920
+ new_bytes: view.shownBytes,
921
+ dropped_bytes: view.droppedBytes,
922
+ },
923
+ // A job that could not be started is the tool's failure; a job that failed is its own result.
924
+ isError: job.ending?.kind === "not-started",
925
+ };
926
+ }
927
+
928
+ function listJobs(now: number = Date.now()): string {
929
+ if (jobs.size === 0) return "no jobs. Start one with busybox_job action=start shell=<command>.";
930
+ const lines = [...jobs.values()].map((job) => headline(job, now));
931
+ const running = runningJobCount();
932
+ lines.push(`${jobs.size} job${jobs.size === 1 ? "" : "s"}, ${running} running (at most ${JOB_LIMIT} at once).`);
933
+ return lines.join("\n");
934
+ }
935
+
936
+ function unknownJob(id: string | undefined): ToolOutcome {
937
+ const known = [...jobs.keys()];
938
+ const asked = id === undefined ? "this action needs 'job' (the id 'start' returned, e.g. J1)" : `no job ${id}`;
939
+ return refuse(`${asked}; ${known.length > 0 ? `jobs: ${known.join(", ")}` : "there are no jobs"}. busybox_job action=list shows them.`);
940
+ }
941
+
942
+ export const JOB_TOOL_DESCRIPTION =
943
+ "Run a command as a background job that outlives this call: a dev server, a watcher, anything a normal bash call would hit its deadline on. " +
944
+ "'start' runs 'shell' through bash -c under its own `busybox run` and returns a job id (J1) with its first output; " +
945
+ "'status' returns only the output that is new since the last start/status call for that job, and whether it is still running or how it ended (exit code, runtime limit, stopped); " +
946
+ "'stop' ends the job and its whole process group and returns the last output; 'list' shows every job. " +
947
+ "'wait_for' (a literal string) with 'wait_s' returns as soon as that text appears, and the result says whether it appeared, the time ran out, or the job exited first. " +
948
+ "stdout lines come back bare, stderr lines start with `err| `. The job's stdin is empty. " +
949
+ `A job is killed at 'max_runtime_s' (default ${DEFAULT_MAX_RUNTIME_SECONDS}); at most ${JOB_LIMIT} run at once. ` +
950
+ "A command that finishes on its own belongs in a normal bash call.";
951
+
952
+ export const JOB_TOOL_GUIDELINES: string[] = [
953
+ "Use busybox_job action=start for a command that must outlive one call (a server, a watcher): a normal bash call would end in a TIMEOUT, and `&` would lose the output. Anything that finishes on its own still belongs in a normal bash call.",
954
+ "After starting a job, wait for readiness with busybox_job action=status job=<id> wait_for=<literal> wait_s=<seconds> instead of `sleep`: it returns the moment the text appears and says whether it did.",
955
+ "Call busybox_job action=stop job=<id> when you are done with a job: it keeps running until stopped.",
956
+ ];
957
+
958
+ /** Register `busybox_job`: start, watch, wait on and stop a long-running command. */
959
+ export function registerJobTool(pi: ExtensionAPI, binDir: string): void {
960
+ pi.registerTool({
961
+ name: "busybox_job",
962
+ label: "BusyBox Job",
963
+ description: JOB_TOOL_DESCRIPTION,
964
+ promptSnippet: "Start a long-running command in the background, read its new output, wait for a line, stop it",
965
+ promptGuidelines: JOB_TOOL_GUIDELINES,
966
+ parameters: Type.Object({
967
+ action: Type.Union([Type.Literal("start"), Type.Literal("status"), Type.Literal("stop"), Type.Literal("list")], {
968
+ description: "start a job, read a job's new output (status), stop a job, or list all jobs.",
969
+ }),
970
+ shell: Type.Optional(Type.String({ description: "start: the command line, run through bash -c. Do not background it with & and do not merge its streams." })),
971
+ cwd: Type.Optional(Type.String({ description: "start: working directory for the command." })),
972
+ job: Type.Optional(Type.String({ description: "status/stop: the job id that start returned, e.g. J1." })),
973
+ wait_for: Type.Optional(
974
+ Type.String({ description: "start/status: a literal string; the call returns as soon as it appears in output not returned before." }),
975
+ ),
976
+ wait_s: Type.Optional(
977
+ Type.Number({
978
+ description: `start/status: how long to wait for wait_for, or for the job to exit, before returning (default ${DEFAULT_START_WAIT_SECONDS} for start, 0 for status; max ${MAX_WAIT_SECONDS}).`,
979
+ }),
980
+ ),
981
+ max_runtime_s: Type.Optional(
982
+ Type.Number({ description: `start: the job is killed after this many seconds (default ${DEFAULT_MAX_RUNTIME_SECONDS}).` }),
983
+ ),
984
+ max_bytes: Type.Optional(
985
+ Type.Number({ description: `Byte budget for the returned output; over it, only the end is shown (default ${DEFAULT_VIEW_BYTES}).` }),
986
+ ),
987
+ }),
988
+ async execute(_toolCallId, params, signal): Promise<ToolOutcome> {
989
+ const maxBytes = Math.floor(clamp(params.max_bytes, DEFAULT_VIEW_BYTES, MIN_VIEW_BYTES, MAX_VIEW_BYTES));
990
+ if (params.wait_for !== undefined && params.wait_for === "") return refuse("wait_for is empty: give the literal text to wait for, or leave it out");
991
+
992
+ if (params.action === "list") {
993
+ for (const job of jobs.values()) pollJob(job);
994
+ return { content: [{ type: "text", text: listJobs() }], details: { jobs: jobs.size, running: runningJobCount() } };
995
+ }
996
+
997
+ if (params.action === "start") {
998
+ const shell = params.shell;
999
+ if (shell === undefined || shell.trim() === "") return refuse("start needs 'shell': the command line to run");
1000
+ // The same view-correctness guard as bash calls and busybox_run: a job's output
1001
+ // comes back by stream, and a merge at the tail would make all of it stdout.
1002
+ const merge = mergeRefusal(shell);
1003
+ if (merge) return refuse(merge.text, { blocked: merge.label });
1004
+ if (!busyboxAvailable(binDir)) {
1005
+ return refuse(`busybox is not installed at ${busyboxBinaryPath(binDir)} (or cannot run) - run managed_tools with action 'update', then start the job again`);
1006
+ }
1007
+ const full = limitRefusal(runningJobCount());
1008
+ if (full) return refuse(full, { running: runningJobCount() });
1009
+ const maxRuntimeS = Math.ceil(clamp(params.max_runtime_s, DEFAULT_MAX_RUNTIME_SECONDS, 1, 7 * 24 * 3600));
1010
+ const waitS = clamp(params.wait_s, DEFAULT_START_WAIT_SECONDS, 0, MAX_WAIT_SECONDS);
1011
+ let job: Job;
1012
+ try {
1013
+ job = startJob({ binary: busyboxBinaryPath(binDir), shell, cwd: params.cwd, maxRuntimeS });
1014
+ } catch (error) {
1015
+ return refuse(`the job could not be started: ${error instanceof Error ? error.message : String(error)}`);
1016
+ }
1017
+ const outcome = await waitOnJob(job, { literal: params.wait_for, waitMs: waitS * 1000, signal });
1018
+ return report(job, {
1019
+ maxBytes,
1020
+ since: "so far",
1021
+ wait: describeWaitOutcome(outcome, { literal: params.wait_for, waitS }),
1022
+ ...(job.ending === undefined
1023
+ ? { hint: `Next: busybox_job action=status job=${job.id} (with wait_for and wait_s to wait for a line); action=stop job=${job.id} when done.` }
1024
+ : {}),
1025
+ });
1026
+ }
1027
+
1028
+ const job = params.job !== undefined ? jobs.get(params.job.trim().toUpperCase()) : undefined;
1029
+ if (!job) return unknownJob(params.job);
1030
+
1031
+ if (params.action === "stop") {
1032
+ const wasRunning = job.ending === undefined;
1033
+ await stopJob(job, { signal });
1034
+ return report(job, {
1035
+ maxBytes,
1036
+ since: "since the last call",
1037
+ removing: true,
1038
+ ...(wasRunning ? {} : { wait: `${job.id} had already ended; its capture was removed.` }),
1039
+ });
1040
+ }
1041
+
1042
+ const waitS = clamp(params.wait_s, 0, 0, MAX_WAIT_SECONDS);
1043
+ const outcome = await waitOnJob(job, { literal: params.wait_for, waitMs: waitS * 1000, signal });
1044
+ return report(job, {
1045
+ maxBytes,
1046
+ since: "since the last call",
1047
+ // On a job that had ended before this call there was nothing to wait for.
1048
+ wait: job.isReported ? undefined : describeWaitOutcome(outcome, { literal: params.wait_for, waitS }),
1049
+ });
1050
+ },
1051
+ });
1052
+ }