@rob-c/pi-managed-tools 0.16.0 → 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/BUSYBOX-CONTRACT.md +440 -0
- package/CHANGELOG.md +441 -0
- package/README.md +464 -35
- package/package.json +7 -4
- package/skills/busybox-applets/SKILL.md +142 -15
- package/skills/managed-tools/SKILL.md +201 -25
- package/skills/managed-tools-reference/SKILL.md +206 -38
- package/src/agentops.ts +813 -0
- package/src/agenttools.ts +391 -0
- package/src/bashtool.ts +103 -0
- package/src/build.ts +142 -0
- package/src/context.ts +157 -0
- package/src/display.ts +79 -0
- package/src/extension.ts +817 -28
- package/src/guard.ts +437 -0
- package/src/jobs.ts +1052 -0
- package/src/timing.ts +364 -0
- package/src/tools.ts +525 -42
- package/src/userstdin.ts +524 -0
- package/src/wrap.ts +683 -0
package/src/agentops.ts
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
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
|
+
* The agent-facing half of the packaged busybox: `peek`, `replace`, `run`, `log`.
|
|
18
|
+
*
|
|
19
|
+
* These four applets exist because a bounded, versioned read and an all-or-nothing
|
|
20
|
+
* write are what a model gets wrong by hand — not because busybox needs more Unix
|
|
21
|
+
* commands. The binary owns every guarantee that matters (byte budgets, the
|
|
22
|
+
* `flock`-guarded write, process-group cleanup, 0600 run artifacts), so this module
|
|
23
|
+
* spawns it and formats the JSON it prints. It never re-implements a guarantee and
|
|
24
|
+
* never retries a mutation.
|
|
25
|
+
*
|
|
26
|
+
* Why spawn and not parse files here: a second implementation of the same contract
|
|
27
|
+
* would drift from the binary the plugin ships, and only the binary's version can
|
|
28
|
+
* match the version it hashes.
|
|
29
|
+
*
|
|
30
|
+
* Nothing here imports pi packages: the extension passes in the bin directory and
|
|
31
|
+
* the tests run this module directly against a stand-in binary.
|
|
32
|
+
*/
|
|
33
|
+
import { spawn } from "node:child_process";
|
|
34
|
+
import { chmodSync, existsSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
35
|
+
import { tmpdir } from "node:os";
|
|
36
|
+
import { join } from "node:path";
|
|
37
|
+
import { platform } from "node:os";
|
|
38
|
+
import { describeCancellation, describeTimeout } from "./timing.ts";
|
|
39
|
+
|
|
40
|
+
export interface AppletRaw {
|
|
41
|
+
/** Null when the process never started or was killed. */
|
|
42
|
+
status: number | null;
|
|
43
|
+
stdout: string;
|
|
44
|
+
stderr: string;
|
|
45
|
+
/** True when this wrapper's own deadline fired. */
|
|
46
|
+
timedOut: boolean;
|
|
47
|
+
/** True when the caller's AbortSignal fired. */
|
|
48
|
+
cancelled: boolean;
|
|
49
|
+
/** Set when the binary could not be spawned at all. */
|
|
50
|
+
error?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface AppletResult<T> extends AppletRaw {
|
|
54
|
+
/** Parsed stdout, when the applet printed JSON. */
|
|
55
|
+
json?: T;
|
|
56
|
+
/** JSON parse failure, or a contract-level error object in the payload. */
|
|
57
|
+
parseError?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function busyboxBinary(binDir: string, plat: string = platform()): string {
|
|
61
|
+
return join(binDir, "busybox" + (plat === "win32" ? ".exe" : ""));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Default output cap per stream; the view budgets are far smaller, this is a leak stop. */
|
|
65
|
+
const STREAM_CAP = 4 * 1024 * 1024;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Run one applet and collect its output.
|
|
69
|
+
*
|
|
70
|
+
* Cancellation is the caller's AbortSignal (pi's tool signal): TERM, then KILL
|
|
71
|
+
* after a grace period. The applets clean up their own process group, so killing
|
|
72
|
+
* the multicall binary is enough — but only because `run` owns its child's group.
|
|
73
|
+
*/
|
|
74
|
+
export function runApplet(options: {
|
|
75
|
+
binDir: string;
|
|
76
|
+
applet: string;
|
|
77
|
+
args: string[];
|
|
78
|
+
cwd?: string;
|
|
79
|
+
timeoutMs?: number;
|
|
80
|
+
signal?: AbortSignal;
|
|
81
|
+
plat?: string;
|
|
82
|
+
stdin?: string;
|
|
83
|
+
}): Promise<AppletRaw> {
|
|
84
|
+
const binary = busyboxBinary(options.binDir, options.plat);
|
|
85
|
+
if (!existsSync(binary)) {
|
|
86
|
+
return Promise.resolve({
|
|
87
|
+
status: null,
|
|
88
|
+
stdout: "",
|
|
89
|
+
stderr: "",
|
|
90
|
+
timedOut: false,
|
|
91
|
+
cancelled: false,
|
|
92
|
+
error: `busybox is not installed at ${binary} - run managed_tools with action 'update'`,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (statSync(binary).size === 0) {
|
|
96
|
+
return Promise.resolve({
|
|
97
|
+
status: null,
|
|
98
|
+
stdout: "",
|
|
99
|
+
stderr: "",
|
|
100
|
+
timedOut: false,
|
|
101
|
+
cancelled: false,
|
|
102
|
+
error: `busybox at ${binary} is empty - run managed_tools with action 'reinstall', tool 'busybox'`,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return new Promise((resolve) => {
|
|
107
|
+
let stdout = "";
|
|
108
|
+
let stderr = "";
|
|
109
|
+
let timedOut = false;
|
|
110
|
+
let cancelled = false;
|
|
111
|
+
let settled = false;
|
|
112
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
113
|
+
let deadline: NodeJS.Timeout | undefined;
|
|
114
|
+
|
|
115
|
+
const child = spawn(binary, [options.applet, ...options.args], {
|
|
116
|
+
cwd: options.cwd,
|
|
117
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
118
|
+
windowsHide: true,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const finish = (result: AppletRaw) => {
|
|
122
|
+
if (settled) return;
|
|
123
|
+
settled = true;
|
|
124
|
+
if (deadline) clearTimeout(deadline);
|
|
125
|
+
if (killTimer) clearTimeout(killTimer);
|
|
126
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
127
|
+
resolve(result);
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** TERM first so the applet can reap its own group, then KILL. */
|
|
131
|
+
const stop = (reason: "timeout" | "cancel") => {
|
|
132
|
+
if (reason === "timeout") timedOut = true;
|
|
133
|
+
else cancelled = true;
|
|
134
|
+
child.kill("SIGTERM");
|
|
135
|
+
killTimer = setTimeout(() => child.kill("SIGKILL"), 2_000);
|
|
136
|
+
// A grandchild that inherited the pipes can hold them open after the applet is
|
|
137
|
+
// gone (a shell wrapper that did not exec). Stop waiting on stdio once the
|
|
138
|
+
// kill has had its chance, so a cancelled tool call always returns.
|
|
139
|
+
setTimeout(() => {
|
|
140
|
+
child.stdout?.destroy();
|
|
141
|
+
child.stderr?.destroy();
|
|
142
|
+
finish({ status: null, stdout, stderr, timedOut, cancelled });
|
|
143
|
+
}, 3_000);
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const onAbort = () => stop("cancel");
|
|
147
|
+
if (options.signal) {
|
|
148
|
+
if (options.signal.aborted) {
|
|
149
|
+
stop("cancel");
|
|
150
|
+
} else {
|
|
151
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (options.timeoutMs && options.timeoutMs > 0) {
|
|
155
|
+
deadline = setTimeout(() => stop("timeout"), options.timeoutMs);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
159
|
+
if (stdout.length < STREAM_CAP) stdout += chunk.toString("utf-8");
|
|
160
|
+
});
|
|
161
|
+
child.stderr?.on("data", (chunk: Buffer) => {
|
|
162
|
+
if (stderr.length < STREAM_CAP) stderr += chunk.toString("utf-8");
|
|
163
|
+
});
|
|
164
|
+
child.on("error", (error: Error) => {
|
|
165
|
+
finish({ status: null, stdout, stderr, timedOut, cancelled, error: error.message });
|
|
166
|
+
});
|
|
167
|
+
child.on("close", (code: number | null) => {
|
|
168
|
+
finish({ status: code, stdout, stderr, timedOut, cancelled });
|
|
169
|
+
});
|
|
170
|
+
if (options.stdin !== undefined) child.stdin?.end(options.stdin);
|
|
171
|
+
else child.stdin?.end();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Run one applet, parse the JSON it prints, and keep the exit status.
|
|
177
|
+
*
|
|
178
|
+
* A usage error (2) or a failure (1) still prints a JSON error object, so the
|
|
179
|
+
* payload is parsed before the status is judged: the code inside the payload is
|
|
180
|
+
* the one worth showing, and the exit status alone cannot say `STALE_INPUT`.
|
|
181
|
+
*/
|
|
182
|
+
export async function runAppletJson<T>(options: Parameters<typeof runApplet>[0]): Promise<AppletResult<T>> {
|
|
183
|
+
const raw = await runApplet(options);
|
|
184
|
+
if (raw.error) return { ...raw };
|
|
185
|
+
const text = raw.stdout.trim();
|
|
186
|
+
if (!text) return { ...raw, parseError: raw.stderr.trim() || "the applet printed nothing" };
|
|
187
|
+
try {
|
|
188
|
+
return { ...raw, json: JSON.parse(text) as T };
|
|
189
|
+
} catch {
|
|
190
|
+
// A crash can print a partial line; show a bounded slice rather than nothing.
|
|
191
|
+
return { ...raw, parseError: text.slice(0, 400) };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// =============================================================================
|
|
196
|
+
// Payload shapes (schema 1)
|
|
197
|
+
// =============================================================================
|
|
198
|
+
|
|
199
|
+
export interface PeekContentLine {
|
|
200
|
+
n: number;
|
|
201
|
+
text: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface PeekResult {
|
|
205
|
+
path: string;
|
|
206
|
+
status: "ok" | "error";
|
|
207
|
+
code?: string;
|
|
208
|
+
message?: string;
|
|
209
|
+
binary?: boolean;
|
|
210
|
+
guessed_type?: string;
|
|
211
|
+
preview?: string;
|
|
212
|
+
version?: string;
|
|
213
|
+
lines?: [number, number][];
|
|
214
|
+
content?: PeekContentLine[];
|
|
215
|
+
shown_bytes?: number;
|
|
216
|
+
truncated?: boolean;
|
|
217
|
+
/** `{"from_byte": N}` when truncated, null otherwise — an object, not a bare number. */
|
|
218
|
+
next?: { from_byte: number } | number | null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export interface PeekPayload {
|
|
222
|
+
schema: number;
|
|
223
|
+
results?: PeekResult[];
|
|
224
|
+
shown_bytes?: number;
|
|
225
|
+
unprocessed?: number;
|
|
226
|
+
error?: { code: string; message: string };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** `--request` wraps its answers in `results`; a single-file edit answers flat. */
|
|
230
|
+
export interface ReplacePayload extends Partial<ReplaceResult> {
|
|
231
|
+
schema: number;
|
|
232
|
+
results?: ReplaceResult[];
|
|
233
|
+
error?: { code: string; message: string };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** One shape for both answers, so the formatter has a single path. */
|
|
237
|
+
export function replaceResults(payload: ReplacePayload): ReplaceResult[] {
|
|
238
|
+
if (payload.results) return payload.results;
|
|
239
|
+
if (payload.status) return [payload as ReplaceResult];
|
|
240
|
+
return [];
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export interface ReplaceResult {
|
|
244
|
+
path: string;
|
|
245
|
+
status: "ok" | "error" | "skipped";
|
|
246
|
+
code?: string | null;
|
|
247
|
+
message?: string;
|
|
248
|
+
dry_run?: boolean;
|
|
249
|
+
changes?: number;
|
|
250
|
+
old_version?: string;
|
|
251
|
+
new_version?: string;
|
|
252
|
+
changed?: boolean;
|
|
253
|
+
diff?: string;
|
|
254
|
+
diff_truncated?: boolean;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export interface RunPayload {
|
|
258
|
+
schema: number;
|
|
259
|
+
run?: string;
|
|
260
|
+
dir?: string;
|
|
261
|
+
exit_code?: number;
|
|
262
|
+
timed_out?: boolean;
|
|
263
|
+
cancelled?: boolean;
|
|
264
|
+
capture_complete?: boolean;
|
|
265
|
+
duration_ms?: number;
|
|
266
|
+
stdout_bytes?: number;
|
|
267
|
+
stderr_bytes?: number;
|
|
268
|
+
view_truncated?: boolean;
|
|
269
|
+
stdout_view?: string;
|
|
270
|
+
stderr_view?: string;
|
|
271
|
+
/** Set by this wrapper when the build printed an unparseable view (see salvageRunPayload). */
|
|
272
|
+
view_unparsable?: boolean;
|
|
273
|
+
/** 0.6.0 metadata: what the command did, not just what it printed. */
|
|
274
|
+
idle?: boolean;
|
|
275
|
+
cpu_user_ms?: number;
|
|
276
|
+
cpu_sys_ms?: number;
|
|
277
|
+
max_rss_kb?: number;
|
|
278
|
+
/** The output is not text — no view can represent it, read the artifacts instead. */
|
|
279
|
+
binary?: boolean;
|
|
280
|
+
/** Capture bytes dropped past the per-stream quota. */
|
|
281
|
+
dropped_bytes?: number;
|
|
282
|
+
/** False when the last output line has no newline: a parse hazard for the next reader. */
|
|
283
|
+
final_newline?: boolean;
|
|
284
|
+
/** The directory the child started in; the model's relative paths resolve here. */
|
|
285
|
+
cwd_start?: string;
|
|
286
|
+
/** The exact command that ran, re-runnable as-is. */
|
|
287
|
+
replay?: string;
|
|
288
|
+
/** `run -x`: what the command changed on disk under its cwd. JSON output only. */
|
|
289
|
+
effects?: Array<{ op: string; path: string; size?: number }>;
|
|
290
|
+
effects_scanned?: number;
|
|
291
|
+
effects_truncated?: boolean;
|
|
292
|
+
error?: { code: string; message: string };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export interface LogPayload {
|
|
296
|
+
schema: number;
|
|
297
|
+
run?: string;
|
|
298
|
+
meta?: string;
|
|
299
|
+
stream?: string;
|
|
300
|
+
status?: string;
|
|
301
|
+
code?: string;
|
|
302
|
+
message?: string;
|
|
303
|
+
lines?: [number, number][];
|
|
304
|
+
content?: PeekContentLine[];
|
|
305
|
+
shown_bytes?: number;
|
|
306
|
+
truncated?: boolean;
|
|
307
|
+
error?: { code: string; message: string };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// =============================================================================
|
|
311
|
+
// Text the model reads
|
|
312
|
+
// =============================================================================
|
|
313
|
+
|
|
314
|
+
/** Numbered lines, exactly as `peek` prints them, so a line number is copyable. */
|
|
315
|
+
function numbered(content: PeekContentLine[] | undefined, limit = 400): string {
|
|
316
|
+
return (content ?? [])
|
|
317
|
+
.slice(0, limit)
|
|
318
|
+
.map((line) => `${line.n} | ${line.text}`)
|
|
319
|
+
.join("\n");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function ranges(lines: [number, number][] | undefined): string {
|
|
323
|
+
return (lines ?? []).map(([a, b]) => (a === b ? `${a}` : `${a}-${b}`)).join(",");
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** `sha256:abcd…` shortened for a status line; the full value goes in details. */
|
|
327
|
+
function shortVersion(version: string | undefined): string {
|
|
328
|
+
if (!version) return "version=unknown";
|
|
329
|
+
const hex = version.replace(/^sha256:/, "");
|
|
330
|
+
return `version=sha256:${hex.slice(0, 12)}`;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export function formatPeek(payload: PeekPayload): string {
|
|
334
|
+
if (payload.error) return `peek failed: ${payload.error.code}: ${payload.error.message}`;
|
|
335
|
+
const blocks: string[] = [];
|
|
336
|
+
for (const result of payload.results ?? []) {
|
|
337
|
+
const where = ranges(result.lines);
|
|
338
|
+
if (result.status !== "ok") {
|
|
339
|
+
blocks.push(`${result.path}: ${result.code}: ${result.message ?? "failed"}`);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
// Binary input is reported, never dumped: the header says so and the body is
|
|
343
|
+
// empty, which is what the applet returns rather than a guess to reproduce.
|
|
344
|
+
const flags = [
|
|
345
|
+
`lines=${where || "none"}`,
|
|
346
|
+
shortVersion(result.version),
|
|
347
|
+
`shown_bytes=${result.shown_bytes ?? 0}`,
|
|
348
|
+
`truncated=${result.truncated === true}`,
|
|
349
|
+
];
|
|
350
|
+
if (result.binary) flags.push(`binary=true guessed_type=${result.guessed_type ?? "unknown"}`);
|
|
351
|
+
const header = `${result.path} ${flags.join(" ")}`;
|
|
352
|
+
const body = result.binary ? (result.preview ?? "") : numbered(result.content);
|
|
353
|
+
// `next` is an object (`{"from_byte": N}`), which is easy to mistake for a number:
|
|
354
|
+
// reading it as one silently drops the continuation and the caller has to re-read.
|
|
355
|
+
const fromByte = typeof result.next === "number" ? result.next : result.next?.from_byte;
|
|
356
|
+
const next =
|
|
357
|
+
result.truncated && typeof fromByte === "number"
|
|
358
|
+
? `\n[more: continue at byte ${fromByte} with from_byte=${fromByte} - nothing was skipped]`
|
|
359
|
+
: "";
|
|
360
|
+
blocks.push([header, body, next].filter(Boolean).join("\n"));
|
|
361
|
+
}
|
|
362
|
+
if ((payload.unprocessed ?? 0) > 0) {
|
|
363
|
+
blocks.push(`[${payload.unprocessed} request(s) not processed: the shared output budget ran out]`);
|
|
364
|
+
}
|
|
365
|
+
return blocks.join("\n\n") || "peek returned nothing";
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function formatReplace(payload: ReplacePayload): string {
|
|
369
|
+
if (payload.error) return `replace failed: ${payload.error.code}: ${payload.error.message}`;
|
|
370
|
+
const blocks: string[] = [];
|
|
371
|
+
const results = replaceResults(payload);
|
|
372
|
+
for (const result of results) {
|
|
373
|
+
if (result.status !== "ok") {
|
|
374
|
+
// The build sends an empty message for a 0-match edit and code INVALID_ARGUMENT;
|
|
375
|
+
// say what was observed rather than inventing a reason.
|
|
376
|
+
const message = result.message?.trim() ? result.message : "(the build sent no message)";
|
|
377
|
+
blocks.push(
|
|
378
|
+
`${result.path}: ${result.code ?? "FAILED"}: ${message}\n` + "The file was not modified by this edit.",
|
|
379
|
+
);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const header = [
|
|
383
|
+
result.path,
|
|
384
|
+
`changes=${result.changes ?? 0}`,
|
|
385
|
+
`dry_run=${result.dry_run === true}`,
|
|
386
|
+
`changed=${result.changed === true}`,
|
|
387
|
+
`new_${shortVersion(result.new_version)}`,
|
|
388
|
+
].join(" ");
|
|
389
|
+
blocks.push([header, result.diff?.trimEnd() ?? "", result.diff_truncated ? "[diff truncated]" : ""].filter(Boolean).join("\n"));
|
|
390
|
+
}
|
|
391
|
+
const failed = results.filter((result) => result.status !== "ok");
|
|
392
|
+
if (failed.length > 0 && results.length > 1) {
|
|
393
|
+
// Batch edits are applied one at a time and the build only stops early for
|
|
394
|
+
// STALE_INPUT/NOT_FOUND, so a later edit may well have landed: state the count and
|
|
395
|
+
// point at the per-edit results rather than promising what was skipped.
|
|
396
|
+
blocks.push(
|
|
397
|
+
`[${results.length - failed.length} of ${results.length} edits applied; check each result above - ` +
|
|
398
|
+
"edits are applied one at a time, not as one transaction]",
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
return blocks.join("\n\n") || "replace returned nothing";
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function formatRun(payload: RunPayload): string {
|
|
405
|
+
if (payload.error) return `run failed: ${payload.error.code}: ${payload.error.message}`;
|
|
406
|
+
const header = [
|
|
407
|
+
`run=${payload.run ?? "?"}`,
|
|
408
|
+
`exit_code=${payload.exit_code ?? "?"}`,
|
|
409
|
+
`timed_out=${payload.timed_out === true}`,
|
|
410
|
+
payload.cancelled ? "cancelled=true" : undefined,
|
|
411
|
+
`duration_ms=${payload.duration_ms ?? 0}`,
|
|
412
|
+
`stdout_bytes=${payload.stdout_bytes ?? 0}`,
|
|
413
|
+
`stderr_bytes=${payload.stderr_bytes ?? 0}`,
|
|
414
|
+
`view_truncated=${payload.view_truncated === true}`,
|
|
415
|
+
`capture_complete=${payload.capture_complete !== false}`,
|
|
416
|
+
]
|
|
417
|
+
.filter(Boolean)
|
|
418
|
+
.join(" ");
|
|
419
|
+
const sections: string[] = [header];
|
|
420
|
+
// One meta line of the 0.6.0 metadata that changes how the output should be read:
|
|
421
|
+
// where relative paths resolved, whether the time was cpu or waiting, whether the
|
|
422
|
+
// output is text at all. Facts only — nothing here is decoration.
|
|
423
|
+
const facts: string[] = [];
|
|
424
|
+
if (payload.cwd_start) facts.push(`cwd=${payload.cwd_start}`);
|
|
425
|
+
if (payload.cpu_user_ms !== undefined || payload.cpu_sys_ms !== undefined)
|
|
426
|
+
facts.push(`cpu=${payload.cpu_user_ms ?? 0}+${payload.cpu_sys_ms ?? 0}ms`);
|
|
427
|
+
if (payload.max_rss_kb !== undefined) facts.push(`rss=${payload.max_rss_kb}KB`);
|
|
428
|
+
if (payload.idle === true) facts.push("idle");
|
|
429
|
+
if (payload.binary === true) facts.push("binary output - the view is a lossy rendering; read the artifacts");
|
|
430
|
+
if (payload.dropped_bytes) facts.push(`dropped=${payload.dropped_bytes} capture bytes`);
|
|
431
|
+
if (payload.final_newline === false) facts.push("no trailing newline");
|
|
432
|
+
if (facts.length > 0) sections.push(`meta ${facts.join(" ")}`);
|
|
433
|
+
// A timed-out run must not read as a failed command: the exit code here is the kill.
|
|
434
|
+
if (payload.timed_out === true) sections.push(describeTimeout({ runId: payload.run }));
|
|
435
|
+
else if (payload.cancelled === true) sections.push(describeCancellation(payload.run));
|
|
436
|
+
for (const [name, view] of [
|
|
437
|
+
["stdout", payload.stdout_view],
|
|
438
|
+
["stderr", payload.stderr_view],
|
|
439
|
+
] as const) {
|
|
440
|
+
if (!view) continue;
|
|
441
|
+
sections.push(`--- ${name} ---\n${view.trimEnd()}`);
|
|
442
|
+
}
|
|
443
|
+
if (payload.view_unparsable && payload.run) {
|
|
444
|
+
// Never re-run to get a readable view: that repeats the command's effects.
|
|
445
|
+
sections.push(
|
|
446
|
+
`[the view could not be parsed from this build (upstream JSON bug), but the capture is complete - ` +
|
|
447
|
+
`retrieve it with busybox_run run_id=${payload.run} lines="1:40", or match=<literal> with stream=stderr]`,
|
|
448
|
+
);
|
|
449
|
+
} else if (payload.view_truncated && payload.run) {
|
|
450
|
+
sections.push(
|
|
451
|
+
`[view truncated, capture is complete: busybox_run run_id=${payload.run} match=<literal> - or lines="a:b", stream=stderr]`,
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
if (payload.capture_complete === false) {
|
|
455
|
+
sections.push("[capture incomplete: a capture quota was reached, so the artifacts are missing bytes]");
|
|
456
|
+
}
|
|
457
|
+
if (payload.effects !== undefined && payload.effects.length > 0) {
|
|
458
|
+
// What the command changed on disk — the filesystem half of "what happened".
|
|
459
|
+
// Symbols keep it one token per file: + added, - removed, ~ changed.
|
|
460
|
+
const symbols: Record<string, string> = { added: "+", removed: "-", changed: "~" };
|
|
461
|
+
const shown = payload.effects.slice(0, 8).map((effect) => `${symbols[effect.op] ?? effect.op}${effect.path}`);
|
|
462
|
+
const rest = payload.effects.length - shown.length;
|
|
463
|
+
const suffix = rest > 0 ? ` …and ${rest} more${payload.effects_truncated === true ? " (scan truncated)" : ""}` : "";
|
|
464
|
+
sections.push(`effects: ${shown.join(", ")}${suffix}`);
|
|
465
|
+
}
|
|
466
|
+
if (payload.exit_code === -1 && payload.timed_out !== true && payload.cancelled !== true) {
|
|
467
|
+
// The silence watchdog's signature: stopped, no exit code, no timeout. This build's
|
|
468
|
+
// JSON payload does not report `idle` (the text header does), so this is the tell.
|
|
469
|
+
sections.push(
|
|
470
|
+
"IDLE — the silence watchdog killed it: no output for its whole run, so this was a hang, not slow work. " +
|
|
471
|
+
"It was not waiting on stdin (stdin is empty unless `stdin` was given, and a read returns end-of-file at once) — check sockets, locks, a child process that never exits.",
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
return sections.join("\n");
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export function formatLog(payload: LogPayload): string {
|
|
478
|
+
if (payload.error) return `log failed: ${payload.error.code}: ${payload.error.message}`;
|
|
479
|
+
// `--meta` returns the run's header as one text blob rather than as fields; it is
|
|
480
|
+
// already the shape a reader wants, so it is passed through unchanged.
|
|
481
|
+
if (payload.meta) return `run=${payload.run ?? "?"}\n${payload.meta.trimEnd()}`;
|
|
482
|
+
if (payload.code && payload.status !== "ok") {
|
|
483
|
+
const hint = payload.code === "NOT_FOUND" ? ` Try stream="both" or the other stream.` : "";
|
|
484
|
+
return `${payload.stream ?? "log"}: ${payload.code}: ${payload.message ?? ""}`.trim() + hint;
|
|
485
|
+
}
|
|
486
|
+
return [
|
|
487
|
+
`${payload.stream ?? "stdout"} lines=${ranges(payload.lines) || "none"} shown_bytes=${payload.shown_bytes ?? 0} truncated=${payload.truncated === true}`,
|
|
488
|
+
numbered(payload.content),
|
|
489
|
+
]
|
|
490
|
+
.filter(Boolean)
|
|
491
|
+
.join("\n");
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// =============================================================================
|
|
495
|
+
// Argument building
|
|
496
|
+
// =============================================================================
|
|
497
|
+
|
|
498
|
+
/** Drop empty and undefined arguments; every applet option here takes a value or is a flag. */
|
|
499
|
+
function args(pairs: Array<[string, string | number | boolean | undefined]>): string[] {
|
|
500
|
+
const out: string[] = [];
|
|
501
|
+
for (const [flag, value] of pairs) {
|
|
502
|
+
if (value === undefined || value === false || value === "") continue;
|
|
503
|
+
if (value === true) out.push(flag);
|
|
504
|
+
else out.push(flag, String(value));
|
|
505
|
+
}
|
|
506
|
+
return out;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
export function peekArgs(params: {
|
|
510
|
+
path: string;
|
|
511
|
+
lines?: string;
|
|
512
|
+
around?: string;
|
|
513
|
+
context?: number;
|
|
514
|
+
regex?: boolean;
|
|
515
|
+
from_byte?: number;
|
|
516
|
+
max_bytes?: number;
|
|
517
|
+
}): string[] {
|
|
518
|
+
return [
|
|
519
|
+
params.path,
|
|
520
|
+
...args([
|
|
521
|
+
["--lines", params.lines],
|
|
522
|
+
["--around", params.around],
|
|
523
|
+
["--context", params.context],
|
|
524
|
+
["--regex", params.regex === true],
|
|
525
|
+
["--from-byte", params.from_byte],
|
|
526
|
+
["--max-bytes", params.max_bytes],
|
|
527
|
+
]),
|
|
528
|
+
"--format",
|
|
529
|
+
"json",
|
|
530
|
+
];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export interface ReplaceEdit {
|
|
534
|
+
old: string;
|
|
535
|
+
new: string;
|
|
536
|
+
expect?: number;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** One edit: the only form where the applet checks the hash under its own lock. */
|
|
540
|
+
export function replaceOneArgs(params: {
|
|
541
|
+
path: string;
|
|
542
|
+
edit: ReplaceEdit;
|
|
543
|
+
sha256?: string;
|
|
544
|
+
dry_run?: boolean;
|
|
545
|
+
follow?: boolean;
|
|
546
|
+
max_diff_bytes?: number;
|
|
547
|
+
}): string[] {
|
|
548
|
+
return [
|
|
549
|
+
params.path,
|
|
550
|
+
...args([
|
|
551
|
+
["--old", params.edit.old],
|
|
552
|
+
["--new", params.edit.new],
|
|
553
|
+
["--expect", params.edit.expect],
|
|
554
|
+
["--sha256", params.sha256],
|
|
555
|
+
["--dry-run", params.dry_run === true],
|
|
556
|
+
["--follow", params.follow === true],
|
|
557
|
+
["--max-diff-bytes", params.max_diff_bytes],
|
|
558
|
+
]),
|
|
559
|
+
"--format",
|
|
560
|
+
"json",
|
|
561
|
+
];
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* The `--request` payload for several edits to one file.
|
|
566
|
+
*
|
|
567
|
+
* No per-edit `sha256`: the applet re-reads the file after each edit, so the
|
|
568
|
+
* original version would fail on edit 2. Each edit is still validated against the
|
|
569
|
+
* file as it stands (that is what stops one replacement chaining into the next),
|
|
570
|
+
* and the caller's hash is checked by `contentVersion()` before the batch runs.
|
|
571
|
+
*/
|
|
572
|
+
export function replaceRequestBody(path: string, edits: ReplaceEdit[]): string {
|
|
573
|
+
return JSON.stringify({
|
|
574
|
+
edits: edits.map((edit) => ({
|
|
575
|
+
path,
|
|
576
|
+
old: edit.old,
|
|
577
|
+
new: edit.new,
|
|
578
|
+
expect: edit.expect ?? 1,
|
|
579
|
+
})),
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export function replaceRequestArgs(params: {
|
|
584
|
+
requestPath: string;
|
|
585
|
+
dry_run?: boolean;
|
|
586
|
+
follow?: boolean;
|
|
587
|
+
max_diff_bytes?: number;
|
|
588
|
+
}): string[] {
|
|
589
|
+
return [
|
|
590
|
+
...args([
|
|
591
|
+
["--request", params.requestPath],
|
|
592
|
+
["--dry-run", params.dry_run === true],
|
|
593
|
+
["--follow", params.follow === true],
|
|
594
|
+
["--max-diff-bytes", params.max_diff_bytes],
|
|
595
|
+
]),
|
|
596
|
+
"--format",
|
|
597
|
+
"json",
|
|
598
|
+
];
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Write a request file the applet can read, with 0600 from the start.
|
|
603
|
+
*
|
|
604
|
+
* The edits can contain source code from a private repository, so the file is not
|
|
605
|
+
* world-readable even for the second it exists.
|
|
606
|
+
*/
|
|
607
|
+
export function writeRequestFile(content: string, dir: string = tmpdir()): { path: string; cleanup: () => void } {
|
|
608
|
+
const holder = mkdtempSync(join(dir, "pi-managed-tools-"));
|
|
609
|
+
chmodSync(holder, 0o700);
|
|
610
|
+
const path = join(holder, "request.json");
|
|
611
|
+
writeFileSync(path, content, { mode: 0o600 });
|
|
612
|
+
return { path, cleanup: () => rmSync(holder, { recursive: true, force: true }) };
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Current content version of a file, as `peek` reports it, or undefined when unreadable. */
|
|
616
|
+
export async function contentVersion(options: {
|
|
617
|
+
binDir: string;
|
|
618
|
+
path: string;
|
|
619
|
+
signal?: AbortSignal;
|
|
620
|
+
}): Promise<{ version?: string; error?: string }> {
|
|
621
|
+
const result = await runAppletJson<PeekPayload>({
|
|
622
|
+
binDir: options.binDir,
|
|
623
|
+
applet: "peek",
|
|
624
|
+
args: [options.path, "--lines", "1:1", "--max-bytes", "1", "--format", "json"],
|
|
625
|
+
signal: options.signal,
|
|
626
|
+
timeoutMs: 30_000,
|
|
627
|
+
});
|
|
628
|
+
if (result.error) return { error: result.error };
|
|
629
|
+
const first = result.json?.results?.[0];
|
|
630
|
+
if (!first) return { error: result.json?.error?.message ?? result.parseError ?? "peek returned no result" };
|
|
631
|
+
if (first.status !== "ok") return { error: `${first.code ?? "FAILED"}: ${first.message ?? "unreadable"}` };
|
|
632
|
+
return { version: first.version };
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export function runArgs(params: {
|
|
636
|
+
argv?: string[];
|
|
637
|
+
shell?: string;
|
|
638
|
+
cwd?: string;
|
|
639
|
+
timeout_s?: number;
|
|
640
|
+
/** Silence watchdog in seconds, emitted with any deadline. */
|
|
641
|
+
idle_s?: number;
|
|
642
|
+
max_bytes?: number;
|
|
643
|
+
/** Defaults to the split pty, so a tool run has the same honest timing as bash. */
|
|
644
|
+
pty?: "split" | "merged" | "raw" | "off";
|
|
645
|
+
}): string[] {
|
|
646
|
+
const pty = params.pty ?? "split";
|
|
647
|
+
return [
|
|
648
|
+
...args([
|
|
649
|
+
["--timeout", params.timeout_s],
|
|
650
|
+
["-W", params.idle_s !== undefined && params.idle_s > 0 ? params.idle_s : undefined],
|
|
651
|
+
["--max-bytes", params.max_bytes],
|
|
652
|
+
["--cwd", params.cwd],
|
|
653
|
+
["--shell", params.shell !== undefined],
|
|
654
|
+
]),
|
|
655
|
+
// Same terminal as the bash wrapper: stdout line-buffers, stderr keeps its pipe.
|
|
656
|
+
// Without this a tool run reports one timestamp for a buffered program.
|
|
657
|
+
...(pty === "off" ? [] : [pty === "merged" ? "--pty" : pty === "raw" ? "--pty-raw" : "--pty-split"]),
|
|
658
|
+
// Keep the timeline artifact too: it is the only thing that answers "in what order",
|
|
659
|
+
// and `log RUN --stream timeline` needs a run that recorded one.
|
|
660
|
+
"--timestamps",
|
|
661
|
+
"--format",
|
|
662
|
+
"json",
|
|
663
|
+
"--",
|
|
664
|
+
...(params.shell !== undefined ? [params.shell] : (params.argv ?? [])),
|
|
665
|
+
];
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
export function logArgs(params: {
|
|
669
|
+
run_id: string;
|
|
670
|
+
lines?: string;
|
|
671
|
+
match?: string;
|
|
672
|
+
context?: number;
|
|
673
|
+
stream?: string;
|
|
674
|
+
meta?: boolean;
|
|
675
|
+
max_bytes?: number;
|
|
676
|
+
}): string[] {
|
|
677
|
+
return [
|
|
678
|
+
params.run_id,
|
|
679
|
+
...args([
|
|
680
|
+
["--lines", params.lines],
|
|
681
|
+
["--match", params.match],
|
|
682
|
+
["--context", params.context],
|
|
683
|
+
["--stream", params.stream],
|
|
684
|
+
["--meta", params.meta === true],
|
|
685
|
+
["--max-bytes", params.max_bytes],
|
|
686
|
+
]),
|
|
687
|
+
"--format",
|
|
688
|
+
"json",
|
|
689
|
+
];
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Why a spawned applet produced nothing usable, or undefined when it ran.
|
|
694
|
+
*
|
|
695
|
+
* Kept separate from the exit status: `run` exits with the child's status, so a
|
|
696
|
+
* failing test suite and a broken wrapper can share a nonzero code and only these
|
|
697
|
+
* fields tell them apart.
|
|
698
|
+
*/
|
|
699
|
+
export function describeAppletFailure(result: AppletResult<unknown>): string | undefined {
|
|
700
|
+
if (result.error) return `busybox: ${result.error}`;
|
|
701
|
+
if (result.cancelled) return "cancelled: the applet was stopped and cleaned up its children";
|
|
702
|
+
if (result.timedOut) return "timed out: this wrapper's backstop deadline fired";
|
|
703
|
+
if (!result.json && result.parseError) return `unexpected output from busybox: ${result.parseError}`;
|
|
704
|
+
return undefined;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Recover a `run` payload whose view string broke the JSON.
|
|
709
|
+
*
|
|
710
|
+
* The upstream build emits the head and tail of a truncated view as two adjacent
|
|
711
|
+
* quoted strings (`"head""tail"`) in JSON mode, which no parser accepts. The scalar
|
|
712
|
+
* metadata is printed before that and is intact, and the capture is complete, so the
|
|
713
|
+
* fields are recovered from the raw text and the view is left to `log` — re-running
|
|
714
|
+
* the command to get a parseable view would repeat its side effects.
|
|
715
|
+
*/
|
|
716
|
+
export function salvageRunPayload(text: string): RunPayload | undefined {
|
|
717
|
+
const num = (key: string) => {
|
|
718
|
+
const match = text.match(new RegExp(`"${key}":(-?\\d+)`));
|
|
719
|
+
return match ? Number(match[1]) : undefined;
|
|
720
|
+
};
|
|
721
|
+
const bool = (key: string) => {
|
|
722
|
+
const match = text.match(new RegExp(`"${key}":(true|false)`));
|
|
723
|
+
return match ? match[1] === "true" : undefined;
|
|
724
|
+
};
|
|
725
|
+
const str = (key: string) => text.match(new RegExp(`"${key}":"([^"\\\\]*)"`))?.[1];
|
|
726
|
+
const run = str("run");
|
|
727
|
+
if (!run) return undefined;
|
|
728
|
+
return {
|
|
729
|
+
schema: 1,
|
|
730
|
+
run,
|
|
731
|
+
dir: str("dir"),
|
|
732
|
+
exit_code: num("exit_code"),
|
|
733
|
+
timed_out: bool("timed_out"),
|
|
734
|
+
cancelled: bool("cancelled"),
|
|
735
|
+
capture_complete: bool("capture_complete"),
|
|
736
|
+
duration_ms: num("duration_ms"),
|
|
737
|
+
stdout_bytes: num("stdout_bytes"),
|
|
738
|
+
stderr_bytes: num("stderr_bytes"),
|
|
739
|
+
view_truncated: bool("view_truncated"),
|
|
740
|
+
view_unparsable: true,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Match a caller-supplied version against the file's current one.
|
|
746
|
+
*
|
|
747
|
+
* `peek` prints a shortened version for the line the model reads, so the natural
|
|
748
|
+
* thing to copy back is a 12-character prefix; the applet's `--sha256` is an exact
|
|
749
|
+
* comparison. A prefix is therefore resolved here, against the current contents, and
|
|
750
|
+
* the full value is what the applet checks under its lock. A prefix that does not
|
|
751
|
+
* match the current file is stale, exactly as a wrong full hash is.
|
|
752
|
+
*/
|
|
753
|
+
export function resolveVersion(
|
|
754
|
+
given: string | undefined,
|
|
755
|
+
current: string | undefined,
|
|
756
|
+
): { ok: true; full?: string } | { ok: false; current?: string } {
|
|
757
|
+
if (!given) return { ok: true };
|
|
758
|
+
const wanted = given.replace(/^sha256:/, "").trim().toLowerCase();
|
|
759
|
+
const have = current?.replace(/^sha256:/, "").toLowerCase();
|
|
760
|
+
if (!have) return { ok: false, current };
|
|
761
|
+
if (!/^[0-9a-f]{4,64}$/.test(wanted)) return { ok: false, current };
|
|
762
|
+
if (!have.startsWith(wanted)) return { ok: false, current };
|
|
763
|
+
return { ok: true, full: have };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Delete old `busybox-run` directories, keeping the newest `keep`.
|
|
768
|
+
*
|
|
769
|
+
* `run --prune N` cannot be relied on here: the wrapper always asks for
|
|
770
|
+
* `--timestamps`, and in this build `--prune` is silently ignored when the timeline is
|
|
771
|
+
* on (measured: 30 runs with `-q --prune 5` leave 5 directories, the same 30 with `-t
|
|
772
|
+
* --prune 5` leave 30). Every wrapped bash call writes one, so without a sweep a session
|
|
773
|
+
* leaves hundreds behind.
|
|
774
|
+
*
|
|
775
|
+
* Only directories whose name matches `R<number>` are ever removed, and symlinks are
|
|
776
|
+
* skipped: the artifact root is under $TMPDIR, which anything could write to.
|
|
777
|
+
*/
|
|
778
|
+
export function sweepRunArtifacts(options: { root?: string; keep?: number; minAgeMs?: number; now?: number } = {}): { scanned: number; removed: number } {
|
|
779
|
+
const root = options.root ?? join(process.env.TMPDIR ?? tmpdir(), "busybox-run");
|
|
780
|
+
const keep = options.keep ?? 20;
|
|
781
|
+
// The root is shared by every session on the machine: a run beyond the newest `keep`
|
|
782
|
+
// is removed only once it is also this old, so one busy session cannot delete the
|
|
783
|
+
// capture another has just been pointed at.
|
|
784
|
+
const minAgeMs = options.minAgeMs ?? 0;
|
|
785
|
+
const now = options.now ?? Date.now();
|
|
786
|
+
if (!existsSync(root)) return { scanned: 0, removed: 0 };
|
|
787
|
+
|
|
788
|
+
const runs: Array<{ path: string; mtimeMs: number }> = [];
|
|
789
|
+
let scanned = 0;
|
|
790
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
791
|
+
scanned++;
|
|
792
|
+
if (!entry.isDirectory() || !/^R\d+$/.test(entry.name)) continue;
|
|
793
|
+
const path = join(root, entry.name);
|
|
794
|
+
try {
|
|
795
|
+
runs.push({ path, mtimeMs: statSync(path).mtimeMs });
|
|
796
|
+
} catch {
|
|
797
|
+
// A directory that vanished mid-scan is already gone.
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
runs.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
802
|
+
let removed = 0;
|
|
803
|
+
for (const stale of runs.slice(keep)) {
|
|
804
|
+
if (minAgeMs > 0 && now - stale.mtimeMs < minAgeMs) continue;
|
|
805
|
+
try {
|
|
806
|
+
rmSync(stale.path, { recursive: true, force: true });
|
|
807
|
+
removed++;
|
|
808
|
+
} catch {
|
|
809
|
+
// Best effort: a run the user is currently reading stays.
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return { scanned, removed };
|
|
813
|
+
}
|