@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.
package/src/tools.ts ADDED
@@ -0,0 +1,1740 @@
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
+ * Keep a small set of developer binaries at the latest upstream release.
18
+ *
19
+ * pi downloads exactly two static binaries itself - fd for the `find` tool and
20
+ * ripgrep for the `grep` tool - into `<agent dir>/bin` (dist/utils/tools-manager.js,
21
+ * `getBinDir()`), and `getToolPath()` prefers that copy over anything on PATH.
22
+ * `ensureTool()` only downloads when the file is *missing*: it never resolves a
23
+ * newer release, so an install keeps whichever release it first fetched for as
24
+ * long as the file exists. This module does the part pi does not - resolve the
25
+ * latest release, compare it with the managed copy, and replace it in place.
26
+ *
27
+ * Two tools are consumed by pi itself (`consumedBy`); the rest are installed for
28
+ * `bash` only, because pi prepends this directory to every command's PATH.
29
+ *
30
+ * Nothing here imports pi packages: the extension passes in its bin directory
31
+ * and the tests run this module directly.
32
+ */
33
+ import { spawnSync } from "node:child_process";
34
+ import { createHash } from "node:crypto";
35
+ import {
36
+ chmodSync,
37
+ copyFileSync,
38
+ createWriteStream,
39
+ existsSync,
40
+ linkSync,
41
+ mkdirSync,
42
+ readFileSync,
43
+ readdirSync,
44
+ renameSync,
45
+ rmSync,
46
+ statSync,
47
+ writeFileSync,
48
+ } from "node:fs";
49
+ import { arch, platform } from "node:os";
50
+ import { delimiter, join } from "node:path";
51
+ import { Readable } from "node:stream";
52
+ import { pipeline } from "node:stream/promises";
53
+
54
+ export type ToolId =
55
+ | "fd"
56
+ | "rg"
57
+ | "bat"
58
+ | "prek"
59
+ | "rtk"
60
+ | "just"
61
+ | "gron"
62
+ | "shellcheck"
63
+ | "ast-grep"
64
+ | "ninja"
65
+ | "jq"
66
+ | "yq"
67
+ | "fzf"
68
+ | "uv"
69
+ | "gh"
70
+ | "bd"
71
+ | "agent-browser"
72
+ | "ruff"
73
+ | "mise"
74
+ | "scc"
75
+ | "duckdb"
76
+ | "miller"
77
+ | "sd"
78
+ | "difftastic"
79
+ | "busybox";
80
+
81
+ export interface ManagedTool {
82
+ id: ToolId;
83
+ /** Name used in messages, matching what pi calls the tool. */
84
+ name: string;
85
+ repo: string;
86
+ binaryName: string;
87
+ /** Release tag prefix: fd tags are `v`-prefixed, ripgrep's are not. */
88
+ tagPrefix: string;
89
+ /** Asset name, which differs between the projects. */
90
+ assetName(version: string, target: string): string;
91
+ /** Names to look for when only a system copy exists. */
92
+ systemBinaryNames: string[];
93
+ /**
94
+ * Platform gate for a tool whose release matrix is narrower than pi's.
95
+ * Defaults to `releaseTarget()`. A tool that publishes no archive for a
96
+ * platform must answer `undefined` here instead of letting the download 404.
97
+ */
98
+ resolveTarget?(plat: string, architecture: string): string | undefined;
99
+ /**
100
+ * pi built-in tools that resolve this binary through `getToolPath()`. An
101
+ * empty list means the binary is only ever reached through `bash`'s PATH.
102
+ */
103
+ consumedBy: string[];
104
+ /**
105
+ * Every binary to take from the archive, keyed by its basename in the
106
+ * archive. Defaults to `[binaryName]`. Listed names are installed unchanged.
107
+ */
108
+ provides?: string[];
109
+ /**
110
+ * Set when the upstream build cannot report its own version (`gron --version`
111
+ * prints "gron version dev"). A missing version is then not a failed install,
112
+ * and the installed version is read back from the recorded state instead.
113
+ */
114
+ versionOptional?: boolean;
115
+ /**
116
+ * The release asset IS the executable, with no archive around it (`jq` ships
117
+ * `jq-macos-arm64` and `yq` ships `yq_linux_amd64`). Such an asset is staged
118
+ * directly instead of being extracted.
119
+ */
120
+ raw?: boolean;
121
+ /**
122
+ * Set only when upstream assets predate GitHub's digest field, which would
123
+ * otherwise make the tool permanently uninstallable under a fail-closed rule.
124
+ * Such an install is reported as unverified, never as verified.
125
+ */
126
+ digestOptional?: boolean;
127
+ /**
128
+ * Set when the shipped binary's build string lags its release tag (sd reports
129
+ * "sd 1.0.0" for tag v1.1.0). The digest already proves the asset is right, so
130
+ * the tag is trusted for version comparison; otherwise every check would read
131
+ * the stale number, decide the tool is outdated, and reinstall it forever.
132
+ */
133
+ trustTagVersion?: boolean;
134
+ }
135
+
136
+ export const MANAGED_TOOLS: Record<ToolId, ManagedTool> = {
137
+ fd: {
138
+ id: "fd",
139
+ name: "fd",
140
+ repo: "sharkdp/fd",
141
+ binaryName: "fd",
142
+ tagPrefix: "v",
143
+ assetName: (version, target) => `fd-v${version}-${target}`,
144
+ systemBinaryNames: ["fd", "fdfind"],
145
+ consumedBy: ["find"],
146
+ },
147
+ rg: {
148
+ id: "rg",
149
+ name: "ripgrep",
150
+ repo: "BurntSushi/ripgrep",
151
+ binaryName: "rg",
152
+ tagPrefix: "",
153
+ assetName: (version, target) => `ripgrep-${version}-${target}`,
154
+ systemBinaryNames: ["rg"],
155
+ consumedBy: ["grep"],
156
+ },
157
+ bat: {
158
+ id: "bat",
159
+ name: "bat",
160
+ repo: "sharkdp/bat",
161
+ binaryName: "bat",
162
+ tagPrefix: "v",
163
+ assetName: (version, target) => `bat-v${version}-${target}`,
164
+ // Debian and Ubuntu install it as `batcat` to avoid clashing with `bat`.
165
+ systemBinaryNames: ["bat", "batcat"],
166
+ consumedBy: [],
167
+ },
168
+ prek: {
169
+ id: "prek",
170
+ name: "prek",
171
+ repo: "j178/prek",
172
+ binaryName: "prek",
173
+ tagPrefix: "v",
174
+ // prek publishes `prek-<target>` with no version in the filename. Tags at
175
+ // or below v0.0.22 used the old `prefligit-` prefix; `latest` never resolves one.
176
+ assetName: (_version, target) => `prek-${target}`,
177
+ systemBinaryNames: ["prek"],
178
+ consumedBy: [],
179
+ },
180
+ rtk: {
181
+ id: "rtk",
182
+ name: "rtk",
183
+ repo: "rtk-ai/rtk",
184
+ binaryName: "rtk",
185
+ tagPrefix: "v",
186
+ // `rtk-oss-<target>`, no version. The plain `rtk-<target>` build bundles a
187
+ // BUSL-1.1 engine (LICENSE-ENGINE); `rtk-oss-` is the Apache-2.0-only build
188
+ // with the same binary name and version banner. Do not switch to `rtk-`
189
+ // without changing the licence note in the README.
190
+ assetName: (_version, target) => `rtk-oss-${target}`,
191
+ systemBinaryNames: ["rtk"],
192
+ // No aarch64-pc-windows-msvc archive is published for any rtk variant.
193
+ resolveTarget: (plat, architecture) =>
194
+ plat === "win32" && architecture === "arm64" ? undefined : releaseTarget(plat, architecture),
195
+ consumedBy: [],
196
+ },
197
+ just: {
198
+ id: "just",
199
+ name: "just",
200
+ repo: "casey/just",
201
+ binaryName: "just",
202
+ // just tags are bare versions (1.59.0) and the asset repeats the version.
203
+ tagPrefix: "",
204
+ assetName: (version, target) => `just-${version}-${target}`,
205
+ systemBinaryNames: ["just"],
206
+ consumedBy: [],
207
+ },
208
+ gron: {
209
+ id: "gron",
210
+ name: "gron",
211
+ repo: "tomnomnom/gron",
212
+ binaryName: "gron",
213
+ tagPrefix: "v",
214
+ // gron names assets by OS and Go arch, not by Rust triple, and ships .tgz
215
+ // on unix and .zip on Windows: gron-darwin-arm64-0.7.1.tgz
216
+ resolveTarget: gronTarget,
217
+ assetName: (version, target) =>
218
+ `gron-${target}-${version}.${target.startsWith("windows") ? "zip" : "tgz"}`,
219
+ systemBinaryNames: ["gron"],
220
+ // Release builds print "gron version dev": no version to compare.
221
+ versionOptional: true,
222
+ // gron's newest release predates GitHub's per-asset digest field, so the
223
+ // release API returns none. Without this it could never install at all;
224
+ // the install is reported as unverified.
225
+ digestOptional: true,
226
+ consumedBy: [],
227
+ },
228
+ shellcheck: {
229
+ id: "shellcheck",
230
+ name: "shellcheck",
231
+ repo: "koalaman/shellcheck",
232
+ binaryName: "shellcheck",
233
+ tagPrefix: "v",
234
+ // shellcheck uses dot-separated OS.arch and has one arch-less zip for
235
+ // Windows x86_64: shellcheck-v0.11.0.darwin.aarch64.tar.gz, shellcheck-v0.11.0.zip
236
+ resolveTarget: shellcheckTarget,
237
+ assetName: (version, target) =>
238
+ target === "zip" ? `shellcheck-v${version}.zip` : `shellcheck-v${version}.${target}`,
239
+ systemBinaryNames: ["shellcheck"],
240
+ consumedBy: [],
241
+ },
242
+ "ast-grep": {
243
+ id: "ast-grep",
244
+ name: "ast-grep",
245
+ repo: "ast-grep/ast-grep",
246
+ binaryName: "ast-grep",
247
+ // ast-grep tags are bare versions (0.51.3).
248
+ tagPrefix: "",
249
+ // Every platform gets a zip named app-<rust triple>.zip, which holds BOTH
250
+ // `ast-grep` and the deprecated `sg` entry point.
251
+ resolveTarget: (plat, architecture) => releaseTarget(plat, architecture)?.replace(/\.tar\.gz$/, ".zip"),
252
+ assetName: (_version, target) => `app-${target}`,
253
+ provides: ["ast-grep", "sg"],
254
+ systemBinaryNames: ["ast-grep"],
255
+ consumedBy: [],
256
+ },
257
+ ninja: {
258
+ id: "ninja",
259
+ name: "ninja",
260
+ repo: "ninja-build/ninja",
261
+ binaryName: "ninja",
262
+ tagPrefix: "v",
263
+ // Arch-less names, and the macOS build is one universal2 binary that runs
264
+ // natively on x86_64 and arm64: ninja-mac.zip, ninja-linux.zip,
265
+ // ninja-linux-aarch64.zip, ninja-win.zip, ninja-winarm64.zip.
266
+ resolveTarget: ninjaTarget,
267
+ assetName: (_version, target) => `ninja-${target}.zip`,
268
+ systemBinaryNames: ["ninja"],
269
+ consumedBy: [],
270
+ },
271
+ jq: {
272
+ id: "jq",
273
+ name: "jq",
274
+ repo: "jqlang/jq",
275
+ binaryName: "jq",
276
+ // jq tags carry their own prefix (jq-1.8.2), and the assets are bare
277
+ // executables with no version in the name: jq-macos-arm64.
278
+ tagPrefix: "jq-",
279
+ resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "macos"),
280
+ assetName: (_version, target) => `jq-${target}${target.startsWith("windows") ? ".exe" : ""}`,
281
+ systemBinaryNames: ["jq"],
282
+ raw: true,
283
+ consumedBy: [],
284
+ },
285
+ yq: {
286
+ id: "yq",
287
+ name: "yq",
288
+ // mikefarah/yq, the Go rewrite (v4 CLI). The other `yq` in the ecosystem is
289
+ // kislyuk/yq, a Python wrapper with a different flag surface.
290
+ repo: "mikefarah/yq",
291
+ binaryName: "yq",
292
+ tagPrefix: "v",
293
+ resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
294
+ assetName: (_version, target) => {
295
+ const name = `yq_${target.replace("-", "_")}`;
296
+ return target.startsWith("windows") ? `${name}.exe` : name;
297
+ },
298
+ systemBinaryNames: ["yq"],
299
+ raw: true,
300
+ consumedBy: [],
301
+ },
302
+ fzf: {
303
+ id: "fzf",
304
+ name: "fzf",
305
+ repo: "junegunn/fzf",
306
+ binaryName: "fzf",
307
+ tagPrefix: "v",
308
+ resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
309
+ assetName: (version, target) => {
310
+ const name = `fzf-${version}-${target.replace("-", "_")}`;
311
+ return target.startsWith("windows") ? `${name}.zip` : `${name}.tar.gz`;
312
+ },
313
+ systemBinaryNames: ["fzf"],
314
+ consumedBy: [],
315
+ },
316
+ uv: {
317
+ id: "uv",
318
+ name: "uv",
319
+ repo: "astral-sh/uv",
320
+ binaryName: "uv",
321
+ tagPrefix: "",
322
+ // Rust triples. The archive also carries `uvx`, which is the same tool's
323
+ // tool-runner entry point, so both commands are installed.
324
+ assetName: (_version, target) => `uv-${target}`,
325
+ provides: ["uv", "uvx"],
326
+ systemBinaryNames: ["uv"],
327
+ consumedBy: [],
328
+ },
329
+ gh: {
330
+ id: "gh",
331
+ name: "gh",
332
+ repo: "cli/cli",
333
+ binaryName: "gh",
334
+ tagPrefix: "v",
335
+ // Linux ships tar.gz; macOS and Windows ship zips, so the extension is part
336
+ // of the target rather than the tool: gh_2.105.0_macOS_arm64.zip
337
+ resolveTarget: (plat, architecture) => ghTarget(plat, architecture),
338
+ assetName: (version, target) => {
339
+ const ext = target.startsWith("linux") ? ".tar.gz" : ".zip";
340
+ return `gh_${version}_${target}${ext}`;
341
+ },
342
+ systemBinaryNames: ["gh"],
343
+ consumedBy: [],
344
+ },
345
+ bd: {
346
+ id: "bd",
347
+ name: "bd",
348
+ // gastownhall/beads: a Dolt-backed issue tracker. The assets are named
349
+ // after the project but the binary is `bd`.
350
+ repo: "gastownhall/beads",
351
+ binaryName: "bd",
352
+ tagPrefix: "v",
353
+ resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
354
+ assetName: (version, target) => {
355
+ const name = `beads_${version}_${target.replace("-", "_")}`;
356
+ return target.startsWith("windows") ? `${name}.zip` : `${name}.tar.gz`;
357
+ },
358
+ systemBinaryNames: ["bd"],
359
+ consumedBy: [],
360
+ },
361
+ "agent-browser": {
362
+ id: "agent-browser",
363
+ name: "agent-browser",
364
+ repo: "vercel-labs/agent-browser",
365
+ binaryName: "agent-browser",
366
+ tagPrefix: "v",
367
+ // Bare executables, Go-style names, `.exe` on win32. No win32-arm64 asset.
368
+ resolveTarget: agentBrowserTarget,
369
+ assetName: (_version, target) =>
370
+ `agent-browser-${target}${target.startsWith("win32") ? ".exe" : ""}`,
371
+ systemBinaryNames: ["agent-browser"],
372
+ raw: true,
373
+ consumedBy: [],
374
+ },
375
+ ruff: {
376
+ id: "ruff",
377
+ name: "ruff",
378
+ repo: "astral-sh/ruff",
379
+ binaryName: "ruff",
380
+ // ruff tags are bare versions (0.17.6) and assets use Rust triples.
381
+ tagPrefix: "",
382
+ assetName: (_version, target) => `ruff-${target}`,
383
+ systemBinaryNames: ["ruff"],
384
+ consumedBy: [],
385
+ },
386
+ mise: {
387
+ id: "mise",
388
+ name: "mise",
389
+ repo: "jdx/mise",
390
+ binaryName: "mise",
391
+ tagPrefix: "v",
392
+ // Dated tags (v2026.11.11) and `x64`/`macos` naming. The archive nests the
393
+ // binary at mise/bin/mise.
394
+ resolveTarget: (plat, architecture) => osArchX64(plat, architecture, "macos"),
395
+ assetName: (version, target) =>
396
+ `mise-v${version}-${target}${target.startsWith("windows") ? ".zip" : ".tar.gz"}`,
397
+ systemBinaryNames: ["mise"],
398
+ consumedBy: [],
399
+ },
400
+ scc: {
401
+ id: "scc",
402
+ name: "scc",
403
+ repo: "boyter/scc",
404
+ binaryName: "scc",
405
+ tagPrefix: "v",
406
+ // Capitalised OS and underscore: scc_Darwin_arm64.tar.gz, scc_Windows_x86_64.zip
407
+ resolveTarget: (plat, architecture) => {
408
+ const os = plat === "darwin" ? "Darwin" : plat === "linux" ? "Linux" : plat === "win32" ? "Windows" : undefined;
409
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x86_64" : undefined;
410
+ if (!os || !cpu) return undefined;
411
+ return `${os}_${cpu}`;
412
+ },
413
+ assetName: (_version, target) =>
414
+ `scc_${target}${target.startsWith("Windows") ? ".zip" : ".tar.gz"}`,
415
+ systemBinaryNames: ["scc"],
416
+ consumedBy: [],
417
+ },
418
+ duckdb: {
419
+ id: "duckdb",
420
+ name: "duckdb",
421
+ repo: "duckdb/duckdb",
422
+ binaryName: "duckdb",
423
+ tagPrefix: "v",
424
+ // osx/linux/windows with amd64: duckdb-cli-osx-arm64.tar.gz
425
+ resolveTarget: (plat, architecture) => goTarget(plat, architecture, "osx", "amd64"),
426
+ assetName: (_version, target) => `duckdb-cli-${target}.tar.gz`,
427
+ systemBinaryNames: ["duckdb"],
428
+ consumedBy: [],
429
+ },
430
+ miller: {
431
+ id: "miller",
432
+ name: "miller",
433
+ repo: "johnkerl/miller",
434
+ binaryName: "mlr",
435
+ tagPrefix: "v",
436
+ // The asset repeats the version without its v: miller-6.22.0-darwin-arm64
437
+ resolveTarget: (plat, architecture) => goTarget(plat, architecture, "darwin", "amd64"),
438
+ assetName: (version, target) =>
439
+ `miller-${version}-${target}${target.startsWith("windows") ? ".zip" : ".tar.gz"}`,
440
+ systemBinaryNames: ["mlr"],
441
+ consumedBy: [],
442
+ },
443
+ sd: {
444
+ id: "sd",
445
+ name: "sd",
446
+ repo: "chmln/sd",
447
+ binaryName: "sd",
448
+ tagPrefix: "v",
449
+ // The asset keeps the v in its name (sd-v1.1.0-...) and there is no
450
+ // win32-arm64 build.
451
+ resolveTarget: (plat, architecture) => {
452
+ const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
453
+ if (!cpu) return undefined;
454
+ if (plat === "darwin") return `${cpu}-apple-darwin`;
455
+ if (plat === "linux") return `${cpu}-unknown-linux-musl`;
456
+ if (plat === "win32") return cpu === "x86_64" ? "x86_64-pc-windows-msvc" : undefined;
457
+ return undefined;
458
+ },
459
+ assetName: (version, target) =>
460
+ `sd-v${version}-${target}${target.includes("windows") ? ".zip" : ".tar.gz"}`,
461
+ systemBinaryNames: ["sd"],
462
+ // sd 1.1.0 ships a binary that still reports 1.0.0.
463
+ trustTagVersion: true,
464
+ consumedBy: [],
465
+ },
466
+ difftastic: {
467
+ id: "difftastic",
468
+ name: "difftastic",
469
+ repo: "Wilfred/difftastic",
470
+ binaryName: "difft",
471
+ // difftastic tags are bare versions (0.72.0).
472
+ tagPrefix: "",
473
+ // Linux arm64 publishes gnu only, so gnu is used for both linux arches.
474
+ resolveTarget: (plat, architecture) => {
475
+ const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
476
+ if (!cpu) return undefined;
477
+ if (plat === "darwin") return `${cpu}-apple-darwin`;
478
+ if (plat === "linux") return `${cpu}-unknown-linux-gnu`;
479
+ if (plat === "win32") return `${cpu}-pc-windows-msvc`;
480
+ return undefined;
481
+ },
482
+ assetName: (version, target) =>
483
+ `difft-${version}-${target}${target.includes("windows") ? ".zip" : ".tar.gz"}`,
484
+ systemBinaryNames: ["difft"],
485
+ consumedBy: [],
486
+ },
487
+ busybox: {
488
+ id: "busybox",
489
+ name: "busybox",
490
+ // rob-c/busybox-static: upstream BusyBox built static (musl/zig on Linux,
491
+ // Mach-O with Darwin port patches on macOS). Assets are bare executables.
492
+ repo: "rob-c/busybox-static",
493
+ binaryName: "busybox",
494
+ tagPrefix: "v",
495
+ // macOS ships one universal2 binary, so a single asset covers both
496
+ // architectures. There is no Windows build.
497
+ resolveTarget: (plat, architecture) => {
498
+ if (plat === "darwin") {
499
+ return architecture === "arm64" || architecture === "x64" ? "darwin-universal" : undefined;
500
+ }
501
+ if (plat === "linux") {
502
+ return architecture === "arm64" ? "linux-arm64" : architecture === "x64" ? "linux-amd64" : undefined;
503
+ }
504
+ return undefined;
505
+ },
506
+ // No v in the asset name despite the v-prefixed tag.
507
+ assetName: (version, target) => `busybox-static-${version}-${target}`,
508
+ systemBinaryNames: ["busybox"],
509
+ raw: true,
510
+ // The binary reports "BusyBox v1.39.0.git" while the tag carries the commit
511
+ // (v1.39.0-aac079e), so the tag is the only version that can be compared.
512
+ trustTagVersion: true,
513
+ consumedBy: [],
514
+ },
515
+ };
516
+
517
+ /** Same order pi's startup download uses, so messages read predictably. */
518
+ export const MANAGED_TOOL_IDS: ToolId[] = [
519
+ "fd",
520
+ "rg",
521
+ "bat",
522
+ "prek",
523
+ "rtk",
524
+ "just",
525
+ "gron",
526
+ "shellcheck",
527
+ "ast-grep",
528
+ "ninja",
529
+ "jq",
530
+ "yq",
531
+ "fzf",
532
+ "uv",
533
+ "gh",
534
+ "bd",
535
+ "agent-browser",
536
+ "ruff",
537
+ "mise",
538
+ "scc",
539
+ "duckdb",
540
+ "miller",
541
+ "sd",
542
+ "difftastic",
543
+ "busybox",
544
+ ];
545
+
546
+ /** Release target for one tool on this platform, or undefined when it has none. */
547
+ export function targetFor(tool: ManagedTool, plat: string, architecture: string): string | undefined {
548
+ return tool.resolveTarget ? tool.resolveTarget(plat, architecture) : releaseTarget(plat, architecture);
549
+ }
550
+
551
+ /** gron encodes OS and Go arch: darwin-arm64, linux-amd64, windows-arm64. */
552
+ function gronTarget(plat: string, architecture: string): string | undefined {
553
+ const os = plat === "darwin" ? "darwin" : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
554
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "amd64" : undefined;
555
+ if (!os || !cpu) return undefined;
556
+ return `${os}-${cpu}`;
557
+ }
558
+
559
+ /** os-cpu pairs for projects whose CPU label differs (x86_64 vs amd64). */
560
+ function goTarget(plat: string, architecture: string, darwinOs: string, x64: string): string | undefined {
561
+ const os =
562
+ plat === "darwin" ? darwinOs : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
563
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? x64 : undefined;
564
+ if (!os || !cpu) return undefined;
565
+ return `${os}-${cpu}`;
566
+ }
567
+
568
+ /** Go-style os-arch pairs, as jq, yq and fzf name their assets. */
569
+ function goOsArch(plat: string, architecture: string, darwinName: string): string | undefined {
570
+ const os =
571
+ plat === "darwin" ? darwinName : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
572
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "amd64" : undefined;
573
+ if (!os || !cpu) return undefined;
574
+ return `${os}-${cpu}`;
575
+ }
576
+
577
+ /** os/arch pairs where the x86_64 build is called `x64`, as mise names them. */
578
+ function osArchX64(plat: string, architecture: string, darwinName: string): string | undefined {
579
+ const os =
580
+ plat === "darwin" ? darwinName : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
581
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x64" : undefined;
582
+ if (!os || !cpu) return undefined;
583
+ return `${os}-${cpu}`;
584
+ }
585
+
586
+ /**
587
+ * agent-browser keeps the OS names lowercase and calls Windows `win32`.
588
+ *
589
+ * The plain linux asset is dynamically linked against glibc (`/lib64/ld-linux`),
590
+ * while the `linux-musl` one is statically linked and so runs on glibc and musl
591
+ * both. Verified with `file` on both linux-x64 builds.
592
+ */
593
+ function agentBrowserTarget(plat: string, architecture: string): string | undefined {
594
+ const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x64" : undefined;
595
+ if (!cpu) return undefined;
596
+ if (plat === "darwin") return `darwin-${cpu}`;
597
+ if (plat === "linux") return `linux-musl-${cpu}`;
598
+ // No win32-arm64 asset is published.
599
+ if (plat === "win32") return cpu === "x64" ? "win32-x64" : undefined;
600
+ return undefined;
601
+ }
602
+
603
+ /** gh names its macOS asset with a capital OS and an underscore. */
604
+ function ghTarget(plat: string, architecture: string): string | undefined {
605
+ const target = goOsArch(plat, architecture, "macOS");
606
+ return target?.replace("-", "_");
607
+ }
608
+
609
+ /** shellcheck encodes OS and arch with dots, and only ships an x64 zip for Windows. */
610
+ /**
611
+ * ninja publishes arch-less names, and its macOS asset is a universal2 binary,
612
+ * so one download serves both mac architectures. Linux and Windows carry a
613
+ * separate asset per architecture.
614
+ */
615
+ function ninjaTarget(plat: string, architecture: string): string | undefined {
616
+ if (plat === "darwin") return architecture === "arm64" || architecture === "x64" ? "mac" : undefined;
617
+ if (plat === "linux") return architecture === "arm64" ? "linux-aarch64" : architecture === "x64" ? "linux" : undefined;
618
+ if (plat === "win32") return architecture === "arm64" ? "winarm64" : architecture === "x64" ? "win" : undefined;
619
+ return undefined;
620
+ }
621
+
622
+ function shellcheckTarget(plat: string, architecture: string): string | undefined {
623
+ if (plat === "win32") return architecture === "x64" ? "zip" : undefined;
624
+ if (plat !== "darwin" && plat !== "linux") return undefined;
625
+ const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
626
+ if (!cpu) return undefined;
627
+ return `${plat}.${cpu}.tar.gz`;
628
+ }
629
+
630
+ const NETWORK_TIMEOUT_MS = 15_000;
631
+ const DOWNLOAD_TIMEOUT_MS = 120_000;
632
+ const STATE_FILE = ".pi-managed-tools.json";
633
+ const DEFAULT_INTERVAL_HOURS = 12;
634
+
635
+ // =============================================================================
636
+ // Platform targets
637
+ // =============================================================================
638
+
639
+ /**
640
+ * Release suffix shared by the fd and ripgrep archives. Mirrors pi's own
641
+ * `getReleaseTarget()`: only x64 and arm64 have prebuilt binaries, and an
642
+ * unknown architecture must not fall back to an x86-64 download.
643
+ */
644
+ export function releaseTarget(plat: string, architecture: string): string | undefined {
645
+ const archName = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
646
+ if (!archName) return undefined;
647
+ if (plat === "darwin") return `${archName}-apple-darwin.tar.gz`;
648
+ if (plat === "linux") return `${archName}-unknown-linux-musl.tar.gz`;
649
+ if (plat === "win32") return `${archName}-pc-windows-msvc.zip`;
650
+ return undefined;
651
+ }
652
+
653
+ export function binaryFileName(tool: ManagedTool, plat: string): string {
654
+ return tool.binaryName + (plat === "win32" ? ".exe" : "");
655
+ }
656
+
657
+ /** Path pi's `getToolPath()` checks first. */
658
+ export function managedBinaryPath(tool: ManagedTool, binDir: string, plat: string = platform()): string {
659
+ return join(binDir, binaryFileName(tool, plat));
660
+ }
661
+
662
+ // =============================================================================
663
+ // Versions
664
+ // =============================================================================
665
+
666
+ /** `fd --version` prints "fd 10.5.2"; `rg --version` prints "ripgrep 15.2.0 (rev ...)". */
667
+ export function parseVersion(output: string): string | undefined {
668
+ const match = output.match(/(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/);
669
+ return match?.[1];
670
+ }
671
+
672
+ /** Ordered compare for the "x.y.z(-prerelease)" versions these projects ship. */
673
+ export function compareVersions(a: string, b: string): number {
674
+ const [aCore, aPre] = splitVersion(a);
675
+ const [bCore, bPre] = splitVersion(b);
676
+ for (let i = 0; i < Math.max(aCore.length, bCore.length); i++) {
677
+ const left = aCore[i] ?? 0;
678
+ const right = bCore[i] ?? 0;
679
+ if (left !== right) return left < right ? -1 : 1;
680
+ }
681
+ // A release outranks any prerelease of the same core version.
682
+ if (aPre === bPre) return 0;
683
+ if (!aPre) return 1;
684
+ if (!bPre) return -1;
685
+ return aPre < bPre ? -1 : 1;
686
+ }
687
+
688
+ function splitVersion(version: string): [number[], string] {
689
+ const [core, pre = ""] = version.replace(/^v/, "").split("-", 2);
690
+ const numbers = core.split(".").map((part) => Number.parseInt(part, 10) || 0);
691
+ return [numbers, pre];
692
+ }
693
+
694
+ /**
695
+ * Run the binary once: did it execute, and did it name a version?
696
+ *
697
+ * Both halves matter. A binary that cannot execute (wrong architecture, glibc
698
+ * against a musl build, a truncated file) exits non-zero or fails to spawn, and
699
+ * a few upstreams build without embedding a version at all (`gron --version`
700
+ * prints "gron version dev"), which is not the same thing as a broken install.
701
+ */
702
+ export function probeBinary(binaryPath: string, pathDir?: string): { ran: boolean; version?: string } {
703
+ if (!existsSync(binaryPath)) return { ran: false };
704
+ // A bundled shim can delegate to a sibling in the same directory (ast-grep's
705
+ // `sg` execs `ast-grep`), so the probe may need that directory on PATH.
706
+ const env = pathDir
707
+ ? { ...process.env, PATH: [pathDir, process.env.PATH ?? ""].join(delimiter) }
708
+ : process.env;
709
+ const result = spawnSync(binaryPath, ["--version"], {
710
+ encoding: "utf-8",
711
+ timeout: 10_000,
712
+ env,
713
+ // A Windows copy is sometimes a shim that needs the real file beside it.
714
+ windowsHide: true,
715
+ });
716
+ if (result.error) return { ran: false };
717
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
718
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
719
+ return { ran: result.status === 0, version: parseVersion(stdout) ?? parseVersion(stderr) };
720
+ }
721
+
722
+ /** Version of an installed binary, or undefined when it cannot report one. */
723
+ export function readToolVersion(binaryPath: string): string | undefined {
724
+ return probeBinary(binaryPath).version;
725
+ }
726
+
727
+ /** Where a plain `fd`/`rg` in the user's PATH lives, which pi falls back to. */
728
+ export function findSystemBinary(tool: ManagedTool, plat: string = platform()): string | undefined {
729
+ const locator = plat === "win32" ? "where" : "which";
730
+ for (const name of tool.systemBinaryNames) {
731
+ const result = spawnSync(locator, [name], { encoding: "utf-8", timeout: 5000, windowsHide: true });
732
+ if (result.status !== 0 || typeof result.stdout !== "string") continue;
733
+ const first = result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)[0];
734
+ if (first) return first;
735
+ }
736
+ return undefined;
737
+ }
738
+
739
+ // =============================================================================
740
+ // Network
741
+ // =============================================================================
742
+
743
+ export interface NetworkOptions {
744
+ /** Injectable for tests; defaults to the global fetch. */
745
+ fetchImpl?: typeof fetch;
746
+ signal?: AbortSignal;
747
+ timeoutMs?: number;
748
+ userAgent?: string;
749
+ }
750
+
751
+ class HttpError extends Error {
752
+ readonly status: number;
753
+
754
+ constructor(status: number, message: string) {
755
+ super(message);
756
+ this.status = status;
757
+ }
758
+ }
759
+
760
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
761
+
762
+ /** One controller for the caller's abort signal plus our own timeout. */
763
+ function withTimeout(signal: AbortSignal | undefined, ms: number): { signal: AbortSignal; dispose(): void } {
764
+ const controller = new AbortController();
765
+ const timer = setTimeout(() => controller.abort(new Error(`timed out after ${ms}ms`)), ms);
766
+ timer.unref?.();
767
+ const onAbort = () => controller.abort(signal?.reason);
768
+ if (signal) {
769
+ if (signal.aborted) onAbort();
770
+ else signal.addEventListener("abort", onAbort, { once: true });
771
+ }
772
+ return {
773
+ signal: controller.signal,
774
+ dispose: () => {
775
+ clearTimeout(timer);
776
+ signal?.removeEventListener("abort", onAbort);
777
+ },
778
+ };
779
+ }
780
+
781
+ function isRetryable(error: unknown): boolean {
782
+ if (error instanceof HttpError) return error.status === 429 || error.status >= 500;
783
+ // Network failures surface as TypeError("fetch failed") with the cause hidden
784
+ // one level down (DNS, TLS, connection reset). An aborted request is the
785
+ // caller's own shutdown, not a transient fault.
786
+ if (error instanceof Error && error.name === "AbortError") return false;
787
+ return error instanceof TypeError;
788
+ }
789
+
790
+ async function fetchWithRetries(
791
+ url: string,
792
+ init: RequestInit,
793
+ options: NetworkOptions,
794
+ attempts = 3,
795
+ ): Promise<Response> {
796
+ const fetchImpl = options.fetchImpl ?? fetch;
797
+ let lastError: unknown;
798
+ for (let attempt = 0; attempt < attempts; attempt++) {
799
+ const timeout = withTimeout(options.signal, options.timeoutMs ?? NETWORK_TIMEOUT_MS);
800
+ try {
801
+ const response = await fetchImpl(url, {
802
+ ...init,
803
+ signal: timeout.signal,
804
+ headers: { "User-Agent": options.userAgent ?? "pi-managed-tools", ...(init.headers as object) },
805
+ });
806
+ if (response.status === 429 || response.status >= 500) {
807
+ throw new HttpError(response.status, `HTTP ${response.status} for ${url}`);
808
+ }
809
+ return response;
810
+ } catch (error) {
811
+ lastError = error;
812
+ if (options.signal?.aborted) throw error;
813
+ if (!isRetryable(error) || attempt === attempts - 1) throw error;
814
+ await sleep(500 * 2 ** attempt);
815
+ } finally {
816
+ timeout.dispose();
817
+ }
818
+ }
819
+ throw lastError;
820
+ }
821
+
822
+ /**
823
+ * Latest release tag, without the `v` prefix.
824
+ *
825
+ * The redirect from `/releases/latest` is used first because the
826
+ * api.github.com endpoint counts against the anonymous 60 requests/hour quota,
827
+ * which shared egress IPs exhaust; the API is only a fallback for the rare
828
+ * answer without a redirect.
829
+ */
830
+ export async function fetchLatestVersion(tool: ManagedTool, options: NetworkOptions = {}): Promise<string> {
831
+ const response = await fetchWithRetries(
832
+ `https://github.com/${tool.repo}/releases/latest`,
833
+ { redirect: "manual" },
834
+ options,
835
+ );
836
+ try {
837
+ await response.body?.cancel();
838
+ } catch {
839
+ // Discarding the body is best-effort.
840
+ }
841
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
842
+ if (location?.includes("/releases/tag/")) {
843
+ const tag = new URL(location, "https://github.com").pathname.split("/").pop();
844
+ if (tag) return stripTagPrefix(decodeURIComponent(tag), tool.tagPrefix);
845
+ }
846
+
847
+ const api = await fetchWithRetries(
848
+ `https://api.github.com/repos/${tool.repo}/releases/latest`,
849
+ { headers: { Accept: "application/vnd.github+json" } },
850
+ options,
851
+ );
852
+ if (!api.ok) throw new HttpError(api.status, `HTTP ${api.status} for api.github.com/${tool.repo}/releases/latest`);
853
+ const payload = (await api.json()) as { tag_name?: unknown };
854
+ if (typeof payload.tag_name !== "string") {
855
+ throw new Error(`Unexpected GitHub API response for ${tool.repo}: no tag_name`);
856
+ }
857
+ return stripTagPrefix(payload.tag_name, tool.tagPrefix);
858
+ }
859
+
860
+ /** jq tags are jq-1.8.2; most projects use a bare or v-prefixed version. */
861
+ function stripTagPrefix(tag: string, prefix: string): string {
862
+ if (prefix && tag.startsWith(prefix)) return tag.slice(prefix.length);
863
+ return tag.replace(/^v/, "");
864
+ }
865
+
866
+ function downloadUrl(tool: ManagedTool, version: string, asset: string): string {
867
+ return `https://github.com/${tool.repo}/releases/download/${tool.tagPrefix}${version}/${asset}`;
868
+ }
869
+
870
+ async function downloadFile(url: string, dest: string, options: NetworkOptions): Promise<void> {
871
+ const response = await fetchWithRetries(url, {}, { ...options, timeoutMs: DOWNLOAD_TIMEOUT_MS });
872
+ if (!response.ok) throw new HttpError(response.status, `Download failed with HTTP ${response.status}: ${url}`);
873
+ if (!response.body) throw new Error(`No response body for ${url}`);
874
+ await pipeline(Readable.fromWeb(response.body as never), createWriteStream(dest));
875
+ }
876
+
877
+ // =============================================================================
878
+ // Integrity
879
+ // =============================================================================
880
+
881
+ /** Set to `1`/`true`/`yes` to install an archive whose digest cannot be confirmed. */
882
+ const ALLOW_UNVERIFIED_ENV = "PI_MANAGED_TOOLS_ALLOW_UNVERIFIED";
883
+
884
+ /**
885
+ * Verification is fail-closed: an unreachable release API means "cannot prove",
886
+ * not "proved good". The opt-out exists for air-gapped mirrors and for the rare
887
+ * asset a project uploads without a digest.
888
+ */
889
+ export function allowUnverified(env: NodeJS.ProcessEnv = process.env): boolean {
890
+ const value = (env[ALLOW_UNVERIFIED_ENV] ?? "").trim().toLowerCase();
891
+ return value === "1" || value === "true" || value === "yes";
892
+ }
893
+
894
+ export function sha256File(path: string): string {
895
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
896
+ }
897
+
898
+ /**
899
+ * The digest GitHub recorded for one release asset, as a bare lowercase hex sha256.
900
+ *
901
+ * GitHub computes this at upload time, so it does not depend on the project
902
+ * publishing sidecar checksums - fd and bat publish none at all. Returns
903
+ * undefined when the release or the asset is not visible to the API.
904
+ */
905
+ export async function fetchAssetDigest(
906
+ tool: ManagedTool,
907
+ version: string,
908
+ asset: string,
909
+ options: NetworkOptions = {},
910
+ ): Promise<string | undefined> {
911
+ const tag = `${tool.tagPrefix}${version}`;
912
+ const url = `https://api.github.com/repos/${tool.repo}/releases/tags/${encodeURIComponent(tag)}`;
913
+ // The anonymous quota is 60 requests/hour per IP, shared with everything else
914
+ // on the host. A token is optional and only raises that limit.
915
+ const token = (process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? "").trim();
916
+ const headers: Record<string, string> = { Accept: "application/vnd.github+json" };
917
+ if (token) headers.Authorization = `Bearer ${token}`;
918
+ const response = await fetchWithRetries(url, { headers }, options);
919
+ if (!response.ok) throw new HttpError(response.status, `HTTP ${response.status} for ${url}`);
920
+ const payload = (await response.json()) as { assets?: Array<{ name?: unknown; digest?: unknown }> };
921
+ const match = payload.assets?.find((entry) => entry?.name === asset);
922
+ if (!match || typeof match.digest !== "string") return undefined;
923
+ const separator = match.digest.indexOf(":");
924
+ if (separator < 0) return undefined;
925
+ const algorithm = match.digest.slice(0, separator).toLowerCase();
926
+ const hex = match.digest.slice(separator + 1).toLowerCase();
927
+ if (algorithm !== "sha256" || !/^[0-9a-f]{64}$/.test(hex)) return undefined;
928
+ return hex;
929
+ }
930
+
931
+ /**
932
+ * Check the downloaded archive against GitHub's digest, and return the digest
933
+ * that was accepted.
934
+ *
935
+ * A `.sha256` sidecar would not be enough on its own: an attacker who can
936
+ * replace a release asset can usually replace the sidecar beside it. The digest
937
+ * comes from the release resource instead.
938
+ */
939
+ export interface VerifiedArchive {
940
+ digest: string;
941
+ /** False only when the unverified opt-out let an unconfirmed archive through. */
942
+ verified: boolean;
943
+ }
944
+
945
+ /**
946
+ * Check the downloaded archive against GitHub's digest.
947
+ *
948
+ * A `.sha256` sidecar would not be enough on its own: an attacker who can
949
+ * replace a release asset can usually replace the sidecar beside it. The digest
950
+ * comes from the release resource instead.
951
+ */
952
+ export async function verifyArchive(
953
+ tool: ManagedTool,
954
+ version: string,
955
+ asset: string,
956
+ archivePath: string,
957
+ options: NetworkOptions & { allowUnverified?: boolean } = {},
958
+ ): Promise<VerifiedArchive> {
959
+ const actual = sha256File(archivePath);
960
+ const permitted = options.allowUnverified ?? allowUnverified();
961
+ let expected: string | undefined;
962
+ try {
963
+ expected = await fetchAssetDigest(tool, version, asset, options);
964
+ } catch (error) {
965
+ if (permitted || tool.digestOptional) return { digest: actual, verified: false };
966
+ const status = error instanceof HttpError ? error.status : undefined;
967
+ const cause =
968
+ status === 403 || status === 429
969
+ ? `GitHub API rate limit or access denied (${status}); set GITHUB_TOKEN to raise the limit`
970
+ : errorMessage(error);
971
+ throw new Error(
972
+ `${tool.name}: cannot verify ${asset}: ${cause}; set ${ALLOW_UNVERIFIED_ENV}=1 to install it unverified`,
973
+ );
974
+ }
975
+ if (!expected) {
976
+ if (permitted || tool.digestOptional) return { digest: actual, verified: false };
977
+ throw new Error(
978
+ `${tool.name}: no digest published for ${asset}; set ${ALLOW_UNVERIFIED_ENV}=1 to install it unverified`,
979
+ );
980
+ }
981
+ if (expected !== actual) {
982
+ throw new Error(`${tool.name}: digest mismatch for ${asset}: expected ${expected}, got ${actual}`);
983
+ }
984
+ return { digest: actual, verified: true };
985
+ }
986
+
987
+ // =============================================================================
988
+ // Archives
989
+ // =============================================================================
990
+
991
+ function runExtraction(command: string, args: string[]): string | null {
992
+ const result = spawnSync(command, args, { encoding: "utf-8", windowsHide: true });
993
+ if (!result.error && result.status === 0) return null;
994
+ const detail = result.error?.message || String(result.stderr ?? "").trim() || `exit status ${result.status}`;
995
+ return `${command}: ${detail}`;
996
+ }
997
+
998
+ /** Windows ships bsdtar as tar.exe; Git Bash's GNU tar cannot read zip archives. */
999
+ function windowsTar(): string {
1000
+ const systemRoot = process.env.SystemRoot;
1001
+ if (systemRoot) {
1002
+ const systemTar = join(systemRoot, "System32", "tar.exe");
1003
+ if (existsSync(systemTar)) return systemTar;
1004
+ }
1005
+ return "tar.exe";
1006
+ }
1007
+
1008
+ function extractZip(archivePath: string, extractDir: string): void {
1009
+ const failures: string[] = [];
1010
+ if (process.platform === "win32") {
1011
+ const tarFailure = runExtraction(windowsTar(), ["xf", archivePath, "-C", extractDir]);
1012
+ if (!tarFailure) return;
1013
+ failures.push(tarFailure);
1014
+ const script =
1015
+ "& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }";
1016
+ const powershellFailure = runExtraction("powershell.exe", [
1017
+ "-NoLogo",
1018
+ "-NoProfile",
1019
+ "-NonInteractive",
1020
+ "-ExecutionPolicy",
1021
+ "Bypass",
1022
+ "-Command",
1023
+ script,
1024
+ archivePath,
1025
+ extractDir,
1026
+ ]);
1027
+ if (!powershellFailure) return;
1028
+ failures.push(powershellFailure);
1029
+ } else {
1030
+ const unzipFailure = runExtraction("unzip", ["-q", archivePath, "-d", extractDir]);
1031
+ if (!unzipFailure) return;
1032
+ failures.push(unzipFailure);
1033
+ const tarFailure = runExtraction("tar", ["xf", archivePath, "-C", extractDir]);
1034
+ if (!tarFailure) return;
1035
+ failures.push(tarFailure);
1036
+ }
1037
+ throw new Error(`Failed to extract ${archivePath}: ${failures.join("; ")}`);
1038
+ }
1039
+
1040
+ function findFileRecursively(rootDir: string, fileName: string): string | undefined {
1041
+ const stack = [rootDir];
1042
+ while (stack.length > 0) {
1043
+ const current = stack.pop() as string;
1044
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
1045
+ const fullPath = join(current, entry.name);
1046
+ if (entry.isFile() && entry.name === fileName) return fullPath;
1047
+ if (entry.isDirectory()) stack.push(fullPath);
1048
+ }
1049
+ }
1050
+ return undefined;
1051
+ }
1052
+
1053
+ function sleepSync(ms: number): void {
1054
+ const shared = new SharedArrayBuffer(4);
1055
+ Atomics.wait(new Int32Array(shared), 0, 0, ms);
1056
+ }
1057
+
1058
+ /**
1059
+ * Put `staged` at `target`, then prove the result runs.
1060
+ *
1061
+ * POSIX renames over the old inode atomically, so a running pi keeps using the
1062
+ * binary it already opened. Windows refuses to replace a running image, so the
1063
+ * old file is linked aside first and restored if either the swap or the version
1064
+ * probe fails. The probe matters for a class of bug the previous version shipped:
1065
+ * reporting the version we *asked for* claims success for a binary that cannot
1066
+ * execute at all (wrong arch, glibc against a musl build, a truncated download).
1067
+ */
1068
+ interface BundleEntry {
1069
+ staged: string;
1070
+ target: string;
1071
+ /** Only the tool's primary binary is required to report a version. */
1072
+ primary: boolean;
1073
+ }
1074
+
1075
+ interface BundlePlan extends BundleEntry {
1076
+ backup: string;
1077
+ hadTarget: boolean;
1078
+ hasBackup: boolean;
1079
+ }
1080
+
1081
+ /** Swap one staged file into place, tolerating Windows' refusal to replace a running image. */
1082
+ function swapIn(entry: BundleEntry, plat: string): void {
1083
+ if (plat !== "win32") {
1084
+ renameSync(entry.staged, entry.target);
1085
+ return;
1086
+ }
1087
+ let lastError: unknown;
1088
+ for (let attempt = 0; attempt < 5; attempt++) {
1089
+ try {
1090
+ rmSync(entry.target, { force: true });
1091
+ renameSync(entry.staged, entry.target);
1092
+ return;
1093
+ } catch (error) {
1094
+ lastError = error;
1095
+ sleepSync(200 * (attempt + 1));
1096
+ }
1097
+ }
1098
+ throw lastError;
1099
+ }
1100
+
1101
+ /**
1102
+ * Install every binary an archive provides, as one unit.
1103
+ *
1104
+ * One archive can carry several commands (ast-grep ships `ast-grep` and the `sg`
1105
+ * shim, which execs its sibling). Swapping them one at a time and probing only
1106
+ * the first leaves a half-repaired bundle: a new `ast-grep` beside a broken `sg`
1107
+ * reports success while the damaged command is still there. So every target is
1108
+ * backed up, every target is swapped, every target is probed, and any failure
1109
+ * restores all of them.
1110
+ */
1111
+ function installBundle(
1112
+ entries: BundleEntry[],
1113
+ plat: string,
1114
+ tool: ManagedTool,
1115
+ unique: string,
1116
+ binDir: string,
1117
+ ): string | undefined {
1118
+ const plan: BundlePlan[] = entries.map((entry) => ({
1119
+ ...entry,
1120
+ // The token keeps a concurrent pi process from overwriting this run's rollback.
1121
+ backup: `${entry.target}.${unique}.previous`,
1122
+ hadTarget: existsSync(entry.target),
1123
+ hasBackup: false,
1124
+ }));
1125
+
1126
+ for (const entry of plan) {
1127
+ if (!entry.hadTarget) continue;
1128
+ // Hardlink rather than copy: keeps the old inode reachable with no extra I/O.
1129
+ // Copy is the fallback for filesystems without hard links.
1130
+ try {
1131
+ linkSync(entry.target, entry.backup);
1132
+ entry.hasBackup = true;
1133
+ } catch {
1134
+ try {
1135
+ copyFileSync(entry.target, entry.backup);
1136
+ entry.hasBackup = true;
1137
+ } catch {
1138
+ entry.hasBackup = false;
1139
+ }
1140
+ }
1141
+ // Replacing a binary we could not back up would leave nothing to restore.
1142
+ if (!entry.hasBackup) {
1143
+ for (const previous of plan) rmSync(previous.backup, { force: true });
1144
+ throw new Error(`${tool.name}: cannot back up ${entry.target}; refusing to replace it`);
1145
+ }
1146
+ }
1147
+
1148
+ try {
1149
+ for (const entry of plan) swapIn(entry, plat);
1150
+
1151
+ let detected: string | undefined;
1152
+ for (const entry of plan) {
1153
+ const probe = probeBinary(entry.target, binDir);
1154
+ if (!probe.ran) throw new Error(`${tool.name}: installed binary did not run: ${entry.target}`);
1155
+ if (entry.primary) {
1156
+ if (!probe.version && !tool.versionOptional) {
1157
+ throw new Error(`${tool.name}: ${entry.target} reported no version; refusing to install it`);
1158
+ }
1159
+ detected = probe.version;
1160
+ }
1161
+ }
1162
+
1163
+ for (const entry of plan) rmSync(entry.backup, { force: true });
1164
+ return detected;
1165
+ } catch (error) {
1166
+ for (const entry of plan) {
1167
+ if (entry.hasBackup) {
1168
+ try {
1169
+ renameSync(entry.backup, entry.target);
1170
+ } catch {
1171
+ // Nothing further to restore from.
1172
+ }
1173
+ } else if (!entry.hadTarget) {
1174
+ // Only remove what this run created.
1175
+ rmSync(entry.target, { force: true });
1176
+ }
1177
+ }
1178
+ throw error;
1179
+ }
1180
+ }
1181
+
1182
+ // =============================================================================
1183
+ // Install
1184
+ // =============================================================================
1185
+
1186
+ export interface InstallOptions extends NetworkOptions {
1187
+ binDir: string;
1188
+ plat?: string;
1189
+ architecture?: string;
1190
+ /** Override the fail-closed digest policy for this call. */
1191
+ allowUnverified?: boolean;
1192
+ onProgress?: (message: string) => void;
1193
+ }
1194
+
1195
+ export interface InstallResult {
1196
+ path: string;
1197
+ version: string | undefined;
1198
+ /** sha256 recorded for the archive this binary came from. */
1199
+ digest?: string;
1200
+ /** False only when the unverified opt-out let an unconfirmed archive through. */
1201
+ verified?: boolean;
1202
+ }
1203
+
1204
+ /**
1205
+ * Download one release and put its binary where pi looks for it.
1206
+ *
1207
+ * The archive is fetched and extracted inside the bin directory so the final
1208
+ * rename stays on one filesystem - a rename across devices fails, and a
1209
+ * non-atomic copy could leave a truncated binary where pi expects a working
1210
+ * one.
1211
+ */
1212
+ export async function installTool(
1213
+ toolId: ToolId,
1214
+ version: string,
1215
+ options: InstallOptions,
1216
+ ): Promise<InstallResult> {
1217
+ const tool = MANAGED_TOOLS[toolId];
1218
+ const plat = options.plat ?? platform();
1219
+ const architecture = options.architecture ?? arch();
1220
+ const target = targetFor(tool, plat, architecture);
1221
+ if (!target) {
1222
+ throw new Error(`${tool.name}: no prebuilt release for ${plat}/${architecture}`);
1223
+ }
1224
+
1225
+ const asset = tool.assetName(version, target);
1226
+ const url = downloadUrl(tool, version, asset);
1227
+ const binDir = options.binDir;
1228
+ mkdirSync(binDir, { recursive: true });
1229
+
1230
+ const unique = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1231
+ const archivePath = join(binDir, `.${asset}.${unique}.download`);
1232
+ const extractDir = join(binDir, `.extract-${tool.id}-${unique}`);
1233
+ const fileName = binaryFileName(tool, plat);
1234
+ const stagedPaths: string[] = [];
1235
+
1236
+ try {
1237
+ options.onProgress?.(`downloading ${asset}`);
1238
+ await downloadFile(url, archivePath, options);
1239
+ const { digest, verified } = await verifyArchive(tool, version, asset, archivePath, options);
1240
+
1241
+ const stagedFiles: Array<{ staged: string; target: string }> = [];
1242
+ if (tool.raw) {
1243
+ // Some projects publish the executable with no archive around it (jq,
1244
+ // yq), so staging the download IS the extraction step.
1245
+ const stagedPath = join(binDir, `.${fileName}.${unique}.new`);
1246
+ renameSync(archivePath, stagedPath);
1247
+ // Registered before chmod: a failing chmod must not leak the file.
1248
+ stagedPaths.push(stagedPath);
1249
+ if (plat !== "win32") chmodSync(stagedPath, 0o755);
1250
+ stagedFiles.push({ staged: stagedPath, target: join(binDir, fileName) });
1251
+ } else {
1252
+ mkdirSync(extractDir, { recursive: true });
1253
+ if (asset.endsWith(".tar.gz") || asset.endsWith(".tgz")) {
1254
+ const failure = runExtraction("tar", ["xzf", archivePath, "-C", extractDir]);
1255
+ if (failure) throw new Error(`Failed to extract ${asset}: ${failure}`);
1256
+ } else if (asset.endsWith(".zip")) {
1257
+ extractZip(archivePath, extractDir);
1258
+ } else {
1259
+ throw new Error(`Unsupported archive format: ${asset}`);
1260
+ }
1261
+
1262
+ // One archive can provide several commands (ast-grep ships both ast-grep
1263
+ // and sg), so every declared name is staged before any is installed.
1264
+ for (const name of tool.provides ?? [tool.binaryName]) {
1265
+ const archiveName = name + (plat === "win32" ? ".exe" : "");
1266
+ const extracted = findFileRecursively(extractDir, archiveName);
1267
+ if (!extracted) throw new Error(`Binary not found in archive: expected ${archiveName} in ${asset}`);
1268
+ const stagedPath = join(binDir, `.${archiveName}.${unique}.new`);
1269
+ renameSync(extracted, stagedPath);
1270
+ stagedPaths.push(stagedPath);
1271
+ if (plat !== "win32") chmodSync(stagedPath, 0o755);
1272
+ stagedFiles.push({ staged: stagedPath, target: join(binDir, archiveName) });
1273
+ }
1274
+ }
1275
+
1276
+ const installedPath = join(binDir, fileName);
1277
+ // The whole bundle is installed and probed as one unit; see installBundle.
1278
+ const detected = installBundle(
1279
+ stagedFiles.map((entry) => ({ ...entry, primary: entry.target === installedPath })),
1280
+ plat,
1281
+ tool,
1282
+ unique,
1283
+ binDir,
1284
+ );
1285
+ stagedPaths.length = 0;
1286
+ // A tool whose build string lags its tag is recorded at the tag version.
1287
+ return {
1288
+ path: installedPath,
1289
+ version: tool.trustTagVersion ? version : (detected ?? version),
1290
+ digest,
1291
+ verified,
1292
+ };
1293
+ } finally {
1294
+ // A failed install used to leave a 0755 executable staged in the same
1295
+ // directory pi searches first.
1296
+ for (const stagedPath of stagedPaths) rmSync(stagedPath, { force: true });
1297
+ rmSync(archivePath, { force: true });
1298
+ rmSync(extractDir, { recursive: true, force: true });
1299
+ }
1300
+ }
1301
+
1302
+ // =============================================================================
1303
+ // Reports
1304
+ // =============================================================================
1305
+
1306
+ export type ToolAction = "installed" | "updated" | "reinstalled" | "unchanged" | "failed" | "skipped";
1307
+
1308
+ export interface ToolReport {
1309
+ tool: ToolId;
1310
+ name: string;
1311
+ action: ToolAction;
1312
+ /** Whether this tool publishes a release for the current platform. */
1313
+ supported: boolean;
1314
+ /** pi built-in tools that resolve this binary; empty means PATH-only. */
1315
+ consumedBy: string[];
1316
+ /** Managed binary in pi's bin directory, when one exists after the call. */
1317
+ path?: string;
1318
+ version?: string;
1319
+ previousVersion?: string;
1320
+ /** Latest upstream version, when it could be resolved. */
1321
+ latest?: string;
1322
+ systemPath?: string;
1323
+ /** sha256 recorded for the archive this binary came from. */
1324
+ digest?: string;
1325
+ /** False only when an archive could not be verified and the opt-out allowed it. */
1326
+ verified?: boolean;
1327
+ /** Set when the installed binary is present but cannot execute. */
1328
+ damaged?: string;
1329
+ error?: string;
1330
+ }
1331
+
1332
+ export interface Report {
1333
+ plat: string;
1334
+ architecture: string;
1335
+ supported: boolean;
1336
+ binDir: string;
1337
+ checkedAt: number;
1338
+ tools: ToolReport[];
1339
+ }
1340
+
1341
+ interface SharedOptions extends NetworkOptions {
1342
+ binDir: string;
1343
+ plat?: string;
1344
+ architecture?: string;
1345
+ /** Override the fail-closed digest policy for this call. */
1346
+ allowUnverified?: boolean;
1347
+ }
1348
+
1349
+ function localState(tool: ManagedTool, binDir: string, plat: string, state: CheckState | undefined) {
1350
+ const path = managedBinaryPath(tool, binDir, plat);
1351
+ const installed = existsSync(path);
1352
+ // Every name the archive provides is checked, not just the primary: a bundled
1353
+ // shim can rot on its own (ast-grep's `sg` execs its sibling and breaks if that
1354
+ // sibling is replaced by something that is not there or will not run).
1355
+ const problems: string[] = [];
1356
+ let version: string | undefined;
1357
+ for (const name of tool.provides ?? [tool.binaryName]) {
1358
+ const binaryPath = join(binDir, name + (plat === "win32" ? ".exe" : ""));
1359
+ const isPrimary = binaryPath === path;
1360
+ if (!existsSync(binaryPath)) {
1361
+ // A missing primary is "not installed". A missing secondary only counts
1362
+ // when the primary is there: otherwise this is a fresh install, not
1363
+ // damage, and a repair would never be the right action.
1364
+ if (!isPrimary && installed) problems.push(`${name} missing`);
1365
+ continue;
1366
+ }
1367
+ // Check the size before trusting the probe: Linux falls back to /bin/sh for a
1368
+ // file without a valid executable header, so a zero-length binary "runs" and
1369
+ // exits 0 there while macOS reports ENOEXEC. Neither should read as healthy.
1370
+ if (statSync(binaryPath).size === 0) {
1371
+ problems.push(`${name} is empty`);
1372
+ continue;
1373
+ }
1374
+ const probe = probeBinary(binaryPath, binDir);
1375
+ if (!probe.ran) problems.push(`${name} does not execute`);
1376
+ if (isPrimary) version = probe.version;
1377
+ }
1378
+ const recorded = installed ? state?.installed?.[tool.id] : undefined;
1379
+ // For a tool that misreports its own build number, the recorded release tag is
1380
+ // the only trustworthy version; otherwise every check would reinstall it.
1381
+ const installedVersion = tool.trustTagVersion ? (recorded ?? version) : (version ?? recorded);
1382
+ return {
1383
+ path: installed ? path : undefined,
1384
+ version: installedVersion,
1385
+ damaged: problems.length > 0 ? problems.join(", ") : undefined,
1386
+ systemPath: findSystemBinary(tool, plat),
1387
+ };
1388
+ }
1389
+
1390
+ /** Resolve a user-supplied tool name or id, for the reinstall argument. */
1391
+ export function findToolId(name: string): ToolId | undefined {
1392
+ const wanted = name.trim().toLowerCase();
1393
+ if (!wanted) return undefined;
1394
+ return MANAGED_TOOL_IDS.find((id) => {
1395
+ const tool = MANAGED_TOOLS[id];
1396
+ const names = [id, tool.name.toLowerCase(), ...(tool.provides ?? []).map((provided) => provided.toLowerCase())];
1397
+ return names.includes(wanted);
1398
+ });
1399
+ }
1400
+
1401
+ export async function inspectTools(options: SharedOptions & { checkLatest?: boolean }): Promise<Report> {
1402
+ const plat = options.plat ?? platform();
1403
+ const architecture = options.architecture ?? arch();
1404
+ const checkedAt = Date.now();
1405
+ const state = readState(options.binDir);
1406
+
1407
+ const tools = await Promise.all(
1408
+ MANAGED_TOOL_IDS.map(async (toolId): Promise<ToolReport> => {
1409
+ const tool = MANAGED_TOOLS[toolId];
1410
+ const local = localState(tool, options.binDir, plat, state);
1411
+ const supported = targetFor(tool, plat, architecture) !== undefined;
1412
+ const report: ToolReport = {
1413
+ tool: toolId,
1414
+ name: tool.name,
1415
+ action: "unchanged",
1416
+ supported,
1417
+ consumedBy: [...tool.consumedBy],
1418
+ path: local.path,
1419
+ version: local.version,
1420
+ damaged: local.damaged,
1421
+ systemPath: local.systemPath,
1422
+ };
1423
+ if (options.checkLatest === false || !supported) return report;
1424
+ try {
1425
+ report.latest = await fetchLatestVersion(tool, options);
1426
+ } catch (error) {
1427
+ report.error = errorMessage(error);
1428
+ }
1429
+ return report;
1430
+ }),
1431
+ );
1432
+
1433
+ return {
1434
+ plat,
1435
+ architecture,
1436
+ supported: tools.some((tool) => tool.supported),
1437
+ binDir: options.binDir,
1438
+ checkedAt,
1439
+ tools,
1440
+ };
1441
+ }
1442
+
1443
+ export type ReinstallRequest = "damaged" | "all" | ToolId[];
1444
+
1445
+ export async function updateTools(
1446
+ options: SharedOptions & { onProgress?: (message: string) => void; reinstall?: ReinstallRequest },
1447
+ ): Promise<Report> {
1448
+ const plat = options.plat ?? platform();
1449
+ const architecture = options.architecture ?? arch();
1450
+ const checkedAt = Date.now();
1451
+ const force = options.reinstall;
1452
+
1453
+ const tools: ToolReport[] = [];
1454
+ const state = readState(options.binDir);
1455
+ for (const toolId of MANAGED_TOOL_IDS) {
1456
+ const tool = MANAGED_TOOLS[toolId];
1457
+ const local = localState(tool, options.binDir, plat, state);
1458
+ const target = targetFor(tool, plat, architecture);
1459
+ const report: ToolReport = {
1460
+ tool: toolId,
1461
+ name: tool.name,
1462
+ action: "unchanged",
1463
+ supported: target !== undefined,
1464
+ consumedBy: [...tool.consumedBy],
1465
+ path: local.path,
1466
+ version: local.version,
1467
+ damaged: local.damaged,
1468
+ systemPath: local.systemPath,
1469
+ };
1470
+ tools.push(report);
1471
+
1472
+ if (!target) {
1473
+ report.action = "skipped";
1474
+ report.error = `no prebuilt release for ${plat}/${architecture}`;
1475
+ continue;
1476
+ }
1477
+
1478
+ // A forced reinstall ignores the version comparison: the point is to replace
1479
+ // a file that is broken, not one that is merely older.
1480
+ const forced =
1481
+ force === "all" ||
1482
+ (force === "damaged" ? local.damaged !== undefined : Array.isArray(force) && force.includes(toolId));
1483
+ const wasDamaged = local.damaged !== undefined;
1484
+
1485
+ try {
1486
+ report.latest = await fetchLatestVersion(tool, options);
1487
+ } catch (error) {
1488
+ // Reinstalling still works offline from the version already on disk, which
1489
+ // is exactly when a repair is most likely to be needed.
1490
+ if (!forced || !report.version) {
1491
+ report.action = "failed";
1492
+ report.error = errorMessage(error);
1493
+ continue;
1494
+ }
1495
+ report.latest = report.version;
1496
+ }
1497
+
1498
+ // A damaged binary is never "up to date", whatever version it claims. The
1499
+ // state fallback supplies a version for a tool that cannot self-report, so
1500
+ // without this check a broken gron would compare equal and never be fixed.
1501
+ if (
1502
+ !forced &&
1503
+ !wasDamaged &&
1504
+ report.version &&
1505
+ compareVersions(report.version, report.latest) >= 0
1506
+ ) {
1507
+ continue;
1508
+ }
1509
+
1510
+ try {
1511
+ const result = await installTool(toolId, report.latest, options);
1512
+ report.previousVersion = report.version;
1513
+ report.version = result.version;
1514
+ report.path = result.path;
1515
+ report.digest = result.digest;
1516
+ report.verified = result.verified;
1517
+ // The probe that matters is the one installBinary just ran.
1518
+ report.damaged = undefined;
1519
+ report.action = forced || wasDamaged ? "reinstalled" : report.previousVersion ? "updated" : "installed";
1520
+ } catch (error) {
1521
+ report.action = "failed";
1522
+ report.error = errorMessage(error);
1523
+ }
1524
+ }
1525
+
1526
+ const report: Report = {
1527
+ plat,
1528
+ architecture,
1529
+ supported: tools.some((tool) => tool.supported),
1530
+ binDir: options.binDir,
1531
+ checkedAt,
1532
+ tools,
1533
+ };
1534
+ // Persist here rather than leaving it to the caller: a tool that cannot report
1535
+ // its own version (gron) is compared against this record, so a caller that
1536
+ // forgets to write it reinstalls that tool on every single run.
1537
+ //
1538
+ // An all-failed run does not advance the timestamp: otherwise one rate-limited
1539
+ // or offline cycle would defer the next attempt for the whole interval, which
1540
+ // is the opposite of what a broken machine needs.
1541
+ const supportedReports = tools.filter((tool) => tool.supported);
1542
+ const allFailed = supportedReports.length > 0 && supportedReports.every((tool) => tool.action === "failed");
1543
+ writeState(options.binDir, report, { advance: !allFailed });
1544
+ return report;
1545
+ }
1546
+
1547
+ export function errorMessage(error: unknown): string {
1548
+ if (error instanceof Error) {
1549
+ const messages = [error.message];
1550
+ for (let current = error.cause, depth = 0; current instanceof Error && depth < 3; current = current.cause, depth++) {
1551
+ if (!messages.includes(current.message)) messages.push(current.message);
1552
+ }
1553
+ return messages.join(": ");
1554
+ }
1555
+ return String(error);
1556
+ }
1557
+
1558
+ // =============================================================================
1559
+ // Check state and settings
1560
+ // =============================================================================
1561
+
1562
+ export interface CheckState {
1563
+ checkedAt: number;
1564
+ latest: Partial<Record<ToolId, string>>;
1565
+ /**
1566
+ * Versions this package last installed. A tool whose binary cannot report its
1567
+ * own version (gron) is compared against this instead, so it is not reinstalled
1568
+ * on every check.
1569
+ */
1570
+ installed?: Partial<Record<ToolId, string>>;
1571
+ /**
1572
+ * Last failure per tool. Without this a tool that cannot install on this host
1573
+ * (no digest published, wrong libc, an upstream rename) keeps its binary
1574
+ * missing, and a missing binary forces a full update cycle on every start.
1575
+ */
1576
+ failures?: Partial<Record<ToolId, { at: number; reason: string }>>;
1577
+ /** sha256 accepted for the installed binary, so a later check can compare. */
1578
+ digests?: Partial<Record<ToolId, string>>;
1579
+ /** Tools whose installed binary was never confirmed against a digest. */
1580
+ unverified?: Partial<Record<ToolId, boolean>>;
1581
+ }
1582
+
1583
+ export function statePath(binDir: string): string {
1584
+ return join(binDir, STATE_FILE);
1585
+ }
1586
+
1587
+ export function readState(binDir: string): CheckState | undefined {
1588
+ try {
1589
+ const parsed = JSON.parse(readFileSync(statePath(binDir), "utf-8")) as Partial<CheckState>;
1590
+ if (typeof parsed?.checkedAt !== "number") return undefined;
1591
+ return {
1592
+ checkedAt: parsed.checkedAt,
1593
+ latest: parsed.latest ?? {},
1594
+ installed: parsed.installed ?? {},
1595
+ failures: parsed.failures ?? {},
1596
+ digests: parsed.digests ?? {},
1597
+ unverified: parsed.unverified ?? {},
1598
+ };
1599
+ } catch {
1600
+ return undefined;
1601
+ }
1602
+ }
1603
+
1604
+ export function writeState(binDir: string, report: Report, options: { advance?: boolean } = {}): void {
1605
+ try {
1606
+ mkdirSync(binDir, { recursive: true });
1607
+ const previous = readState(binDir);
1608
+ const latest: Partial<Record<ToolId, string>> = { ...previous?.latest };
1609
+ for (const tool of report.tools) if (tool.latest) latest[tool.tool] = tool.latest;
1610
+ // Only overwrite an installed version with a version we actually saw; a
1611
+ // status check that resolved nothing must not erase it.
1612
+ const installed: Partial<Record<ToolId, string>> = { ...previous?.installed };
1613
+ for (const tool of report.tools) if (tool.version) installed[tool.tool] = tool.version;
1614
+ const failures: Partial<Record<ToolId, { at: number; reason: string }>> = { ...previous?.failures };
1615
+ const digests: Partial<Record<ToolId, string>> = { ...previous?.digests };
1616
+ const unverified: Partial<Record<ToolId, boolean>> = { ...previous?.unverified };
1617
+ for (const tool of report.tools) {
1618
+ if (tool.action === "failed") {
1619
+ failures[tool.tool] = { at: report.checkedAt, reason: tool.error ?? "unknown error" };
1620
+ } else if (tool.action !== "skipped") {
1621
+ // Any other outcome means the tool is usable; forget the failure.
1622
+ delete failures[tool.tool];
1623
+ }
1624
+ if (tool.digest) digests[tool.tool] = tool.digest;
1625
+ if (tool.verified === false) unverified[tool.tool] = true;
1626
+ else if (tool.verified === true) delete unverified[tool.tool];
1627
+ }
1628
+ // A run where everything failed still records per-tool failures, so a host
1629
+ // that cannot install a tool stops retrying it, but it must not move
1630
+ // checkedAt: that would defer the next real attempt for a whole interval.
1631
+ const checkedAt = options.advance === false ? (previous?.checkedAt ?? report.checkedAt) : report.checkedAt;
1632
+ const state: CheckState = { checkedAt, latest, installed, failures, digests, unverified };
1633
+ const path = statePath(binDir);
1634
+ const temporary = `${path}.${process.pid}.tmp`;
1635
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`);
1636
+ renameSync(temporary, path);
1637
+ } catch {
1638
+ // A missing state file only costs an extra check next start.
1639
+ }
1640
+ }
1641
+
1642
+ /**
1643
+ * Whether to look for newer releases now. A missing managed binary always
1644
+ * triggers a check: pi would otherwise download it itself with no version
1645
+ * comparison at all.
1646
+ */
1647
+ export function shouldCheck(
1648
+ state: CheckState | undefined,
1649
+ intervalHours: number,
1650
+ binDir: string,
1651
+ plat: string = platform(),
1652
+ architecture: string = arch(),
1653
+ now = Date.now(),
1654
+ ): boolean {
1655
+ if (intervalHours <= 0) return true;
1656
+ const intervalMs = intervalHours * 60 * 60 * 1000;
1657
+ for (const toolId of MANAGED_TOOL_IDS) {
1658
+ const tool = MANAGED_TOOLS[toolId];
1659
+ // A tool with no release for this platform can never be installed here, so
1660
+ // its missing binary must not force a network check on every single start.
1661
+ if (targetFor(tool, plat, architecture) === undefined) continue;
1662
+ if (existsSync(managedBinaryPath(tool, binDir, plat))) continue;
1663
+ // Same reasoning for a tool that just failed: retrying it on every start
1664
+ // turns one uninstallable tool into a full download cycle each time.
1665
+ const failure = state?.failures?.[toolId];
1666
+ if (failure && now - failure.at >= 0 && now - failure.at < intervalMs) continue;
1667
+ return true;
1668
+ }
1669
+ if (!state) return true;
1670
+ const elapsed = now - state.checkedAt;
1671
+ return !(elapsed >= 0 && elapsed < intervalMs);
1672
+ }
1673
+
1674
+ export interface ToolSettings {
1675
+ enabled: boolean;
1676
+ intervalHours: number;
1677
+ /** Rewrite absolute host paths to bare names on bash tool calls. */
1678
+ rewritePaths: boolean;
1679
+ }
1680
+
1681
+ /** Every name this package installs, including provided secondaries (sg, uvx). */
1682
+ export function managedBinaryNames(): Set<string> {
1683
+ const names = new Set<string>();
1684
+ for (const id of MANAGED_TOOL_IDS) {
1685
+ const tool = MANAGED_TOOLS[id];
1686
+ names.add(tool.binaryName);
1687
+ for (const name of tool.provides ?? []) names.add(name);
1688
+ }
1689
+ return names;
1690
+ }
1691
+
1692
+ const HOST_BIN_DIRS = ["/usr/bin", "/bin", "/usr/local/bin", "/opt/homebrew/bin"];
1693
+
1694
+ function escapeRegExp(value: string): string {
1695
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1696
+ }
1697
+
1698
+ /**
1699
+ * Replace an absolute host path for a managed tool with its bare name.
1700
+ *
1701
+ * `/usr/bin/jq -r .a` becomes `jq -r .a`, so the packaged binary runs instead of
1702
+ * the host's older build. Only a token in command position is touched (start of
1703
+ * string, or after whitespace, `;`, `|`, `&`, `(`), so `echo "/usr/bin/jq"` is
1704
+ * left alone, and only names this package manages, so `/usr/bin/tar` is untouched.
1705
+ */
1706
+ export function rewriteToolPaths(
1707
+ command: string,
1708
+ names: Set<string> = managedBinaryNames(),
1709
+ extraDirs: string[] = [],
1710
+ ): { command: string; rewrites: string[] } {
1711
+ const rewrites: string[] = [];
1712
+ let out = command;
1713
+ for (const dir of [...HOST_BIN_DIRS, ...extraDirs]) {
1714
+ const pattern = new RegExp(`(^|[\\s;|&(])${escapeRegExp(dir)}/([A-Za-z0-9._+-]+)`, "g");
1715
+ out = out.replace(pattern, (match, lead: string, name: string) => {
1716
+ if (!names.has(name)) return match;
1717
+ rewrites.push(`${dir}/${name}`);
1718
+ return `${lead}${name}`;
1719
+ });
1720
+ }
1721
+ return { command: out, rewrites };
1722
+ }
1723
+
1724
+ function isOffline(env: NodeJS.ProcessEnv): boolean {
1725
+ const value = (env.PI_OFFLINE ?? "").toLowerCase();
1726
+ return value === "1" || value === "true" || value === "yes";
1727
+ }
1728
+
1729
+ export function readSettings(env: NodeJS.ProcessEnv = process.env): ToolSettings {
1730
+ const raw = (env.PI_MANAGED_TOOLS ?? "").trim().toLowerCase();
1731
+ const disabled = raw === "0" || raw === "off" || raw === "false" || raw === "no";
1732
+ const interval = Number(env.PI_MANAGED_TOOLS_INTERVAL_HOURS);
1733
+ const rewriteRaw = (env.PI_MANAGED_TOOLS_REWRITE ?? "").trim().toLowerCase();
1734
+ const rewriteOff = rewriteRaw === "0" || rewriteRaw === "off" || rewriteRaw === "false" || rewriteRaw === "no";
1735
+ return {
1736
+ enabled: !disabled && !isOffline(env),
1737
+ intervalHours: Number.isFinite(interval) && interval >= 0 ? interval : DEFAULT_INTERVAL_HOURS,
1738
+ rewritePaths: !rewriteOff,
1739
+ };
1740
+ }