@rob-c/pi-managed-tools 0.0.0-stage → 0.16.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,440 @@
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
+ * `pi-managed-tools` - keep pi's managed binaries, and a few PATH-only extras,
18
+ * at the latest upstream release.
19
+ *
20
+ * Why this exists: pi's own tools manager downloads fd and ripgrep the first
21
+ * time `find`/`grep` need them and then never looks again, so a machine keeps
22
+ * whatever release it happened to fetch. This extension updates that copy in
23
+ * the directory pi already searches first (`<agent dir>/bin`), so the built-in
24
+ * `find` and `grep` tools - and every `bash` command, because pi prepends that
25
+ * directory to PATH - use the newer binaries without any other change.
26
+ *
27
+ * Tools with an empty `consumedBy` are not used by any pi built-in: they are
28
+ * installed for `bash` only, and are reported that way rather than implied to
29
+ * be part of pi's own tool surface.
30
+ */
31
+ import { join } from "node:path";
32
+ import { type ExtensionAPI, type ExtensionContext, VERSION, getAgentDir, isToolCallEventType } from "@earendil-works/pi-coding-agent";
33
+ import { Type } from "typebox";
34
+ import {
35
+ compareVersions,
36
+ errorMessage,
37
+ findToolId,
38
+ inspectTools,
39
+ MANAGED_TOOL_IDS,
40
+ MANAGED_TOOLS,
41
+ readSettings,
42
+ readState,
43
+ type Report,
44
+ type ToolId,
45
+ rewriteToolPaths,
46
+ shouldCheck,
47
+ type ToolReport,
48
+ updateTools,
49
+ } from "./tools.ts";
50
+
51
+ /** Same location pi's `getBinDir()` resolves, including $PI_CODING_AGENT_DIR. */
52
+ const BIN_DIR = join(getAgentDir(), "bin");
53
+ const STATUS_KEY = "pi-managed-tools";
54
+ const USER_AGENT = `@rob-c/pi-managed-tools/0.16.0 (pi ${VERSION})`;
55
+ const TOOL_LIST = MANAGED_TOOL_IDS.map((id) => MANAGED_TOOLS[id].name).join(", ");
56
+
57
+ /**
58
+ * Environment rules stated in every turn rather than only when a skill loads.
59
+ *
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.
63
+ */
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
+ ];
68
+ const GUIDELINE_MARK = "Wrap multi-step shell logic as busybox sh";
69
+
70
+ /** Absolute host paths replaced in this process, reported by /managed-tools status. */
71
+ let rewrittenPaths = 0;
72
+
73
+ const ENV_SECTION_KEY = "managed_tools_environment";
74
+ /** Models worth naming in the environment line, in the order they are used. */
75
+ const ENV_HIGHLIGHTS: ToolId[] = ["rg", "jq", "bat", "scc", "busybox"];
76
+
77
+ let cachedEnvSection: string | undefined;
78
+
79
+ /**
80
+ * The CLI facts a model would otherwise discover by exploring.
81
+ *
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.
86
+ */
87
+ function environmentSection(): string {
88
+ if (cachedEnvSection) return cachedEnvSection;
89
+ const installed = readState(BIN_DIR)?.installed ?? {};
90
+ const versions = ENV_HIGHLIGHTS.filter((id) => installed[id])
91
+ .map((id) => `${MANAGED_TOOLS[id].binaryName} ${String(installed[id]).replace(/-.*$/, "")}`)
92
+ .join(", ");
93
+ cachedEnvSection = [
94
+ `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;`,
96
+ "write multi-step shell logic as busybox sh -c '...'. This is already established —",
97
+ "do not spend a turn probing it.",
98
+ ].join(" ");
99
+ return cachedEnvSection;
100
+ }
101
+
102
+ function toolLine(tool: ToolReport, report: Report): string {
103
+ const state = tool.version ? `installed ${tool.version}` : "not installed";
104
+ const installed = tool.damaged ? `${state} - DAMAGED (${tool.damaged}); run reinstall` : state;
105
+ if (!tool.supported) {
106
+ return `${tool.name}: ${installed}; no release published for ${report.plat}/${report.architecture}`;
107
+ }
108
+ const latest = tool.latest
109
+ ? `latest ${tool.latest}`
110
+ : tool.error
111
+ ? `latest unknown (${tool.error})`
112
+ : "latest not checked";
113
+ const verdict = !tool.latest
114
+ ? ""
115
+ : !tool.version
116
+ ? " - missing, run update"
117
+ : compareVersions(tool.version, tool.latest) < 0
118
+ ? " - update available"
119
+ : " - up to date";
120
+ const where = tool.path
121
+ ? tool.path
122
+ : tool.systemPath
123
+ ? `no managed copy; pi falls back to ${tool.systemPath}`
124
+ : "no managed copy and nothing on PATH";
125
+ const consumer =
126
+ tool.consumedBy.length > 0
127
+ ? `pi ${tool.consumedBy.join("/")}`
128
+ : "PATH only - no pi built-in tool uses it";
129
+ return `${tool.name}: ${installed}; ${latest}${verdict}\n ${where}\n used by: ${consumer}`;
130
+ }
131
+
132
+ function formatInspection(report: Report): string {
133
+ const lines = [`pi managed tools - ${report.plat}/${report.architecture}`, `bin dir: ${report.binDir}`];
134
+ const unsupported = report.tools.filter((tool) => !tool.supported);
135
+ if (unsupported.length > 0) {
136
+ lines.push(`no prebuilt release for ${unsupported.map((tool) => tool.name).join(", ")} on this platform`);
137
+ }
138
+ for (const tool of report.tools) lines.push(toolLine(tool, report));
139
+ return lines.join("\n");
140
+ }
141
+
142
+ function formatUpdate(report: Report, mode: "update" | "reinstall" = "update"): string {
143
+ const lines = [`pi managed tools - ${report.plat}/${report.architecture}`];
144
+ let changed = 0;
145
+ const digest = (tool: ToolReport) => {
146
+ if (!tool.digest) return "";
147
+ // An install that went through the unverified opt-out must not be reported
148
+ // the same way as a verified one.
149
+ const state = tool.verified === false ? "UNVERIFIED" : "verified";
150
+ return ` [sha256 ${tool.digest.slice(0, 16)} ${state}]`;
151
+ };
152
+ for (const tool of report.tools) {
153
+ if (tool.action === "updated" || tool.action === "reinstalled") {
154
+ changed++;
155
+ const verb = tool.action === "reinstalled" ? "reinstalled" : "updated";
156
+ lines.push(
157
+ `${tool.name}: ${verb} ${tool.previousVersion ?? "?"} -> ${tool.version} (${tool.path})${digest(tool)}`,
158
+ );
159
+ } else if (tool.action === "installed") {
160
+ changed++;
161
+ lines.push(`${tool.name}: installed ${tool.version} (${tool.path})${digest(tool)}`);
162
+ } else if (tool.action === "failed") {
163
+ lines.push(`${tool.name}: update failed - ${tool.error ?? "unknown error"}`);
164
+ } else if (tool.action === "skipped") {
165
+ lines.push(`${tool.name}: skipped - ${tool.error ?? "unsupported platform"}`);
166
+ } else if (tool.damaged) {
167
+ lines.push(`${tool.name}: DAMAGED (${tool.damaged}) - reinstall did not run`);
168
+ } else {
169
+ lines.push(`${tool.name}: unchanged (${tool.version ?? "unknown version"})`);
170
+ }
171
+ }
172
+ if (!report.supported) lines.push("no managed binary has a prebuilt release on this platform");
173
+ if (
174
+ changed === 0 &&
175
+ report.tools.every((tool) => tool.action !== "failed") &&
176
+ report.tools.every((tool) => !tool.damaged)
177
+ ) {
178
+ lines.push(mode === "reinstall" ? "no damaged tools to reinstall" : "everything already current");
179
+ }
180
+ return lines.join("\n");
181
+ }
182
+
183
+ /** One-line TUI notice for a silent startup update, or undefined when nothing changed. */
184
+ function updateNotice(report: Report): string | undefined {
185
+ const changed = report.tools.filter((tool) => tool.action === "updated" || tool.action === "installed");
186
+ if (changed.length === 0) return undefined;
187
+ const parts = changed.map((tool) => {
188
+ const version =
189
+ tool.action === "updated"
190
+ ? `${tool.name} ${tool.previousVersion ?? "?"} -> ${tool.version}`
191
+ : `${tool.name} ${tool.version}`;
192
+ // An install that could not be digest-checked must not look like the rest.
193
+ return tool.verified === false ? `${version} (UNVERIFIED)` : version;
194
+ });
195
+ return `managed tools updated: ${parts.join(", ")}`;
196
+ }
197
+
198
+ export default function (pi: ExtensionAPI) {
199
+ const settings = readSettings();
200
+ let autoUpdate: AbortController | undefined;
201
+ let warned = false;
202
+
203
+ /**
204
+ * Look for newer releases without holding up startup.
205
+ *
206
+ * A check happens only when a managed binary is missing or the last check
207
+ * is older than the configured interval, so a normal start makes no network
208
+ * call at all.
209
+ */
210
+ const refreshInBackground = (ctx: ExtensionContext) => {
211
+ if (!settings.enabled) return;
212
+ if (!shouldCheck(readState(BIN_DIR), settings.intervalHours, BIN_DIR)) return;
213
+
214
+ autoUpdate?.abort();
215
+ autoUpdate = new AbortController();
216
+ const signal = autoUpdate.signal;
217
+
218
+ void (async () => {
219
+ const progress: ((message: string | undefined) => void) | undefined = ctx.hasUI
220
+ ? (message) => ctx.ui.setStatus(STATUS_KEY, message)
221
+ : undefined;
222
+ try {
223
+ progress?.(`checking ${TOOL_LIST} releases...`);
224
+ const report = await updateTools({
225
+ binDir: BIN_DIR,
226
+ signal,
227
+ userAgent: USER_AGENT,
228
+ onProgress: progress,
229
+ });
230
+ if (signal.aborted) return;
231
+ // updateTools already persisted the result, including the per-tool
232
+ // failure memory that keeps a broken tool from retrying on every
233
+ // start. Writing again here would undo the all-failed guard.
234
+ const notice = updateNotice(report);
235
+ if (ctx.hasUI) {
236
+ if (notice) ctx.ui.notify(notice, "info");
237
+ const failures = report.tools.filter((tool) => tool.action === "failed");
238
+ if (failures.length > 0 && !warned) {
239
+ warned = true;
240
+ ctx.ui.notify(
241
+ `managed tools: could not update ${failures.map((tool) => tool.name).join(", ")} (${failures[0]?.error})`,
242
+ "warning",
243
+ );
244
+ }
245
+ }
246
+ } catch (error) {
247
+ if (!signal.aborted && ctx.hasUI && !warned) {
248
+ warned = true;
249
+ ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "warning");
250
+ }
251
+ } finally {
252
+ progress?.(undefined);
253
+ }
254
+ })();
255
+ };
256
+
257
+ pi.on("session_start", (_event, ctx) => {
258
+ refreshInBackground(ctx);
259
+ });
260
+
261
+ /**
262
+ * Keep the two environment rules in the system prompt for every turn.
263
+ *
264
+ * Idempotent: this fires on each run, and a duplicate would be paid for on
265
+ * every turn of the session.
266
+ */
267
+ pi.on("before_agent_start", (event) => {
268
+ const options = event.systemPromptOptions;
269
+ if (!options) return;
270
+ const current = options.promptGuidelines ?? [];
271
+ if (!current.some((line) => line.includes(GUIDELINE_MARK))) {
272
+ options.promptGuidelines = [...current, ...ENV_GUIDELINES];
273
+ }
274
+ // State the environment instead of leaving it to be explored.
275
+ const sections = options.sections ?? {};
276
+ if (!sections[ENV_SECTION_KEY]) {
277
+ options.sections = { ...sections, [ENV_SECTION_KEY]: environmentSection() };
278
+ }
279
+ });
280
+
281
+ /**
282
+ * Rewrite `/usr/bin/jq` to `jq` before execution.
283
+ *
284
+ * Deterministic where prompt text is not: an absolute path bypasses both of
285
+ * pi's resolution mechanisms and pins the host's older build, and a model that
286
+ * has already decided to write one will not be talked out of it every time.
287
+ * `PI_MANAGED_TOOLS_REWRITE=off` disables it.
288
+ */
289
+ pi.on("tool_call", (event) => {
290
+ if (!settings.rewritePaths) return;
291
+ 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;
296
+ });
297
+
298
+ pi.on("session_shutdown", () => {
299
+ autoUpdate?.abort();
300
+ autoUpdate = undefined;
301
+ });
302
+
303
+ pi.registerTool({
304
+ name: "managed_tools",
305
+ label: "Managed Tools",
306
+ description:
307
+ `Report, update or repair the binaries pi manages for its find and grep tools (${TOOL_LIST}). ` +
308
+ "'status' shows installed and latest versions, which binary pi uses, and any binary that is present but cannot run; " +
309
+ "'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. " +
311
+ "Downloads are checked against the sha256 GitHub records for each release asset.",
312
+ promptSnippet: `Check, update or repair pi's managed binaries (${TOOL_LIST})`,
313
+ 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.`,
315
+ "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
+ "Only find and grep are backed by pi built-in tools; the others are reachable from bash only.",
317
+ // These two are environment rules an agent gets wrong silently: an absolute
318
+ // path pins the host's older build, and an unwrapped shell drifts to
319
+ // whichever bash the host resolved. Stated here as well as in the skill
320
+ // because a skill only loads when the model decides it is relevant.
321
+ "Invoke the packed-in binaries by bare name (rg, fd, bat, jq, scc); never by absolute path such as /usr/bin/jq or /opt/homebrew/bin/gh.",
322
+ "Wrap multi-step shell logic as busybox sh -c '...' — loops, pipelines, several statements — and use plain bash only for arrays, ${v^^} or mapfile.",
323
+ ],
324
+ parameters: Type.Object({
325
+ action: Type.Union([Type.Literal("status"), Type.Literal("update"), Type.Literal("reinstall")]),
326
+ tool: Type.Optional(
327
+ Type.String({
328
+ description:
329
+ "For reinstall: a tool name or id. Omit to replace every managed binary that is present but does not execute.",
330
+ }),
331
+ ),
332
+ check_latest: Type.Optional(
333
+ Type.Boolean({
334
+ description: "For status: query GitHub for the latest releases (default true). False reports local state only.",
335
+ }),
336
+ ),
337
+ }),
338
+ async execute(_toolCallId, params, signal, onUpdate, _ctx) {
339
+ const options = {
340
+ binDir: BIN_DIR,
341
+ signal,
342
+ userAgent: USER_AGENT,
343
+ };
344
+ if (params.action === "reinstall") {
345
+ const requested = params.tool ? findToolId(params.tool) : undefined;
346
+ if (params.tool && !requested) {
347
+ return {
348
+ content: [
349
+ { type: "text", text: `Unknown tool: ${params.tool}. Managed tools: ${TOOL_LIST}.` },
350
+ ],
351
+ details: undefined,
352
+ isError: true,
353
+ };
354
+ }
355
+ onUpdate?.({
356
+ content: [
357
+ {
358
+ type: "text",
359
+ text: requested
360
+ ? `Reinstalling ${MANAGED_TOOLS[requested].name}...`
361
+ : "Reinstalling damaged tools...",
362
+ },
363
+ ],
364
+ details: undefined,
365
+ });
366
+ // updateTools persists state itself; writing again here would defeat
367
+ // its all-failed guard and defer the next attempt for a full interval.
368
+ const report = await updateTools({
369
+ ...options,
370
+ reinstall: requested ? [requested] : "damaged",
371
+ });
372
+ return {
373
+ content: [{ type: "text", text: formatUpdate(report, "reinstall") }],
374
+ details: undefined,
375
+ isError: report.tools.some((tool) => tool.action === "failed" || tool.damaged !== undefined),
376
+ };
377
+ }
378
+ if (params.action === "update") {
379
+ onUpdate?.({
380
+ content: [{ type: "text", text: `Checking the latest ${TOOL_LIST} releases...` }],
381
+ details: undefined,
382
+ });
383
+ const report = await updateTools(options);
384
+ return {
385
+ content: [{ type: "text", text: formatUpdate(report) }],
386
+ details: undefined,
387
+ isError: report.tools.some((tool) => tool.action === "failed" || tool.damaged !== undefined),
388
+ };
389
+ }
390
+ const report = await inspectTools({ ...options, checkLatest: params.check_latest !== false });
391
+ return { content: [{ type: "text", text: formatInspection(report) }], details: undefined };
392
+ },
393
+ });
394
+
395
+ pi.registerCommand("managed-tools", {
396
+ description: `Show, update, or reinstall pi's managed binaries (${TOOL_LIST})`,
397
+ handler: async (args, ctx) => {
398
+ const [verb = "status", ...rest] = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
399
+ const options = { binDir: BIN_DIR, userAgent: USER_AGENT };
400
+ if (verb === "reinstall") {
401
+ const requested = rest[0] ? findToolId(rest[0]) : undefined;
402
+ if (rest[0] && !requested) {
403
+ ctx.ui.notify(`managed tools: unknown tool ${rest[0]}. Managed: ${TOOL_LIST}`, "error");
404
+ return;
405
+ }
406
+ ctx.ui.setStatus(STATUS_KEY, requested ? `reinstalling ${rest[0]}...` : `reinstalling ${TOOL_LIST}...`);
407
+ try {
408
+ const report = await updateTools({ ...options, reinstall: requested ? [requested] : "damaged" });
409
+ ctx.ui.notify(formatUpdate(report, "reinstall"), "info");
410
+ } catch (error) {
411
+ ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
412
+ } finally {
413
+ ctx.ui.setStatus(STATUS_KEY, undefined);
414
+ }
415
+ return;
416
+ }
417
+ if (verb === "update") {
418
+ ctx.ui.setStatus(STATUS_KEY, `updating ${TOOL_LIST}...`);
419
+ try {
420
+ const report = await updateTools(options);
421
+ ctx.ui.notify(formatUpdate(report), "info");
422
+ } catch (error) {
423
+ ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
424
+ } finally {
425
+ ctx.ui.setStatus(STATUS_KEY, undefined);
426
+ }
427
+ return;
428
+ }
429
+ try {
430
+ const report = await inspectTools({ ...options, checkLatest: verb !== "status-only" });
431
+ const damaged = report.tools.filter((tool) => tool.damaged);
432
+ const rewritten =
433
+ rewrittenPaths > 0 ? `\nabsolute paths rewritten to packaged binaries: ${rewrittenPaths}` : "";
434
+ ctx.ui.notify(formatInspection(report) + rewritten, damaged.length > 0 ? "warning" : "info");
435
+ } catch (error) {
436
+ ctx.ui.notify(`managed tools: ${errorMessage(error)}`, "error");
437
+ }
438
+ },
439
+ });
440
+ }