@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/src/wrap.ts ADDED
@@ -0,0 +1,683 @@
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
+ * Every bash command, run through `busybox run --timestamps`.
18
+ *
19
+ * Why: concatenating stdout and stderr loses the only information that explains a
20
+ * confusing log — the order. `run -t` prints one interleaved, dmesg-style line per
21
+ * record with a microsecond offset and the stream it came from:
22
+ *
23
+ * [ 0.011354 out] ok 1
24
+ * [ 0.066632 err] FAILED test_x
25
+ * [ 0.128234 out] done
26
+ *
27
+ * So a model can tell "the warning came before the failure" from "the tool printed
28
+ * warnings in a block at the end", and a burst of lines sharing one timestamp is
29
+ * itself evidence of a buffered writer flushing at exit.
30
+ *
31
+ * The wrapper is deliberately transparent: the child's exit status is what the shell
32
+ * returns, the command runs in the same shell, cwd and environment it would have
33
+ * had, and stderr is still tagged `err` instead of being merged.
34
+ *
35
+ * Nothing here imports pi packages; the extension passes the binary path in.
36
+ */
37
+
38
+ /** How much of a command's output comes back, and whether it is reduced. */
39
+ export type Verbosity = "quiet" | "normal" | "verbose" | "brief";
40
+
41
+ /**
42
+ * Whether the child gets a pseudo-terminal, and how.
43
+ *
44
+ * `split` (the default) puts stdout on the pty and leaves stderr on a pipe. That is the
45
+ * whole trick behind honest timing: libc line-buffers when stdout is a terminal, so a
46
+ * Python/Node/Ruby/Java program emits each line as it happens instead of flushing the
47
+ * lot at exit — and the timeline then shows the real intervals. stderr is unbuffered
48
+ * whether or not it is a terminal, so keeping it on a pipe costs nothing and preserves
49
+ * the `err` tag.
50
+ *
51
+ * `off` is the byte-exact, no-tty mode (`isatty()` is false, programs take their
52
+ * non-interactive paths). `merged` gives 0/1/2 the same pty, which loses the stream tag
53
+ * but is what a full-screen tool expects. `raw` adds `--pty-raw`, which switches the
54
+ * line discipline off (no CR/NL translation, byte-exact beyond the canonical line
55
+ * limit).
56
+ */
57
+ export type PtyMode = "split" | "merged" | "raw" | "off";
58
+
59
+ export const PTY_MODES: readonly PtyMode[] = ["split", "merged", "raw", "off"];
60
+
61
+ export const VERBOSITIES: readonly Verbosity[] = ["quiet", "normal", "verbose", "brief"];
62
+
63
+ export interface WrapSettings {
64
+ /** False when `PI_MANAGED_TOOLS_WRAP=off`: bash commands run untouched. */
65
+ enabled: boolean;
66
+ verbosity: Verbosity;
67
+ /** Pseudo-terminal for the child; see PtyMode. */
68
+ pty: PtyMode;
69
+ /** Deadline applied when the caller gave none, in seconds; 0 means no deadline. */
70
+ timeoutSeconds: number;
71
+ /** Silence watchdog, in seconds; 0 means none. Rides with any deadline. */
72
+ idleSeconds: number;
73
+ /** Set the variables that switch runtimes' output buffering off (STREAM_ENV and the preludes). */
74
+ unbuffer: boolean;
75
+ /** Also preload `stdbuf`'s library on Linux, so C-stdio programs line-buffer there too. */
76
+ preload: boolean;
77
+ /** Extra `NAME=VALUE` for the wrapped child, from `PI_MANAGED_TOOLS_EXTRA_ENV`. */
78
+ extraEnv: Array<[string, string]>;
79
+ }
80
+
81
+ /**
82
+ * Environment that makes a runtime write each line when it prints it.
83
+ *
84
+ * It matters wherever a program's stdout is not the terminal: a stage inside a pipeline
85
+ * (`cmd | tee log`, `cmd | grep x`), output sent to a file a later call reads
86
+ * (`server > srv.log &`), or `PI_MANAGED_TOOLS_PTY=off`. There a runtime that
87
+ * block-buffers holds its lines until 4-64 KB have piled up or it exits, and every
88
+ * offset the timeline shows is then the flush, not the event.
89
+ *
90
+ * Measured with a probe per runtime (print, wait a second, print; stdout a pipe), on
91
+ * macOS 27 and Debian 12:
92
+ *
93
+ * live with no help sh builtins, Node, Deno, Bun, PHP, Tcl, R, Java, Elixir, Go,
94
+ * Rust, C++ iostream, Lua 5.4, make
95
+ * fixed here Python, Ruby, Perl, LuaJIT — and on macOS every C-stdio program:
96
+ * compiled C and Swift, grep, sed, awk, cut, tr, jq
97
+ * fixed by a preload the same C-stdio programs on Linux (glibc has no variable for
98
+ * it): `stdbuf`'s library, off unless asked for, see STDBUF_LIBS
99
+ * not fixable Haskell (GHC) on a pipe, OCaml's Printf, mawk's input buffer
100
+ *
101
+ * Stderr needed nothing in any of them but OCaml's Printf.
102
+ */
103
+ export const STREAM_ENV: ReadonlyArray<[string, string]> = [
104
+ // Python: stdout and stderr both, for the whole process tree.
105
+ ["PYTHONUNBUFFERED", "1"],
106
+ // macOS and FreeBSD libc: line-buffer whatever is on descriptor 1 (setvbuf(3),
107
+ // ENVIRONMENT). One variable covers every C-stdio program, which is most of a
108
+ // pipeline. glibc and musl ignore it.
109
+ ["STDBUF1", "L"],
110
+ // Foundation: unbuffered stdout for a Swift or Objective-C program.
111
+ ["NSUnbufferedIO", "YES"],
112
+ ];
113
+
114
+ /**
115
+ * `LUA_INIT`, run by the standalone interpreter before the script: line-buffer stdout.
116
+ *
117
+ * A long-bracket string, so the snippet carries no quote of either kind and survives the
118
+ * double-quoted `${LUA_INIT:-…}` it is emitted in. Only used when the person has no
119
+ * `LUA_INIT` of their own.
120
+ */
121
+ export const LUA_INIT = "io.stdout:setvbuf[[line]]";
122
+
123
+ /** The rest of the wrapper's environment: encoding, colour, pagers, prompts. */
124
+ export const QUIET_ENV: ReadonlyArray<[string, string]> = [
125
+ ["PYTHONIOENCODING", "utf-8"],
126
+ // No __pycache__ writes: they add mtime churn to every run and never help here.
127
+ ["PYTHONDONTWRITEBYTECODE", "1"],
128
+ // Colour and pager control: ANSI escapes make a timeline unreadable and a pager
129
+ // can block forever with no TTY.
130
+ ["NO_COLOR", "1"],
131
+ ["CLICOLOR", "0"],
132
+ ["FORCE_COLOR", "0"],
133
+ ["TERM", "dumb"],
134
+ ["PAGER", "cat"],
135
+ ["GIT_PAGER", "cat"],
136
+ ["GIT_TERMINAL_PROMPT", "0"],
137
+ ["CARGO_TERM_COLOR", "never"],
138
+ // A prompt on a package install cannot be answered: stdin is empty.
139
+ ["DEBIAN_FRONTEND", "noninteractive"],
140
+ ];
141
+
142
+ /**
143
+ * Option lists a build tool reads from the environment, added to whatever is there.
144
+ *
145
+ * Both tools print a progress bar (or a spinner) into a captured stream, unusable in a
146
+ * timeline. They are appended, never assigned: a `GRADLE_OPTS=-Xmx4g` the person's build
147
+ * depends on has to survive the wrapper (it did not, when these were assigned).
148
+ */
149
+ export const TOOL_OPTIONS_ENV: ReadonlyArray<[string, string]> = [
150
+ ["MAVEN_ARGS", "-B -ntp"],
151
+ ["GRADLE_OPTS", "-Dorg.gradle.console=plain -Dorg.gradle.daemon=false"],
152
+ ];
153
+
154
+ /** Every plain assignment the wrapper makes with buffering switched off, in the order emitted. */
155
+ export const UNBUFFERED_ENV: ReadonlyArray<[string, string]> = [...STREAM_ENV, ...QUIET_ENV];
156
+
157
+ /**
158
+ * Where GNU coreutils keeps `stdbuf`'s preload library, by distribution.
159
+ *
160
+ * glibc reads no variable for stdio buffering, so on Linux the only way to line-buffer a
161
+ * C-stdio program from outside is the way `stdbuf -oL` does it: `LD_PRELOAD` this library
162
+ * and set `_STDBUF_O=L`. It is not on by default, because a preload reaches every dynamic
163
+ * program the command starts — an AddressSanitizer build refuses to run unless its own
164
+ * runtime is first in that list.
165
+ */
166
+ export const STDBUF_LIBS: readonly string[] = [
167
+ "/usr/libexec/coreutils/libstdbuf.so",
168
+ "/usr/lib/x86_64-linux-gnu/coreutils/libstdbuf.so",
169
+ "/usr/lib/aarch64-linux-gnu/coreutils/libstdbuf.so",
170
+ "/usr/lib/coreutils/libstdbuf.so",
171
+ "/usr/lib64/coreutils/libstdbuf.so",
172
+ ];
173
+
174
+ /** `run` flags for each verbosity, on top of the always-present `--timestamps`. */
175
+ const LADDER: Record<Verbosity, { flags: string[]; timestamps: boolean }> = {
176
+ // A short view: enough to see what happened, not enough to drown the answer.
177
+ quiet: { flags: ["--max-bytes", "6000"], timestamps: true },
178
+ normal: { flags: ["--max-bytes", "48000"], timestamps: true },
179
+ // The most pi passes on: its bash tool keeps the LAST 50 KB (or 2000 lines) of
180
+ // whatever a command printed. At 200 KB the model was handed the tail end of the
181
+ // view with the `run=` header cut off (measured with pi's own truncateTail), so a
182
+ // bigger number here was a smaller, headless view in practice.
183
+ verbose: { flags: ["--max-bytes", "49000"], timestamps: true },
184
+ // `--brief` reduces repeats, and this build ignores it when `--timestamps` is set
185
+ // (`run -t` takes the timeline branch first), so this mode drops the timing on
186
+ // purpose: it is the answer for "this output is 40 000 lines of the same thing".
187
+ brief: { flags: ["--max-bytes", "12000", "--brief", "both"], timestamps: false },
188
+ };
189
+
190
+ /**
191
+ * `PI_MANAGED_TOOLS_USER_WRAP=off` (or 0/false/no) routes the human's `!` commands
192
+ * through pi's plain local execution again; wrapping them is on by default.
193
+ */
194
+ export function readUserWrapEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
195
+ const raw = (env.PI_MANAGED_TOOLS_USER_WRAP ?? "").trim().toLowerCase();
196
+ return !(raw === "0" || raw === "off" || raw === "false" || raw === "no");
197
+ }
198
+
199
+ /**
200
+ * `PI_MANAGED_TOOLS_USER_STDIN=off` (or 0/false/no) runs the human's `!` commands the way
201
+ * they ran before: stdin empty, output shown when the command exits. On by default: a
202
+ * `!` command's output is shown as it arrives and what the person types reaches it.
203
+ */
204
+ export function readUserStdinEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
205
+ const raw = (env.PI_MANAGED_TOOLS_USER_STDIN ?? "").trim().toLowerCase();
206
+ return !(raw === "0" || raw === "off" || raw === "false" || raw === "no");
207
+ }
208
+
209
+ /**
210
+ * How long a `!` command may wait for the person to type, in seconds, before it is
211
+ * stopped.
212
+ *
213
+ * Longer than the 120s deadline a model's command gets, on purpose: that one bounds a
214
+ * program, this one bounds a person, who may be reading the question, finding a password
215
+ * or simply away from the keyboard for a moment. It only runs while the command is taken
216
+ * to be waiting on its input (the dialog is open), never while it is working.
217
+ */
218
+ export const DEFAULT_STDIN_TIMEOUT_SECONDS = 300;
219
+
220
+ /** `PI_MANAGED_TOOLS_STDIN_TIMEOUT=<seconds>` changes it; `0`/`off` waits for as long as it takes. */
221
+ export function readStdinTimeout(env: NodeJS.ProcessEnv = process.env): number {
222
+ const raw = (env.PI_MANAGED_TOOLS_STDIN_TIMEOUT ?? "").trim().toLowerCase();
223
+ if (raw === "0" || raw === "off" || raw === "false" || raw === "no" || raw === "none") return 0;
224
+ const seconds = Number(raw);
225
+ if (raw === "" || !Number.isFinite(seconds) || seconds < 0) return DEFAULT_STDIN_TIMEOUT_SECONDS;
226
+ return Math.floor(seconds);
227
+ }
228
+
229
+ /**
230
+ * The knobs a `managedTools` block in pi's settings may set, and the variable each one is.
231
+ *
232
+ * Every switch of this package was an environment variable only, which is the wrong home
233
+ * for something a person sets once: it has to be exported before pi starts, in every
234
+ * shell. pi's settings file (global or project) is where such things live.
235
+ */
236
+ export const SETTINGS_KEYS: Readonly<Record<string, string>> = {
237
+ wrap: "PI_MANAGED_TOOLS_WRAP",
238
+ verbosity: "PI_MANAGED_TOOLS_VERBOSITY",
239
+ pty: "PI_MANAGED_TOOLS_PTY",
240
+ timeout: "PI_MANAGED_TOOLS_TIMEOUT",
241
+ idle: "PI_MANAGED_TOOLS_IDLE",
242
+ guard: "PI_MANAGED_TOOLS_GUARD",
243
+ unbuffer: "PI_MANAGED_TOOLS_UNBUFFER",
244
+ preload: "PI_MANAGED_TOOLS_PRELOAD",
245
+ extraEnv: "PI_MANAGED_TOOLS_EXTRA_ENV",
246
+ userWrap: "PI_MANAGED_TOOLS_USER_WRAP",
247
+ userStdin: "PI_MANAGED_TOOLS_USER_STDIN",
248
+ stdinTimeout: "PI_MANAGED_TOOLS_STDIN_TIMEOUT",
249
+ compactStamps: "PI_MANAGED_TOOLS_COMPACT_STAMPS",
250
+ ageOut: "PI_MANAGED_TOOLS_AGE_OUT",
251
+ rewrite: "PI_MANAGED_TOOLS_REWRITE",
252
+ };
253
+
254
+ /**
255
+ * Take `managedTools` from pi's settings as defaults *under* the environment.
256
+ *
257
+ * Written into this process's environment, and only where a variable is not already set:
258
+ * every reader in the package then sees one source, an exported variable still wins for
259
+ * one run, and nothing has to be threaded through. `true`/`false` become `on`/`off`.
260
+ * Returns the names it set.
261
+ */
262
+ export function applySettings(settings: unknown, env: NodeJS.ProcessEnv = process.env): string[] {
263
+ const block = (settings as { managedTools?: unknown } | undefined)?.managedTools;
264
+ if (typeof block !== "object" || block === null) return [];
265
+ const applied: string[] = [];
266
+ for (const [key, name] of Object.entries(SETTINGS_KEYS)) {
267
+ const value = (block as Record<string, unknown>)[key];
268
+ if (value === undefined || value === null) continue;
269
+ if ((env[name] ?? "").trim() !== "") continue;
270
+ if (typeof value === "boolean") env[name] = value ? "on" : "off";
271
+ else if (typeof value === "number" && Number.isFinite(value)) env[name] = String(value);
272
+ else if (typeof value === "string" && value.trim() !== "") env[name] = value;
273
+ else continue;
274
+ applied.push(name);
275
+ }
276
+ return applied;
277
+ }
278
+
279
+ /** An on/off variable: unset or unrecognised leaves the fallback. */
280
+ export function readSwitch(raw: string | undefined, fallback: boolean): boolean {
281
+ const value = (raw ?? "").trim().toLowerCase();
282
+ if (value === "1" || value === "on" || value === "true" || value === "yes") return true;
283
+ if (value === "0" || value === "off" || value === "false" || value === "no") return false;
284
+ return fallback;
285
+ }
286
+
287
+ /** `PI_MANAGED_TOOLS_WRAP=off` (or 0/false/no) turns the wrapper off entirely. */
288
+ export function readWrapSettings(env: NodeJS.ProcessEnv = process.env, override?: Verbosity): WrapSettings {
289
+ const raw = (env.PI_MANAGED_TOOLS_WRAP ?? "").trim().toLowerCase();
290
+ const disabled = raw === "0" || raw === "off" || raw === "false" || raw === "no";
291
+ const requested = (override ?? (env.PI_MANAGED_TOOLS_VERBOSITY ?? "")).trim().toLowerCase();
292
+ const verbosity = (VERBOSITIES as readonly string[]).includes(requested)
293
+ ? (requested as Verbosity)
294
+ : "normal";
295
+ return {
296
+ enabled: !disabled,
297
+ verbosity,
298
+ pty: readPtyMode(env.PI_MANAGED_TOOLS_PTY),
299
+ timeoutSeconds: readDefaultTimeout(env),
300
+ idleSeconds: readIdleTimeout(env),
301
+ unbuffer: readSwitch(env.PI_MANAGED_TOOLS_UNBUFFER, true),
302
+ preload: readSwitch(env.PI_MANAGED_TOOLS_PRELOAD, false),
303
+ extraEnv: parseExtraEnv(env.PI_MANAGED_TOOLS_EXTRA_ENV),
304
+ };
305
+ }
306
+
307
+ /**
308
+ * `PI_MANAGED_TOOLS_PTY`: `split` (default), `merged`/`on`, `raw`, or `off`.
309
+ *
310
+ * Anything unrecognised is the default, never a silent switch to a tty: a child that
311
+ * sees a terminal behaves differently, so opting in has to be explicit.
312
+ */
313
+ export function readPtyMode(raw: string | undefined): PtyMode {
314
+ switch ((raw ?? "").trim().toLowerCase()) {
315
+ case "off":
316
+ case "0":
317
+ case "false":
318
+ case "no":
319
+ case "none":
320
+ case "pipe":
321
+ return "off";
322
+ case "merged":
323
+ case "on":
324
+ case "pty":
325
+ case "yes":
326
+ case "1":
327
+ return "merged";
328
+ case "raw":
329
+ return "raw";
330
+ default:
331
+ return "split";
332
+ }
333
+ }
334
+
335
+ /** The flag that gives the child a terminal, or undefined for a plain pipe. */
336
+ export function ptyFlags(mode: PtyMode): string[] {
337
+ switch (mode) {
338
+ case "merged":
339
+ return ["--pty"];
340
+ case "raw":
341
+ return ["--pty-raw"];
342
+ case "split":
343
+ return ["--pty-split"];
344
+ default:
345
+ return [];
346
+ }
347
+ }
348
+
349
+ /** `NAME=VALUE,NAME2=VALUE2` — commas brace values, so no comma survives inside one. */
350
+ export function parseExtraEnv(raw: string | undefined): Array<[string, string]> {
351
+ const out: Array<[string, string]> = [];
352
+ for (const pair of (raw ?? "").split(",")) {
353
+ const trimmed = pair.trim();
354
+ const eq = trimmed.indexOf("=");
355
+ if (eq <= 0) continue;
356
+ const name = trimmed.slice(0, eq).trim();
357
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
358
+ out.push([name, trimmed.slice(eq + 1)]);
359
+ }
360
+ return out;
361
+ }
362
+
363
+ /**
364
+ * Quote one argument for a POSIX shell, so the wrapper survives pi's own `bash -c`.
365
+ *
366
+ * Single quotes make every byte literal (newlines, `$`, backticks, `!`), and an
367
+ * embedded quote becomes `'\''`: close, escaped quote, reopen.
368
+ */
369
+ export function shellQuote(value: string): string {
370
+ return `'${value.split("'").join(`'\\''`)}'`;
371
+ }
372
+
373
+ /**
374
+ * Quote a value only when it needs quoting, so an emitted wrapper stays readable.
375
+ *
376
+ * An env value like `MAVEN_ARGS=-B -ntp` contains a space: left unquoted, the shell
377
+ * splits it and busybox sees `-ntp` as an option. Values made only of safe characters
378
+ * stay bare, so a logged wrapper can be read at a glance.
379
+ */
380
+ export function shellValue(value: string): string {
381
+ return /^[A-Za-z0-9_.:=+@/-]+$/.test(value) ? value : shellQuote(value);
382
+ }
383
+
384
+ /**
385
+ * Applets that only *start another command*: `busybox sh -c '…'` is the model's own
386
+ * script in a different shell, not a busybox result to read.
387
+ *
388
+ * These used to count as "already wrapped" along with every other `busybox …` call, and
389
+ * the per-turn guidelines recommend `busybox sh -c` for multi-step logic — so exactly the
390
+ * longest commands ran with no timeline, no deadline and no silence watchdog (pi has no
391
+ * default timeout of its own).
392
+ */
393
+ const RUNNER_APPLETS: readonly string[] = ["sh", "ash", "hush", "env", "timeout", "nice", "nohup", "time"];
394
+
395
+ /**
396
+ * True when a command is already the wrapper, or a direct `busybox <applet>` call whose
397
+ * output is the applet's own record (`run`, `log`, `peek`, `json`, …), so a second pass
398
+ * over the same tool call cannot nest two timelines or re-tag a capture being read back.
399
+ *
400
+ * A direct call to a runner applet is not that: it is wrapped like any other command.
401
+ */
402
+ export function isWrapped(command: string): boolean {
403
+ const match = /^(?:busybox|'[^']*\/busybox'|[^'\s]*\/busybox)\s+(\S+)/.exec(command.trimStart());
404
+ return match !== null && !RUNNER_APPLETS.includes(match[1] as string);
405
+ }
406
+
407
+ /**
408
+ * `command <cmd>` runs unwrapped, for byte-exact output (a JSON document, a checksum,
409
+ * anything a prefix would corrupt). It is POSIX, so the escape costs nothing when
410
+ * unused.
411
+ *
412
+ * The check accepts the builtin at the start of *any* segment, because the command
413
+ * that reaches the hook is rarely the bare one: a model writes
414
+ * `cd /repo && jq -r .a f.json`, and an escape that only worked as the very first word
415
+ * would silently do nothing there (observed in the first live run).
416
+ */
417
+ export function wantsRaw(command: string): boolean {
418
+ return /(?:^|[;&|(\n])\s*command\s+\S/.test(command);
419
+ }
420
+
421
+ export interface WrapOptions {
422
+ busybox: string;
423
+ /** The shell pi itself would have used; the child keeps it, so `[[ ]]` still works. */
424
+ shell: string;
425
+ verbosity: Verbosity;
426
+ /** Defaults to `off` so the tests here describe plain pipes; the extension passes its setting. */
427
+ pty?: PtyMode;
428
+ extraEnv?: Array<[string, string]>;
429
+ /** Pi's own deadline for this call, in seconds; the wrapper takes it over, slightly earlier. */
430
+ timeoutSeconds?: number;
431
+ /** Silence watchdog in seconds; emitted with any deadline. */
432
+ idleSeconds?: number;
433
+ /** Path to the Ruby prelude; when it exists, RUBYOPT requires it so $stdout.sync is on. */
434
+ rubyPrelude?: string;
435
+ /** Folder holding the Perl prelude; when it exists, PERL5OPT loads it so `$|` is on. */
436
+ perlPrelude?: string;
437
+ /** `stdbuf`'s preload library, when one was found and the person asked for it (Linux). */
438
+ stdbufLib?: string;
439
+ /** False leaves every runtime's buffering as it is: no STREAM_ENV, no prelude, no preload. */
440
+ unbuffer?: boolean;
441
+ /**
442
+ * False for a build without `run --stamp-ns` (before 0.6.0): the caller reads the
443
+ * binary's own feature list, and an older build is never handed a flag it does not know.
444
+ */
445
+ stampNs?: boolean;
446
+ /**
447
+ * Have the guest shell leave two facts in the run's folder when it exits: its final
448
+ * directory and the statuses of its last pipeline. They replace guesses on the result
449
+ * ("the command's own status is unknown") with what happened. See REPORT_TRAP.
450
+ */
451
+ reportShell?: boolean;
452
+ /** Skip the unbuffered environment (used by tests). */
453
+ noEnv?: boolean;
454
+ /**
455
+ * The human's view, for the `user_bash` path: the command's own bytes and nothing
456
+ * else — `-q` suppresses the run header and section markers, and no timeline is
457
+ * taken, because the reader is a person in the TUI, not a model reading tags.
458
+ * The capture still happens: artifacts land in the run directory for `busybox log`.
459
+ */
460
+ passthrough?: boolean;
461
+ /**
462
+ * Where the guest's stdin comes from (`run --stdin`): a file, or a named pipe another
463
+ * process writes to as a person types. Without it the guest reads end-of-file at once,
464
+ * because pi starts every command with its own stdin closed.
465
+ */
466
+ stdinFile?: string;
467
+ /**
468
+ * A private artifact root (`run --dir`) holding this one run, so its capture files
469
+ * can be followed while the command runs. The caller removes it afterwards, which is
470
+ * why no `--prune` is emitted with it.
471
+ */
472
+ artifactDir?: string;
473
+ }
474
+
475
+ /**
476
+ * Build the replacement command, or undefined when the command should run as written.
477
+ *
478
+ * The shape is `busybox run <flags> --env ... -- <shell> -c '<command>'`. `run` exits
479
+ * with the child's status, so `&&`, `;` and `$?` behave exactly as before.
480
+ */
481
+ export function wrapCommand(command: string, options: WrapOptions): string | undefined {
482
+ if (!command.trim()) return undefined;
483
+ if (isWrapped(command) || wantsRaw(command)) return undefined;
484
+
485
+ const ladder = LADDER[options.verbosity];
486
+ const env = options.noEnv ? [] : envFlags(options);
487
+ const parts = [shellQuote(options.busybox), "run"];
488
+ if (options.passthrough) {
489
+ // The human's view: header suppressed, no timeline, and the capture is still kept.
490
+ parts.push("-q");
491
+ } else {
492
+ // ns stamps: 0.5.0-era us stamps could not tell two events in the same microsecond
493
+ // apart, and the clock is ns anyway. Old captures (us) stay parsable everywhere.
494
+ if (ladder.timestamps) parts.push("--timestamps", ...(options.stampNs === false ? [] : ["--stamp-ns"]));
495
+ parts.push(...ladder.flags);
496
+ }
497
+ // The terminal goes after the view flags: it changes how the child buffers, not what
498
+ // the view means.
499
+ parts.push(...ptyFlags(options.pty ?? "off"));
500
+ // No `--prune`: the artifact root is shared by every session on the machine, and
501
+ // "keep the newest 20" let twenty commands in one session delete the capture another
502
+ // session had just been pointed at. The extension sweeps by age instead.
503
+ if (options.artifactDir) parts.push("--dir", shellQuote(options.artifactDir));
504
+ if (options.stdinFile) parts.push("--stdin", shellQuote(options.stdinFile));
505
+ if (options.timeoutSeconds !== undefined) {
506
+ // Emitted verbatim: the caller decides the number. The extension pre-empts pi's own
507
+ // deadline by a second before calling in, so the applet's deadline fires first and
508
+ // still prints the timeline, instead of pi's SIGKILL printing nothing.
509
+ parts.push("--timeout", String(Math.max(0, Math.floor(options.timeoutSeconds))));
510
+ // The silence watchdog rides along with any deadline: `idle=true` in the result
511
+ // is a hang signature, and it is what stops a raised deadline from meaning
512
+ // "wait the full ten minutes for a command that died at second one".
513
+ if (options.idleSeconds !== undefined && options.idleSeconds > 0) {
514
+ parts.push("-W", String(options.idleSeconds));
515
+ }
516
+ }
517
+ for (const flag of env) parts.push("--env", flag);
518
+ const prelude = options.reportShell && !options.passthrough ? reportTrap(options.shell) : "";
519
+ parts.push("--", shellQuote(options.shell), "-c", shellQuote(prelude + command));
520
+ return parts.join(" ");
521
+ }
522
+
523
+ /** The file, in the run's own folder, where the guest leaves its last pipeline's statuses. */
524
+ export const PIPESTATUS_FILE = "pipestatus";
525
+ /** The file `run` itself names (`$BUSYBOX_RUN_CWD`) for the guest's final directory. */
526
+ export const CWD_FILE = "cwd";
527
+
528
+ /**
529
+ * An EXIT trap that leaves two facts in the run's folder: the final directory and, under
530
+ * bash, the exit status of every stage of the last pipeline.
531
+ *
532
+ * `run` hands the guest `$BUSYBOX_RUN_DIR` (its own folder), so nothing has to be passed
533
+ * in. On the command's own first line, never a line of its own: a prelude line would
534
+ * shift every line number the shell reports. `PIPESTATUS` is read before anything else in
535
+ * the trap can overwrite it. A command that sets its own EXIT trap replaces this one, and
536
+ * a syntax error never reaches it — both simply leave no facts, and the result falls back
537
+ * to saying what it cannot know.
538
+ *
539
+ * Measured cost: about 4 ms a call.
540
+ */
541
+ export function reportTrap(shell: string): string {
542
+ const isBash = /(?:^|\/)(?:bash|zsh)$/.test(shell);
543
+ const status = isBash ? '__pt_ps="${PIPESTATUS[*]}"; ' : "";
544
+ const write = isBash ? ` printf "%s\\n" "$__pt_ps" >"$BUSYBOX_RUN_DIR/${PIPESTATUS_FILE}";` : "";
545
+ return `trap '${status}if [ -n "\${BUSYBOX_RUN_DIR:-}" ]; then pwd -P >"$BUSYBOX_RUN_DIR/${CWD_FILE}";${write} fi 2>/dev/null' EXIT; `;
546
+ }
547
+
548
+ /** A value made literal inside a shell's double quotes. */
549
+ function inDoubleQuotes(value: string): string {
550
+ return value.replace(/[\\"$`]/g, "\\$&");
551
+ }
552
+
553
+ /**
554
+ * The `NAME=VALUE` arguments of the wrapper's environment, each quoted for the shell.
555
+ *
556
+ * Four ways a variable meets what the person already has, because one rule does not fit:
557
+ *
558
+ * - assigned: a switch with one right value here (`PYTHONUNBUFFERED=1`, `TERM=dumb`);
559
+ * - appended: an option list, where theirs must survive and ours comes last
560
+ * (`"RUBYOPT=${RUBYOPT:+$RUBYOPT }-r…"`) — `RUBYOPT`, `PERL5OPT`, `MAVEN_ARGS`,
561
+ * `GRADLE_OPTS`;
562
+ * - only if unset: a snippet that cannot be merged with another (`LUA_INIT`);
563
+ * - joined with a colon: a path list (`LD_PRELOAD`).
564
+ *
565
+ * The merging forms are double-quoted so the shell that runs the wrapper expands them —
566
+ * pi's own `bash -c`. The person's extra environment comes last, and the last assignment
567
+ * of a name wins.
568
+ */
569
+ function envFlags(options: WrapOptions): string[] {
570
+ const isUnbuffered = options.unbuffer !== false;
571
+ const assign = ([name, value]: readonly [string, string]) => shellValue(`${name}=${value}`);
572
+ const append = (name: string, value: string) => `"${name}=\${${name}:+$${name} }${inDoubleQuotes(value)}"`;
573
+ const flags: string[] = [];
574
+ if (isUnbuffered) flags.push(...STREAM_ENV.map(assign));
575
+ flags.push(...QUIET_ENV.map(assign));
576
+ for (const [name, value] of TOOL_OPTIONS_ENV) flags.push(append(name, value));
577
+ if (isUnbuffered) {
578
+ flags.push(`"LUA_INIT=\${LUA_INIT:-${inDoubleQuotes(LUA_INIT)}}"`);
579
+ // Each only when its file is actually on disk: an option naming a missing file
580
+ // makes every ruby, or every perl, fail to start.
581
+ if (options.rubyPrelude) flags.push(append("RUBYOPT", `-r${options.rubyPrelude}`));
582
+ if (options.perlPrelude) flags.push(append("PERL5OPT", `-I${options.perlPrelude} -M${PERL_PRELUDE_MODULE}`));
583
+ if (options.stdbufLib) {
584
+ flags.push(`"LD_PRELOAD=\${LD_PRELOAD:+$LD_PRELOAD:}${inDoubleQuotes(options.stdbufLib)}"`, assign(["_STDBUF_O", "L"]));
585
+ }
586
+ }
587
+ flags.push(...(options.extraEnv ?? []).map(assign));
588
+ return flags;
589
+ }
590
+
591
+ /**
592
+ * How many run directories are always kept for `busybox log`, whatever their age.
593
+ *
594
+ * The root is shared by every session on the machine, so the number has to cover all of
595
+ * them at once; a run beyond it is only removed once it is also older than RUN_MIN_AGE_MS.
596
+ */
597
+ export const RUN_RETENTION = 200;
598
+ /** A run younger than this is never swept: a session may still be pointed at it. */
599
+ export const RUN_MIN_AGE_MS = 2 * 60 * 60 * 1000;
600
+
601
+ /**
602
+ * Default deadline for every wrapped command, in seconds.
603
+ *
604
+ * A model that hits a hanging command — a loop on a bad path, a server that never exits, a
605
+ * prompt waiting on stdin — otherwise waits until the harness gives up, which can be
606
+ * minutes of nothing. Two minutes is long enough for a real build step and short enough
607
+ * that the model gets a *recoverable* answer instead of silence.
608
+ */
609
+ export const DEFAULT_TIMEOUT_SECONDS = 120;
610
+
611
+ /**
612
+ * The silence watchdog: kill after this many seconds without any output, whatever the
613
+ * deadline is. A command that hangs silently — the stdin-pty trap, a socket, a lock —
614
+ * reports `idle=true` instead of `timed_out=true`, so the notice can say "a hang, not
615
+ * slow work". Inert when the deadline is shorter; valuable when a caller raises it.
616
+ */
617
+ export const DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
618
+
619
+ /**
620
+ * \`PI_MANAGED_TOOLS_TIMEOUT\` overrides it: seconds, or \`0\`/\`off\` for no deadline.
621
+ *
622
+ * A caller's own timeout always wins (pi passes one as the bash tool's \`timeout\`
623
+ * parameter); this is only the default when nobody asked for one.
624
+ */
625
+ /** `PI_MANAGED_TOOLS_IDLE=<seconds>` changes it; `0`/`off` removes the watchdog. */
626
+ export function readIdleTimeout(env: NodeJS.ProcessEnv = process.env): number {
627
+ const raw = (env.PI_MANAGED_TOOLS_IDLE ?? "").trim().toLowerCase();
628
+ if (raw === "0" || raw === "off" || raw === "false" || raw === "no" || raw === "none") return 0;
629
+ const seconds = Number(raw);
630
+ if (!Number.isFinite(seconds) || seconds < 0) return DEFAULT_IDLE_TIMEOUT_SECONDS;
631
+ return seconds > 0 ? Math.floor(seconds) : DEFAULT_IDLE_TIMEOUT_SECONDS;
632
+ }
633
+
634
+ export function readDefaultTimeout(env: NodeJS.ProcessEnv = process.env): number {
635
+ const raw = (env.PI_MANAGED_TOOLS_TIMEOUT ?? "").trim().toLowerCase();
636
+ if (raw === "0" || raw === "off" || raw === "false" || raw === "no" || raw === "none") return 0;
637
+ const seconds = Number(raw);
638
+ if (!Number.isFinite(seconds) || seconds < 0) return DEFAULT_TIMEOUT_SECONDS;
639
+ return seconds > 0 ? Math.floor(seconds) : DEFAULT_TIMEOUT_SECONDS;
640
+ }
641
+
642
+ /** The `command` escape, stated once for the prompt section and the skills. */
643
+ export const RAW_ESCAPE =
644
+ "Prefix a command, or any `&&`/`;` segment of one, with `command ` to run it unwrapped — an escape for when a consumer needs exact bytes (a checksum, a parser), not the default: it returns no timeline, no stream tags, no timing.";
645
+
646
+ /** Plain-English meaning of each level, so choosing one is not a guess. */
647
+ export function describeVerbosity(level: Verbosity): string {
648
+ switch (level) {
649
+ case "quiet":
650
+ return "timeline, 6 KB view";
651
+ case "verbose":
652
+ return "timeline, 49 KB view (the most pi passes on)";
653
+ case "brief":
654
+ return "repeats collapsed, no timeline";
655
+ default:
656
+ return "timeline, 48 KB view";
657
+ }
658
+ }
659
+
660
+ /**
661
+ * Ruby has no environment variable for `$stdout.sync`, but `RUBYOPT` is inherited by
662
+ * every ruby process, so a two-line prelude sets it for the whole tree.
663
+ *
664
+ * This is the only way to un-buffer Ruby from outside the program; Go's `os.Stdout` is
665
+ * already unbuffered (a `bufio.Writer` inside the program is not ours to fix) and
666
+ * Java's `System.out` has no such switch at all.
667
+ */
668
+ export const RUBY_PRELUDE = "$stdout.sync = true\n$stderr.sync = true\n";
669
+
670
+ /** File name of the Ruby prelude, written next to the bin directory. */
671
+ export const RUBY_PRELUDE_NAME = "pi-unbuffer.rb";
672
+
673
+ /**
674
+ * Perl has no variable for `$|` either, but `PERL5OPT` may name a module to load, and a
675
+ * module that sets `$|` at load time sets it on STDOUT, the handle selected then.
676
+ * Perl's STDERR is unbuffered already. (`perl -T` ignores `PERL5OPT`, and so this.)
677
+ */
678
+ export const PERL_PRELUDE_MODULE = "PiTimeUnbuffer";
679
+
680
+ /** The module's file, written next to the bin directory and found through `-I`. */
681
+ export const PERL_PRELUDE_NAME = `${PERL_PRELUDE_MODULE}.pm`;
682
+
683
+ export const PERL_PRELUDE = `package ${PERL_PRELUDE_MODULE};\n# Loaded through PERL5OPT by pi-managed-tools: STDOUT writes each line as it is printed.\n$| = 1;\n1;\n`;