@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/extension.ts CHANGED
@@ -28,47 +28,158 @@
28
28
  * installed for `bash` only, and are reported that way rather than implied to
29
29
  * be part of pi's own tool surface.
30
30
  */
31
+ import { closeSync, existsSync, openSync, readFileSync, readSync, realpathSync, writeFileSync } from "node:fs";
32
+ import { tmpdir } from "node:os";
31
33
  import { join } from "node:path";
32
- import { type ExtensionAPI, type ExtensionContext, VERSION, getAgentDir, isToolCallEventType } from "@earendil-works/pi-coding-agent";
34
+ import {
35
+ type BashOperations,
36
+ type ExtensionAPI,
37
+ type ExtensionContext,
38
+ VERSION,
39
+ createLocalBashOperations,
40
+ getAgentDir,
41
+ isBashToolResult,
42
+ isToolCallEventType,
43
+ } from "@earendil-works/pi-coding-agent";
33
44
  import { Type } from "typebox";
45
+ import { type LogPayload, type PeekPayload, formatLog, formatPeek, formatReplace, formatRun, runApplet, runAppletJson } from "./agentops.ts";
46
+ import { busyboxAvailable, busyboxBinaryPath, registerAgentTools } from "./agenttools.ts";
47
+ import { sweepRunArtifacts } from "./agentops.ts";
48
+ import { registerTimelineBash } from "./bashtool.ts";
49
+ import { type BuildProbe, DEFAULT_STAMP, exampleStamp, probeBuild } from "./build.ts";
50
+ import { ageOutMessages, type ContextMessage, swapUserBash, type UserView } from "./context.ts";
51
+ import { registerJobTool, stopAllJobs } from "./jobs.ts";
52
+ import { blockReason, detectEndless, detectTailMerge, endlessReason, guardEnabled, hasOverride, type RunFacts, resultNotes } from "./guard.ts";
34
53
  import {
54
+ APPLET_DIRNAME,
35
55
  compareVersions,
56
+ ensurePathOrder,
36
57
  errorMessage,
37
58
  findToolId,
38
59
  inspectTools,
39
60
  MANAGED_TOOL_IDS,
40
61
  MANAGED_TOOLS,
62
+ managedBinaryNames,
63
+ readAppletPolicy,
41
64
  readSettings,
42
65
  readState,
43
66
  type Report,
44
- type ToolId,
45
67
  rewriteToolPaths,
46
68
  shouldCheck,
69
+ syncBusyboxApplets,
70
+ type ToolId,
47
71
  type ToolReport,
48
72
  updateTools,
49
73
  } from "./tools.ts";
74
+ import { compactStamps, outcomeNotice, parseDurationMs, parseHeader, parseTimeline, summarizeTiming, truncationHint } from "./timing.ts";
75
+ import { interactiveExec, type LiveTarget } from "./userstdin.ts";
76
+ import {
77
+ CWD_FILE,
78
+ applySettings,
79
+ describeVerbosity,
80
+ isWrapped,
81
+ PERL_PRELUDE,
82
+ PERL_PRELUDE_NAME,
83
+ PIPESTATUS_FILE,
84
+ RAW_ESCAPE,
85
+ PTY_MODES,
86
+ readPtyMode,
87
+ readSwitch,
88
+ RUN_MIN_AGE_MS,
89
+ RUN_RETENTION,
90
+ STDBUF_LIBS,
91
+ wantsRaw,
92
+ readStdinTimeout,
93
+ readUserStdinEnabled,
94
+ readUserWrapEnabled,
95
+ readWrapSettings,
96
+ RUBY_PRELUDE,
97
+ RUBY_PRELUDE_NAME,
98
+ type PtyMode,
99
+ type Verbosity,
100
+ VERBOSITIES,
101
+ wrapCommand,
102
+ } from "./wrap.ts";
50
103
 
51
104
  /** Same location pi's `getBinDir()` resolves, including $PI_CODING_AGENT_DIR. */
52
105
  const BIN_DIR = join(getAgentDir(), "bin");
106
+ /**
107
+ * BusyBox applet symlinks, one PATH entry after the bin directory.
108
+ *
109
+ * Not inside the bin directory: PATH order is the only thing that decides which build
110
+ * a bare name runs, and two names in one directory have no order. The dedicated static
111
+ * build wins because its directory is listed first.
112
+ */
113
+ const APPLET_DIR = join(getAgentDir(), APPLET_DIRNAME);
53
114
  const STATUS_KEY = "pi-managed-tools";
54
- const USER_AGENT = `@rob-c/pi-managed-tools/0.16.0 (pi ${VERSION})`;
115
+ const USER_AGENT = `@rob-c/pi-managed-tools/0.23.0 (pi ${VERSION})`;
55
116
  const TOOL_LIST = MANAGED_TOOL_IDS.map((id) => MANAGED_TOOLS[id].name).join(", ");
56
117
 
57
118
  /**
58
119
  * Environment rules stated in every turn rather than only when a skill loads.
59
120
  *
60
- * A skill's body reaches the model only once it decides the skill is relevant,
61
- * which it does not do for one-liners; these two were measured to fire
62
- * inconsistently from skill text alone.
121
+ * A skill's body reaches the model only once it decides the skill is relevant, which
122
+ * it does not do for one-liners; these were measured to fire inconsistently from skill
123
+ * text alone.
63
124
  */
64
- const ENV_GUIDELINES = [
65
- "Invoke the packaged binaries by bare name (rg, fd, bat, jq, scc, busybox); never an absolute path such as /usr/bin/jq or /opt/homebrew/bin/gh.",
66
- "Wrap multi-step shell logic as busybox sh -c '...' — loops, pipelines, several statements — and use plain bash only for arrays, ${v^^} or mapfile.",
67
- ];
125
+ function envGuidelines(): string[] {
126
+ // The example is cut from a line this build really printed (the session-start probe),
127
+ // so the prompt cannot quote a shape the results do not have.
128
+ const shape = build?.stamp ?? DEFAULT_STAMP;
129
+ const ditto = compactStampsEnabled() ? ' A line that arrived at the same offset as the one above carries "[= out]" instead of the digits again.' : "";
130
+ return [
131
+ "Invoke the packaged binaries by bare name (rg, fd, bat, jq, scc, busybox); never an absolute path such as /usr/bin/jq or /opt/homebrew/bin/gh.",
132
+ "Wrap multi-step shell logic as busybox sh -c '...' — loops, pipelines, several statements — and use plain bash only for arrays, ${v^^} or mapfile.",
133
+ `Every bash call comes back as a timeline: "${exampleStamp(shape, "out")}" or "${exampleStamp(shape, "err", true)}" per line (seconds since the command started), so ordering is real.${ditto} ${RAW_ESCAPE}`,
134
+ "Each bash call starts fresh in the session's cwd: `cd` does not persist between calls — `cd` within the call, or use absolute paths.",
135
+ "A command's stdin is empty here: a read returns end-of-file at once, so a prompt (`[y/N]`, a password) takes its default or fails instead of waiting — nobody can answer it. Give the answer in the command: `printf 'y\\n' | cmd`, `cmd < file`, a `<<'EOF'` heredoc, a `--yes` flag, or busybox_run's `stdin`.",
136
+ "Nobody can press a key or Ctrl-C either: a pager, an editor, `tail -f`, `watch` or a foreground server never ends here and is refused before it runs. Start anything that must keep running with busybox_job, and stop it when done.",
137
+ ];
138
+ }
68
139
  const GUIDELINE_MARK = "Wrap multi-step shell logic as busybox sh";
69
140
 
141
+ /** `PI_MANAGED_TOOLS_COMPACT_STAMPS=off` prints the full offset on every line again. */
142
+ function compactStampsEnabled(): boolean {
143
+ return readSwitch(process.env.PI_MANAGED_TOOLS_COMPACT_STAMPS, true);
144
+ }
145
+
146
+ /** `PI_MANAGED_TOOLS_AGE_OUT=off` keeps every old result's offsets after a compaction. */
147
+ function ageOutEnabled(): boolean {
148
+ return readSwitch(process.env.PI_MANAGED_TOOLS_AGE_OUT, true);
149
+ }
150
+
70
151
  /** Absolute host paths replaced in this process, reported by /managed-tools status. */
71
152
  let rewrittenPaths = 0;
153
+ /** Applet names currently linked, so a rewrite of `/usr/bin/xxd` knows it is ours. */
154
+ let appletNames: string[] = [];
155
+ /** What the last applet sync did, for /managed-tools status. */
156
+ let appletSummary: string | undefined;
157
+ /** Commands wrapped this session, shown by status. */
158
+ let wrappedCommands = 0;
159
+
160
+ /**
161
+ * Session verbosity, set by `/managed-tools verbosity` or the `managed_tools` tool.
162
+ *
163
+ * It overrides PI_MANAGED_TOOLS_VERBOSITY for this session only: pi runs one process
164
+ * per session, so the next session starts from the environment again.
165
+ */
166
+ let verbosityOverride: Verbosity | undefined;
167
+ /** Session override for the terminal mode, from `/managed-tools pty`. */
168
+ let ptyOverride: PtyMode | undefined;
169
+ /**
170
+ * What the installed binary said about itself when it was run at session start; undefined
171
+ * until then (and in tests that never start a session), in which case the wrapper acts as
172
+ * it did before there was a probe.
173
+ */
174
+ let build: BuildProbe | undefined;
175
+ /** Result notes already given in full this session; a repeat comes back in a few words. */
176
+ const seenNotes = new Set<string>();
177
+ /** Timelines of the human's `!` commands, kept so the model can be sent them. */
178
+ const userViews: UserView[] = [];
179
+ /** Where `busybox run` keeps its captures: one root for every session on the machine. */
180
+ const RUN_ROOT = join(process.env.TMPDIR ?? tmpdir(), "busybox-run");
181
+ /** The custom session entry that carries this session's `/managed-tools` switches. */
182
+ const STATE_ENTRY = "managed-tools-state";
72
183
 
73
184
  const ENV_SECTION_KEY = "managed_tools_environment";
74
185
  /** Models worth naming in the environment line, in the order they are used. */
@@ -77,22 +188,332 @@ const ENV_HIGHLIGHTS: ToolId[] = ["rg", "jq", "bat", "scc", "busybox"];
77
188
  let cachedEnvSection: string | undefined;
78
189
 
79
190
  /**
80
- * The CLI facts a model would otherwise discover by exploring.
191
+ * The shell pi would have run the command in, so the wrapped child keeps it.
81
192
  *
82
- * Versions come from the state file rather than from running five binaries, and
83
- * the whole string is computed once per process so the prompt section is stable
84
- * across turns — pi diffs sections, and a string that changes per turn costs a
85
- * prompt patch every turn.
193
+ * pi's own `getShellConfig()` prefers /bin/bash on Unix and falls back to bash on PATH;
194
+ * a wrapper that substituted `sh` would break `[[ ]]`, arrays and `$'...'` in commands
195
+ * that work today.
86
196
  */
197
+ function piShell(): string {
198
+ for (const candidate of ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]) {
199
+ if (existsSync(candidate)) return candidate;
200
+ }
201
+ return "/bin/sh";
202
+ }
203
+
204
+ /**
205
+ * Write the Ruby prelude that turns off `$stdout.sync` buffering.
206
+ *
207
+ * Written next to the bin directory and required through RUBYOPT, which every ruby
208
+ * process inherits. It is only referenced when the write succeeded: a RUBYOPT pointing
209
+ * at a missing file would break every ruby command in the session.
210
+ */
211
+ function ensureRubyPrelude(): string | undefined {
212
+ const path = join(getAgentDir(), RUBY_PRELUDE_NAME);
213
+ // RUBYOPT is split on whitespace: a path with a space in it would be read as two
214
+ // options, and every ruby command in the session would fail to start.
215
+ if (/\s/.test(path)) return undefined;
216
+ try {
217
+ if (!existsSync(path)) writeFileSync(path, RUBY_PRELUDE);
218
+ return existsSync(path) ? path : undefined;
219
+ } catch {
220
+ return undefined;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Replace a bash command with `busybox run --timestamps ...`.
226
+ *
227
+ * Returns undefined when the command must run as written: the wrapper is off, the
228
+ * binary is missing, the command is already wrapped, or the caller asked for
229
+ * byte-exact output with the `command` prefix.
230
+ */
231
+ /** The Perl prelude, written like the Ruby one and only named when it is on disk. */
232
+ function ensurePerlPrelude(): string | undefined {
233
+ const dir = getAgentDir();
234
+ // PERL5OPT is split on whitespace: a folder with a space in it cannot be named there.
235
+ if (/\s/.test(dir)) return undefined;
236
+ const path = join(dir, PERL_PRELUDE_NAME);
237
+ try {
238
+ if (!existsSync(path)) writeFileSync(path, PERL_PRELUDE);
239
+ return existsSync(path) ? dir : undefined;
240
+ } catch {
241
+ return undefined;
242
+ }
243
+ }
244
+
245
+ let cachedStdbufLib: string | null | undefined;
246
+ /** `stdbuf`'s preload library, looked for once; only used when the person asked for it. */
247
+ function findStdbufLib(): string | undefined {
248
+ if (cachedStdbufLib === undefined) cachedStdbufLib = STDBUF_LIBS.find((path) => existsSync(path)) ?? null;
249
+ return cachedStdbufLib ?? undefined;
250
+ }
251
+
252
+ /** What switches output buffering off for a wrapped command: the preludes on disk, and the preload if asked for. */
253
+ function streamOptions(wrap: ReturnType<typeof readWrapSettings>): {
254
+ unbuffer: boolean;
255
+ rubyPrelude?: string;
256
+ perlPrelude?: string;
257
+ stdbufLib?: string;
258
+ } {
259
+ if (!wrap.unbuffer) return { unbuffer: false };
260
+ return {
261
+ unbuffer: true,
262
+ rubyPrelude: ensureRubyPrelude(),
263
+ perlPrelude: ensurePerlPrelude(),
264
+ stdbufLib: wrap.preload ? findStdbufLib() : undefined,
265
+ };
266
+ }
267
+
268
+ function wrapBashCommand(command: string, timeoutSeconds: unknown): string | undefined {
269
+ const wrap = readWrapSettings(process.env, verbosityOverride);
270
+ if (ptyOverride) wrap.pty = ptyOverride;
271
+ if (!wrap.enabled) return undefined;
272
+ if (!busyboxAvailable(BIN_DIR)) return undefined;
273
+ // The binary failed its own self-test: running commands as written beats failing them all.
274
+ if (build && !build.ok) return undefined;
275
+ // A terminal was wanted and refused when the session started: plain pipes from then on.
276
+ if (build && !build.pty && wrap.pty !== "off") wrap.pty = "off";
277
+ // A caller's deadline wins and is taken over one second earlier, so the applet owns it
278
+ // and still prints the timeline. With no caller deadline the configured default applies
279
+ // (120s unless PI_MANAGED_TOOLS_TIMEOUT says otherwise), which is what stops a hang from
280
+ // costing the model minutes of silence.
281
+ const asked = typeof timeoutSeconds === "number" && timeoutSeconds > 0 ? timeoutSeconds : undefined;
282
+ const budget = asked ? Math.max(0, asked - 1) : wrap.timeoutSeconds > 0 ? wrap.timeoutSeconds : undefined;
283
+ const wrapped = wrapCommand(command, {
284
+ busybox: busyboxBinaryPath(BIN_DIR),
285
+ shell: piShell(),
286
+ verbosity: wrap.verbosity,
287
+ pty: wrap.pty,
288
+ extraEnv: wrap.extraEnv,
289
+ ...streamOptions(wrap),
290
+ timeoutSeconds: budget,
291
+ // The silence watchdog rides with any deadline: idle=true is the hang signature.
292
+ // Only for a build that has it (asked at session start; assumed before that).
293
+ idleSeconds: budget !== undefined && build?.idleTimeout !== false ? wrap.idleSeconds : undefined,
294
+ stampNs: build ? build.stampNs : true,
295
+ reportShell: true,
296
+ });
297
+ if (wrapped) {
298
+ wrappedCommands++;
299
+ // A long session runs hundreds of commands; sweeping only at startup would let
300
+ // the artifact root grow for as long as the session lives.
301
+ if (wrappedCommands % 25 === 0) sweepRuns();
302
+ }
303
+ return wrapped;
304
+ }
305
+
306
+ /**
307
+ * Remove old captures: beyond the newest RUN_RETENTION, and only once they are hours old.
308
+ *
309
+ * The root is shared by every pi session on the machine (and anything else that uses the
310
+ * same binary), so "keep the newest 20" let one session delete the capture another had
311
+ * just been told to read.
312
+ */
313
+ function sweepRuns(): void {
314
+ sweepRunArtifacts({ root: RUN_ROOT, keep: RUN_RETENTION, minAgeMs: RUN_MIN_AGE_MS });
315
+ }
316
+
317
+ /** What the guest shell left in its run folder about how it ended, if anything. */
318
+ function readRunFacts(runId: string, cwdStart: string | undefined): RunFacts {
319
+ const facts: RunFacts = {};
320
+ const read = (name: string) => {
321
+ try {
322
+ return readFileSync(join(RUN_ROOT, runId, name), "utf-8").trim();
323
+ } catch {
324
+ return undefined;
325
+ }
326
+ };
327
+ const statuses = read(PIPESTATUS_FILE);
328
+ if (statuses && /^\d+(?: \d+)*$/.test(statuses)) facts.pipestatus = statuses.split(" ").map(Number);
329
+ const final = read(CWD_FILE);
330
+ if (final && cwdStart) {
331
+ facts.cwdFinal = final;
332
+ try {
333
+ // The guest wrote `pwd -P`; compare like with like.
334
+ facts.cwdStart = realpathSync(cwdStart);
335
+ } catch {
336
+ facts.cwdStart = cwdStart;
337
+ }
338
+ }
339
+ return facts;
340
+ }
341
+
342
+ /** The first bytes of a file: enough for the two header lines `run` prints. */
343
+ function readHead(path: string, bytes = 512): string {
344
+ let fd: number | undefined;
345
+ try {
346
+ fd = openSync(path, "r");
347
+ const buffer = Buffer.alloc(bytes);
348
+ return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0)).toString("utf-8");
349
+ } catch {
350
+ return "";
351
+ } finally {
352
+ if (fd !== undefined) closeSync(fd);
353
+ }
354
+ }
355
+
356
+ /** How many stderr lines a run captured in all, from `log --summary`; undefined when it cannot be asked. */
357
+ async function stderrLineCount(runId: string, signal?: AbortSignal): Promise<number | undefined> {
358
+ if (build && !build.logQuery) return undefined;
359
+ const result = await runApplet({ binDir: BIN_DIR, applet: "log", args: [runId, "--summary"], timeoutMs: 5_000, signal });
360
+ const match = / stderr=(\d+)\b/.exec(result.stdout);
361
+ return match ? Number(match[1]) : undefined;
362
+ }
363
+
364
+ /**
365
+ * Point every `bash` call's PATH at what this package installs, in order.
366
+ *
367
+ * pi's `getShellEnv()` prepends the bin directory only when it is *absent*, so a second
368
+ * directory cannot be added through it, and a shell rc that appended
369
+ * `$HOME/.pi/agent/bin` leaves host binaries winning. Rewriting this process's PATH is
370
+ * the hook that reaches every spawn: `getShellEnv()` re-reads it on each call and then
371
+ * leaves an order it already contains alone.
372
+ */
373
+ function integrateBusybox(): void {
374
+ const previous = appletNames.length;
375
+ const sync = syncBusyboxApplets({ binDir: BIN_DIR, appletDir: APPLET_DIR, policy: readAppletPolicy() });
376
+ appletNames = sync.linked;
377
+ // The prompt section quotes the applet directory, so a change invalidates it.
378
+ if (sync.linked.length !== previous) cachedEnvSection = undefined;
379
+ const first = sync.linked.length > 0 ? [BIN_DIR, APPLET_DIR] : [BIN_DIR];
380
+ const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") ?? "PATH";
381
+ process.env[pathKey] = ensurePathOrder(process.env[pathKey] ?? "", first);
382
+ appletSummary = sync.linked.length
383
+ ? `${sync.linked.length} applet names linked in ${APPLET_DIR} (policy ${sync.policy})`
384
+ : `no applet names linked - ${sync.error ?? "unknown reason"}`;
385
+ }
386
+
387
+ /** Whether a finished update changed a binary on disk, so the applet links need rebuilding. */
388
+ function installedSomething(report: Report): boolean {
389
+ return report.tools.some(
390
+ (tool) => tool.action === "installed" || tool.action === "updated" || tool.action === "reinstalled",
391
+ );
392
+ }
393
+
394
+ /**
395
+ * The installed build's own identity, straight from `busybox --caps`.
396
+ *
397
+ * The state file records the release tag a binary came from; a build installed by hand
398
+ * (or a development build ahead of the release) reports something else, and only the
399
+ * binary can say which applets and features it actually carries.
400
+ */
401
+ async function capsLine(): Promise<string | undefined> {
402
+ const result = await runAppletJson<{ version?: string; count?: number; features?: string[] }>({
403
+ binDir: BIN_DIR,
404
+ applet: "--caps",
405
+ args: ["--format", "json"],
406
+ timeoutMs: 10_000,
407
+ });
408
+ if (!result.json?.version) return undefined;
409
+ const features = (result.json.features ?? []).join(",");
410
+ return `busybox build: ${result.json.version}, ${result.json.count ?? "?"} applets${features ? `, features: ${features}` : ""}`;
411
+ }
412
+
413
+ /** The caps line with its leading newline, or nothing when the build cannot be asked. */
414
+ async function capsSuffix(): Promise<string> {
415
+ const caps = await capsLine();
416
+ return caps ? `\n${caps}` : "";
417
+ }
418
+
419
+ /** One line for status output: what the applet directory currently resolves. */
420
+ function appletLine(): string {
421
+ return `busybox applets: ${appletSummary ?? "not synced yet"}`;
422
+ }
423
+
424
+ /** One line for status output: how bash commands are being wrapped right now. */
425
+ function wrapLine(): string {
426
+ const wrap = readWrapSettings(process.env, verbosityOverride);
427
+ if (ptyOverride) wrap.pty = ptyOverride;
428
+ if (!wrap.enabled) return "bash wrapper: off";
429
+ if (!busyboxAvailable(BIN_DIR)) return "bash wrapper: on, but busybox is not installed";
430
+ if (build && !build.ok) {
431
+ return `bash wrapper: NOT wrapping — the installed busybox failed its self-test (${build.reason ?? "no reason given"}); bash runs unwrapped until it is updated or reinstalled`;
432
+ }
433
+ const pty = build && !build.pty && wrap.pty !== "off" ? `${wrap.pty} wanted but refused here, so plain pipes` : wrap.pty;
434
+ const flags = build
435
+ ? `; this build: ${build.stampNs ? "ns stamps" : "us stamps"}, ${build.idleTimeout ? "silence watchdog" : "no silence watchdog"}, ${build.logQuery ? "log queries" : "basic log"}`
436
+ : "";
437
+ const buffering = wrap.unbuffer
438
+ ? `; buffering switched off for Python, Ruby, Perl, Lua and (macOS) C stdio${wrap.preload ? (findStdbufLib() ? ", and by preload for C stdio on Linux" : "; preload asked for but no libstdbuf.so found") : ""}`
439
+ : "; buffering left to each program";
440
+ return `bash wrapper: on, verbosity ${wrap.verbosity}, pty ${pty}, ${wrappedCommands} command(s) wrapped this session${flags}${buffering}`;
441
+ }
442
+
443
+ /** What each pty mode means, in words. */
444
+ function describePty(mode: PtyMode): string {
445
+ switch (mode) {
446
+ case "off":
447
+ return "plain pipes, isatty() false, byte-exact";
448
+ case "merged":
449
+ return "one pty for 0/1/2, streams merged";
450
+ case "raw":
451
+ return "pty with the line discipline off";
452
+ default:
453
+ return "stdout on a pty (line-buffered, real timing), stderr on a pipe";
454
+ }
455
+ }
456
+
457
+ /** Set the terminal mode for wrapped commands, reporting what it will do. */
458
+ function setPty(mode: string): string {
459
+ const wanted = mode.trim().toLowerCase();
460
+ if (!(PTY_MODES as readonly string[]).includes(wanted)) {
461
+ return `unknown pty mode "${mode}"; use ${PTY_MODES.join(", ")}`;
462
+ }
463
+ ptyOverride = wanted as PtyMode;
464
+ cachedEnvSection = undefined;
465
+ return `bash wrapper pty: ${wanted} (${describePty(wanted as PtyMode)})`;
466
+ }
467
+
468
+ /** Set the session verbosity, reporting what it will do in one line. */
469
+ function setVerbosity(level: string): string {
470
+ const wanted = level.trim().toLowerCase();
471
+ if (!(VERBOSITIES as readonly string[]).includes(wanted)) {
472
+ return `unknown verbosity "${level}"; use ${VERBOSITIES.join(", ")}`;
473
+ }
474
+ verbosityOverride = wanted as Verbosity;
475
+ const wrap = readWrapSettings(process.env, verbosityOverride);
476
+ return `bash wrapper verbosity: ${wrap.verbosity} (${describeVerbosity(wrap.verbosity)})`;
477
+ }
478
+
87
479
  function environmentSection(): string {
88
480
  if (cachedEnvSection) return cachedEnvSection;
89
481
  const installed = readState(BIN_DIR)?.installed ?? {};
90
482
  const versions = ENV_HIGHLIGHTS.filter((id) => installed[id])
91
483
  .map((id) => `${MANAGED_TOOLS[id].binaryName} ${String(installed[id]).replace(/-.*$/, "")}`)
92
484
  .join(", ");
485
+ const wrap = readWrapSettings(process.env, verbosityOverride);
486
+ if (ptyOverride) wrap.pty = ptyOverride;
487
+ // Every claim below is checked against the binary at session start: the example line
488
+ // is this build's own shape, and the terminal is only described if one was granted.
489
+ const shape = build?.stamp ?? DEFAULT_STAMP;
490
+ const hasPty = wrap.pty !== "off" && build?.pty !== false;
491
+ const terminal = hasPty
492
+ ? " The child runs under a split pseudo-terminal (stdout a tty, stderr a pipe), so `isatty()` is true and line-buffered programs report real intervals."
493
+ : " The child's streams are plain pipes here (`isatty()` is false).";
494
+ const buffering = wrap.unbuffer
495
+ ? " Where a program's stdout is not the terminal — a stage inside a pipeline, output sent to a file — buffering is switched off through the environment for Python, Ruby, Perl and Lua (and for C-stdio programs on macOS); elsewhere such a stage may hold its lines until it flushes, so use `grep --line-buffered`, `sed -u` or `stdbuf -oL` when its timing matters."
496
+ : "";
497
+ const wrapped =
498
+ wrap.enabled && busyboxAvailable(BIN_DIR) && build?.ok !== false
499
+ ? ` Every bash command runs inside a timestamped capture (\`busybox run --timestamps\`, ${describeVerbosity(wrap.verbosity)}),`
500
+ + ` so each line comes back as "${exampleStamp(shape, "out")}" or "${exampleStamp(shape, "err", true)}" (seconds since the command started) in true arrival order:`
501
+ + " read the offsets to tell a warning printed before a failure from one printed in a block at the end,"
502
+ + ` and a burst sharing one offset is a writer that flushed at once.${compactStampsEnabled() ? ' Within such a burst the offset is printed once: "[= out]" means "the same offset as the line above".' : ""}${terminal}${buffering}`
503
+ + " A result opens with what happened only when that is not the command's own exit (`TIMEOUT`, `IDLE`, `CANCELLED`, `KILLED`); a view marked `truncated=true` shows the head and the tail, and the line after it names the omitted range and how to read it."
504
+ + " The `command` prefix runs one segment unwrapped for exact bytes (a checksum, a parser's input) — rarely worth it: it returns no timeline, no stream tags, no timing."
505
+ : "";
506
+ // The applet directory is stated only when it exists: a claim that does not match
507
+ // the PATH is worse than no claim, and the model is told not to probe.
508
+ const applets =
509
+ appletNames.length > 0
510
+ ? ` Then ${APPLET_DIR}, where ${appletNames.length} busybox applet names (xxd, hexdump, sha256sum,`
511
+ + " unzip, timeout, nproc, peek, waitfor, ...) are symlinks to the packaged busybox. `sed`, `grep`, `find`, `awk`,"
512
+ + " `tar` and `sh` are deliberately not shadowed: write `busybox sed ...` when busybox is wanted."
513
+ : "";
93
514
  cachedEnvSection = [
94
515
  `Commands run under pi's own shell, with ${BIN_DIR} first on PATH, so the packaged`,
95
- `binaries are what run${versions ? ` (${versions})` : ""}. Invoke them by bare name;`,
516
+ `binaries are what run${versions ? ` (${versions})` : ""}.${applets}${wrapped} Invoke them by bare name;`,
96
517
  "write multi-step shell logic as busybox sh -c '...'. This is already established —",
97
518
  "do not spend a turn probing it.",
98
519
  ].join(" ");
@@ -231,6 +652,11 @@ export default function (pi: ExtensionAPI) {
231
652
  // updateTools already persisted the result, including the per-tool
232
653
  // failure memory that keeps a broken tool from retrying on every
233
654
  // start. Writing again here would undo the all-failed guard.
655
+ if (installedSomething(report)) {
656
+ integrateBusybox();
657
+ // A different binary may have different flags, or pass a self-test the old one failed.
658
+ await probe().catch(() => {});
659
+ }
234
660
  const notice = updateNotice(report);
235
661
  if (ctx.hasUI) {
236
662
  if (notice) ctx.ui.notify(notice, "info");
@@ -254,7 +680,71 @@ export default function (pi: ExtensionAPI) {
254
680
  })();
255
681
  };
256
682
 
257
- pi.on("session_start", (_event, ctx) => {
683
+ /**
684
+ * Run the installed binary once, with the flags a wrapped command gets, and keep what
685
+ * it says: its feature list, whether a terminal can be had, and what a timeline line
686
+ * looks like. A binary that fails turns the wrapper off for the session, loudly —
687
+ * bash then runs as written instead of every call failing.
688
+ */
689
+ const probe = async (ctx?: ExtensionContext) => {
690
+ const wrap = readWrapSettings(process.env, verbosityOverride);
691
+ if (!wrap.enabled || !busyboxAvailable(BIN_DIR)) {
692
+ build = undefined;
693
+ return;
694
+ }
695
+ const previous = build;
696
+ build = await probeBuild({ binDir: BIN_DIR, wantPty: (ptyOverride ?? wrap.pty) !== "off" });
697
+ cachedEnvSection = undefined;
698
+ if (!ctx?.hasUI) return;
699
+ if (!build.ok && previous?.ok !== false) {
700
+ ctx.ui.notify(
701
+ `managed tools: the installed busybox failed its self-test (${build.reason ?? "no reason given"}), so bash commands run unwrapped this session. /managed-tools reinstall busybox replaces it.`,
702
+ "warning",
703
+ );
704
+ } else if (build.ok && !build.pty && (ptyOverride ?? wrap.pty) !== "off" && previous?.pty !== false) {
705
+ ctx.ui.notify("managed tools: no pseudo-terminal can be allocated here, so wrapped commands run on plain pipes.", "info");
706
+ }
707
+ };
708
+
709
+ /** Put this session's `/managed-tools` switches back, from the entry the last change wrote. */
710
+ const restoreSwitches = (ctx: ExtensionContext) => {
711
+ try {
712
+ const entries = (ctx.sessionManager as { getEntries?: () => Array<{ type: string; customType?: string; data?: unknown }> } | undefined)?.getEntries?.() ?? [];
713
+ for (const entry of entries) {
714
+ if (entry.type !== "custom" || entry.customType !== STATE_ENTRY) continue;
715
+ const data = (entry.data ?? {}) as { verbosity?: string; pty?: string };
716
+ verbosityOverride = (VERBOSITIES as readonly string[]).includes(data.verbosity ?? "") ? (data.verbosity as Verbosity) : undefined;
717
+ ptyOverride = (PTY_MODES as readonly string[]).includes(data.pty ?? "") ? (data.pty as PtyMode) : undefined;
718
+ }
719
+ } catch {
720
+ // A session that cannot be read starts from the environment, as before.
721
+ }
722
+ };
723
+
724
+ /** Record the switches, so a resumed or reloaded session keeps them. Never in the model's context. */
725
+ const rememberSwitches = () => {
726
+ try {
727
+ pi.appendEntry?.(STATE_ENTRY, { verbosity: verbosityOverride, pty: ptyOverride });
728
+ } catch {
729
+ // Not every host can append: the switch still holds for this process.
730
+ }
731
+ cachedEnvSection = undefined;
732
+ };
733
+
734
+ pi.on("session_start", async (_event, ctx) => {
735
+ // Settings from pi's own settings file, under the environment: `managedTools` there
736
+ // holds the same knobs the PI_MANAGED_TOOLS_* variables do.
737
+ applySettings((pi as { getSettings?: () => unknown }).getSettings?.());
738
+ seenNotes.clear();
739
+ userViews.length = 0;
740
+ restoreSwitches(ctx);
741
+ // Before the update check: PATH must be right even when nothing is downloaded.
742
+ integrateBusybox();
743
+ // Housekeeping: every wrapped call leaves a run directory in a root all sessions share.
744
+ sweepRuns();
745
+ await probe(ctx).catch(() => {
746
+ build = undefined;
747
+ });
258
748
  refreshInBackground(ctx);
259
749
  });
260
750
 
@@ -269,7 +759,7 @@ export default function (pi: ExtensionAPI) {
269
759
  if (!options) return;
270
760
  const current = options.promptGuidelines ?? [];
271
761
  if (!current.some((line) => line.includes(GUIDELINE_MARK))) {
272
- options.promptGuidelines = [...current, ...ENV_GUIDELINES];
762
+ options.promptGuidelines = [...current, ...envGuidelines()];
273
763
  }
274
764
  // State the environment instead of leaving it to be explored.
275
765
  const sections = options.sections ?? {};
@@ -287,15 +777,226 @@ export default function (pi: ExtensionAPI) {
287
777
  * `PI_MANAGED_TOOLS_REWRITE=off` disables it.
288
778
  */
289
779
  pi.on("tool_call", (event) => {
290
- if (!settings.rewritePaths) return;
291
780
  if (!isToolCallEventType("bash", event)) return;
292
- const { command, rewrites } = rewriteToolPaths(event.input.command, undefined, [BIN_DIR]);
293
- if (rewrites.length === 0) return;
294
- event.input.command = command;
295
- rewrittenPaths += rewrites.length;
781
+ if (settings.rewritePaths) {
782
+ // Applet names count as ours once linked: `/usr/bin/xxd` bypasses the PATH
783
+ // order exactly like `/usr/bin/jq` does.
784
+ const names =
785
+ appletNames.length > 0 ? new Set([...managedBinaryNames(), ...appletNames]) : managedBinaryNames();
786
+ const dirs = appletNames.length > 0 ? [BIN_DIR, APPLET_DIR] : [BIN_DIR];
787
+ const { command, rewrites } = rewriteToolPaths(event.input.command, names, dirs);
788
+ if (rewrites.length > 0) {
789
+ event.input.command = command;
790
+ rewrittenPaths += rewrites.length;
791
+ }
792
+ }
793
+ // The view-correctness guard: a stream merge at the command's *tail* is the
794
+ // reflex the skills ban, so it is refused before running and the model is asked
795
+ // to rewrite. Only the tail is checked (last two lines, ~24 chars each): a merge
796
+ // deep inside a script the model authored is left alone, and the honest tail
797
+ // case can declare itself with `# pitime-safe`.
798
+ if (guardEnabled() && !hasOverride(event.input.command)) {
799
+ const merge = detectTailMerge(event.input.command);
800
+ if (merge) return { block: true, reason: blockReason(merge) };
801
+ // The other thing that cannot work here: a command that only ends when somebody
802
+ // presses a key. It would sit until the deadline and come back as a TIMEOUT.
803
+ // Not for a direct `busybox …` call or the `command` escape: those are not ours.
804
+ if (!isWrapped(event.input.command) && !wantsRaw(event.input.command)) {
805
+ const endless = detectEndless(event.input.command);
806
+ if (endless) return { block: true, reason: endlessReason(endless) };
807
+ }
808
+ }
809
+ // The timeline wrapper is NOT applied here. It used to be, by rewriting
810
+ // `event.input.command` — which showed every later extension's `tool_call` handler
811
+ // the wrapper instead of what the model wrote. The bash override's `execute` does
812
+ // it now (see bashtool.ts), where pi's per-call timeout is just as available.
813
+ });
814
+
815
+ /**
816
+ * Append one line that says where the time went.
817
+ *
818
+ * The timeline already carries the offsets, but "8.4s total, silent 6.1s after the
819
+ * last line" is the sentence a reader actually needs, and it costs one line instead of
820
+ * asking the model to diff 300 timestamps. This runs on the *result*, so the model and
821
+ * the session keep it; the bash renderer strips it for the human, who has the duration
822
+ * in the footer already.
823
+ */
824
+ pi.on("tool_result", async (event, ctx) => {
825
+ if (!isBashToolResult(event)) return;
826
+ const wrap = readWrapSettings(process.env, verbosityOverride);
827
+ const command = String((event as { input?: { command?: unknown } }).input?.command ?? "");
828
+ let text = event.content
829
+ .map((part) => (part.type === "text" ? part.text : ""))
830
+ .join("\n");
831
+ const before: string[] = [];
832
+ const extra: string[] = [];
833
+
834
+ // pi keeps the LAST 2000 lines / 50 KB of what a command printed. When that cut a
835
+ // wrapped view, its first lines — the `run=` header among them — are gone, and
836
+ // with them the run id, the exit status and every notice below. They are still in
837
+ // what pi kept aside, so they are put back, and the cut is said.
838
+ let header = parseHeader(text);
839
+ const details = (event.details ?? undefined) as { truncation?: { truncated?: boolean }; fullOutputPath?: string } | undefined;
840
+ const structured = (event as { structuredContent?: { output?: unknown } }).structuredContent;
841
+ if (!header && details?.truncation?.truncated && parseTimeline(text).length > 0) {
842
+ const full = typeof structured?.output === "string" ? structured.output.slice(0, 512) : details.fullOutputPath ? readHead(details.fullOutputPath) : "";
843
+ const lost = full.split("\n").filter((line) => /^(?:run=R\d+ |timeline_lines=)/.test(line));
844
+ if (lost.length > 0 && /^run=R\d+ /.test(lost[0] as string)) {
845
+ const runId = /^run=(R\d+) /.exec(lost[0] as string)?.[1];
846
+ text = `${lost.join("\n")}\n--- timeline ---\n${text}`;
847
+ header = parseHeader(text);
848
+ extra.push(
849
+ `pi kept only the end of this view (its own 50 KB / 2000-line limit), so the lines above start partway through; the header was restored from the full output. The capture is complete: busybox log ${runId} --stream timeline --lines 1:40 reads the start, --match STR finds a literal.`,
850
+ );
851
+ }
852
+ }
853
+
854
+ // A one-liner is not a timing problem: only a run long enough to have shape earns
855
+ // the extra line.
856
+ const summary = summarizeTiming(parseTimeline(text), parseDurationMs(text));
857
+ if (summary) extra.push(summary);
858
+ // A truncated view is only useful if the model can say what it wants next — and
859
+ // only honest if it says whether the part it lacks holds errors.
860
+ if (header?.truncated) {
861
+ const stderrTotal = await stderrLineCount(header.runId, ctx?.signal).catch(() => undefined);
862
+ const hint = truncationHint(text, { stderrTotal });
863
+ if (hint) extra.push(hint);
864
+ }
865
+ // How it ended, when that was not the command's own exit, goes FIRST: a timeout
866
+ // used to open with `exit_code=-1`, then up to 48 KB of output, and only then say
867
+ // that nothing had failed.
868
+ const notice = outcomeNotice(text, wrap.timeoutSeconds || undefined, wrap.idleSeconds || undefined);
869
+ if (notice) before.push(notice);
870
+ // What the command hid from its own result — or, where the run reported it, what
871
+ // actually happened: each pipeline stage's status, the directory it ended in.
872
+ const facts = header ? readRunFacts(header.runId, ctx?.cwd) : undefined;
873
+ extra.push(
874
+ ...resultNotes(command, {
875
+ escaped: !header && wantsRaw(command),
876
+ seen: seenNotes,
877
+ facts,
878
+ exitCode: header?.exitCode,
879
+ }),
880
+ );
881
+
882
+ const body = header && compactStampsEnabled() ? compactStamps(text) : text;
883
+ if (before.length === 0 && extra.length === 0 && body === text && !header) return;
884
+ // What the header says, as data: a renderer or another extension need not parse text.
885
+ const piTime = header
886
+ ? {
887
+ run: header.runId,
888
+ exit_code: header.exitCode,
889
+ timed_out: header.timedOut,
890
+ idle: header.idle,
891
+ cancelled: header.cancelled,
892
+ duration_ms: header.durationMs,
893
+ lines_total: header.linesTotal,
894
+ lines_shown: header.linesShown,
895
+ truncated: header.truncated,
896
+ ...(facts?.pipestatus ? { pipestatus: facts.pipestatus } : {}),
897
+ ...(facts?.cwdFinal ? { cwd_final: facts.cwdFinal } : {}),
898
+ }
899
+ : undefined;
900
+ const content = [
901
+ ...(before.length > 0 ? [{ type: "text" as const, text: before.join("\n") }] : []),
902
+ { type: "text" as const, text: body },
903
+ ...(extra.length > 0 ? [{ type: "text" as const, text: extra.join("\n") }] : []),
904
+ ];
905
+ // pi types a patch per tool; this one adds a field beside pi's own, hence the cast.
906
+ return {
907
+ content,
908
+ ...(piTime ? { details: { ...(event.details ?? {}), piTime } } : {}),
909
+ // Replacing `content` alone would drop pi's structured result; keep it, with ours beside it.
910
+ ...(structured ? { structuredContent: { ...structured, ...(piTime ? { pi_time: piTime } : {}) } } : {}),
911
+ } as never;
912
+ });
913
+
914
+ /**
915
+ * What the model is sent of results it has already read (see context.ts): old
916
+ * timelines lose their offsets once a compaction has rebuilt the prompt anyway, and a
917
+ * `!` command's plain bytes are swapped for the timeline its capture took.
918
+ */
919
+ pi.on("context", (event) => {
920
+ const original = (event as { messages: ContextMessage[] }).messages;
921
+ let messages = original;
922
+ if (ageOutEnabled()) messages = ageOutMessages(messages);
923
+ messages = swapUserBash(messages, userViews);
924
+ if (messages === original) return;
925
+ return { messages } as never;
926
+ });
927
+
928
+ /**
929
+ * The human's `!` commands, through the wrapper too — pi's `user_bash` hook, which
930
+ * hands back the local backend with a wrapped command inside it.
931
+ *
932
+ * What the human gets: live streamed output (the pty line-buffers), the unbuffered
933
+ * environment, and a captured run directory they can re-read with `busybox log`.
934
+ * What they do not get: the timeline — `-q` passthrough shows the command's own
935
+ * bytes, because the reader is a person, not a model reading tags. No deadline is
936
+ * applied: a `!` command belongs to its owner, Ctrl-C included. The `command`
937
+ * escape works here too — an unwrappable call falls through to pi's normal path.
938
+ *
939
+ * And the human can answer it. pi starts every command with stdin closed, and
940
+ * `run -q` prints only at exit, so a `!` command used to show nothing until it ended
941
+ * and read end-of-file for every question (measured: `Proceed? [y/N]` took its default
942
+ * and exited 0). `interactiveExec` shows the output as it arrives and feeds what is
943
+ * typed into pi's input dialog to the guest, through `run --stdin`; see userstdin.ts.
944
+ * `PI_MANAGED_TOOLS_USER_STDIN=off` restores the old path.
945
+ */
946
+ pi.on("user_bash", (event, ctx) => {
947
+ if (!readUserWrapEnabled()) return;
948
+ const wrap = readWrapSettings(process.env, verbosityOverride);
949
+ if (!wrap.enabled || !busyboxAvailable(BIN_DIR)) return;
950
+ if (build && !build.ok) return;
951
+ const wrapUser = (command: string, live?: LiveTarget) =>
952
+ wrapCommand(command, {
953
+ busybox: busyboxBinaryPath(BIN_DIR),
954
+ shell: piShell(),
955
+ verbosity: wrap.verbosity,
956
+ pty: build && !build.pty ? "off" : "split",
957
+ // On the live path the person's screen is fed from the capture files, and what
958
+ // `run` prints at exit is kept for the model instead — so it can be the
959
+ // timeline. Without a live target `run -q` is the only output there is.
960
+ passthrough: live === undefined,
961
+ stampNs: build ? build.stampNs : true,
962
+ extraEnv: wrap.extraEnv,
963
+ ...streamOptions(wrap),
964
+ ...(live ?? {}),
965
+ });
966
+ if (!wrapUser(event.command)) return;
967
+ const local = createLocalBashOperations();
968
+ const plain: BashOperations["exec"] = (command, cwd, options) => local.exec(wrapUser(command) ?? command, cwd, options);
969
+ if (!readUserStdinEnabled()) return { operations: { exec: plain } };
970
+ return {
971
+ operations: {
972
+ exec: interactiveExec({
973
+ local,
974
+ fallback: plain,
975
+ busybox: busyboxBinaryPath(BIN_DIR),
976
+ wrap: wrapUser,
977
+ // The model reads this command as it reads its own: a timeline, with the
978
+ // digest. Kept here and swapped in by the `context` hook; the session file
979
+ // and the screen keep the plain bytes.
980
+ onView: ({ command, view, notice }) => {
981
+ if (event.excludeFromContext || !parseHeader(view)) return;
982
+ const digest = summarizeTiming(parseTimeline(view), parseDurationMs(view));
983
+ const shown = compactStampsEnabled() ? compactStamps(view) : view;
984
+ userViews.push({ command, endedAt: Date.now(), view: [shown.trimEnd(), ...(digest ? [digest] : []), ...(notice ? [notice] : [])].join("\n") });
985
+ if (userViews.length > 40) userViews.shift();
986
+ },
987
+ // Without a UI nobody can type: stdin stays empty, the output is still live.
988
+ ui: ctx?.hasUI && typeof ctx.ui?.input === "function" ? ctx.ui : undefined,
989
+ // A person gets longer than a program: five minutes to answer a question
990
+ // before the command is stopped, counted only while it waits on them.
991
+ inputTimeoutMs: readStdinTimeout() * 1000,
992
+ }) as BashOperations["exec"],
993
+ },
994
+ };
296
995
  });
297
996
 
298
997
  pi.on("session_shutdown", () => {
998
+ // Nothing this session started is left running after it.
999
+ stopAllJobs();
299
1000
  autoUpdate?.abort();
300
1001
  autoUpdate = undefined;
301
1002
  });
@@ -307,11 +1008,12 @@ export default function (pi: ExtensionAPI) {
307
1008
  `Report, update or repair the binaries pi manages for its find and grep tools (${TOOL_LIST}). ` +
308
1009
  "'status' shows installed and latest versions, which binary pi uses, and any binary that is present but cannot run; " +
309
1010
  "'update' verifies and installs the latest release in place; " +
310
- "'reinstall' forces a fresh download of one named tool, or of every damaged binary when no tool is given. " +
1011
+ "'reinstall' forces a fresh download of one named tool, or of every damaged binary when no tool is given; " +
1012
+ "'verbosity' sets how much of each bash command's timestamped output comes back for this session (quiet, normal, verbose, brief). " +
311
1013
  "Downloads are checked against the sha256 GitHub records for each release asset.",
312
1014
  promptSnippet: `Check, update or repair pi's managed binaries (${TOOL_LIST})`,
313
1015
  promptGuidelines: [
314
- `Use managed_tools when the user asks which fd, rg, bat, prek, rtk, just, gron, shellcheck, ast-grep or ninja binary pi uses, whether those tools are current, or to update them.`,
1016
+ `Use managed_tools when the user asks which fd, rg, bat, prek, just, gron, shellcheck, ast-grep or ninja binary pi uses, whether those tools are current, or to update them.`,
315
1017
  "Use managed_tools with action 'reinstall' when a managed binary is missing, corrupt, fails to execute, or the user asks to repair one; pass 'tool' to target a single binary.",
316
1018
  "Only find and grep are backed by pi built-in tools; the others are reachable from bash only.",
317
1019
  // These two are environment rules an agent gets wrong silently: an absolute
@@ -322,7 +1024,25 @@ export default function (pi: ExtensionAPI) {
322
1024
  "Wrap multi-step shell logic as busybox sh -c '...' — loops, pipelines, several statements — and use plain bash only for arrays, ${v^^} or mapfile.",
323
1025
  ],
324
1026
  parameters: Type.Object({
325
- action: Type.Union([Type.Literal("status"), Type.Literal("update"), Type.Literal("reinstall")]),
1027
+ action: Type.Union([
1028
+ Type.Literal("status"),
1029
+ Type.Literal("update"),
1030
+ Type.Literal("reinstall"),
1031
+ Type.Literal("verbosity"),
1032
+ Type.Literal("pty"),
1033
+ ]),
1034
+ pty: Type.Optional(
1035
+ Type.String({
1036
+ description:
1037
+ "For action 'pty': split (default: stdout on a pty so output streams with real timing, stderr on a pipe), merged, raw or off. A child that sees a terminal behaves differently, so this is explicit.",
1038
+ }),
1039
+ ),
1040
+ verbosity: Type.Optional(
1041
+ Type.String({
1042
+ description:
1043
+ "For action 'verbosity': quiet, normal, verbose or brief. Controls how much of each bash command's timestamped output comes back for the rest of this session.",
1044
+ }),
1045
+ ),
326
1046
  tool: Type.Optional(
327
1047
  Type.String({
328
1048
  description:
@@ -341,6 +1061,28 @@ export default function (pi: ExtensionAPI) {
341
1061
  signal,
342
1062
  userAgent: USER_AGENT,
343
1063
  };
1064
+ if (params.action === "pty") {
1065
+ const message = setPty(params.pty ?? "");
1066
+ rememberSwitches();
1067
+ // A terminal that was refused may be granted now, or the other way round.
1068
+ await probe().catch(() => {});
1069
+ return {
1070
+ content: [{ type: "text", text: message }],
1071
+ details: undefined,
1072
+ isError: message.startsWith("unknown pty mode"),
1073
+ };
1074
+ }
1075
+ if (params.action === "verbosity") {
1076
+ const message = setVerbosity(params.verbosity ?? "");
1077
+ // The section quotes the verbosity, so it has to be rebuilt next turn; and
1078
+ // the switch is recorded, so a resumed session keeps it.
1079
+ rememberSwitches();
1080
+ return {
1081
+ content: [{ type: "text", text: message }],
1082
+ details: undefined,
1083
+ isError: message.startsWith("unknown verbosity"),
1084
+ };
1085
+ }
344
1086
  if (params.action === "reinstall") {
345
1087
  const requested = params.tool ? findToolId(params.tool) : undefined;
346
1088
  if (params.tool && !requested) {
@@ -369,6 +1111,11 @@ export default function (pi: ExtensionAPI) {
369
1111
  ...options,
370
1112
  reinstall: requested ? [requested] : "damaged",
371
1113
  });
1114
+ if (installedSomething(report)) {
1115
+ integrateBusybox();
1116
+ // A different binary may have different flags, or pass a self-test the old one failed.
1117
+ await probe().catch(() => {});
1118
+ }
372
1119
  return {
373
1120
  content: [{ type: "text", text: formatUpdate(report, "reinstall") }],
374
1121
  details: undefined,
@@ -381,6 +1128,11 @@ export default function (pi: ExtensionAPI) {
381
1128
  details: undefined,
382
1129
  });
383
1130
  const report = await updateTools(options);
1131
+ if (installedSomething(report)) {
1132
+ integrateBusybox();
1133
+ // A different binary may have different flags, or pass a self-test the old one failed.
1134
+ await probe().catch(() => {});
1135
+ }
384
1136
  return {
385
1137
  content: [{ type: "text", text: formatUpdate(report) }],
386
1138
  details: undefined,
@@ -388,14 +1140,38 @@ export default function (pi: ExtensionAPI) {
388
1140
  };
389
1141
  }
390
1142
  const report = await inspectTools({ ...options, checkLatest: params.check_latest !== false });
391
- return { content: [{ type: "text", text: formatInspection(report) }], details: undefined };
1143
+ return {
1144
+ content: [
1145
+ { type: "text", text: `${formatInspection(report)}\n${appletLine()}\n${wrapLine()}${await capsSuffix()}` },
1146
+ ],
1147
+ details: undefined,
1148
+ };
392
1149
  },
393
1150
  });
394
1151
 
1152
+ registerAgentTools(pi, BIN_DIR);
1153
+ // A command that must outlive one call: a server, a watcher. pi has no background mode.
1154
+ registerJobTool(pi, BIN_DIR);
1155
+ // Re-register bash so the timeline can be shown to the model and hidden from the
1156
+ // human: pi's own runner executes, only the result renderer differs.
1157
+ registerTimelineBash(pi, { cwd: process.cwd(), wrap: wrapBashCommand });
1158
+
395
1159
  pi.registerCommand("managed-tools", {
396
1160
  description: `Show, update, or reinstall pi's managed binaries (${TOOL_LIST})`,
397
1161
  handler: async (args, ctx) => {
398
1162
  const [verb = "status", ...rest] = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
1163
+ if (verb === "pty") {
1164
+ ctx.ui.notify(setPty(rest[0] ?? ""), "info");
1165
+ rememberSwitches();
1166
+ await probe(ctx).catch(() => {});
1167
+ return;
1168
+ }
1169
+ if (verb === "verbosity") {
1170
+ const message = setVerbosity(rest[0] ?? "");
1171
+ rememberSwitches();
1172
+ ctx.ui.notify(message, message.startsWith("unknown verbosity") ? "error" : "info");
1173
+ return;
1174
+ }
399
1175
  const options = { binDir: BIN_DIR, userAgent: USER_AGENT };
400
1176
  if (verb === "reinstall") {
401
1177
  const requested = rest[0] ? findToolId(rest[0]) : undefined;
@@ -406,6 +1182,11 @@ export default function (pi: ExtensionAPI) {
406
1182
  ctx.ui.setStatus(STATUS_KEY, requested ? `reinstalling ${rest[0]}...` : `reinstalling ${TOOL_LIST}...`);
407
1183
  try {
408
1184
  const report = await updateTools({ ...options, reinstall: requested ? [requested] : "damaged" });
1185
+ if (installedSomething(report)) {
1186
+ integrateBusybox();
1187
+ // A different binary may have different flags, or pass a self-test the old one failed.
1188
+ await probe().catch(() => {});
1189
+ }
409
1190
  ctx.ui.notify(formatUpdate(report, "reinstall"), "info");
410
1191
  } catch (error) {
411
1192
  ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
@@ -418,6 +1199,11 @@ export default function (pi: ExtensionAPI) {
418
1199
  ctx.ui.setStatus(STATUS_KEY, `updating ${TOOL_LIST}...`);
419
1200
  try {
420
1201
  const report = await updateTools(options);
1202
+ if (installedSomething(report)) {
1203
+ integrateBusybox();
1204
+ // A different binary may have different flags, or pass a self-test the old one failed.
1205
+ await probe().catch(() => {});
1206
+ }
421
1207
  ctx.ui.notify(formatUpdate(report), "info");
422
1208
  } catch (error) {
423
1209
  ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
@@ -431,7 +1217,10 @@ export default function (pi: ExtensionAPI) {
431
1217
  const damaged = report.tools.filter((tool) => tool.damaged);
432
1218
  const rewritten =
433
1219
  rewrittenPaths > 0 ? `\nabsolute paths rewritten to packaged binaries: ${rewrittenPaths}` : "";
434
- ctx.ui.notify(formatInspection(report) + rewritten, damaged.length > 0 ? "warning" : "info");
1220
+ ctx.ui.notify(
1221
+ `${formatInspection(report)}\n${appletLine()}\n${wrapLine()}${await capsSuffix()}${rewritten}`,
1222
+ damaged.length > 0 ? "warning" : "info",
1223
+ );
435
1224
  } catch (error) {
436
1225
  ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
437
1226
  }