@rob-c/pi-managed-tools 0.0.0-stage → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BUSYBOX-CONTRACT.md +440 -0
- package/CHANGELOG.md +775 -0
- package/LICENSE +338 -0
- package/README.md +849 -2
- package/package.json +79 -5
- package/skills/busybox-applets/SKILL.md +266 -0
- package/skills/managed-tools/SKILL.md +328 -0
- package/skills/managed-tools-reference/SKILL.md +738 -0
- package/src/agentops.ts +813 -0
- package/src/agenttools.ts +391 -0
- package/src/bashtool.ts +103 -0
- package/src/build.ts +142 -0
- package/src/context.ts +157 -0
- package/src/display.ts +79 -0
- package/src/extension.ts +1229 -0
- package/src/guard.ts +437 -0
- package/src/jobs.ts +1052 -0
- package/src/timing.ts +364 -0
- package/src/tools.ts +2223 -0
- package/src/userstdin.ts +524 -0
- package/src/wrap.ts +683 -0
package/src/tools.ts
ADDED
|
@@ -0,0 +1,2223 @@
|
|
|
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
|
+
lstatSync,
|
|
42
|
+
mkdirSync,
|
|
43
|
+
readFileSync,
|
|
44
|
+
readdirSync,
|
|
45
|
+
readlinkSync,
|
|
46
|
+
renameSync,
|
|
47
|
+
rmSync,
|
|
48
|
+
statSync,
|
|
49
|
+
symlinkSync,
|
|
50
|
+
writeFileSync,
|
|
51
|
+
} from "node:fs";
|
|
52
|
+
import { arch, platform } from "node:os";
|
|
53
|
+
import { delimiter, join } from "node:path";
|
|
54
|
+
import { Readable } from "node:stream";
|
|
55
|
+
import { pipeline } from "node:stream/promises";
|
|
56
|
+
|
|
57
|
+
export type ToolId =
|
|
58
|
+
| "fd"
|
|
59
|
+
| "rg"
|
|
60
|
+
| "bat"
|
|
61
|
+
| "prek"
|
|
62
|
+
| "just"
|
|
63
|
+
| "gron"
|
|
64
|
+
| "shellcheck"
|
|
65
|
+
| "ast-grep"
|
|
66
|
+
| "ninja"
|
|
67
|
+
| "jq"
|
|
68
|
+
| "yq"
|
|
69
|
+
| "fzf"
|
|
70
|
+
| "uv"
|
|
71
|
+
| "gh"
|
|
72
|
+
| "bd"
|
|
73
|
+
| "agent-browser"
|
|
74
|
+
| "ruff"
|
|
75
|
+
| "mise"
|
|
76
|
+
| "scc"
|
|
77
|
+
| "duckdb"
|
|
78
|
+
| "miller"
|
|
79
|
+
| "sd"
|
|
80
|
+
| "difftastic"
|
|
81
|
+
| "busybox";
|
|
82
|
+
|
|
83
|
+
export interface ManagedTool {
|
|
84
|
+
id: ToolId;
|
|
85
|
+
/** Name used in messages, matching what pi calls the tool. */
|
|
86
|
+
name: string;
|
|
87
|
+
repo: string;
|
|
88
|
+
binaryName: string;
|
|
89
|
+
/** Release tag prefix: fd tags are `v`-prefixed, ripgrep's are not. */
|
|
90
|
+
tagPrefix: string;
|
|
91
|
+
/** Asset name, which differs between the projects. */
|
|
92
|
+
assetName(version: string, target: string): string;
|
|
93
|
+
/**
|
|
94
|
+
* Asset selection for a project whose asset names do not follow its release version.
|
|
95
|
+
*
|
|
96
|
+
* busybox-static tags releases with the project version (v0.4.0) while the assets
|
|
97
|
+
* keep the upstream build version
|
|
98
|
+
* (busybox-static-1.39.0-aac079e-darwin-universal), so there is nothing to construct
|
|
99
|
+
* from the tag: the matching name comes from the release's own asset list. Must not
|
|
100
|
+
* be a global regex.
|
|
101
|
+
*/
|
|
102
|
+
assetPattern?(target: string): RegExp;
|
|
103
|
+
/**
|
|
104
|
+
* Versions recorded under a superseded naming scheme, older than any release of the
|
|
105
|
+
* current one. busybox-static shipped 1.39.0-aac079e and 0.3.0-dev before settling
|
|
106
|
+
* on 0.4.0, and 1.39.0 sorts *above* 0.4.0, so without this a stored 1.39.0-aac079e
|
|
107
|
+
* looks newer than every future release and is never replaced.
|
|
108
|
+
*/
|
|
109
|
+
legacyVersionPattern?: RegExp;
|
|
110
|
+
/** Names to look for when only a system copy exists. */
|
|
111
|
+
systemBinaryNames: string[];
|
|
112
|
+
/**
|
|
113
|
+
* Platform gate for a tool whose release matrix is narrower than pi's.
|
|
114
|
+
* Defaults to `releaseTarget()`. A tool that publishes no archive for a
|
|
115
|
+
* platform must answer `undefined` here instead of letting the download 404.
|
|
116
|
+
*/
|
|
117
|
+
resolveTarget?(plat: string, architecture: string): string | undefined;
|
|
118
|
+
/**
|
|
119
|
+
* pi built-in tools that resolve this binary through `getToolPath()`. An
|
|
120
|
+
* empty list means the binary is only ever reached through `bash`'s PATH.
|
|
121
|
+
*/
|
|
122
|
+
consumedBy: string[];
|
|
123
|
+
/**
|
|
124
|
+
* Every binary to take from the archive, keyed by its basename in the
|
|
125
|
+
* archive. Defaults to `[binaryName]`. Listed names are installed unchanged.
|
|
126
|
+
*/
|
|
127
|
+
provides?: string[];
|
|
128
|
+
/**
|
|
129
|
+
* Set when the upstream build cannot report its own version (`gron --version`
|
|
130
|
+
* prints "gron version dev"). A missing version is then not a failed install,
|
|
131
|
+
* and the installed version is read back from the recorded state instead.
|
|
132
|
+
*/
|
|
133
|
+
versionOptional?: boolean;
|
|
134
|
+
/**
|
|
135
|
+
* The release asset IS the executable, with no archive around it (`jq` ships
|
|
136
|
+
* `jq-macos-arm64` and `yq` ships `yq_linux_amd64`). Such an asset is staged
|
|
137
|
+
* directly instead of being extracted.
|
|
138
|
+
*/
|
|
139
|
+
raw?: boolean;
|
|
140
|
+
/**
|
|
141
|
+
* Set only when upstream assets predate GitHub's digest field, which would
|
|
142
|
+
* otherwise make the tool permanently uninstallable under a fail-closed rule.
|
|
143
|
+
* Such an install is reported as unverified, never as verified.
|
|
144
|
+
*/
|
|
145
|
+
digestOptional?: boolean;
|
|
146
|
+
/**
|
|
147
|
+
* Set when the shipped binary's build string lags its release tag (sd reports
|
|
148
|
+
* "sd 1.0.0" for tag v1.1.0). The digest already proves the asset is right, so
|
|
149
|
+
* the tag is trusted for version comparison; otherwise every check would read
|
|
150
|
+
* the stale number, decide the tool is outdated, and reinstall it forever.
|
|
151
|
+
*/
|
|
152
|
+
trustTagVersion?: boolean;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const MANAGED_TOOLS: Record<ToolId, ManagedTool> = {
|
|
156
|
+
fd: {
|
|
157
|
+
id: "fd",
|
|
158
|
+
name: "fd",
|
|
159
|
+
repo: "sharkdp/fd",
|
|
160
|
+
binaryName: "fd",
|
|
161
|
+
tagPrefix: "v",
|
|
162
|
+
assetName: (version, target) => `fd-v${version}-${target}`,
|
|
163
|
+
systemBinaryNames: ["fd", "fdfind"],
|
|
164
|
+
consumedBy: ["find"],
|
|
165
|
+
},
|
|
166
|
+
rg: {
|
|
167
|
+
id: "rg",
|
|
168
|
+
name: "ripgrep",
|
|
169
|
+
repo: "BurntSushi/ripgrep",
|
|
170
|
+
binaryName: "rg",
|
|
171
|
+
tagPrefix: "",
|
|
172
|
+
assetName: (version, target) => `ripgrep-${version}-${target}`,
|
|
173
|
+
systemBinaryNames: ["rg"],
|
|
174
|
+
consumedBy: ["grep"],
|
|
175
|
+
},
|
|
176
|
+
bat: {
|
|
177
|
+
id: "bat",
|
|
178
|
+
name: "bat",
|
|
179
|
+
repo: "sharkdp/bat",
|
|
180
|
+
binaryName: "bat",
|
|
181
|
+
tagPrefix: "v",
|
|
182
|
+
assetName: (version, target) => `bat-v${version}-${target}`,
|
|
183
|
+
// Debian and Ubuntu install it as `batcat` to avoid clashing with `bat`.
|
|
184
|
+
systemBinaryNames: ["bat", "batcat"],
|
|
185
|
+
consumedBy: [],
|
|
186
|
+
},
|
|
187
|
+
prek: {
|
|
188
|
+
id: "prek",
|
|
189
|
+
name: "prek",
|
|
190
|
+
repo: "j178/prek",
|
|
191
|
+
binaryName: "prek",
|
|
192
|
+
tagPrefix: "v",
|
|
193
|
+
// prek publishes `prek-<target>` with no version in the filename. Tags at
|
|
194
|
+
// or below v0.0.22 used the old `prefligit-` prefix; `latest` never resolves one.
|
|
195
|
+
assetName: (_version, target) => `prek-${target}`,
|
|
196
|
+
systemBinaryNames: ["prek"],
|
|
197
|
+
consumedBy: [],
|
|
198
|
+
},
|
|
199
|
+
// rtk used to be installed here. It is no longer downloaded or updated by this
|
|
200
|
+
// package: it summarises output, which is a preference rather than a managed binary,
|
|
201
|
+
// and it is not part of the toolkit the skills advertise any more. An existing
|
|
202
|
+
// <agent dir>/bin/rtk is left alone; nothing reads or refreshes it.
|
|
203
|
+
just: {
|
|
204
|
+
id: "just",
|
|
205
|
+
name: "just",
|
|
206
|
+
repo: "casey/just",
|
|
207
|
+
binaryName: "just",
|
|
208
|
+
// just tags are bare versions (1.59.0) and the asset repeats the version.
|
|
209
|
+
tagPrefix: "",
|
|
210
|
+
assetName: (version, target) => `just-${version}-${target}`,
|
|
211
|
+
systemBinaryNames: ["just"],
|
|
212
|
+
consumedBy: [],
|
|
213
|
+
},
|
|
214
|
+
gron: {
|
|
215
|
+
id: "gron",
|
|
216
|
+
name: "gron",
|
|
217
|
+
repo: "tomnomnom/gron",
|
|
218
|
+
binaryName: "gron",
|
|
219
|
+
tagPrefix: "v",
|
|
220
|
+
// gron names assets by OS and Go arch, not by Rust triple, and ships .tgz
|
|
221
|
+
// on unix and .zip on Windows: gron-darwin-arm64-0.7.1.tgz
|
|
222
|
+
resolveTarget: gronTarget,
|
|
223
|
+
assetName: (version, target) =>
|
|
224
|
+
`gron-${target}-${version}.${target.startsWith("windows") ? "zip" : "tgz"}`,
|
|
225
|
+
systemBinaryNames: ["gron"],
|
|
226
|
+
// Release builds print "gron version dev": no version to compare.
|
|
227
|
+
versionOptional: true,
|
|
228
|
+
// gron's newest release predates GitHub's per-asset digest field, so the
|
|
229
|
+
// release API returns none. Without this it could never install at all;
|
|
230
|
+
// the install is reported as unverified.
|
|
231
|
+
digestOptional: true,
|
|
232
|
+
consumedBy: [],
|
|
233
|
+
},
|
|
234
|
+
shellcheck: {
|
|
235
|
+
id: "shellcheck",
|
|
236
|
+
name: "shellcheck",
|
|
237
|
+
repo: "koalaman/shellcheck",
|
|
238
|
+
binaryName: "shellcheck",
|
|
239
|
+
tagPrefix: "v",
|
|
240
|
+
// shellcheck uses dot-separated OS.arch and has one arch-less zip for
|
|
241
|
+
// Windows x86_64: shellcheck-v0.11.0.darwin.aarch64.tar.gz, shellcheck-v0.11.0.zip
|
|
242
|
+
resolveTarget: shellcheckTarget,
|
|
243
|
+
assetName: (version, target) =>
|
|
244
|
+
target === "zip" ? `shellcheck-v${version}.zip` : `shellcheck-v${version}.${target}`,
|
|
245
|
+
systemBinaryNames: ["shellcheck"],
|
|
246
|
+
consumedBy: [],
|
|
247
|
+
},
|
|
248
|
+
"ast-grep": {
|
|
249
|
+
id: "ast-grep",
|
|
250
|
+
name: "ast-grep",
|
|
251
|
+
repo: "ast-grep/ast-grep",
|
|
252
|
+
binaryName: "ast-grep",
|
|
253
|
+
// ast-grep tags are bare versions (0.51.3).
|
|
254
|
+
tagPrefix: "",
|
|
255
|
+
// Every platform gets a zip named app-<rust triple>.zip, which holds BOTH
|
|
256
|
+
// `ast-grep` and the deprecated `sg` entry point.
|
|
257
|
+
resolveTarget: (plat, architecture) => releaseTarget(plat, architecture)?.replace(/\.tar\.gz$/, ".zip"),
|
|
258
|
+
assetName: (_version, target) => `app-${target}`,
|
|
259
|
+
provides: ["ast-grep", "sg"],
|
|
260
|
+
systemBinaryNames: ["ast-grep"],
|
|
261
|
+
consumedBy: [],
|
|
262
|
+
},
|
|
263
|
+
ninja: {
|
|
264
|
+
id: "ninja",
|
|
265
|
+
name: "ninja",
|
|
266
|
+
repo: "ninja-build/ninja",
|
|
267
|
+
binaryName: "ninja",
|
|
268
|
+
tagPrefix: "v",
|
|
269
|
+
// Arch-less names, and the macOS build is one universal2 binary that runs
|
|
270
|
+
// natively on x86_64 and arm64: ninja-mac.zip, ninja-linux.zip,
|
|
271
|
+
// ninja-linux-aarch64.zip, ninja-win.zip, ninja-winarm64.zip.
|
|
272
|
+
resolveTarget: ninjaTarget,
|
|
273
|
+
assetName: (_version, target) => `ninja-${target}.zip`,
|
|
274
|
+
systemBinaryNames: ["ninja"],
|
|
275
|
+
consumedBy: [],
|
|
276
|
+
},
|
|
277
|
+
jq: {
|
|
278
|
+
id: "jq",
|
|
279
|
+
name: "jq",
|
|
280
|
+
repo: "jqlang/jq",
|
|
281
|
+
binaryName: "jq",
|
|
282
|
+
// jq tags carry their own prefix (jq-1.8.2), and the assets are bare
|
|
283
|
+
// executables with no version in the name: jq-macos-arm64.
|
|
284
|
+
tagPrefix: "jq-",
|
|
285
|
+
resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "macos"),
|
|
286
|
+
assetName: (_version, target) => `jq-${target}${target.startsWith("windows") ? ".exe" : ""}`,
|
|
287
|
+
systemBinaryNames: ["jq"],
|
|
288
|
+
raw: true,
|
|
289
|
+
consumedBy: [],
|
|
290
|
+
},
|
|
291
|
+
yq: {
|
|
292
|
+
id: "yq",
|
|
293
|
+
name: "yq",
|
|
294
|
+
// mikefarah/yq, the Go rewrite (v4 CLI). The other `yq` in the ecosystem is
|
|
295
|
+
// kislyuk/yq, a Python wrapper with a different flag surface.
|
|
296
|
+
repo: "mikefarah/yq",
|
|
297
|
+
binaryName: "yq",
|
|
298
|
+
tagPrefix: "v",
|
|
299
|
+
resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
|
|
300
|
+
assetName: (_version, target) => {
|
|
301
|
+
const name = `yq_${target.replace("-", "_")}`;
|
|
302
|
+
return target.startsWith("windows") ? `${name}.exe` : name;
|
|
303
|
+
},
|
|
304
|
+
systemBinaryNames: ["yq"],
|
|
305
|
+
raw: true,
|
|
306
|
+
consumedBy: [],
|
|
307
|
+
},
|
|
308
|
+
fzf: {
|
|
309
|
+
id: "fzf",
|
|
310
|
+
name: "fzf",
|
|
311
|
+
repo: "junegunn/fzf",
|
|
312
|
+
binaryName: "fzf",
|
|
313
|
+
tagPrefix: "v",
|
|
314
|
+
resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
|
|
315
|
+
assetName: (version, target) => {
|
|
316
|
+
const name = `fzf-${version}-${target.replace("-", "_")}`;
|
|
317
|
+
return target.startsWith("windows") ? `${name}.zip` : `${name}.tar.gz`;
|
|
318
|
+
},
|
|
319
|
+
systemBinaryNames: ["fzf"],
|
|
320
|
+
consumedBy: [],
|
|
321
|
+
},
|
|
322
|
+
uv: {
|
|
323
|
+
id: "uv",
|
|
324
|
+
name: "uv",
|
|
325
|
+
repo: "astral-sh/uv",
|
|
326
|
+
binaryName: "uv",
|
|
327
|
+
tagPrefix: "",
|
|
328
|
+
// Rust triples. The archive also carries `uvx`, which is the same tool's
|
|
329
|
+
// tool-runner entry point, so both commands are installed.
|
|
330
|
+
assetName: (_version, target) => `uv-${target}`,
|
|
331
|
+
provides: ["uv", "uvx"],
|
|
332
|
+
systemBinaryNames: ["uv"],
|
|
333
|
+
consumedBy: [],
|
|
334
|
+
},
|
|
335
|
+
gh: {
|
|
336
|
+
id: "gh",
|
|
337
|
+
name: "gh",
|
|
338
|
+
repo: "cli/cli",
|
|
339
|
+
binaryName: "gh",
|
|
340
|
+
tagPrefix: "v",
|
|
341
|
+
// Linux ships tar.gz; macOS and Windows ship zips, so the extension is part
|
|
342
|
+
// of the target rather than the tool: gh_2.105.0_macOS_arm64.zip
|
|
343
|
+
resolveTarget: (plat, architecture) => ghTarget(plat, architecture),
|
|
344
|
+
assetName: (version, target) => {
|
|
345
|
+
const ext = target.startsWith("linux") ? ".tar.gz" : ".zip";
|
|
346
|
+
return `gh_${version}_${target}${ext}`;
|
|
347
|
+
},
|
|
348
|
+
systemBinaryNames: ["gh"],
|
|
349
|
+
consumedBy: [],
|
|
350
|
+
},
|
|
351
|
+
bd: {
|
|
352
|
+
id: "bd",
|
|
353
|
+
name: "bd",
|
|
354
|
+
// gastownhall/beads: a Dolt-backed issue tracker. The assets are named
|
|
355
|
+
// after the project but the binary is `bd`.
|
|
356
|
+
repo: "gastownhall/beads",
|
|
357
|
+
binaryName: "bd",
|
|
358
|
+
tagPrefix: "v",
|
|
359
|
+
resolveTarget: (plat, architecture) => goOsArch(plat, architecture, "darwin"),
|
|
360
|
+
assetName: (version, target) => {
|
|
361
|
+
const name = `beads_${version}_${target.replace("-", "_")}`;
|
|
362
|
+
return target.startsWith("windows") ? `${name}.zip` : `${name}.tar.gz`;
|
|
363
|
+
},
|
|
364
|
+
systemBinaryNames: ["bd"],
|
|
365
|
+
consumedBy: [],
|
|
366
|
+
},
|
|
367
|
+
"agent-browser": {
|
|
368
|
+
id: "agent-browser",
|
|
369
|
+
name: "agent-browser",
|
|
370
|
+
repo: "vercel-labs/agent-browser",
|
|
371
|
+
binaryName: "agent-browser",
|
|
372
|
+
tagPrefix: "v",
|
|
373
|
+
// Bare executables, Go-style names, `.exe` on win32. No win32-arm64 asset.
|
|
374
|
+
resolveTarget: agentBrowserTarget,
|
|
375
|
+
assetName: (_version, target) =>
|
|
376
|
+
`agent-browser-${target}${target.startsWith("win32") ? ".exe" : ""}`,
|
|
377
|
+
systemBinaryNames: ["agent-browser"],
|
|
378
|
+
raw: true,
|
|
379
|
+
consumedBy: [],
|
|
380
|
+
},
|
|
381
|
+
ruff: {
|
|
382
|
+
id: "ruff",
|
|
383
|
+
name: "ruff",
|
|
384
|
+
repo: "astral-sh/ruff",
|
|
385
|
+
binaryName: "ruff",
|
|
386
|
+
// ruff tags are bare versions (0.17.6) and assets use Rust triples.
|
|
387
|
+
tagPrefix: "",
|
|
388
|
+
assetName: (_version, target) => `ruff-${target}`,
|
|
389
|
+
systemBinaryNames: ["ruff"],
|
|
390
|
+
consumedBy: [],
|
|
391
|
+
},
|
|
392
|
+
mise: {
|
|
393
|
+
id: "mise",
|
|
394
|
+
name: "mise",
|
|
395
|
+
repo: "jdx/mise",
|
|
396
|
+
binaryName: "mise",
|
|
397
|
+
tagPrefix: "v",
|
|
398
|
+
// Dated tags (v2026.11.11) and `x64`/`macos` naming. The archive nests the
|
|
399
|
+
// binary at mise/bin/mise.
|
|
400
|
+
resolveTarget: (plat, architecture) => osArchX64(plat, architecture, "macos"),
|
|
401
|
+
assetName: (version, target) =>
|
|
402
|
+
`mise-v${version}-${target}${target.startsWith("windows") ? ".zip" : ".tar.gz"}`,
|
|
403
|
+
systemBinaryNames: ["mise"],
|
|
404
|
+
consumedBy: [],
|
|
405
|
+
},
|
|
406
|
+
scc: {
|
|
407
|
+
id: "scc",
|
|
408
|
+
name: "scc",
|
|
409
|
+
repo: "boyter/scc",
|
|
410
|
+
binaryName: "scc",
|
|
411
|
+
tagPrefix: "v",
|
|
412
|
+
// Capitalised OS and underscore: scc_Darwin_arm64.tar.gz, scc_Windows_x86_64.zip
|
|
413
|
+
resolveTarget: (plat, architecture) => {
|
|
414
|
+
const os = plat === "darwin" ? "Darwin" : plat === "linux" ? "Linux" : plat === "win32" ? "Windows" : undefined;
|
|
415
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x86_64" : undefined;
|
|
416
|
+
if (!os || !cpu) return undefined;
|
|
417
|
+
return `${os}_${cpu}`;
|
|
418
|
+
},
|
|
419
|
+
assetName: (_version, target) =>
|
|
420
|
+
`scc_${target}${target.startsWith("Windows") ? ".zip" : ".tar.gz"}`,
|
|
421
|
+
systemBinaryNames: ["scc"],
|
|
422
|
+
consumedBy: [],
|
|
423
|
+
},
|
|
424
|
+
duckdb: {
|
|
425
|
+
id: "duckdb",
|
|
426
|
+
name: "duckdb",
|
|
427
|
+
repo: "duckdb/duckdb",
|
|
428
|
+
binaryName: "duckdb",
|
|
429
|
+
tagPrefix: "v",
|
|
430
|
+
// osx/linux/windows with amd64: duckdb-cli-osx-arm64.tar.gz
|
|
431
|
+
resolveTarget: (plat, architecture) => goTarget(plat, architecture, "osx", "amd64"),
|
|
432
|
+
assetName: (_version, target) => `duckdb-cli-${target}.tar.gz`,
|
|
433
|
+
systemBinaryNames: ["duckdb"],
|
|
434
|
+
consumedBy: [],
|
|
435
|
+
},
|
|
436
|
+
miller: {
|
|
437
|
+
id: "miller",
|
|
438
|
+
name: "miller",
|
|
439
|
+
repo: "johnkerl/miller",
|
|
440
|
+
binaryName: "mlr",
|
|
441
|
+
tagPrefix: "v",
|
|
442
|
+
// The asset repeats the version without its v: miller-6.22.0-darwin-arm64
|
|
443
|
+
resolveTarget: (plat, architecture) => goTarget(plat, architecture, "darwin", "amd64"),
|
|
444
|
+
assetName: (version, target) =>
|
|
445
|
+
`miller-${version}-${target}${target.startsWith("windows") ? ".zip" : ".tar.gz"}`,
|
|
446
|
+
systemBinaryNames: ["mlr"],
|
|
447
|
+
consumedBy: [],
|
|
448
|
+
},
|
|
449
|
+
sd: {
|
|
450
|
+
id: "sd",
|
|
451
|
+
name: "sd",
|
|
452
|
+
repo: "chmln/sd",
|
|
453
|
+
binaryName: "sd",
|
|
454
|
+
tagPrefix: "v",
|
|
455
|
+
// The asset keeps the v in its name (sd-v1.1.0-...) and there is no
|
|
456
|
+
// win32-arm64 build.
|
|
457
|
+
resolveTarget: (plat, architecture) => {
|
|
458
|
+
const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
|
|
459
|
+
if (!cpu) return undefined;
|
|
460
|
+
if (plat === "darwin") return `${cpu}-apple-darwin`;
|
|
461
|
+
if (plat === "linux") return `${cpu}-unknown-linux-musl`;
|
|
462
|
+
if (plat === "win32") return cpu === "x86_64" ? "x86_64-pc-windows-msvc" : undefined;
|
|
463
|
+
return undefined;
|
|
464
|
+
},
|
|
465
|
+
assetName: (version, target) =>
|
|
466
|
+
`sd-v${version}-${target}${target.includes("windows") ? ".zip" : ".tar.gz"}`,
|
|
467
|
+
systemBinaryNames: ["sd"],
|
|
468
|
+
// sd 1.1.0 ships a binary that still reports 1.0.0.
|
|
469
|
+
trustTagVersion: true,
|
|
470
|
+
consumedBy: [],
|
|
471
|
+
},
|
|
472
|
+
difftastic: {
|
|
473
|
+
id: "difftastic",
|
|
474
|
+
name: "difftastic",
|
|
475
|
+
repo: "Wilfred/difftastic",
|
|
476
|
+
binaryName: "difft",
|
|
477
|
+
// difftastic tags are bare versions (0.72.0).
|
|
478
|
+
tagPrefix: "",
|
|
479
|
+
// Linux arm64 publishes gnu only, so gnu is used for both linux arches.
|
|
480
|
+
resolveTarget: (plat, architecture) => {
|
|
481
|
+
const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
|
|
482
|
+
if (!cpu) return undefined;
|
|
483
|
+
if (plat === "darwin") return `${cpu}-apple-darwin`;
|
|
484
|
+
if (plat === "linux") return `${cpu}-unknown-linux-gnu`;
|
|
485
|
+
if (plat === "win32") return `${cpu}-pc-windows-msvc`;
|
|
486
|
+
return undefined;
|
|
487
|
+
},
|
|
488
|
+
assetName: (version, target) =>
|
|
489
|
+
`difft-${version}-${target}${target.includes("windows") ? ".zip" : ".tar.gz"}`,
|
|
490
|
+
systemBinaryNames: ["difft"],
|
|
491
|
+
consumedBy: [],
|
|
492
|
+
},
|
|
493
|
+
busybox: {
|
|
494
|
+
id: "busybox",
|
|
495
|
+
name: "busybox",
|
|
496
|
+
// rob-c/busybox-static: upstream BusyBox built static (musl/zig on Linux,
|
|
497
|
+
// Mach-O with Darwin port patches on macOS). Assets are bare executables.
|
|
498
|
+
repo: "rob-c/busybox-static",
|
|
499
|
+
binaryName: "busybox",
|
|
500
|
+
tagPrefix: "v",
|
|
501
|
+
// macOS ships one universal2 binary, so a single asset covers both
|
|
502
|
+
// architectures. There is no Windows build.
|
|
503
|
+
resolveTarget: (plat, architecture) => {
|
|
504
|
+
if (plat === "darwin") {
|
|
505
|
+
return architecture === "arm64" || architecture === "x64" ? "darwin-universal" : undefined;
|
|
506
|
+
}
|
|
507
|
+
if (plat === "linux") {
|
|
508
|
+
return architecture === "arm64" ? "linux-arm64" : architecture === "x64" ? "linux-amd64" : undefined;
|
|
509
|
+
}
|
|
510
|
+
return undefined;
|
|
511
|
+
},
|
|
512
|
+
// No v in the asset name despite the v-prefixed tag, and since 0.4.0 the asset
|
|
513
|
+
// carries the *busybox* version rather than the project version, so the name comes
|
|
514
|
+
// from the release's asset list (see assetPattern).
|
|
515
|
+
assetName: (version, target) => `busybox-static-${version}-${target}`,
|
|
516
|
+
assetPattern: (target) => {
|
|
517
|
+
// busybox-static-1.39.0-aac079e-darwin-universal. The -pure variants are
|
|
518
|
+
// deliberately not matched: they drop nslookup, which the curated set uses.
|
|
519
|
+
const suffix = target.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
520
|
+
return new RegExp(`^busybox-static-\\d+\\.\\d+\\.\\d+(-[0-9a-f]+)?-${suffix}$`);
|
|
521
|
+
},
|
|
522
|
+
legacyVersionPattern: /^\d+\.\d+\.\d+-[0-9a-f]{7,}$/,
|
|
523
|
+
systemBinaryNames: ["busybox"],
|
|
524
|
+
raw: true,
|
|
525
|
+
// The binary reports "BusyBox v1.39.0.git" while the tag carries the commit
|
|
526
|
+
// (v1.39.0-aac079e), so the tag is the only version that can be compared.
|
|
527
|
+
trustTagVersion: true,
|
|
528
|
+
consumedBy: [],
|
|
529
|
+
},
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
/** Same order pi's startup download uses, so messages read predictably. */
|
|
533
|
+
export const MANAGED_TOOL_IDS: ToolId[] = [
|
|
534
|
+
"fd",
|
|
535
|
+
"rg",
|
|
536
|
+
"bat",
|
|
537
|
+
"prek",
|
|
538
|
+
"just",
|
|
539
|
+
"gron",
|
|
540
|
+
"shellcheck",
|
|
541
|
+
"ast-grep",
|
|
542
|
+
"ninja",
|
|
543
|
+
"jq",
|
|
544
|
+
"yq",
|
|
545
|
+
"fzf",
|
|
546
|
+
"uv",
|
|
547
|
+
"gh",
|
|
548
|
+
"bd",
|
|
549
|
+
"agent-browser",
|
|
550
|
+
"ruff",
|
|
551
|
+
"mise",
|
|
552
|
+
"scc",
|
|
553
|
+
"duckdb",
|
|
554
|
+
"miller",
|
|
555
|
+
"sd",
|
|
556
|
+
"difftastic",
|
|
557
|
+
"busybox",
|
|
558
|
+
];
|
|
559
|
+
|
|
560
|
+
/** Release target for one tool on this platform, or undefined when it has none. */
|
|
561
|
+
export function targetFor(tool: ManagedTool, plat: string, architecture: string): string | undefined {
|
|
562
|
+
return tool.resolveTarget ? tool.resolveTarget(plat, architecture) : releaseTarget(plat, architecture);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** gron encodes OS and Go arch: darwin-arm64, linux-amd64, windows-arm64. */
|
|
566
|
+
function gronTarget(plat: string, architecture: string): string | undefined {
|
|
567
|
+
const os = plat === "darwin" ? "darwin" : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
|
|
568
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "amd64" : undefined;
|
|
569
|
+
if (!os || !cpu) return undefined;
|
|
570
|
+
return `${os}-${cpu}`;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** os-cpu pairs for projects whose CPU label differs (x86_64 vs amd64). */
|
|
574
|
+
function goTarget(plat: string, architecture: string, darwinOs: string, x64: string): string | undefined {
|
|
575
|
+
const os =
|
|
576
|
+
plat === "darwin" ? darwinOs : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
|
|
577
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? x64 : undefined;
|
|
578
|
+
if (!os || !cpu) return undefined;
|
|
579
|
+
return `${os}-${cpu}`;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Go-style os-arch pairs, as jq, yq and fzf name their assets. */
|
|
583
|
+
function goOsArch(plat: string, architecture: string, darwinName: string): string | undefined {
|
|
584
|
+
const os =
|
|
585
|
+
plat === "darwin" ? darwinName : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
|
|
586
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "amd64" : undefined;
|
|
587
|
+
if (!os || !cpu) return undefined;
|
|
588
|
+
return `${os}-${cpu}`;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** os/arch pairs where the x86_64 build is called `x64`, as mise names them. */
|
|
592
|
+
function osArchX64(plat: string, architecture: string, darwinName: string): string | undefined {
|
|
593
|
+
const os =
|
|
594
|
+
plat === "darwin" ? darwinName : plat === "linux" ? "linux" : plat === "win32" ? "windows" : undefined;
|
|
595
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x64" : undefined;
|
|
596
|
+
if (!os || !cpu) return undefined;
|
|
597
|
+
return `${os}-${cpu}`;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* agent-browser keeps the OS names lowercase and calls Windows `win32`.
|
|
602
|
+
*
|
|
603
|
+
* The plain linux asset is dynamically linked against glibc (`/lib64/ld-linux`),
|
|
604
|
+
* while the `linux-musl` one is statically linked and so runs on glibc and musl
|
|
605
|
+
* both. Verified with `file` on both linux-x64 builds.
|
|
606
|
+
*/
|
|
607
|
+
function agentBrowserTarget(plat: string, architecture: string): string | undefined {
|
|
608
|
+
const cpu = architecture === "arm64" ? "arm64" : architecture === "x64" ? "x64" : undefined;
|
|
609
|
+
if (!cpu) return undefined;
|
|
610
|
+
if (plat === "darwin") return `darwin-${cpu}`;
|
|
611
|
+
if (plat === "linux") return `linux-musl-${cpu}`;
|
|
612
|
+
// No win32-arm64 asset is published.
|
|
613
|
+
if (plat === "win32") return cpu === "x64" ? "win32-x64" : undefined;
|
|
614
|
+
return undefined;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** gh names its macOS asset with a capital OS and an underscore. */
|
|
618
|
+
function ghTarget(plat: string, architecture: string): string | undefined {
|
|
619
|
+
const target = goOsArch(plat, architecture, "macOS");
|
|
620
|
+
return target?.replace("-", "_");
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** shellcheck encodes OS and arch with dots, and only ships an x64 zip for Windows. */
|
|
624
|
+
/**
|
|
625
|
+
* ninja publishes arch-less names, and its macOS asset is a universal2 binary,
|
|
626
|
+
* so one download serves both mac architectures. Linux and Windows carry a
|
|
627
|
+
* separate asset per architecture.
|
|
628
|
+
*/
|
|
629
|
+
function ninjaTarget(plat: string, architecture: string): string | undefined {
|
|
630
|
+
if (plat === "darwin") return architecture === "arm64" || architecture === "x64" ? "mac" : undefined;
|
|
631
|
+
if (plat === "linux") return architecture === "arm64" ? "linux-aarch64" : architecture === "x64" ? "linux" : undefined;
|
|
632
|
+
if (plat === "win32") return architecture === "arm64" ? "winarm64" : architecture === "x64" ? "win" : undefined;
|
|
633
|
+
return undefined;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function shellcheckTarget(plat: string, architecture: string): string | undefined {
|
|
637
|
+
if (plat === "win32") return architecture === "x64" ? "zip" : undefined;
|
|
638
|
+
if (plat !== "darwin" && plat !== "linux") return undefined;
|
|
639
|
+
const cpu = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
|
|
640
|
+
if (!cpu) return undefined;
|
|
641
|
+
return `${plat}.${cpu}.tar.gz`;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
const NETWORK_TIMEOUT_MS = 15_000;
|
|
645
|
+
const DOWNLOAD_TIMEOUT_MS = 120_000;
|
|
646
|
+
const STATE_FILE = ".pi-managed-tools.json";
|
|
647
|
+
const DEFAULT_INTERVAL_HOURS = 12;
|
|
648
|
+
|
|
649
|
+
// =============================================================================
|
|
650
|
+
// Platform targets
|
|
651
|
+
// =============================================================================
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Release suffix shared by the fd and ripgrep archives. Mirrors pi's own
|
|
655
|
+
* `getReleaseTarget()`: only x64 and arm64 have prebuilt binaries, and an
|
|
656
|
+
* unknown architecture must not fall back to an x86-64 download.
|
|
657
|
+
*/
|
|
658
|
+
export function releaseTarget(plat: string, architecture: string): string | undefined {
|
|
659
|
+
const archName = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
|
|
660
|
+
if (!archName) return undefined;
|
|
661
|
+
if (plat === "darwin") return `${archName}-apple-darwin.tar.gz`;
|
|
662
|
+
if (plat === "linux") return `${archName}-unknown-linux-musl.tar.gz`;
|
|
663
|
+
if (plat === "win32") return `${archName}-pc-windows-msvc.zip`;
|
|
664
|
+
return undefined;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
export function binaryFileName(tool: ManagedTool, plat: string): string {
|
|
668
|
+
return tool.binaryName + (plat === "win32" ? ".exe" : "");
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Path pi's `getToolPath()` checks first. */
|
|
672
|
+
export function managedBinaryPath(tool: ManagedTool, binDir: string, plat: string = platform()): string {
|
|
673
|
+
return join(binDir, binaryFileName(tool, plat));
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// =============================================================================
|
|
677
|
+
// Versions
|
|
678
|
+
// =============================================================================
|
|
679
|
+
|
|
680
|
+
/** `fd --version` prints "fd 10.5.2"; `rg --version` prints "ripgrep 15.2.0 (rev ...)". */
|
|
681
|
+
export function parseVersion(output: string): string | undefined {
|
|
682
|
+
const match = output.match(/(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/);
|
|
683
|
+
return match?.[1];
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Ordered compare for the "x.y.z(-prerelease)" versions these projects ship. */
|
|
687
|
+
export function compareVersions(a: string, b: string): number {
|
|
688
|
+
const [aCore, aPre] = splitVersion(a);
|
|
689
|
+
const [bCore, bPre] = splitVersion(b);
|
|
690
|
+
for (let i = 0; i < Math.max(aCore.length, bCore.length); i++) {
|
|
691
|
+
const left = aCore[i] ?? 0;
|
|
692
|
+
const right = bCore[i] ?? 0;
|
|
693
|
+
if (left !== right) return left < right ? -1 : 1;
|
|
694
|
+
}
|
|
695
|
+
// A release outranks any prerelease of the same core version.
|
|
696
|
+
if (aPre === bPre) return 0;
|
|
697
|
+
if (!aPre) return 1;
|
|
698
|
+
if (!bPre) return -1;
|
|
699
|
+
return aPre < bPre ? -1 : 1;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function splitVersion(version: string): [number[], string] {
|
|
703
|
+
const [core, pre = ""] = version.replace(/^v/, "").split("-", 2);
|
|
704
|
+
const numbers = core.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
|
705
|
+
return [numbers, pre];
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Run the binary once: did it execute, and did it name a version?
|
|
710
|
+
*
|
|
711
|
+
* Both halves matter. A binary that cannot execute (wrong architecture, glibc
|
|
712
|
+
* against a musl build, a truncated file) exits non-zero or fails to spawn, and
|
|
713
|
+
* a few upstreams build without embedding a version at all (`gron --version`
|
|
714
|
+
* prints "gron version dev"), which is not the same thing as a broken install.
|
|
715
|
+
*/
|
|
716
|
+
export function probeBinary(binaryPath: string, pathDir?: string): { ran: boolean; version?: string } {
|
|
717
|
+
if (!existsSync(binaryPath)) return { ran: false };
|
|
718
|
+
// A bundled shim can delegate to a sibling in the same directory (ast-grep's
|
|
719
|
+
// `sg` execs `ast-grep`), so the probe may need that directory on PATH.
|
|
720
|
+
const env = pathDir
|
|
721
|
+
? { ...process.env, PATH: [pathDir, process.env.PATH ?? ""].join(delimiter) }
|
|
722
|
+
: process.env;
|
|
723
|
+
const result = spawnSync(binaryPath, ["--version"], {
|
|
724
|
+
encoding: "utf-8",
|
|
725
|
+
timeout: 10_000,
|
|
726
|
+
env,
|
|
727
|
+
// A Windows copy is sometimes a shim that needs the real file beside it.
|
|
728
|
+
windowsHide: true,
|
|
729
|
+
});
|
|
730
|
+
if (result.error) return { ran: false };
|
|
731
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
732
|
+
const stderr = typeof result.stderr === "string" ? result.stderr : "";
|
|
733
|
+
return { ran: result.status === 0, version: parseVersion(stdout) ?? parseVersion(stderr) };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Version of an installed binary, or undefined when it cannot report one. */
|
|
737
|
+
export function readToolVersion(binaryPath: string): string | undefined {
|
|
738
|
+
return probeBinary(binaryPath).version;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** Where a plain `fd`/`rg` in the user's PATH lives, which pi falls back to. */
|
|
742
|
+
export function findSystemBinary(tool: ManagedTool, plat: string = platform()): string | undefined {
|
|
743
|
+
const locator = plat === "win32" ? "where" : "which";
|
|
744
|
+
for (const name of tool.systemBinaryNames) {
|
|
745
|
+
const result = spawnSync(locator, [name], { encoding: "utf-8", timeout: 5000, windowsHide: true });
|
|
746
|
+
if (result.status !== 0 || typeof result.stdout !== "string") continue;
|
|
747
|
+
const first = result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)[0];
|
|
748
|
+
if (first) return first;
|
|
749
|
+
}
|
|
750
|
+
return undefined;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// =============================================================================
|
|
754
|
+
// Network
|
|
755
|
+
// =============================================================================
|
|
756
|
+
|
|
757
|
+
export interface NetworkOptions {
|
|
758
|
+
/** Injectable for tests; defaults to the global fetch. */
|
|
759
|
+
fetchImpl?: typeof fetch;
|
|
760
|
+
signal?: AbortSignal;
|
|
761
|
+
timeoutMs?: number;
|
|
762
|
+
userAgent?: string;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
class HttpError extends Error {
|
|
766
|
+
readonly status: number;
|
|
767
|
+
|
|
768
|
+
constructor(status: number, message: string) {
|
|
769
|
+
super(message);
|
|
770
|
+
this.status = status;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
775
|
+
|
|
776
|
+
/** One controller for the caller's abort signal plus our own timeout. */
|
|
777
|
+
function withTimeout(signal: AbortSignal | undefined, ms: number): { signal: AbortSignal; dispose(): void } {
|
|
778
|
+
const controller = new AbortController();
|
|
779
|
+
const timer = setTimeout(() => controller.abort(new Error(`timed out after ${ms}ms`)), ms);
|
|
780
|
+
timer.unref?.();
|
|
781
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
782
|
+
if (signal) {
|
|
783
|
+
if (signal.aborted) onAbort();
|
|
784
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
785
|
+
}
|
|
786
|
+
return {
|
|
787
|
+
signal: controller.signal,
|
|
788
|
+
dispose: () => {
|
|
789
|
+
clearTimeout(timer);
|
|
790
|
+
signal?.removeEventListener("abort", onAbort);
|
|
791
|
+
},
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function isRetryable(error: unknown): boolean {
|
|
796
|
+
if (error instanceof HttpError) return error.status === 429 || error.status >= 500;
|
|
797
|
+
// Network failures surface as TypeError("fetch failed") with the cause hidden
|
|
798
|
+
// one level down (DNS, TLS, connection reset). An aborted request is the
|
|
799
|
+
// caller's own shutdown, not a transient fault.
|
|
800
|
+
if (error instanceof Error && error.name === "AbortError") return false;
|
|
801
|
+
return error instanceof TypeError;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
async function fetchWithRetries(
|
|
805
|
+
url: string,
|
|
806
|
+
init: RequestInit,
|
|
807
|
+
options: NetworkOptions,
|
|
808
|
+
attempts = 3,
|
|
809
|
+
): Promise<Response> {
|
|
810
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
811
|
+
let lastError: unknown;
|
|
812
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
813
|
+
const timeout = withTimeout(options.signal, options.timeoutMs ?? NETWORK_TIMEOUT_MS);
|
|
814
|
+
try {
|
|
815
|
+
const response = await fetchImpl(url, {
|
|
816
|
+
...init,
|
|
817
|
+
signal: timeout.signal,
|
|
818
|
+
headers: { "User-Agent": options.userAgent ?? "pi-managed-tools", ...(init.headers as object) },
|
|
819
|
+
});
|
|
820
|
+
if (response.status === 429 || response.status >= 500) {
|
|
821
|
+
throw new HttpError(response.status, `HTTP ${response.status} for ${url}`);
|
|
822
|
+
}
|
|
823
|
+
return response;
|
|
824
|
+
} catch (error) {
|
|
825
|
+
lastError = error;
|
|
826
|
+
if (options.signal?.aborted) throw error;
|
|
827
|
+
if (!isRetryable(error) || attempt === attempts - 1) throw error;
|
|
828
|
+
await sleep(500 * 2 ** attempt);
|
|
829
|
+
} finally {
|
|
830
|
+
timeout.dispose();
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
throw lastError;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Latest release tag, without the `v` prefix.
|
|
838
|
+
*
|
|
839
|
+
* The redirect from `/releases/latest` is used first because the
|
|
840
|
+
* api.github.com endpoint counts against the anonymous 60 requests/hour quota,
|
|
841
|
+
* which shared egress IPs exhaust; the API is only a fallback for the rare
|
|
842
|
+
* answer without a redirect.
|
|
843
|
+
*/
|
|
844
|
+
export async function fetchLatestVersion(tool: ManagedTool, options: NetworkOptions = {}): Promise<string> {
|
|
845
|
+
const response = await fetchWithRetries(
|
|
846
|
+
`https://github.com/${tool.repo}/releases/latest`,
|
|
847
|
+
{ redirect: "manual" },
|
|
848
|
+
options,
|
|
849
|
+
);
|
|
850
|
+
try {
|
|
851
|
+
await response.body?.cancel();
|
|
852
|
+
} catch {
|
|
853
|
+
// Discarding the body is best-effort.
|
|
854
|
+
}
|
|
855
|
+
const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
|
|
856
|
+
if (location?.includes("/releases/tag/")) {
|
|
857
|
+
const tag = new URL(location, "https://github.com").pathname.split("/").pop();
|
|
858
|
+
if (tag) return stripTagPrefix(decodeURIComponent(tag), tool.tagPrefix);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const api = await fetchWithRetries(
|
|
862
|
+
`https://api.github.com/repos/${tool.repo}/releases/latest`,
|
|
863
|
+
{ headers: { Accept: "application/vnd.github+json" } },
|
|
864
|
+
options,
|
|
865
|
+
);
|
|
866
|
+
if (!api.ok) throw new HttpError(api.status, `HTTP ${api.status} for api.github.com/${tool.repo}/releases/latest`);
|
|
867
|
+
const payload = (await api.json()) as { tag_name?: unknown };
|
|
868
|
+
if (typeof payload.tag_name !== "string") {
|
|
869
|
+
throw new Error(`Unexpected GitHub API response for ${tool.repo}: no tag_name`);
|
|
870
|
+
}
|
|
871
|
+
return stripTagPrefix(payload.tag_name, tool.tagPrefix);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** jq tags are jq-1.8.2; most projects use a bare or v-prefixed version. */
|
|
875
|
+
function stripTagPrefix(tag: string, prefix: string): string {
|
|
876
|
+
if (prefix && tag.startsWith(prefix)) return tag.slice(prefix.length);
|
|
877
|
+
return tag.replace(/^v/, "");
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function downloadUrl(tool: ManagedTool, version: string, asset: string): string {
|
|
881
|
+
return `https://github.com/${tool.repo}/releases/download/${tool.tagPrefix}${version}/${asset}`;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
async function downloadFile(url: string, dest: string, options: NetworkOptions): Promise<void> {
|
|
885
|
+
const response = await fetchWithRetries(url, {}, { ...options, timeoutMs: DOWNLOAD_TIMEOUT_MS });
|
|
886
|
+
if (!response.ok) throw new HttpError(response.status, `Download failed with HTTP ${response.status}: ${url}`);
|
|
887
|
+
if (!response.body) throw new Error(`No response body for ${url}`);
|
|
888
|
+
await pipeline(Readable.fromWeb(response.body as never), createWriteStream(dest));
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// =============================================================================
|
|
892
|
+
// Integrity
|
|
893
|
+
// =============================================================================
|
|
894
|
+
|
|
895
|
+
/** Set to `1`/`true`/`yes` to install an archive whose digest cannot be confirmed. */
|
|
896
|
+
const ALLOW_UNVERIFIED_ENV = "PI_MANAGED_TOOLS_ALLOW_UNVERIFIED";
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Verification is fail-closed: an unreachable release API means "cannot prove",
|
|
900
|
+
* not "proved good". The opt-out exists for air-gapped mirrors and for the rare
|
|
901
|
+
* asset a project uploads without a digest.
|
|
902
|
+
*/
|
|
903
|
+
export function allowUnverified(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
904
|
+
const value = (env[ALLOW_UNVERIFIED_ENV] ?? "").trim().toLowerCase();
|
|
905
|
+
return value === "1" || value === "true" || value === "yes";
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
export function sha256File(path: string): string {
|
|
909
|
+
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* The digest GitHub recorded for one release asset, as a bare lowercase hex sha256.
|
|
914
|
+
*
|
|
915
|
+
* GitHub computes this at upload time, so it does not depend on the project
|
|
916
|
+
* publishing sidecar checksums - fd and bat publish none at all. Returns
|
|
917
|
+
* undefined when the release or the asset is not visible to the API.
|
|
918
|
+
*/
|
|
919
|
+
/** The release's asset list, so a name can be matched instead of constructed. */
|
|
920
|
+
export async function releaseAssets(
|
|
921
|
+
tool: ManagedTool,
|
|
922
|
+
version: string,
|
|
923
|
+
options: NetworkOptions = {},
|
|
924
|
+
): Promise<Array<{ name?: unknown; digest?: unknown }>> {
|
|
925
|
+
const tag = `${tool.tagPrefix}${version}`;
|
|
926
|
+
const url = `https://api.github.com/repos/${tool.repo}/releases/tags/${encodeURIComponent(tag)}`;
|
|
927
|
+
// The anonymous quota is 60 requests/hour per IP, shared with everything else
|
|
928
|
+
// on the host. A token is optional and only raises that limit.
|
|
929
|
+
const token = (process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? "").trim();
|
|
930
|
+
const headers: Record<string, string> = { Accept: "application/vnd.github+json" };
|
|
931
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
932
|
+
const response = await fetchWithRetries(url, { headers }, options);
|
|
933
|
+
if (!response.ok) throw new HttpError(response.status, `HTTP ${response.status} for ${url}`);
|
|
934
|
+
const payload = (await response.json()) as { assets?: Array<{ name?: unknown; digest?: unknown }> };
|
|
935
|
+
return payload.assets ?? [];
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
export async function fetchAssetDigest(
|
|
939
|
+
tool: ManagedTool,
|
|
940
|
+
version: string,
|
|
941
|
+
asset: string,
|
|
942
|
+
options: NetworkOptions = {},
|
|
943
|
+
): Promise<string | undefined> {
|
|
944
|
+
const assets = await releaseAssets(tool, version, options);
|
|
945
|
+
const match = assets.find((entry) => entry?.name === asset);
|
|
946
|
+
if (!match || typeof match.digest !== "string") return undefined;
|
|
947
|
+
const separator = match.digest.indexOf(":");
|
|
948
|
+
if (separator < 0) return undefined;
|
|
949
|
+
const algorithm = match.digest.slice(0, separator).toLowerCase();
|
|
950
|
+
const hex = match.digest.slice(separator + 1).toLowerCase();
|
|
951
|
+
if (algorithm !== "sha256" || !/^[0-9a-f]{64}$/.test(hex)) return undefined;
|
|
952
|
+
return hex;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* Check the downloaded archive against GitHub's digest, and return the digest
|
|
957
|
+
* that was accepted.
|
|
958
|
+
*
|
|
959
|
+
* A `.sha256` sidecar would not be enough on its own: an attacker who can
|
|
960
|
+
* replace a release asset can usually replace the sidecar beside it. The digest
|
|
961
|
+
* comes from the release resource instead.
|
|
962
|
+
*/
|
|
963
|
+
export interface VerifiedArchive {
|
|
964
|
+
digest: string;
|
|
965
|
+
/** False only when the unverified opt-out let an unconfirmed archive through. */
|
|
966
|
+
verified: boolean;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Check the downloaded archive against GitHub's digest.
|
|
971
|
+
*
|
|
972
|
+
* A `.sha256` sidecar would not be enough on its own: an attacker who can
|
|
973
|
+
* replace a release asset can usually replace the sidecar beside it. The digest
|
|
974
|
+
* comes from the release resource instead.
|
|
975
|
+
*/
|
|
976
|
+
export async function verifyArchive(
|
|
977
|
+
tool: ManagedTool,
|
|
978
|
+
version: string,
|
|
979
|
+
asset: string,
|
|
980
|
+
archivePath: string,
|
|
981
|
+
options: NetworkOptions & { allowUnverified?: boolean } = {},
|
|
982
|
+
): Promise<VerifiedArchive> {
|
|
983
|
+
const actual = sha256File(archivePath);
|
|
984
|
+
const permitted = options.allowUnverified ?? allowUnverified();
|
|
985
|
+
let expected: string | undefined;
|
|
986
|
+
try {
|
|
987
|
+
expected = await fetchAssetDigest(tool, version, asset, options);
|
|
988
|
+
} catch (error) {
|
|
989
|
+
if (permitted || tool.digestOptional) return { digest: actual, verified: false };
|
|
990
|
+
const status = error instanceof HttpError ? error.status : undefined;
|
|
991
|
+
const cause =
|
|
992
|
+
status === 403 || status === 429
|
|
993
|
+
? `GitHub API rate limit or access denied (${status}); set GITHUB_TOKEN to raise the limit`
|
|
994
|
+
: errorMessage(error);
|
|
995
|
+
throw new Error(
|
|
996
|
+
`${tool.name}: cannot verify ${asset}: ${cause}; set ${ALLOW_UNVERIFIED_ENV}=1 to install it unverified`,
|
|
997
|
+
);
|
|
998
|
+
}
|
|
999
|
+
if (!expected) {
|
|
1000
|
+
if (permitted || tool.digestOptional) return { digest: actual, verified: false };
|
|
1001
|
+
throw new Error(
|
|
1002
|
+
`${tool.name}: no digest published for ${asset}; set ${ALLOW_UNVERIFIED_ENV}=1 to install it unverified`,
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
if (expected !== actual) {
|
|
1006
|
+
throw new Error(`${tool.name}: digest mismatch for ${asset}: expected ${expected}, got ${actual}`);
|
|
1007
|
+
}
|
|
1008
|
+
return { digest: actual, verified: true };
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// =============================================================================
|
|
1012
|
+
// Archives
|
|
1013
|
+
// =============================================================================
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* Absolute paths for helpers, deliberately outside the PATH this package rewrites.
|
|
1017
|
+
*
|
|
1018
|
+
* `<agent dir>/busybox-applets` links an `unzip` (and, under PI_MANAGED_TOOLS_APPLETS=all,
|
|
1019
|
+
* a `tar`), so a bare `spawnSync("unzip")` resolves to the packaged busybox — and this
|
|
1020
|
+
* build's `unzip -d DIR` exits 0 having extracted nothing, which silently breaks every
|
|
1021
|
+
* zip-based install. Extraction therefore looks for a system binary first and never
|
|
1022
|
+
* trusts PATH order it controls itself.
|
|
1023
|
+
*/
|
|
1024
|
+
const SYSTEM_BIN_DIRS = ["/usr/bin", "/bin", "/usr/local/bin", "/opt/homebrew/bin"];
|
|
1025
|
+
|
|
1026
|
+
function systemToolPath(name: string): string | undefined {
|
|
1027
|
+
if (process.platform === "win32") return undefined;
|
|
1028
|
+
for (const dir of SYSTEM_BIN_DIRS) {
|
|
1029
|
+
const candidate = join(dir, name);
|
|
1030
|
+
if (existsSync(candidate)) return candidate;
|
|
1031
|
+
}
|
|
1032
|
+
return undefined;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function runExtraction(command: string, args: string[]): string | null {
|
|
1036
|
+
const result = spawnSync(command, args, { encoding: "utf-8", windowsHide: true });
|
|
1037
|
+
if (!result.error && result.status === 0) return null;
|
|
1038
|
+
const detail = result.error?.message || String(result.stderr ?? "").trim() || `exit status ${result.status}`;
|
|
1039
|
+
return `${command}: ${detail}`;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/** Windows ships bsdtar as tar.exe; Git Bash's GNU tar cannot read zip archives. */
|
|
1043
|
+
function windowsTar(): string {
|
|
1044
|
+
const systemRoot = process.env.SystemRoot;
|
|
1045
|
+
if (systemRoot) {
|
|
1046
|
+
const systemTar = join(systemRoot, "System32", "tar.exe");
|
|
1047
|
+
if (existsSync(systemTar)) return systemTar;
|
|
1048
|
+
}
|
|
1049
|
+
return "tar.exe";
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
function extractZip(archivePath: string, extractDir: string, binDir?: string): void {
|
|
1053
|
+
const failures: string[] = [];
|
|
1054
|
+
if (process.platform === "win32") {
|
|
1055
|
+
const tarFailure = runExtraction(windowsTar(), ["xf", archivePath, "-C", extractDir]);
|
|
1056
|
+
if (!tarFailure) return;
|
|
1057
|
+
failures.push(tarFailure);
|
|
1058
|
+
const script =
|
|
1059
|
+
"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }";
|
|
1060
|
+
const powershellFailure = runExtraction("powershell.exe", [
|
|
1061
|
+
"-NoLogo",
|
|
1062
|
+
"-NoProfile",
|
|
1063
|
+
"-NonInteractive",
|
|
1064
|
+
"-ExecutionPolicy",
|
|
1065
|
+
"Bypass",
|
|
1066
|
+
"-Command",
|
|
1067
|
+
script,
|
|
1068
|
+
archivePath,
|
|
1069
|
+
extractDir,
|
|
1070
|
+
]);
|
|
1071
|
+
if (!powershellFailure) return;
|
|
1072
|
+
failures.push(powershellFailure);
|
|
1073
|
+
} else {
|
|
1074
|
+
// Order matters: a system unzip, then bsdtar (which reads zip; GNU tar does not),
|
|
1075
|
+
// then the packaged busybox as an absolute path. A bare name would pick up our own
|
|
1076
|
+
// applet symlink instead of the host tool.
|
|
1077
|
+
for (const unzip of [systemToolPath("unzip"), "unzip"].filter((path): path is string => Boolean(path))) {
|
|
1078
|
+
const failure = runExtraction(unzip, ["-q", archivePath, "-d", extractDir]);
|
|
1079
|
+
if (!failure) return;
|
|
1080
|
+
failures.push(failure);
|
|
1081
|
+
}
|
|
1082
|
+
for (const tar of [systemToolPath("tar"), "tar"].filter((path): path is string => Boolean(path))) {
|
|
1083
|
+
const failure = runExtraction(tar, ["xf", archivePath, "-C", extractDir]);
|
|
1084
|
+
if (!failure) return;
|
|
1085
|
+
failures.push(failure);
|
|
1086
|
+
}
|
|
1087
|
+
if (binDir) {
|
|
1088
|
+
// Last resort: the multicall binary by absolute path, whose unzip needs no -d
|
|
1089
|
+
// because it extracts into the working directory.
|
|
1090
|
+
const busybox = join(binDir, "busybox");
|
|
1091
|
+
if (existsSync(busybox)) {
|
|
1092
|
+
const failure = runExtraction(busybox, ["unzip", "-q", archivePath], );
|
|
1093
|
+
if (!failure) {
|
|
1094
|
+
// Move the result into place: the applet writes into cwd.
|
|
1095
|
+
for (const entry of readdirSync(process.cwd())) {
|
|
1096
|
+
const from = join(process.cwd(), entry);
|
|
1097
|
+
const to = join(extractDir, entry);
|
|
1098
|
+
if (!existsSync(to) && entry !== archivePath) renameSync(from, to);
|
|
1099
|
+
}
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
failures.push(failure);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
throw new Error(`Failed to extract ${archivePath}: ${failures.join("; ")}`);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
function findFileRecursively(rootDir: string, fileName: string): string | undefined {
|
|
1110
|
+
const stack = [rootDir];
|
|
1111
|
+
while (stack.length > 0) {
|
|
1112
|
+
const current = stack.pop() as string;
|
|
1113
|
+
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
1114
|
+
const fullPath = join(current, entry.name);
|
|
1115
|
+
if (entry.isFile() && entry.name === fileName) return fullPath;
|
|
1116
|
+
if (entry.isDirectory()) stack.push(fullPath);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return undefined;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
function sleepSync(ms: number): void {
|
|
1123
|
+
const shared = new SharedArrayBuffer(4);
|
|
1124
|
+
Atomics.wait(new Int32Array(shared), 0, 0, ms);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* Put `staged` at `target`, then prove the result runs.
|
|
1129
|
+
*
|
|
1130
|
+
* POSIX renames over the old inode atomically, so a running pi keeps using the
|
|
1131
|
+
* binary it already opened. Windows refuses to replace a running image, so the
|
|
1132
|
+
* old file is linked aside first and restored if either the swap or the version
|
|
1133
|
+
* probe fails. The probe matters for a class of bug the previous version shipped:
|
|
1134
|
+
* reporting the version we *asked for* claims success for a binary that cannot
|
|
1135
|
+
* execute at all (wrong arch, glibc against a musl build, a truncated download).
|
|
1136
|
+
*/
|
|
1137
|
+
interface BundleEntry {
|
|
1138
|
+
staged: string;
|
|
1139
|
+
target: string;
|
|
1140
|
+
/** Only the tool's primary binary is required to report a version. */
|
|
1141
|
+
primary: boolean;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
interface BundlePlan extends BundleEntry {
|
|
1145
|
+
backup: string;
|
|
1146
|
+
hadTarget: boolean;
|
|
1147
|
+
hasBackup: boolean;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/** Swap one staged file into place, tolerating Windows' refusal to replace a running image. */
|
|
1151
|
+
function swapIn(entry: BundleEntry, plat: string): void {
|
|
1152
|
+
if (plat !== "win32") {
|
|
1153
|
+
renameSync(entry.staged, entry.target);
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
let lastError: unknown;
|
|
1157
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1158
|
+
try {
|
|
1159
|
+
rmSync(entry.target, { force: true });
|
|
1160
|
+
renameSync(entry.staged, entry.target);
|
|
1161
|
+
return;
|
|
1162
|
+
} catch (error) {
|
|
1163
|
+
lastError = error;
|
|
1164
|
+
sleepSync(200 * (attempt + 1));
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
throw lastError;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* Install every binary an archive provides, as one unit.
|
|
1172
|
+
*
|
|
1173
|
+
* One archive can carry several commands (ast-grep ships `ast-grep` and the `sg`
|
|
1174
|
+
* shim, which execs its sibling). Swapping them one at a time and probing only
|
|
1175
|
+
* the first leaves a half-repaired bundle: a new `ast-grep` beside a broken `sg`
|
|
1176
|
+
* reports success while the damaged command is still there. So every target is
|
|
1177
|
+
* backed up, every target is swapped, every target is probed, and any failure
|
|
1178
|
+
* restores all of them.
|
|
1179
|
+
*/
|
|
1180
|
+
function installBundle(
|
|
1181
|
+
entries: BundleEntry[],
|
|
1182
|
+
plat: string,
|
|
1183
|
+
tool: ManagedTool,
|
|
1184
|
+
unique: string,
|
|
1185
|
+
binDir: string,
|
|
1186
|
+
): string | undefined {
|
|
1187
|
+
const plan: BundlePlan[] = entries.map((entry) => ({
|
|
1188
|
+
...entry,
|
|
1189
|
+
// The token keeps a concurrent pi process from overwriting this run's rollback.
|
|
1190
|
+
backup: `${entry.target}.${unique}.previous`,
|
|
1191
|
+
hadTarget: existsSync(entry.target),
|
|
1192
|
+
hasBackup: false,
|
|
1193
|
+
}));
|
|
1194
|
+
|
|
1195
|
+
for (const entry of plan) {
|
|
1196
|
+
if (!entry.hadTarget) continue;
|
|
1197
|
+
// Hardlink rather than copy: keeps the old inode reachable with no extra I/O.
|
|
1198
|
+
// Copy is the fallback for filesystems without hard links.
|
|
1199
|
+
try {
|
|
1200
|
+
linkSync(entry.target, entry.backup);
|
|
1201
|
+
entry.hasBackup = true;
|
|
1202
|
+
} catch {
|
|
1203
|
+
try {
|
|
1204
|
+
copyFileSync(entry.target, entry.backup);
|
|
1205
|
+
entry.hasBackup = true;
|
|
1206
|
+
} catch {
|
|
1207
|
+
entry.hasBackup = false;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
// Replacing a binary we could not back up would leave nothing to restore.
|
|
1211
|
+
if (!entry.hasBackup) {
|
|
1212
|
+
for (const previous of plan) rmSync(previous.backup, { force: true });
|
|
1213
|
+
throw new Error(`${tool.name}: cannot back up ${entry.target}; refusing to replace it`);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
try {
|
|
1218
|
+
for (const entry of plan) swapIn(entry, plat);
|
|
1219
|
+
|
|
1220
|
+
let detected: string | undefined;
|
|
1221
|
+
for (const entry of plan) {
|
|
1222
|
+
const probe = probeBinary(entry.target, binDir);
|
|
1223
|
+
if (!probe.ran) throw new Error(`${tool.name}: installed binary did not run: ${entry.target}`);
|
|
1224
|
+
if (entry.primary) {
|
|
1225
|
+
if (!probe.version && !tool.versionOptional) {
|
|
1226
|
+
throw new Error(`${tool.name}: ${entry.target} reported no version; refusing to install it`);
|
|
1227
|
+
}
|
|
1228
|
+
detected = probe.version;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
for (const entry of plan) rmSync(entry.backup, { force: true });
|
|
1233
|
+
return detected;
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
for (const entry of plan) {
|
|
1236
|
+
if (entry.hasBackup) {
|
|
1237
|
+
try {
|
|
1238
|
+
renameSync(entry.backup, entry.target);
|
|
1239
|
+
} catch {
|
|
1240
|
+
// Nothing further to restore from.
|
|
1241
|
+
}
|
|
1242
|
+
} else if (!entry.hadTarget) {
|
|
1243
|
+
// Only remove what this run created.
|
|
1244
|
+
rmSync(entry.target, { force: true });
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
throw error;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// =============================================================================
|
|
1252
|
+
// Install
|
|
1253
|
+
// =============================================================================
|
|
1254
|
+
|
|
1255
|
+
export interface InstallOptions extends NetworkOptions {
|
|
1256
|
+
binDir: string;
|
|
1257
|
+
plat?: string;
|
|
1258
|
+
architecture?: string;
|
|
1259
|
+
/** Override the fail-closed digest policy for this call. */
|
|
1260
|
+
allowUnverified?: boolean;
|
|
1261
|
+
onProgress?: (message: string) => void;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
export interface InstallResult {
|
|
1265
|
+
path: string;
|
|
1266
|
+
version: string | undefined;
|
|
1267
|
+
/** sha256 recorded for the archive this binary came from. */
|
|
1268
|
+
digest?: string;
|
|
1269
|
+
/** False only when the unverified opt-out let an unconfirmed archive through. */
|
|
1270
|
+
verified?: boolean;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* Download one release and put its binary where pi looks for it.
|
|
1275
|
+
*
|
|
1276
|
+
* The archive is fetched and extracted inside the bin directory so the final
|
|
1277
|
+
* rename stays on one filesystem - a rename across devices fails, and a
|
|
1278
|
+
* non-atomic copy could leave a truncated binary where pi expects a working
|
|
1279
|
+
* one.
|
|
1280
|
+
*/
|
|
1281
|
+
/**
|
|
1282
|
+
* The asset to download for a release.
|
|
1283
|
+
*
|
|
1284
|
+
* Constructed from the version when the project names assets predictably, matched
|
|
1285
|
+
* against the release's own list when it does not (busybox-static keeps the upstream
|
|
1286
|
+
* build version in its asset names across project releases).
|
|
1287
|
+
*/
|
|
1288
|
+
export async function resolveAsset(
|
|
1289
|
+
tool: ManagedTool,
|
|
1290
|
+
version: string,
|
|
1291
|
+
target: string,
|
|
1292
|
+
options: NetworkOptions = {},
|
|
1293
|
+
): Promise<string> {
|
|
1294
|
+
if (!tool.assetPattern) return tool.assetName(version, target);
|
|
1295
|
+
const pattern = tool.assetPattern(target);
|
|
1296
|
+
const names = (await releaseAssets(tool, version, options))
|
|
1297
|
+
.map((entry) => entry?.name)
|
|
1298
|
+
.filter((name): name is string => typeof name === "string");
|
|
1299
|
+
const match = names.find((name) => pattern.test(name));
|
|
1300
|
+
if (!match) {
|
|
1301
|
+
throw new Error(`${tool.name}: no release asset matching ${pattern} in ${tool.tagPrefix}${version}`);
|
|
1302
|
+
}
|
|
1303
|
+
return match;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
export async function installTool(
|
|
1307
|
+
toolId: ToolId,
|
|
1308
|
+
version: string,
|
|
1309
|
+
options: InstallOptions,
|
|
1310
|
+
): Promise<InstallResult> {
|
|
1311
|
+
const tool = MANAGED_TOOLS[toolId];
|
|
1312
|
+
const plat = options.plat ?? platform();
|
|
1313
|
+
const architecture = options.architecture ?? arch();
|
|
1314
|
+
const target = targetFor(tool, plat, architecture);
|
|
1315
|
+
if (!target) {
|
|
1316
|
+
throw new Error(`${tool.name}: no prebuilt release for ${plat}/${architecture}`);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
const asset = await resolveAsset(tool, version, target, options);
|
|
1320
|
+
const url = downloadUrl(tool, version, asset);
|
|
1321
|
+
const binDir = options.binDir;
|
|
1322
|
+
mkdirSync(binDir, { recursive: true });
|
|
1323
|
+
|
|
1324
|
+
const unique = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1325
|
+
const archivePath = join(binDir, `.${asset}.${unique}.download`);
|
|
1326
|
+
const extractDir = join(binDir, `.extract-${tool.id}-${unique}`);
|
|
1327
|
+
const fileName = binaryFileName(tool, plat);
|
|
1328
|
+
const stagedPaths: string[] = [];
|
|
1329
|
+
|
|
1330
|
+
try {
|
|
1331
|
+
options.onProgress?.(`downloading ${asset}`);
|
|
1332
|
+
await downloadFile(url, archivePath, options);
|
|
1333
|
+
const { digest, verified } = await verifyArchive(tool, version, asset, archivePath, options);
|
|
1334
|
+
|
|
1335
|
+
const stagedFiles: Array<{ staged: string; target: string }> = [];
|
|
1336
|
+
if (tool.raw) {
|
|
1337
|
+
// Some projects publish the executable with no archive around it (jq,
|
|
1338
|
+
// yq), so staging the download IS the extraction step.
|
|
1339
|
+
const stagedPath = join(binDir, `.${fileName}.${unique}.new`);
|
|
1340
|
+
renameSync(archivePath, stagedPath);
|
|
1341
|
+
// Registered before chmod: a failing chmod must not leak the file.
|
|
1342
|
+
stagedPaths.push(stagedPath);
|
|
1343
|
+
if (plat !== "win32") chmodSync(stagedPath, 0o755);
|
|
1344
|
+
stagedFiles.push({ staged: stagedPath, target: join(binDir, fileName) });
|
|
1345
|
+
} else {
|
|
1346
|
+
mkdirSync(extractDir, { recursive: true });
|
|
1347
|
+
if (asset.endsWith(".tar.gz") || asset.endsWith(".tgz")) {
|
|
1348
|
+
const failure = runExtraction(systemToolPath("tar") ?? "tar", ["xzf", archivePath, "-C", extractDir]);
|
|
1349
|
+
if (failure) throw new Error(`Failed to extract ${asset}: ${failure}`);
|
|
1350
|
+
} else if (asset.endsWith(".zip")) {
|
|
1351
|
+
extractZip(archivePath, extractDir, binDir);
|
|
1352
|
+
} else {
|
|
1353
|
+
throw new Error(`Unsupported archive format: ${asset}`);
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// One archive can provide several commands (ast-grep ships both ast-grep
|
|
1357
|
+
// and sg), so every declared name is staged before any is installed.
|
|
1358
|
+
for (const name of tool.provides ?? [tool.binaryName]) {
|
|
1359
|
+
const archiveName = name + (plat === "win32" ? ".exe" : "");
|
|
1360
|
+
const extracted = findFileRecursively(extractDir, archiveName);
|
|
1361
|
+
if (!extracted) throw new Error(`Binary not found in archive: expected ${archiveName} in ${asset}`);
|
|
1362
|
+
const stagedPath = join(binDir, `.${archiveName}.${unique}.new`);
|
|
1363
|
+
renameSync(extracted, stagedPath);
|
|
1364
|
+
stagedPaths.push(stagedPath);
|
|
1365
|
+
if (plat !== "win32") chmodSync(stagedPath, 0o755);
|
|
1366
|
+
stagedFiles.push({ staged: stagedPath, target: join(binDir, archiveName) });
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
const installedPath = join(binDir, fileName);
|
|
1371
|
+
// The whole bundle is installed and probed as one unit; see installBundle.
|
|
1372
|
+
const detected = installBundle(
|
|
1373
|
+
stagedFiles.map((entry) => ({ ...entry, primary: entry.target === installedPath })),
|
|
1374
|
+
plat,
|
|
1375
|
+
tool,
|
|
1376
|
+
unique,
|
|
1377
|
+
binDir,
|
|
1378
|
+
);
|
|
1379
|
+
stagedPaths.length = 0;
|
|
1380
|
+
// A tool whose build string lags its tag is recorded at the tag version.
|
|
1381
|
+
return {
|
|
1382
|
+
path: installedPath,
|
|
1383
|
+
version: tool.trustTagVersion ? version : (detected ?? version),
|
|
1384
|
+
digest,
|
|
1385
|
+
verified,
|
|
1386
|
+
};
|
|
1387
|
+
} finally {
|
|
1388
|
+
// A failed install used to leave a 0755 executable staged in the same
|
|
1389
|
+
// directory pi searches first.
|
|
1390
|
+
for (const stagedPath of stagedPaths) rmSync(stagedPath, { force: true });
|
|
1391
|
+
rmSync(archivePath, { force: true });
|
|
1392
|
+
rmSync(extractDir, { recursive: true, force: true });
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// =============================================================================
|
|
1397
|
+
// Reports
|
|
1398
|
+
// =============================================================================
|
|
1399
|
+
|
|
1400
|
+
export type ToolAction = "installed" | "updated" | "reinstalled" | "unchanged" | "failed" | "skipped";
|
|
1401
|
+
|
|
1402
|
+
export interface ToolReport {
|
|
1403
|
+
tool: ToolId;
|
|
1404
|
+
name: string;
|
|
1405
|
+
action: ToolAction;
|
|
1406
|
+
/** Whether this tool publishes a release for the current platform. */
|
|
1407
|
+
supported: boolean;
|
|
1408
|
+
/** pi built-in tools that resolve this binary; empty means PATH-only. */
|
|
1409
|
+
consumedBy: string[];
|
|
1410
|
+
/** Managed binary in pi's bin directory, when one exists after the call. */
|
|
1411
|
+
path?: string;
|
|
1412
|
+
version?: string;
|
|
1413
|
+
previousVersion?: string;
|
|
1414
|
+
/** Latest upstream version, when it could be resolved. */
|
|
1415
|
+
latest?: string;
|
|
1416
|
+
systemPath?: string;
|
|
1417
|
+
/** sha256 recorded for the archive this binary came from. */
|
|
1418
|
+
digest?: string;
|
|
1419
|
+
/** False only when an archive could not be verified and the opt-out allowed it. */
|
|
1420
|
+
verified?: boolean;
|
|
1421
|
+
/** Set when the installed binary is present but cannot execute. */
|
|
1422
|
+
damaged?: string;
|
|
1423
|
+
error?: string;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
export interface Report {
|
|
1427
|
+
plat: string;
|
|
1428
|
+
architecture: string;
|
|
1429
|
+
supported: boolean;
|
|
1430
|
+
binDir: string;
|
|
1431
|
+
checkedAt: number;
|
|
1432
|
+
tools: ToolReport[];
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
interface SharedOptions extends NetworkOptions {
|
|
1436
|
+
binDir: string;
|
|
1437
|
+
plat?: string;
|
|
1438
|
+
architecture?: string;
|
|
1439
|
+
/** Override the fail-closed digest policy for this call. */
|
|
1440
|
+
allowUnverified?: boolean;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
function localState(tool: ManagedTool, binDir: string, plat: string, state: CheckState | undefined) {
|
|
1444
|
+
const path = managedBinaryPath(tool, binDir, plat);
|
|
1445
|
+
const installed = existsSync(path);
|
|
1446
|
+
// Every name the archive provides is checked, not just the primary: a bundled
|
|
1447
|
+
// shim can rot on its own (ast-grep's `sg` execs its sibling and breaks if that
|
|
1448
|
+
// sibling is replaced by something that is not there or will not run).
|
|
1449
|
+
const problems: string[] = [];
|
|
1450
|
+
let version: string | undefined;
|
|
1451
|
+
for (const name of tool.provides ?? [tool.binaryName]) {
|
|
1452
|
+
const binaryPath = join(binDir, name + (plat === "win32" ? ".exe" : ""));
|
|
1453
|
+
const isPrimary = binaryPath === path;
|
|
1454
|
+
if (!existsSync(binaryPath)) {
|
|
1455
|
+
// A missing primary is "not installed". A missing secondary only counts
|
|
1456
|
+
// when the primary is there: otherwise this is a fresh install, not
|
|
1457
|
+
// damage, and a repair would never be the right action.
|
|
1458
|
+
if (!isPrimary && installed) problems.push(`${name} missing`);
|
|
1459
|
+
continue;
|
|
1460
|
+
}
|
|
1461
|
+
// Check the size before trusting the probe: Linux falls back to /bin/sh for a
|
|
1462
|
+
// file without a valid executable header, so a zero-length binary "runs" and
|
|
1463
|
+
// exits 0 there while macOS reports ENOEXEC. Neither should read as healthy.
|
|
1464
|
+
if (statSync(binaryPath).size === 0) {
|
|
1465
|
+
problems.push(`${name} is empty`);
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
const probe = probeBinary(binaryPath, binDir);
|
|
1469
|
+
if (!probe.ran) problems.push(`${name} does not execute`);
|
|
1470
|
+
if (isPrimary) version = probe.version;
|
|
1471
|
+
}
|
|
1472
|
+
const recorded = installed ? state?.installed?.[tool.id] : undefined;
|
|
1473
|
+
// For a tool that misreports its own build number, the recorded release tag is
|
|
1474
|
+
// the only trustworthy version; otherwise every check would reinstall it.
|
|
1475
|
+
const installedVersion = tool.trustTagVersion ? (recorded ?? version) : (version ?? recorded);
|
|
1476
|
+
return {
|
|
1477
|
+
path: installed ? path : undefined,
|
|
1478
|
+
version: installedVersion,
|
|
1479
|
+
damaged: problems.length > 0 ? problems.join(", ") : undefined,
|
|
1480
|
+
systemPath: findSystemBinary(tool, plat),
|
|
1481
|
+
};
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
/** Resolve a user-supplied tool name or id, for the reinstall argument. */
|
|
1485
|
+
export function findToolId(name: string): ToolId | undefined {
|
|
1486
|
+
const wanted = name.trim().toLowerCase();
|
|
1487
|
+
if (!wanted) return undefined;
|
|
1488
|
+
return MANAGED_TOOL_IDS.find((id) => {
|
|
1489
|
+
const tool = MANAGED_TOOLS[id];
|
|
1490
|
+
const names = [id, tool.name.toLowerCase(), ...(tool.provides ?? []).map((provided) => provided.toLowerCase())];
|
|
1491
|
+
return names.includes(wanted);
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
export async function inspectTools(options: SharedOptions & { checkLatest?: boolean }): Promise<Report> {
|
|
1496
|
+
const plat = options.plat ?? platform();
|
|
1497
|
+
const architecture = options.architecture ?? arch();
|
|
1498
|
+
const checkedAt = Date.now();
|
|
1499
|
+
const state = readState(options.binDir);
|
|
1500
|
+
|
|
1501
|
+
const tools = await Promise.all(
|
|
1502
|
+
MANAGED_TOOL_IDS.map(async (toolId): Promise<ToolReport> => {
|
|
1503
|
+
const tool = MANAGED_TOOLS[toolId];
|
|
1504
|
+
const local = localState(tool, options.binDir, plat, state);
|
|
1505
|
+
const supported = targetFor(tool, plat, architecture) !== undefined;
|
|
1506
|
+
const report: ToolReport = {
|
|
1507
|
+
tool: toolId,
|
|
1508
|
+
name: tool.name,
|
|
1509
|
+
action: "unchanged",
|
|
1510
|
+
supported,
|
|
1511
|
+
consumedBy: [...tool.consumedBy],
|
|
1512
|
+
path: local.path,
|
|
1513
|
+
version: local.version,
|
|
1514
|
+
damaged: local.damaged,
|
|
1515
|
+
systemPath: local.systemPath,
|
|
1516
|
+
};
|
|
1517
|
+
if (options.checkLatest === false || !supported) return report;
|
|
1518
|
+
try {
|
|
1519
|
+
report.latest = await fetchLatestVersion(tool, options);
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
report.error = errorMessage(error);
|
|
1522
|
+
}
|
|
1523
|
+
return report;
|
|
1524
|
+
}),
|
|
1525
|
+
);
|
|
1526
|
+
|
|
1527
|
+
return {
|
|
1528
|
+
plat,
|
|
1529
|
+
architecture,
|
|
1530
|
+
supported: tools.some((tool) => tool.supported),
|
|
1531
|
+
binDir: options.binDir,
|
|
1532
|
+
checkedAt,
|
|
1533
|
+
tools,
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
export type ReinstallRequest = "damaged" | "all" | ToolId[];
|
|
1538
|
+
|
|
1539
|
+
export async function updateTools(
|
|
1540
|
+
options: SharedOptions & { onProgress?: (message: string) => void; reinstall?: ReinstallRequest },
|
|
1541
|
+
): Promise<Report> {
|
|
1542
|
+
const plat = options.plat ?? platform();
|
|
1543
|
+
const architecture = options.architecture ?? arch();
|
|
1544
|
+
const checkedAt = Date.now();
|
|
1545
|
+
const force = options.reinstall;
|
|
1546
|
+
|
|
1547
|
+
const tools: ToolReport[] = [];
|
|
1548
|
+
const state = readState(options.binDir);
|
|
1549
|
+
for (const toolId of MANAGED_TOOL_IDS) {
|
|
1550
|
+
const tool = MANAGED_TOOLS[toolId];
|
|
1551
|
+
const local = localState(tool, options.binDir, plat, state);
|
|
1552
|
+
const target = targetFor(tool, plat, architecture);
|
|
1553
|
+
const report: ToolReport = {
|
|
1554
|
+
tool: toolId,
|
|
1555
|
+
name: tool.name,
|
|
1556
|
+
action: "unchanged",
|
|
1557
|
+
supported: target !== undefined,
|
|
1558
|
+
consumedBy: [...tool.consumedBy],
|
|
1559
|
+
path: local.path,
|
|
1560
|
+
version: local.version,
|
|
1561
|
+
damaged: local.damaged,
|
|
1562
|
+
systemPath: local.systemPath,
|
|
1563
|
+
};
|
|
1564
|
+
tools.push(report);
|
|
1565
|
+
|
|
1566
|
+
if (!target) {
|
|
1567
|
+
report.action = "skipped";
|
|
1568
|
+
report.error = `no prebuilt release for ${plat}/${architecture}`;
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// A forced reinstall ignores the version comparison: the point is to replace
|
|
1573
|
+
// a file that is broken, not one that is merely older.
|
|
1574
|
+
const forced =
|
|
1575
|
+
force === "all" ||
|
|
1576
|
+
(force === "damaged" ? local.damaged !== undefined : Array.isArray(force) && force.includes(toolId));
|
|
1577
|
+
const wasDamaged = local.damaged !== undefined;
|
|
1578
|
+
|
|
1579
|
+
try {
|
|
1580
|
+
report.latest = await fetchLatestVersion(tool, options);
|
|
1581
|
+
} catch (error) {
|
|
1582
|
+
// Reinstalling still works offline from the version already on disk, which
|
|
1583
|
+
// is exactly when a repair is most likely to be needed.
|
|
1584
|
+
if (!forced || !report.version) {
|
|
1585
|
+
report.action = "failed";
|
|
1586
|
+
report.error = errorMessage(error);
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1589
|
+
report.latest = report.version;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
// A damaged binary is never "up to date", whatever version it claims. The
|
|
1593
|
+
// state fallback supplies a version for a tool that cannot self-report, so
|
|
1594
|
+
// without this check a broken gron would compare equal and never be fixed.
|
|
1595
|
+
if (!forced && !wasDamaged && !needsUpdate(tool, report.version, report.latest)) {
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
try {
|
|
1600
|
+
const result = await installTool(toolId, report.latest, options);
|
|
1601
|
+
report.previousVersion = report.version;
|
|
1602
|
+
report.version = result.version;
|
|
1603
|
+
report.path = result.path;
|
|
1604
|
+
report.digest = result.digest;
|
|
1605
|
+
report.verified = result.verified;
|
|
1606
|
+
// The probe that matters is the one installBinary just ran.
|
|
1607
|
+
report.damaged = undefined;
|
|
1608
|
+
report.action = forced || wasDamaged ? "reinstalled" : report.previousVersion ? "updated" : "installed";
|
|
1609
|
+
} catch (error) {
|
|
1610
|
+
report.action = "failed";
|
|
1611
|
+
report.error = errorMessage(error);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
const report: Report = {
|
|
1616
|
+
plat,
|
|
1617
|
+
architecture,
|
|
1618
|
+
supported: tools.some((tool) => tool.supported),
|
|
1619
|
+
binDir: options.binDir,
|
|
1620
|
+
checkedAt,
|
|
1621
|
+
tools,
|
|
1622
|
+
};
|
|
1623
|
+
// Persist here rather than leaving it to the caller: a tool that cannot report
|
|
1624
|
+
// its own version (gron) is compared against this record, so a caller that
|
|
1625
|
+
// forgets to write it reinstalls that tool on every single run.
|
|
1626
|
+
//
|
|
1627
|
+
// An all-failed run does not advance the timestamp: otherwise one rate-limited
|
|
1628
|
+
// or offline cycle would defer the next attempt for the whole interval, which
|
|
1629
|
+
// is the opposite of what a broken machine needs.
|
|
1630
|
+
const supportedReports = tools.filter((tool) => tool.supported);
|
|
1631
|
+
const allFailed = supportedReports.length > 0 && supportedReports.every((tool) => tool.action === "failed");
|
|
1632
|
+
writeState(options.binDir, report, { advance: !allFailed });
|
|
1633
|
+
return report;
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
export function errorMessage(error: unknown): string {
|
|
1637
|
+
if (error instanceof Error) {
|
|
1638
|
+
const messages = [error.message];
|
|
1639
|
+
for (let current = error.cause, depth = 0; current instanceof Error && depth < 3; current = current.cause, depth++) {
|
|
1640
|
+
if (!messages.includes(current.message)) messages.push(current.message);
|
|
1641
|
+
}
|
|
1642
|
+
return messages.join(": ");
|
|
1643
|
+
}
|
|
1644
|
+
return String(error);
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
// =============================================================================
|
|
1648
|
+
// Check state and settings
|
|
1649
|
+
// =============================================================================
|
|
1650
|
+
|
|
1651
|
+
export interface CheckState {
|
|
1652
|
+
checkedAt: number;
|
|
1653
|
+
latest: Partial<Record<ToolId, string>>;
|
|
1654
|
+
/**
|
|
1655
|
+
* Versions this package last installed. A tool whose binary cannot report its
|
|
1656
|
+
* own version (gron) is compared against this instead, so it is not reinstalled
|
|
1657
|
+
* on every check.
|
|
1658
|
+
*/
|
|
1659
|
+
installed?: Partial<Record<ToolId, string>>;
|
|
1660
|
+
/**
|
|
1661
|
+
* Last failure per tool. Without this a tool that cannot install on this host
|
|
1662
|
+
* (no digest published, wrong libc, an upstream rename) keeps its binary
|
|
1663
|
+
* missing, and a missing binary forces a full update cycle on every start.
|
|
1664
|
+
*/
|
|
1665
|
+
failures?: Partial<Record<ToolId, { at: number; reason: string }>>;
|
|
1666
|
+
/** sha256 accepted for the installed binary, so a later check can compare. */
|
|
1667
|
+
digests?: Partial<Record<ToolId, string>>;
|
|
1668
|
+
/** Tools whose installed binary was never confirmed against a digest. */
|
|
1669
|
+
unverified?: Partial<Record<ToolId, boolean>>;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
export function statePath(binDir: string): string {
|
|
1673
|
+
return join(binDir, STATE_FILE);
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
export function readState(binDir: string): CheckState | undefined {
|
|
1677
|
+
try {
|
|
1678
|
+
const parsed = JSON.parse(readFileSync(statePath(binDir), "utf-8")) as Partial<CheckState>;
|
|
1679
|
+
if (typeof parsed?.checkedAt !== "number") return undefined;
|
|
1680
|
+
return {
|
|
1681
|
+
checkedAt: parsed.checkedAt,
|
|
1682
|
+
latest: parsed.latest ?? {},
|
|
1683
|
+
installed: parsed.installed ?? {},
|
|
1684
|
+
failures: parsed.failures ?? {},
|
|
1685
|
+
digests: parsed.digests ?? {},
|
|
1686
|
+
unverified: parsed.unverified ?? {},
|
|
1687
|
+
};
|
|
1688
|
+
} catch {
|
|
1689
|
+
return undefined;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
export function writeState(binDir: string, report: Report, options: { advance?: boolean } = {}): void {
|
|
1694
|
+
try {
|
|
1695
|
+
mkdirSync(binDir, { recursive: true });
|
|
1696
|
+
const previous = readState(binDir);
|
|
1697
|
+
const latest: Partial<Record<ToolId, string>> = { ...previous?.latest };
|
|
1698
|
+
for (const tool of report.tools) if (tool.latest) latest[tool.tool] = tool.latest;
|
|
1699
|
+
// Only overwrite an installed version with a version we actually saw; a
|
|
1700
|
+
// status check that resolved nothing must not erase it.
|
|
1701
|
+
const installed: Partial<Record<ToolId, string>> = { ...previous?.installed };
|
|
1702
|
+
for (const tool of report.tools) if (tool.version) installed[tool.tool] = tool.version;
|
|
1703
|
+
const failures: Partial<Record<ToolId, { at: number; reason: string }>> = { ...previous?.failures };
|
|
1704
|
+
const digests: Partial<Record<ToolId, string>> = { ...previous?.digests };
|
|
1705
|
+
const unverified: Partial<Record<ToolId, boolean>> = { ...previous?.unverified };
|
|
1706
|
+
for (const tool of report.tools) {
|
|
1707
|
+
if (tool.action === "failed") {
|
|
1708
|
+
failures[tool.tool] = { at: report.checkedAt, reason: tool.error ?? "unknown error" };
|
|
1709
|
+
} else if (tool.action !== "skipped") {
|
|
1710
|
+
// Any other outcome means the tool is usable; forget the failure.
|
|
1711
|
+
delete failures[tool.tool];
|
|
1712
|
+
}
|
|
1713
|
+
if (tool.digest) digests[tool.tool] = tool.digest;
|
|
1714
|
+
if (tool.verified === false) unverified[tool.tool] = true;
|
|
1715
|
+
else if (tool.verified === true) delete unverified[tool.tool];
|
|
1716
|
+
}
|
|
1717
|
+
// A run where everything failed still records per-tool failures, so a host
|
|
1718
|
+
// that cannot install a tool stops retrying it, but it must not move
|
|
1719
|
+
// checkedAt: that would defer the next real attempt for a whole interval.
|
|
1720
|
+
const checkedAt = options.advance === false ? (previous?.checkedAt ?? report.checkedAt) : report.checkedAt;
|
|
1721
|
+
// A tool that left the registry (rtk) must not linger in the state: the record is
|
|
1722
|
+
// what a later release would compare against, and "installed 1.2.1" for a tool this
|
|
1723
|
+
// package no longer manages is simply wrong.
|
|
1724
|
+
const known = new Set<string>(MANAGED_TOOL_IDS);
|
|
1725
|
+
const prune = <T,>(record: Partial<Record<ToolId, T>>): Partial<Record<ToolId, T>> =>
|
|
1726
|
+
Object.fromEntries(Object.entries(record).filter(([id]) => known.has(id))) as Partial<Record<ToolId, T>>;
|
|
1727
|
+
const state: CheckState = {
|
|
1728
|
+
checkedAt,
|
|
1729
|
+
latest: prune(latest),
|
|
1730
|
+
installed: prune(installed),
|
|
1731
|
+
failures: prune(failures),
|
|
1732
|
+
digests: prune(digests),
|
|
1733
|
+
unverified: prune(unverified),
|
|
1734
|
+
};
|
|
1735
|
+
const path = statePath(binDir);
|
|
1736
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
1737
|
+
writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`);
|
|
1738
|
+
renameSync(temporary, path);
|
|
1739
|
+
} catch {
|
|
1740
|
+
// A missing state file only costs an extra check next start.
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
/**
|
|
1745
|
+
* Whether the installed copy is older than the release.
|
|
1746
|
+
*
|
|
1747
|
+
* A version recorded under a superseded naming scheme is older than every release of
|
|
1748
|
+
* the current one, whatever the numbers say.
|
|
1749
|
+
*/
|
|
1750
|
+
export function needsUpdate(tool: ManagedTool, installed: string | undefined, latest: string | undefined): boolean {
|
|
1751
|
+
if (!latest) return false;
|
|
1752
|
+
if (!installed) return true;
|
|
1753
|
+
if (tool.legacyVersionPattern?.test(installed)) return true;
|
|
1754
|
+
return compareVersions(installed, latest) < 0;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/** Whether to look for newer releases now. A missing managed binary always
|
|
1758
|
+
* triggers a check: pi would otherwise download it itself with no version
|
|
1759
|
+
* comparison at all.
|
|
1760
|
+
*/
|
|
1761
|
+
export function shouldCheck(
|
|
1762
|
+
state: CheckState | undefined,
|
|
1763
|
+
intervalHours: number,
|
|
1764
|
+
binDir: string,
|
|
1765
|
+
plat: string = platform(),
|
|
1766
|
+
architecture: string = arch(),
|
|
1767
|
+
now = Date.now(),
|
|
1768
|
+
): boolean {
|
|
1769
|
+
if (intervalHours <= 0) return true;
|
|
1770
|
+
const intervalMs = intervalHours * 60 * 60 * 1000;
|
|
1771
|
+
for (const toolId of MANAGED_TOOL_IDS) {
|
|
1772
|
+
const tool = MANAGED_TOOLS[toolId];
|
|
1773
|
+
// A tool with no release for this platform can never be installed here, so
|
|
1774
|
+
// its missing binary must not force a network check on every single start.
|
|
1775
|
+
if (targetFor(tool, plat, architecture) === undefined) continue;
|
|
1776
|
+
if (existsSync(managedBinaryPath(tool, binDir, plat))) continue;
|
|
1777
|
+
// Same reasoning for a tool that just failed: retrying it on every start
|
|
1778
|
+
// turns one uninstallable tool into a full download cycle each time.
|
|
1779
|
+
const failure = state?.failures?.[toolId];
|
|
1780
|
+
if (failure && now - failure.at >= 0 && now - failure.at < intervalMs) continue;
|
|
1781
|
+
return true;
|
|
1782
|
+
}
|
|
1783
|
+
if (!state) return true;
|
|
1784
|
+
const elapsed = now - state.checkedAt;
|
|
1785
|
+
return !(elapsed >= 0 && elapsed < intervalMs);
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
export interface ToolSettings {
|
|
1789
|
+
enabled: boolean;
|
|
1790
|
+
intervalHours: number;
|
|
1791
|
+
/** Rewrite absolute host paths to bare names on bash tool calls. */
|
|
1792
|
+
rewritePaths: boolean;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
/** Every name this package installs, including provided secondaries (sg, uvx). */
|
|
1796
|
+
export function managedBinaryNames(): Set<string> {
|
|
1797
|
+
const names = new Set<string>();
|
|
1798
|
+
for (const id of MANAGED_TOOL_IDS) {
|
|
1799
|
+
const tool = MANAGED_TOOLS[id];
|
|
1800
|
+
names.add(tool.binaryName);
|
|
1801
|
+
for (const name of tool.provides ?? []) names.add(name);
|
|
1802
|
+
}
|
|
1803
|
+
return names;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
const HOST_BIN_DIRS = ["/usr/bin", "/bin", "/usr/local/bin", "/opt/homebrew/bin"];
|
|
1807
|
+
|
|
1808
|
+
function escapeRegExp(value: string): string {
|
|
1809
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
/**
|
|
1813
|
+
* Replace an absolute host path for a managed tool with its bare name.
|
|
1814
|
+
*
|
|
1815
|
+
* `/usr/bin/jq -r .a` becomes `jq -r .a`, so the packaged binary runs instead of
|
|
1816
|
+
* the host's older build. Only a token in command position is touched (start of
|
|
1817
|
+
* string, or after whitespace, `;`, `|`, `&`, `(`), so `echo "/usr/bin/jq"` is
|
|
1818
|
+
* left alone, and only names this package manages, so `/usr/bin/tar` is untouched.
|
|
1819
|
+
*/
|
|
1820
|
+
export function rewriteToolPaths(
|
|
1821
|
+
command: string,
|
|
1822
|
+
names: Set<string> = managedBinaryNames(),
|
|
1823
|
+
extraDirs: string[] = [],
|
|
1824
|
+
): { command: string; rewrites: string[] } {
|
|
1825
|
+
const rewrites: string[] = [];
|
|
1826
|
+
let out = command;
|
|
1827
|
+
for (const dir of [...HOST_BIN_DIRS, ...extraDirs]) {
|
|
1828
|
+
const pattern = new RegExp(`(^|[\\s;|&(])${escapeRegExp(dir)}/([A-Za-z0-9._+-]+)`, "g");
|
|
1829
|
+
out = out.replace(pattern, (match, lead: string, name: string) => {
|
|
1830
|
+
if (!names.has(name)) return match;
|
|
1831
|
+
rewrites.push(`${dir}/${name}`);
|
|
1832
|
+
return `${lead}${name}`;
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
return { command: out, rewrites };
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
function isOffline(env: NodeJS.ProcessEnv): boolean {
|
|
1839
|
+
const value = (env.PI_OFFLINE ?? "").toLowerCase();
|
|
1840
|
+
return value === "1" || value === "true" || value === "yes";
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
export function readSettings(env: NodeJS.ProcessEnv = process.env): ToolSettings {
|
|
1844
|
+
const raw = (env.PI_MANAGED_TOOLS ?? "").trim().toLowerCase();
|
|
1845
|
+
const disabled = raw === "0" || raw === "off" || raw === "false" || raw === "no";
|
|
1846
|
+
const interval = Number(env.PI_MANAGED_TOOLS_INTERVAL_HOURS);
|
|
1847
|
+
const rewriteRaw = (env.PI_MANAGED_TOOLS_REWRITE ?? "").trim().toLowerCase();
|
|
1848
|
+
const rewriteOff = rewriteRaw === "0" || rewriteRaw === "off" || rewriteRaw === "false" || rewriteRaw === "no";
|
|
1849
|
+
return {
|
|
1850
|
+
enabled: !disabled && !isOffline(env),
|
|
1851
|
+
intervalHours: Number.isFinite(interval) && interval >= 0 ? interval : DEFAULT_INTERVAL_HOURS,
|
|
1852
|
+
rewritePaths: !rewriteOff,
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
// =============================================================================
|
|
1857
|
+
// BusyBox applet names
|
|
1858
|
+
// =============================================================================
|
|
1859
|
+
|
|
1860
|
+
/**
|
|
1861
|
+
* BusyBox dispatches on `argv[0]`: a symlink named `xxd` pointing at the
|
|
1862
|
+
* multicall binary runs the `xxd` applet. That is the only way to reach an
|
|
1863
|
+
* applet by bare name while the installed file keeps the name `busybox`, which
|
|
1864
|
+
* every other applet invocation depends on.
|
|
1865
|
+
*
|
|
1866
|
+
* The links live in their own directory rather than in the bin directory, for one
|
|
1867
|
+
* reason: PATH order is the only thing that decides which build a bare name runs,
|
|
1868
|
+
* and two names in the same directory cannot have an order. `<agent dir>/bin`
|
|
1869
|
+
* (one file per dedicated static tool) is listed first, this directory second, and
|
|
1870
|
+
* only then the user's and the system's directories.
|
|
1871
|
+
*
|
|
1872
|
+
* `busybox --install -s <dir>` is deliberately not used: it links all 236 applets,
|
|
1873
|
+
* including `sh`, `rm`, `mount` and `init`.
|
|
1874
|
+
*/
|
|
1875
|
+
export const APPLET_DIRNAME = "busybox-applets";
|
|
1876
|
+
|
|
1877
|
+
/** `core` (default) = the curated list below; `all` = every applet the build has; `off` = no links. */
|
|
1878
|
+
export type AppletPolicy = "core" | "all" | "off";
|
|
1879
|
+
|
|
1880
|
+
/**
|
|
1881
|
+
* Applets exposed by default, grouped by why they are here.
|
|
1882
|
+
*
|
|
1883
|
+
* The rule for this list: an applet belongs here when the host may not have the
|
|
1884
|
+
* tool at all, or when the busybox implementation is a safe substitute for the
|
|
1885
|
+
* flags anyone actually passes. A name where a host build is both near-universal
|
|
1886
|
+
* and functionally richer stays out, so that no working command changes meaning:
|
|
1887
|
+
* `grep`, `sed`, `find`, `awk`, `tar`, `diff`, `ls`, `cat`, `cp`, `mv`, `rm`,
|
|
1888
|
+
* `ln`, `chmod`, `chown`, `mkdir`, `touch`, `stat`, `df`, `du`, `ps`, `kill`,
|
|
1889
|
+
* `bc`, `mktemp`, `which`, `env`, `nohup`, `date` and `patch` are all reached via
|
|
1890
|
+
* `busybox <applet>` instead. `sh`/`ash`/`hush` are never linked: a bare `sh`
|
|
1891
|
+
* resolving to busybox would change every `sh -c` on the machine, and the rule in
|
|
1892
|
+
* this package is to write `busybox sh -c '...'` where a known shell is wanted.
|
|
1893
|
+
*/
|
|
1894
|
+
export const CORE_APPLETS: readonly string[] = [
|
|
1895
|
+
// Hashes, encoders and checksums: macOS ships no sha3sum, crc32, base32,
|
|
1896
|
+
// uuencode or uuidgen, and these never appear in a pipeline needing host flags.
|
|
1897
|
+
"base32",
|
|
1898
|
+
"base64",
|
|
1899
|
+
"cksum",
|
|
1900
|
+
"crc32",
|
|
1901
|
+
"md5sum",
|
|
1902
|
+
"sha1sum",
|
|
1903
|
+
"sha256sum",
|
|
1904
|
+
"sha384sum",
|
|
1905
|
+
"sha512sum",
|
|
1906
|
+
"sha3sum",
|
|
1907
|
+
"sum",
|
|
1908
|
+
"uuencode",
|
|
1909
|
+
"uudecode",
|
|
1910
|
+
"uuidgen",
|
|
1911
|
+
// Binary and hex inspectors. These read stdin or a file and print.
|
|
1912
|
+
"hd",
|
|
1913
|
+
"hexdump",
|
|
1914
|
+
"od",
|
|
1915
|
+
"strings",
|
|
1916
|
+
"xxd",
|
|
1917
|
+
// Text shaping where the busybox flags are additive, not a subset.
|
|
1918
|
+
"cmp",
|
|
1919
|
+
"comm",
|
|
1920
|
+
"expand",
|
|
1921
|
+
"factor",
|
|
1922
|
+
"fold",
|
|
1923
|
+
"join",
|
|
1924
|
+
"nl",
|
|
1925
|
+
"paste",
|
|
1926
|
+
"rev",
|
|
1927
|
+
"seq",
|
|
1928
|
+
"tac",
|
|
1929
|
+
"ts",
|
|
1930
|
+
"tsort",
|
|
1931
|
+
"unexpand",
|
|
1932
|
+
// Archives and compression: cpio, dpkg-deb and rpm2cpio have no macOS build,
|
|
1933
|
+
// and the gzip family is used for its flags, not for host-specific output.
|
|
1934
|
+
"bzcat",
|
|
1935
|
+
"bunzip2",
|
|
1936
|
+
"bzip2",
|
|
1937
|
+
"cpio",
|
|
1938
|
+
"dpkg-deb",
|
|
1939
|
+
"gunzip",
|
|
1940
|
+
"gzip",
|
|
1941
|
+
"lzcat",
|
|
1942
|
+
"lzma",
|
|
1943
|
+
"rpm2cpio",
|
|
1944
|
+
"unlzma",
|
|
1945
|
+
"unxz",
|
|
1946
|
+
"unzip",
|
|
1947
|
+
"xzcat",
|
|
1948
|
+
"zcat",
|
|
1949
|
+
// Agent-facing applets, linked by bare name: read-only, distinctive and not a
|
|
1950
|
+
// name any host tool claims. `replace`, `run`, `log`, `bench`, `check`, `json`,
|
|
1951
|
+
// `snapshot` and `brief` are NOT linked: some run a command, some write a file, and
|
|
1952
|
+
// the rest are words a project script or another tool already owns. They are
|
|
1953
|
+
// reached as `busybox <applet>` or through the plugin's own tools.
|
|
1954
|
+
"peek",
|
|
1955
|
+
"waitfor",
|
|
1956
|
+
"doctor",
|
|
1957
|
+
"why",
|
|
1958
|
+
"patchcheck",
|
|
1959
|
+
"brief",
|
|
1960
|
+
// Process, network and path helpers a host commonly does not provide.
|
|
1961
|
+
"ipcalc",
|
|
1962
|
+
"nproc",
|
|
1963
|
+
"readlink",
|
|
1964
|
+
"realpath",
|
|
1965
|
+
"setsid",
|
|
1966
|
+
"timeout",
|
|
1967
|
+
"usleep",
|
|
1968
|
+
"wget",
|
|
1969
|
+
// Out on purpose despite fitting the rule: busybox `tree` takes a directory and
|
|
1970
|
+
// no flags at all, so the near-universal `tree -L 2` fails. It stays reachable
|
|
1971
|
+
// as `busybox tree`.
|
|
1972
|
+
];
|
|
1973
|
+
|
|
1974
|
+
/**
|
|
1975
|
+
* Names never linked, whatever the policy: shells, anything that changes the
|
|
1976
|
+
* machine, anything that serves the network, and every package manager. These
|
|
1977
|
+
* stay reachable as `busybox <applet>`, which is a deliberate act.
|
|
1978
|
+
*/
|
|
1979
|
+
export const NEVER_APPLETS: readonly string[] = [
|
|
1980
|
+
// Shells and session tools: a bare `sh` or `login` must stay the host's.
|
|
1981
|
+
"add-shell",
|
|
1982
|
+
"ash",
|
|
1983
|
+
"chpasswd",
|
|
1984
|
+
"cttyhack",
|
|
1985
|
+
"hush",
|
|
1986
|
+
"login",
|
|
1987
|
+
"nologin",
|
|
1988
|
+
"passwd",
|
|
1989
|
+
"remove-shell",
|
|
1990
|
+
"sh",
|
|
1991
|
+
"su",
|
|
1992
|
+
// Boot, kernel, device and filesystem administration.
|
|
1993
|
+
"chroot",
|
|
1994
|
+
"devmem",
|
|
1995
|
+
"fdformat",
|
|
1996
|
+
"flashcp",
|
|
1997
|
+
"flash_erase",
|
|
1998
|
+
"fbset",
|
|
1999
|
+
"freeramdisk",
|
|
2000
|
+
"fsck",
|
|
2001
|
+
"halt",
|
|
2002
|
+
"hwclock",
|
|
2003
|
+
"init",
|
|
2004
|
+
"insmod",
|
|
2005
|
+
"ip",
|
|
2006
|
+
"ifconfig",
|
|
2007
|
+
"losetup",
|
|
2008
|
+
"makedevs",
|
|
2009
|
+
"mdev",
|
|
2010
|
+
"mkfs.ext2",
|
|
2011
|
+
"mkfs.minix",
|
|
2012
|
+
"mkfs.vfat",
|
|
2013
|
+
"mkswap",
|
|
2014
|
+
"modprobe",
|
|
2015
|
+
"mount",
|
|
2016
|
+
"pivot_root",
|
|
2017
|
+
"poweroff",
|
|
2018
|
+
"raidautorun",
|
|
2019
|
+
"reboot",
|
|
2020
|
+
"rmmod",
|
|
2021
|
+
"route",
|
|
2022
|
+
"rtcwake",
|
|
2023
|
+
"setconsole",
|
|
2024
|
+
"setkeycodes",
|
|
2025
|
+
"swapoff",
|
|
2026
|
+
"swapon",
|
|
2027
|
+
"switch_root",
|
|
2028
|
+
"sysctl",
|
|
2029
|
+
"udhcpc",
|
|
2030
|
+
"udhcpd",
|
|
2031
|
+
"umount",
|
|
2032
|
+
"watchdog",
|
|
2033
|
+
// Servers and remote shell endpoints.
|
|
2034
|
+
"fakeidentd",
|
|
2035
|
+
"ftpd",
|
|
2036
|
+
"ftpput",
|
|
2037
|
+
"ftpget",
|
|
2038
|
+
"httpd",
|
|
2039
|
+
"inetd",
|
|
2040
|
+
"ssl_server",
|
|
2041
|
+
"tcpsvd",
|
|
2042
|
+
"telnetd",
|
|
2043
|
+
"tftpd",
|
|
2044
|
+
"udpsvd",
|
|
2045
|
+
// Package managers: a busybox `dpkg` would install into the live root.
|
|
2046
|
+
"dpkg",
|
|
2047
|
+
"rpm",
|
|
2048
|
+
];
|
|
2049
|
+
|
|
2050
|
+
/** A bare name on PATH has to be a usable filename; this also drops `[` and `[[`. */
|
|
2051
|
+
const APPLET_NAME = /^[A-Za-z0-9._+-]+$/;
|
|
2052
|
+
|
|
2053
|
+
/** Policy from `PI_MANAGED_TOOLS_APPLETS`: `off`, `all`, or unset/`core`. */
|
|
2054
|
+
export function readAppletPolicy(env: NodeJS.ProcessEnv = process.env): AppletPolicy {
|
|
2055
|
+
const raw = (env.PI_MANAGED_TOOLS_APPLETS ?? "").trim().toLowerCase();
|
|
2056
|
+
if (raw === "0" || raw === "off" || raw === "false" || raw === "no" || raw === "none") return "off";
|
|
2057
|
+
if (raw === "all" || raw === "shadow") return "all";
|
|
2058
|
+
return "core";
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
/** Every applet the installed build was compiled with, or undefined when it will not run. */
|
|
2062
|
+
export function listBusyboxApplets(busyboxPath: string): string[] | undefined {
|
|
2063
|
+
const result = spawnSync(busyboxPath, ["--list"], { encoding: "utf-8", timeout: 10_000, windowsHide: true });
|
|
2064
|
+
if (result.error || result.status !== 0 || typeof result.stdout !== "string") return undefined;
|
|
2065
|
+
const names = result.stdout
|
|
2066
|
+
.split(/\r?\n/)
|
|
2067
|
+
.map((line) => line.trim())
|
|
2068
|
+
.filter(Boolean);
|
|
2069
|
+
return names.length > 0 ? [...new Set(names)].sort() : undefined;
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
/** Names a policy asks for, before asking what this build actually has. */
|
|
2073
|
+
function policyWanted(policy: AppletPolicy, available: readonly string[]): string[] {
|
|
2074
|
+
if (policy === "off") return [];
|
|
2075
|
+
return policy === "all" ? [...available] : [...CORE_APPLETS];
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
/**
|
|
2079
|
+
* The names to link: wanted by the policy, present in this build, and neither a
|
|
2080
|
+
* NEVER_APPLETS name, a dedicated tool, nor blocked by the caller.
|
|
2081
|
+
*
|
|
2082
|
+
* A managed name is filtered even under `all`. Busybox has no applet that shadows
|
|
2083
|
+
* one today, but the promise this directory makes is that a bare name runs the
|
|
2084
|
+
* dedicated static build, and that must not depend on upstream applet additions.
|
|
2085
|
+
*/
|
|
2086
|
+
export function chooseApplets(
|
|
2087
|
+
available: readonly string[],
|
|
2088
|
+
policy: AppletPolicy,
|
|
2089
|
+
blocked: readonly string[] = [],
|
|
2090
|
+
): string[] {
|
|
2091
|
+
const present = new Set(available);
|
|
2092
|
+
const skip = new Set<string>([...NEVER_APPLETS, ...blocked, ...managedBinaryNames()]);
|
|
2093
|
+
return [...new Set(policyWanted(policy, available))]
|
|
2094
|
+
.filter((name) => present.has(name) && !skip.has(name) && APPLET_NAME.test(name))
|
|
2095
|
+
.sort();
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
/**
|
|
2099
|
+
* Put `first` at the front of a PATH value, in order, removing any earlier
|
|
2100
|
+
* occurrence so repeated calls cannot stack duplicates.
|
|
2101
|
+
*
|
|
2102
|
+
* This exists because pi's `getShellEnv()` prepends the bin directory only when it
|
|
2103
|
+
* is *absent*: if a shell rc appended it (`PATH="$PATH:$HOME/.pi/agent/bin"`) the
|
|
2104
|
+
* order is left alone and host binaries win, and no second directory can be added
|
|
2105
|
+
* that way at all.
|
|
2106
|
+
*/
|
|
2107
|
+
export function ensurePathOrder(
|
|
2108
|
+
currentPath: string,
|
|
2109
|
+
first: readonly string[],
|
|
2110
|
+
options: { pathSeparator?: string; caseInsensitive?: boolean } = {},
|
|
2111
|
+
): string {
|
|
2112
|
+
const separator = options.pathSeparator ?? delimiter;
|
|
2113
|
+
const fold = (value: string) => (options.caseInsensitive ?? platform() === "win32" ? value.toLowerCase() : value);
|
|
2114
|
+
const wanted = [...new Set(first.filter(Boolean))];
|
|
2115
|
+
const wantedFolded = new Set(wanted.map(fold));
|
|
2116
|
+
const rest = currentPath
|
|
2117
|
+
.split(separator)
|
|
2118
|
+
.filter(Boolean)
|
|
2119
|
+
.filter((entry) => !wantedFolded.has(fold(entry)));
|
|
2120
|
+
return [...wanted, ...rest].join(separator);
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
export interface AppletSyncOptions {
|
|
2124
|
+
binDir: string;
|
|
2125
|
+
appletDir: string;
|
|
2126
|
+
/** Defaults to `readAppletPolicy()`. */
|
|
2127
|
+
policy?: AppletPolicy;
|
|
2128
|
+
/** Defaults to `<binDir>/busybox`; injectable so a test needs no real build. */
|
|
2129
|
+
busyboxPath?: string;
|
|
2130
|
+
plat?: string;
|
|
2131
|
+
/** Extra names to leave out, on top of NEVER_APPLETS and the dedicated tools. */
|
|
2132
|
+
blocked?: readonly string[];
|
|
2133
|
+
}
|
|
2134
|
+
|
|
2135
|
+
export interface AppletSync {
|
|
2136
|
+
dir: string;
|
|
2137
|
+
policy: AppletPolicy;
|
|
2138
|
+
/** Names that now resolve to the multicall binary. */
|
|
2139
|
+
linked: string[];
|
|
2140
|
+
/** Stale links left by an earlier run, now removed. */
|
|
2141
|
+
removed: string[];
|
|
2142
|
+
/** Applets the policy wants that this build was not compiled with. */
|
|
2143
|
+
unavailable: string[];
|
|
2144
|
+
/** Why nothing is linked, when nothing is. */
|
|
2145
|
+
error?: string;
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
/**
|
|
2149
|
+
* Make the applet directory match the installed busybox and the policy.
|
|
2150
|
+
*
|
|
2151
|
+
* Idempotent and cheap enough to run on every session start: one `busybox --list`
|
|
2152
|
+
* spawn and a readdir. Only symlinks are ever created or deleted — a real file in
|
|
2153
|
+
* the applet directory is not this package's to remove.
|
|
2154
|
+
*/
|
|
2155
|
+
export function syncBusyboxApplets(options: AppletSyncOptions): AppletSync {
|
|
2156
|
+
const plat = options.plat ?? platform();
|
|
2157
|
+
const policy = options.policy ?? readAppletPolicy();
|
|
2158
|
+
const busyboxPath =
|
|
2159
|
+
options.busyboxPath ?? join(options.binDir, "busybox" + (plat === "win32" ? ".exe" : ""));
|
|
2160
|
+
const result: AppletSync = { dir: options.appletDir, policy, linked: [], removed: [], unavailable: [] };
|
|
2161
|
+
|
|
2162
|
+
let desired: string[] = [];
|
|
2163
|
+
if (policy === "off") {
|
|
2164
|
+
result.error = "applet names disabled (PI_MANAGED_TOOLS_APPLETS=off)";
|
|
2165
|
+
} else if (plat === "win32") {
|
|
2166
|
+
result.error = "no busybox build for Windows";
|
|
2167
|
+
} else if (!existsSync(busyboxPath)) {
|
|
2168
|
+
result.error = "busybox is not installed";
|
|
2169
|
+
} else if (statSync(busyboxPath).size === 0) {
|
|
2170
|
+
// An empty binary "runs" on Linux (the loader falls back to /bin/sh), so
|
|
2171
|
+
// linking it would replace working names with a no-op.
|
|
2172
|
+
result.error = "busybox is empty";
|
|
2173
|
+
} else {
|
|
2174
|
+
const available = listBusyboxApplets(busyboxPath);
|
|
2175
|
+
if (!available) {
|
|
2176
|
+
result.error = "busybox --list failed";
|
|
2177
|
+
} else {
|
|
2178
|
+
desired = chooseApplets(available, policy, options.blocked);
|
|
2179
|
+
const present = new Set(available);
|
|
2180
|
+
result.unavailable = [...new Set(policyWanted(policy, available))]
|
|
2181
|
+
.filter((name) => !present.has(name))
|
|
2182
|
+
.sort();
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
const wanted = new Set(desired);
|
|
2187
|
+
// Absolute target, deliberately: a relative link is resolved by the kernel from
|
|
2188
|
+
// the *real* directory, so a parent that is itself a symlink (macOS /tmp →
|
|
2189
|
+
// /private/tmp, many /home setups) walks through the target side and misses.
|
|
2190
|
+
// If the agent directory ever moves, the next sync sees a stale link and
|
|
2191
|
+
// replaces it, because the target is compared on every run.
|
|
2192
|
+
const target = busyboxPath;
|
|
2193
|
+
|
|
2194
|
+
if (existsSync(options.appletDir)) {
|
|
2195
|
+
for (const entry of readdirSync(options.appletDir, { withFileTypes: true })) {
|
|
2196
|
+
if (!entry.isSymbolicLink() || wanted.has(entry.name)) continue;
|
|
2197
|
+
rmSync(join(options.appletDir, entry.name), { force: true });
|
|
2198
|
+
result.removed.push(entry.name);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
if (desired.length > 0) {
|
|
2203
|
+
mkdirSync(options.appletDir, { recursive: true });
|
|
2204
|
+
for (const name of desired) {
|
|
2205
|
+
const linkPath = join(options.appletDir, name);
|
|
2206
|
+
const existing = lstatSync(linkPath, { throwIfNoEntry: false });
|
|
2207
|
+
if (existing?.isSymbolicLink()) {
|
|
2208
|
+
if (readlinkSync(linkPath) === target) {
|
|
2209
|
+
result.linked.push(name);
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
rmSync(linkPath, { force: true });
|
|
2213
|
+
} else if (existing) {
|
|
2214
|
+
// A regular file or directory under an applet name: leave it alone.
|
|
2215
|
+
continue;
|
|
2216
|
+
}
|
|
2217
|
+
symlinkSync(target, linkPath);
|
|
2218
|
+
result.linked.push(name);
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
return result;
|
|
2223
|
+
}
|