@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.
@@ -0,0 +1,391 @@
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 three model tools over the packaged busybox's agent applets.
18
+ *
19
+ * They live in their own module so the extension's own concerns (update checks, PATH
20
+ * and applet wiring) stay readable, and so a test can load the tools without the
21
+ * session start machinery. Every guarantee they expose belongs to the binary; this
22
+ * module only builds argv, parses JSON and renders text.
23
+ */
24
+ import { existsSync, statSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
27
+ import { blockReason, detectTailMerge, guardEnabled, hasOverride } from "./guard.ts";
28
+ import { DEFAULT_TIMEOUT_SECONDS, readIdleTimeout } from "./wrap.ts";
29
+ import { Type } from "typebox";
30
+ import {
31
+ contentVersion,
32
+ describeAppletFailure,
33
+ formatLog,
34
+ formatPeek,
35
+ formatReplace,
36
+ formatRun,
37
+ logArgs,
38
+ type LogPayload,
39
+ peekArgs,
40
+ type PeekPayload,
41
+ replaceOneArgs,
42
+ replaceRequestBody,
43
+ replaceRequestArgs,
44
+ type ReplaceEdit,
45
+ type ReplacePayload,
46
+ resolveVersion,
47
+ runAppletJson,
48
+ runArgs,
49
+ type RunPayload,
50
+ salvageRunPayload,
51
+ writeRequestFile,
52
+ } from "./agentops.ts";
53
+
54
+ /** One result shape: the details payload differs per tool, so it is typed loosely. */
55
+ interface ToolOutcome {
56
+ content: { type: "text"; text: string }[];
57
+ details: Record<string, unknown> | undefined;
58
+ isError?: boolean;
59
+ }
60
+
61
+ export function registerAgentTools(pi: ExtensionAPI, binDir: string): void {
62
+ pi.registerTool({
63
+ name: "busybox_peek",
64
+ label: "BusyBox Peek",
65
+ description:
66
+ "Read a file through the packaged `busybox peek`: numbered lines, an explicit byte budget, and the file's sha256 version " +
67
+ "taken from the same bytes that were printed. " +
68
+ "'lines' takes a 1-based inclusive range (120:180, 7, :40); 'around' takes a literal string (or a regex with regex=true) and merges overlapping windows; " +
69
+ "'max_bytes' caps the returned bytes and a truncated answer carries a 'next' byte offset to continue from, so nothing is skipped. " +
70
+ "Binary files are reported, not dumped. Use it instead of read when the version must guard a later busybox_replace, or when the answer must fit a byte budget.",
71
+ promptSnippet: "Read a file with a version hash, line range and byte budget (busybox peek)",
72
+ promptGuidelines: [
73
+ "Use busybox_peek when you need a file's sha256 version to guard an edit, when you want lines around a literal match, or when output must stay inside a byte budget; plain reading is fine with read.",
74
+ ],
75
+ parameters: Type.Object({
76
+ path: Type.String({ description: "File to read." }),
77
+ lines: Type.Optional(Type.String({ description: "1-based inclusive range: 'A:B', 'A' or ':B'." })),
78
+ around: Type.Optional(Type.String({ description: "Show windows around each match of this literal string." })),
79
+ context: Type.Optional(Type.Number({ description: "Context lines for around (default 10)." })),
80
+ regex: Type.Optional(Type.Boolean({ description: "Treat 'around' as a POSIX extended regex." })),
81
+ from_byte: Type.Optional(
82
+ Type.Number({ description: "Continue at this byte offset (the 'next' value of a truncated read)." }),
83
+ ),
84
+ max_bytes: Type.Optional(Type.Number({ description: "Byte budget for the printed content (default 16384)." })),
85
+ }),
86
+ async execute(_toolCallId, params, signal): Promise<ToolOutcome> {
87
+ const result = await runAppletJson<PeekPayload>({
88
+ binDir,
89
+ applet: "peek",
90
+ args: peekArgs(params),
91
+ signal,
92
+ timeoutMs: 30_000,
93
+ });
94
+ const failure = describeAppletFailure(result);
95
+ const payload = result.json;
96
+ return {
97
+ content: [{ type: "text", text: failure ?? (payload ? formatPeek(payload) : "peek printed no result") }],
98
+ details: { peek: payload ?? undefined, exit: result.status },
99
+ isError: failure !== undefined || (result.status ?? 0) !== 0 || payload?.error !== undefined,
100
+ };
101
+ },
102
+ });
103
+
104
+ pi.registerTool({
105
+ name: "busybox_replace",
106
+ label: "BusyBox Replace",
107
+ description:
108
+ "Replace exact text in one file through `busybox replace`: all edits are validated before anything is written, the write is atomic, " +
109
+ "and a mismatched 'sha256' (from busybox_peek: the full hash or the short prefix it printed) is refused as stale rather than applied. " +
110
+ "Each edit states how many matches it expects (default 1); fewer or more matches leaves the file byte-identical and reports the candidate lines. " +
111
+ "Literal matching only. 'dry_run' prints a bounded diff and writes nothing. " +
112
+ "Use it over edit when you have a version hash to guard against, or when several edits must all be checked first.",
113
+ promptSnippet: "Guarded, all-or-nothing literal replacement with stale-input rejection (busybox replace)",
114
+ promptGuidelines: [
115
+ "Prefer busybox_replace over edit when a sha256 version from busybox_peek is available: a stale input is refused instead of applied, and dry_run gives a diff without writing.",
116
+ ],
117
+ parameters: Type.Object({
118
+ path: Type.String({ description: "File to edit." }),
119
+ edits: Type.Array(
120
+ Type.Object({
121
+ old: Type.String({ description: "Exact text to replace." }),
122
+ new: Type.String({ description: "Replacement text (empty deletes)." }),
123
+ expect: Type.Optional(Type.Number({ description: "Required match count (default 1)." })),
124
+ }),
125
+ { description: "Edits validated against the file before any write." },
126
+ ),
127
+ sha256: Type.Optional(
128
+ Type.String({
129
+ description:
130
+ "Content version from busybox_peek: the full hash or the short prefix it printed. A mismatch is STALE_INPUT and nothing is written.",
131
+ }),
132
+ ),
133
+ dry_run: Type.Optional(Type.Boolean({ description: "Print the diff, change nothing." })),
134
+ follow: Type.Optional(Type.Boolean({ description: "Allow editing through a symlink (refused by default)." })),
135
+ max_diff_bytes: Type.Optional(Type.Number({ description: "Cap the printed diff (default 4096)." })),
136
+ }),
137
+ async execute(_toolCallId, params, signal): Promise<ToolOutcome> {
138
+ const edits = params.edits ?? [];
139
+ if (edits.length === 0) {
140
+ return { content: [{ type: "text", text: "replace needs at least one edit" }], details: undefined, isError: true };
141
+ }
142
+ let wanted = params.sha256?.replace(/^sha256:/, "");
143
+ // `peek` prints a shortened version, so a copied prefix has to work: it is
144
+ // resolved against the file as it stands now, and the applet then compares the
145
+ // full value under its own lock.
146
+ if (wanted && wanted.length < 64) {
147
+ const current = await contentVersion({ binDir, path: params.path, signal });
148
+ if (current.error) {
149
+ return {
150
+ content: [{ type: "text", text: `${params.path}: ${current.error}\nNo files changed.` }],
151
+ details: undefined,
152
+ isError: true,
153
+ };
154
+ }
155
+ const resolved = resolveVersion(wanted, current.version);
156
+ if (!resolved.ok) {
157
+ return {
158
+ content: [
159
+ {
160
+ type: "text",
161
+ text:
162
+ `${params.path}: STALE_INPUT: content version is ${current.version ?? "unknown"}` +
163
+ "\nNo files changed. Re-read it with busybox_peek to get the current version.",
164
+ },
165
+ ],
166
+ details: { currentVersion: current.version },
167
+ isError: true,
168
+ };
169
+ }
170
+ wanted = resolved.full;
171
+ }
172
+ let request: { path: string; cleanup: () => void } | undefined;
173
+ try {
174
+ let argsOut: string[];
175
+ if (edits.length === 1) {
176
+ argsOut = replaceOneArgs({ ...params, path: params.path, edit: edits[0] as ReplaceEdit, sha256: wanted });
177
+ } else {
178
+ // Several edits go through --request, which re-reads the file per edit; the
179
+ // hash therefore has to be checked here, before the batch starts.
180
+ if (wanted) {
181
+ const current = await contentVersion({ binDir, path: params.path, signal });
182
+ if (current.error) {
183
+ return {
184
+ content: [{ type: "text", text: `${params.path}: ${current.error}\nNo files changed.` }],
185
+ details: undefined,
186
+ isError: true,
187
+ };
188
+ }
189
+ if (current.version?.replace(/^sha256:/, "") !== wanted) {
190
+ return {
191
+ content: [
192
+ {
193
+ type: "text",
194
+ text:
195
+ `${params.path}: STALE_INPUT: content version is ${current.version}` +
196
+ "\nNo files changed. Re-read it with busybox_peek to get the current version.",
197
+ },
198
+ ],
199
+ details: { currentVersion: current.version },
200
+ isError: true,
201
+ };
202
+ }
203
+ }
204
+ request = writeRequestFile(replaceRequestBody(params.path, edits));
205
+ argsOut = replaceRequestArgs({ ...params, requestPath: request.path });
206
+ }
207
+ const result = await runAppletJson<ReplacePayload>({
208
+ binDir,
209
+ applet: "replace",
210
+ args: argsOut,
211
+ signal,
212
+ timeoutMs: 60_000,
213
+ });
214
+ const failure = describeAppletFailure(result);
215
+ const payload = result.json;
216
+ return {
217
+ content: [{ type: "text", text: failure ?? (payload ? formatReplace(payload) : "replace printed no result") }],
218
+ details: { replace: payload ?? undefined, exit: result.status },
219
+ isError: failure !== undefined || (result.status ?? 0) !== 0 || payload?.error !== undefined,
220
+ };
221
+ } finally {
222
+ request?.cleanup();
223
+ }
224
+ },
225
+ });
226
+
227
+ pi.registerTool({
228
+ name: "busybox_run",
229
+ label: "BusyBox Run",
230
+ description:
231
+ "Run a command through `busybox run` and keep the evidence, or read that evidence back with 'run_id'. " +
232
+ "stdout and stderr are captured separately into artifacts and only a bounded head-and-tail view is returned; " +
233
+ "'view_truncated' means the view was cut while the capture is complete, so busybox_run run_id=... lines=\"200:280\" or match=<literal> retrieves the rest. " +
234
+ "Exit codes: the command's own status when it finished, 3 when this wrapper timed out or was cancelled, 1 when it could not start - check timed_out/cancelled in the text rather than the number alone. " +
235
+ "Give 'argv' to exec directly, or 'shell' for pipelines and shell syntax, never both. " +
236
+ "A command that asks a question gets its answer from 'stdin'; nobody can type one. " +
237
+ "bash calls are already wrapped in a timestamped `busybox run`, so use this tool when you need the structured record instead of the timeline. The child gets the same split pseudo-terminal (stdout line-buffered, stderr piped), so a program that buffers on a pipe still reports when each line happened.",
238
+ promptSnippet: "Run a command with captured artifacts, or retrieve part of an earlier run's output (busybox run/log)",
239
+ promptGuidelines: [
240
+ "Use busybox_run when a command's output may need re-reading after truncation, or when stdout and stderr must be inspected separately: the capture is kept, so a second call with run_id retrieves lines the view left out. A nonzero exit_code is the command's status, not a failure of the tool.",
241
+ ],
242
+ parameters: Type.Object({
243
+ argv: Type.Optional(Type.Array(Type.String(), { description: "Program and arguments, exec'd verbatim." })),
244
+ shell: Type.Optional(Type.String({ description: "Command line run through sh -c, for pipelines and redirection." })),
245
+ cwd: Type.Optional(Type.String({ description: "Working directory for the child." })),
246
+ stdin: Type.Optional(
247
+ Type.String({
248
+ description:
249
+ "Text fed to the command's standard input, followed by end-of-file: the answers to its prompts, one per line (\"y\\n\"). Without it stdin is empty and a read returns end-of-file at once.",
250
+ }),
251
+ ),
252
+ timeout_s: Type.Optional(Type.Number({ description: "Kill the process group after this many seconds." })),
253
+ max_bytes: Type.Optional(Type.Number({ description: "Byte budget for the returned view (default 12000)." })),
254
+ run_id: Type.Optional(Type.String({ description: "Retrieve part of this earlier run instead of executing anything." })),
255
+ lines: Type.Optional(Type.String({ description: "For run_id: 1-based inclusive line range of the artifact." })),
256
+ match: Type.Optional(Type.String({ description: "For run_id: show artifact lines containing this literal string." })),
257
+ context: Type.Optional(Type.Number({ description: "For match: context lines (default 3)." })),
258
+ stream: Type.Optional(
259
+ Type.Union([Type.Literal("stdout"), Type.Literal("stderr"), Type.Literal("both"), Type.Literal("timeline")], {
260
+ description: "For run_id: which captured stream to read (default stdout). timeline interleaves both by timestamp.",
261
+ }),
262
+ ),
263
+ meta: Type.Optional(Type.Boolean({ description: "For run_id: print the run's metadata only." })),
264
+ }),
265
+ async execute(_toolCallId, params, signal): Promise<ToolOutcome> {
266
+ const retrieving = params.run_id !== undefined;
267
+ if (retrieving && (params.argv !== undefined || params.shell !== undefined)) {
268
+ return {
269
+ content: [{ type: "text", text: "give either run_id (retrieve) or argv/shell (execute), not both" }],
270
+ details: undefined,
271
+ isError: true,
272
+ };
273
+ }
274
+ if (!retrieving && params.argv === undefined && params.shell === undefined) {
275
+ return { content: [{ type: "text", text: "run needs argv, shell or run_id" }], details: undefined, isError: true };
276
+ }
277
+ if (!retrieving && params.argv !== undefined && params.shell !== undefined) {
278
+ return {
279
+ content: [{ type: "text", text: "give either argv (exec) or shell (sh -c), not both" }],
280
+ details: undefined,
281
+ isError: true,
282
+ };
283
+ }
284
+
285
+ if (retrieving) {
286
+ const query = { ...params, run_id: params.run_id as string };
287
+ const run = (stream?: string) =>
288
+ runAppletJson<LogPayload>({
289
+ binDir,
290
+ applet: "log",
291
+ // `--stream both` emits two JSON objects rather than one, so the streams are
292
+ // asked for one at a time and the answer that matched is the one shown.
293
+ args: logArgs(stream ? { ...query, stream } : query),
294
+ signal,
295
+ timeoutMs: 60_000,
296
+ });
297
+
298
+ let result = await run();
299
+ // A literal match with no stream named means "find this line": stderr is where
300
+ // most diagnostics live, and answering NOT_FOUND on stdout alone costs a call.
301
+ if (params.match !== undefined && params.stream === undefined && result.json?.code === "NOT_FOUND") {
302
+ const onErr = await run("stderr");
303
+ if (onErr.json?.code !== "NOT_FOUND") result = onErr;
304
+ }
305
+ const failure = describeAppletFailure(result);
306
+ const payload = result.json;
307
+ return {
308
+ content: [{ type: "text", text: failure ?? (payload ? formatLog(payload) : "log printed no result") }],
309
+ details: { log: payload ?? undefined, exit: result.status },
310
+ isError: failure !== undefined || (result.status ?? 0) !== 0 || payload?.error !== undefined,
311
+ };
312
+ }
313
+
314
+ // The same view-correctness guard as bash calls: a stream merge at the tail of
315
+ // the `shell` script is refused before running, so the capture never lies.
316
+ if (guardEnabled() && params.shell !== undefined) {
317
+ const merge = detectTailMerge(params.shell);
318
+ if (merge && !hasOverride(params.shell)) {
319
+ return {
320
+ content: [{ type: "text", text: blockReason(merge) }],
321
+ details: { blocked: merge.label },
322
+ isError: true,
323
+ };
324
+ }
325
+ }
326
+ // Always give the applet a deadline: it kills the child process group, and this
327
+ // wrapper only sends a single signal to the applet itself.
328
+ const budget = params.timeout_s ?? DEFAULT_TIMEOUT_SECONDS;
329
+ // The same silence watchdog as bash calls: `idle=true` is a hang signature.
330
+ const idle = readIdleTimeout();
331
+ const result = await runAppletJson<RunPayload>({
332
+ binDir,
333
+ applet: "run",
334
+ args: runArgs({ ...params, timeout_s: budget, idle_s: idle }),
335
+ // `run` passes its own stdin on to the child, through the pty or not, and ends
336
+ // it with end-of-file; with nothing given the child reads end-of-file at once.
337
+ ...(params.stdin !== undefined ? { stdin: params.stdin } : {}),
338
+ signal,
339
+ // The applet owns the real deadline; this one is only a backstop so a wedged
340
+ // wrapper cannot hold the tool open forever.
341
+ timeoutMs: (budget + 15) * 1000,
342
+ });
343
+ // A truncated view is emitted as two adjacent quoted strings by this build, so
344
+ // the payload has to be recovered from the text rather than re-run.
345
+ const payload = result.json ?? salvageRunPayload(result.stdout);
346
+ const failure = payload ? undefined : describeAppletFailure(result);
347
+ // A nonzero child exit is the command's result, not a tool failure: the whole
348
+ // point is that a failing test suite still reports its output and status.
349
+ const wrapperFailed =
350
+ failure !== undefined ||
351
+ payload?.timed_out === true ||
352
+ payload?.cancelled === true ||
353
+ payload?.error !== undefined ||
354
+ // An idle kill stopped the command. Reaching this clause already means the
355
+ // timeout and cancellation clauses were false: no exit code is the tell.
356
+ payload?.exit_code === -1;
357
+ return {
358
+ content: [{ type: "text", text: failure ?? (payload ? formatRun(payload) : "run printed no result") }],
359
+ details: { run: payload ?? undefined, exit: result.status, salvaged: result.json === undefined && payload !== undefined },
360
+ isError: wrapperFailed,
361
+ };
362
+ },
363
+ });
364
+ }
365
+
366
+ /** Re-exported so the extension can report the wrappers' own paths in status output. */
367
+ export function busyboxBinaryPath(binDir: string, plat: string = process.platform): string {
368
+ return join(binDir, "busybox" + (plat === "win32" ? ".exe" : ""));
369
+ }
370
+
371
+ /**
372
+ * True when the packaged binary can actually be executed.
373
+ *
374
+ * Existence is not enough: a zero-length file "runs" on Linux (the loader falls back to
375
+ * /bin/sh) and fails with ENOEXEC on macOS, and a truncated download or a half-written
376
+ * install produces exactly that. Wrapping a command in a binary that cannot run turns
377
+ * every bash call into silent empty output — the worst possible failure mode — so the
378
+ * check is size and the executable bit, not just presence.
379
+ */
380
+ export function busyboxAvailable(binDir: string, plat: string = process.platform): boolean {
381
+ const path = busyboxBinaryPath(binDir, plat);
382
+ if (!existsSync(path)) return false;
383
+ try {
384
+ const stats = statSync(path);
385
+ if (stats.size === 0) return false;
386
+ // Windows has no executable bit; the file extension is the only signal there.
387
+ return plat === "win32" ? true : (stats.mode & 0o111) !== 0;
388
+ } catch {
389
+ return false;
390
+ }
391
+ }
@@ -0,0 +1,103 @@
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
+ * `bash`, re-registered so the timeline reaches the model but not the screen.
18
+ *
19
+ * pi's built-in `bash` runner is reused unchanged — `createBashToolDefinition` — so
20
+ * command execution, output truncation, temp files, process-tree killing and signal
21
+ * handling stay exactly as they were. Two things are added:
22
+ *
23
+ * 1. `execute` hands the command to the timeline wrapper and passes the *wrapped* text to
24
+ * pi's runner. Here, and not in the `tool_call` hook: a hook that rewrites
25
+ * `event.input.command` shows every later extension's `tool_call` handler the wrapper
26
+ * instead of what the model wrote — a permission or safety extension would be matching
27
+ * its rules against `busybox run … -c '…'`. In `execute` the call id, the command and
28
+ * pi's `timeout` are all at hand, and nobody else's view of the call changes.
29
+ * 2. `renderResult` draws the command's own lines, with the wrapper's decoration
30
+ * stripped, for the TUI and for HTML exports — by handing the stripped text to pi's
31
+ * own renderer, so the collapsed preview, the expand key, the truncation warning and
32
+ * the timer are pi's. The tool *result* is untouched, so the model still reads the
33
+ * offsets and the session still stores them.
34
+ *
35
+ * Reading this file, the split is: `execute`/result = model, `renderResult` = human.
36
+ */
37
+ import { Text } from "@earendil-works/pi-tui";
38
+ import { createBashToolDefinition, type BashToolDetails, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
39
+ import { hasTimeline, stripTimeline } from "./display.ts";
40
+
41
+ export interface TimelineBashOptions {
42
+ /** Registration-time cwd; pi overrides it per call with the session cwd. */
43
+ cwd: string;
44
+ /**
45
+ * The wrapped form of a command, or undefined to run it as written (the wrapper is
46
+ * off, the binary is missing, a direct capture call, the `command` escape).
47
+ */
48
+ wrap?: (command: string, timeoutSeconds: unknown) => string | undefined;
49
+ }
50
+
51
+ /**
52
+ * The last command handed to pi's runner, as written and as run.
53
+ *
54
+ * For the testbench and for status output: with the wrapping done inside `execute`,
55
+ * nothing outside this module would otherwise see the wrapped text.
56
+ */
57
+ export const lastRun: { original?: string; wrapped?: string } = {};
58
+
59
+ /**
60
+ * Register the bash override. Returns false when the host does not expose the bash
61
+ * tool factory, so a different harness still gets a working extension.
62
+ */
63
+ export function registerTimelineBash(pi: ExtensionAPI, options: TimelineBashOptions): boolean {
64
+ if (typeof createBashToolDefinition !== "function") return false;
65
+ const builtin = createBashToolDefinition(options.cwd);
66
+ const builtinRender = (builtin as { renderResult?: (...args: unknown[]) => unknown }).renderResult;
67
+
68
+ pi.registerTool({
69
+ ...builtin,
70
+ // Execution is the built-in's; only the command text it is given differs.
71
+ execute(toolCallId, params, ...rest) {
72
+ const input = params as { command: string; timeout?: number };
73
+ const wrapped = options.wrap?.(input.command, input.timeout);
74
+ lastRun.original = input.command;
75
+ lastRun.wrapped = wrapped;
76
+ return builtin.execute(toolCallId, (wrapped ? { ...input, command: wrapped } : params) as typeof params, ...rest);
77
+ },
78
+ renderResult(result, renderOptions, theme, ...rest) {
79
+ const text = result.content
80
+ .map((part) => (part.type === "text" ? part.text : ""))
81
+ .join("\n");
82
+ const details = result.details as BashToolDetails | undefined;
83
+ const body = hasTimeline(text) ? stripTimeline(text) : text;
84
+ if (typeof builtinRender === "function" && rest.length > 0) {
85
+ // pi's renderer, on the command's own lines: its preview, its expand hint, its
86
+ // "Full output" warning. It needs the render context pi passes as a fourth
87
+ // argument; without one (an older host, a test) the plain fallback below draws.
88
+ return builtinRender.call(builtin, { ...result, content: [{ type: "text", text: body }] }, renderOptions, theme, ...rest) as ReturnType<
89
+ NonNullable<typeof builtin.renderResult>
90
+ >;
91
+ }
92
+ let shown = body;
93
+ if (details?.fullOutputPath) {
94
+ // pi keeps the full output in a temp file when it truncates; the human still
95
+ // needs the way back to it.
96
+ shown += `\n${theme.fg("dim", `(full output: ${details.fullOutputPath})`)}`;
97
+ }
98
+ if (renderOptions.isPartial) return new Text(theme.fg("dim", shown || "(running…)"), 0, 0);
99
+ return new Text(shown, 0, 0);
100
+ },
101
+ });
102
+ return true;
103
+ }
package/src/build.ts ADDED
@@ -0,0 +1,142 @@
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
+ * Ask the installed binary what it is, by running it.
18
+ *
19
+ * Three things used to be assumed and were each wrong at some point:
20
+ *
21
+ * - that the build has the flags the wrapper passes. `--stamp-ns` and `-W` arrived in
22
+ * 0.6.0 and were emitted unconditionally; a pinned or stale build would have failed
23
+ * every bash call with "unknown option";
24
+ * - that a pseudo-terminal can be had. A container without `/dev/ptmx`, or a sandbox,
25
+ * refuses one, and `run --pty-split` then starts nothing;
26
+ * - what a timeline line looks like. The prompt quoted `[00000.123456789 out]` for a
27
+ * build that had started printing `[0.123456789 out]` a release earlier — and a claim
28
+ * that does not match the results is worse than no claim.
29
+ *
30
+ * So one short run, with exactly the flags a wrapped command will get, settles all three
31
+ * at session start: the flags are taken from the build's own feature list, the terminal
32
+ * is tried and dropped if refused, and the prompt's example is cut from a real line.
33
+ */
34
+ import { runApplet, runAppletJson } from "./agentops.ts";
35
+
36
+ /** How this build writes the offset at the start of a timeline line. */
37
+ export interface StampShape {
38
+ /** `none`: `[0.012…`; `space`: `[ 0.012…`; `zero`: `[00000.012…`. */
39
+ pad: "none" | "space" | "zero";
40
+ /** Width of the seconds field when padded. */
41
+ width: number;
42
+ /** Fraction digits printed for an offset under one second: six or nine. */
43
+ digits: number;
44
+ }
45
+
46
+ /** What 0.6.1 and later print with `--stamp-ns`: the shape assumed until a build says otherwise. */
47
+ export const DEFAULT_STAMP: StampShape = { pad: "none", width: 1, digits: 9 };
48
+
49
+ export interface BuildProbe {
50
+ /** False when no wrapped command can be run with this binary. */
51
+ ok: boolean;
52
+ /** Why not, in the binary's own words where it gave any. */
53
+ reason?: string;
54
+ /** The build's feature list, from `--caps`; empty when it could not be asked. */
55
+ features: string[];
56
+ stampNs: boolean;
57
+ idleTimeout: boolean;
58
+ logQuery: boolean;
59
+ /** False when a pseudo-terminal was wanted and refused: commands run on plain pipes. */
60
+ pty: boolean;
61
+ stamp: StampShape;
62
+ }
63
+
64
+ /** Read the shape of the stamp off one real timeline line, e.g. `[ 0.006244 out] probe`. */
65
+ export function stampShape(line: string): StampShape | undefined {
66
+ const match = /^\[(\s*)(\d+)\.(\d{1,9}) (?:out|err)\] /.exec(line);
67
+ if (!match) return undefined;
68
+ const [, spaces = "", whole = "", fraction = ""] = match;
69
+ if (spaces.length > 0) return { pad: "space", width: spaces.length + whole.length, digits: fraction.length };
70
+ if (whole.length > 1 && /^0+$/.test(whole.slice(0, -1))) return { pad: "zero", width: whole.length, digits: fraction.length };
71
+ return { pad: "none", width: whole.length, digits: fraction.length };
72
+ }
73
+
74
+ /**
75
+ * An example prefix in this build's own shape: `[0.012345678 out]`.
76
+ *
77
+ * `second` gives the companion example a later offset, so two lines in a prompt read as
78
+ * two events.
79
+ */
80
+ export function exampleStamp(shape: StampShape, stream: "out" | "err", second = false): string {
81
+ const fraction = (second ? "012349012" : "012345678").slice(0, Math.min(9, Math.max(1, shape.digits)));
82
+ const whole = shape.pad === "space" ? "0".padStart(shape.width, " ") : shape.pad === "zero" ? "0".padStart(shape.width, "0") : "0";
83
+ return `[${whole}.${fraction} ${stream}]`;
84
+ }
85
+
86
+ const PROBE_WORD = "pi-time-probe";
87
+
88
+ /**
89
+ * Run the probe: the feature list first, then one wrapped `echo` with the flags a real
90
+ * command would get. With a terminal if one is wanted; without, if that is refused.
91
+ */
92
+ export async function probeBuild(options: { binDir: string; wantPty: boolean; signal?: AbortSignal }): Promise<BuildProbe> {
93
+ const caps = await runAppletJson<{ features?: string[] }>({
94
+ binDir: options.binDir,
95
+ applet: "--caps",
96
+ args: ["--format", "json"],
97
+ timeoutMs: 10_000,
98
+ signal: options.signal,
99
+ });
100
+ const features = Array.isArray(caps.json?.features) ? caps.json.features.filter((item): item is string => typeof item === "string") : [];
101
+ const stampNs = features.includes("stamp-ns");
102
+ const idleTimeout = features.includes("idle-timeout");
103
+ const base = { features, stampNs, idleTimeout, logQuery: features.includes("log-query") };
104
+
105
+ const attempt = async (pty: boolean) => {
106
+ const result = await runApplet({
107
+ binDir: options.binDir,
108
+ applet: "run",
109
+ args: [
110
+ "--timestamps",
111
+ ...(stampNs ? ["--stamp-ns"] : []),
112
+ "--max-bytes",
113
+ "4000",
114
+ ...(pty ? ["--pty-split"] : []),
115
+ "--timeout",
116
+ "10",
117
+ ...(idleTimeout ? ["-W", "10"] : []),
118
+ "--",
119
+ "/bin/sh",
120
+ "-c",
121
+ `echo ${PROBE_WORD}`,
122
+ ],
123
+ timeoutMs: 15_000,
124
+ signal: options.signal,
125
+ });
126
+ const line = result.stdout.split("\n").find((candidate) => candidate.endsWith(` ${PROBE_WORD}`) && candidate.startsWith("["));
127
+ const isRun = /^run=R\d+ exit_code=0 /m.test(result.stdout);
128
+ return { ok: isRun && line !== undefined, line, said: (result.error ?? result.stderr.trim() ?? result.stdout.trim()).split("\n")[0] ?? "" };
129
+ };
130
+
131
+ let pty = options.wantPty;
132
+ let tried = await attempt(pty);
133
+ if (!tried.ok && pty) {
134
+ // No terminal to be had here: the same run on plain pipes.
135
+ pty = false;
136
+ tried = await attempt(false);
137
+ }
138
+ if (!tried.ok) {
139
+ return { ...base, ok: false, pty: false, stamp: DEFAULT_STAMP, reason: tried.said || "it printed no timeline for a wrapped `echo`" };
140
+ }
141
+ return { ...base, ok: true, pty, stamp: stampShape(tried.line as string) ?? DEFAULT_STAMP };
142
+ }