@rob-c/pi-managed-tools 0.16.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BUSYBOX-CONTRACT.md +440 -0
- package/CHANGELOG.md +441 -0
- package/README.md +464 -35
- package/package.json +7 -4
- package/skills/busybox-applets/SKILL.md +142 -15
- package/skills/managed-tools/SKILL.md +201 -25
- package/skills/managed-tools-reference/SKILL.md +206 -38
- 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 +817 -28
- package/src/guard.ts +437 -0
- package/src/jobs.ts +1052 -0
- package/src/timing.ts +364 -0
- package/src/tools.ts +525 -42
- package/src/userstdin.ts +524 -0
- package/src/wrap.ts +683 -0
package/src/tools.ts
CHANGED
|
@@ -38,12 +38,15 @@ import {
|
|
|
38
38
|
createWriteStream,
|
|
39
39
|
existsSync,
|
|
40
40
|
linkSync,
|
|
41
|
+
lstatSync,
|
|
41
42
|
mkdirSync,
|
|
42
43
|
readFileSync,
|
|
43
44
|
readdirSync,
|
|
45
|
+
readlinkSync,
|
|
44
46
|
renameSync,
|
|
45
47
|
rmSync,
|
|
46
48
|
statSync,
|
|
49
|
+
symlinkSync,
|
|
47
50
|
writeFileSync,
|
|
48
51
|
} from "node:fs";
|
|
49
52
|
import { arch, platform } from "node:os";
|
|
@@ -56,7 +59,6 @@ export type ToolId =
|
|
|
56
59
|
| "rg"
|
|
57
60
|
| "bat"
|
|
58
61
|
| "prek"
|
|
59
|
-
| "rtk"
|
|
60
62
|
| "just"
|
|
61
63
|
| "gron"
|
|
62
64
|
| "shellcheck"
|
|
@@ -88,6 +90,23 @@ export interface ManagedTool {
|
|
|
88
90
|
tagPrefix: string;
|
|
89
91
|
/** Asset name, which differs between the projects. */
|
|
90
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;
|
|
91
110
|
/** Names to look for when only a system copy exists. */
|
|
92
111
|
systemBinaryNames: string[];
|
|
93
112
|
/**
|
|
@@ -177,23 +196,10 @@ export const MANAGED_TOOLS: Record<ToolId, ManagedTool> = {
|
|
|
177
196
|
systemBinaryNames: ["prek"],
|
|
178
197
|
consumedBy: [],
|
|
179
198
|
},
|
|
180
|
-
rtk
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
binaryName: "rtk",
|
|
185
|
-
tagPrefix: "v",
|
|
186
|
-
// `rtk-oss-<target>`, no version. The plain `rtk-<target>` build bundles a
|
|
187
|
-
// BUSL-1.1 engine (LICENSE-ENGINE); `rtk-oss-` is the Apache-2.0-only build
|
|
188
|
-
// with the same binary name and version banner. Do not switch to `rtk-`
|
|
189
|
-
// without changing the licence note in the README.
|
|
190
|
-
assetName: (_version, target) => `rtk-oss-${target}`,
|
|
191
|
-
systemBinaryNames: ["rtk"],
|
|
192
|
-
// No aarch64-pc-windows-msvc archive is published for any rtk variant.
|
|
193
|
-
resolveTarget: (plat, architecture) =>
|
|
194
|
-
plat === "win32" && architecture === "arm64" ? undefined : releaseTarget(plat, architecture),
|
|
195
|
-
consumedBy: [],
|
|
196
|
-
},
|
|
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.
|
|
197
203
|
just: {
|
|
198
204
|
id: "just",
|
|
199
205
|
name: "just",
|
|
@@ -503,8 +509,17 @@ export const MANAGED_TOOLS: Record<ToolId, ManagedTool> = {
|
|
|
503
509
|
}
|
|
504
510
|
return undefined;
|
|
505
511
|
},
|
|
506
|
-
// No v in the asset name despite the v-prefixed tag.
|
|
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).
|
|
507
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,}$/,
|
|
508
523
|
systemBinaryNames: ["busybox"],
|
|
509
524
|
raw: true,
|
|
510
525
|
// The binary reports "BusyBox v1.39.0.git" while the tag carries the commit
|
|
@@ -520,7 +535,6 @@ export const MANAGED_TOOL_IDS: ToolId[] = [
|
|
|
520
535
|
"rg",
|
|
521
536
|
"bat",
|
|
522
537
|
"prek",
|
|
523
|
-
"rtk",
|
|
524
538
|
"just",
|
|
525
539
|
"gron",
|
|
526
540
|
"shellcheck",
|
|
@@ -902,12 +916,12 @@ export function sha256File(path: string): string {
|
|
|
902
916
|
* publishing sidecar checksums - fd and bat publish none at all. Returns
|
|
903
917
|
* undefined when the release or the asset is not visible to the API.
|
|
904
918
|
*/
|
|
905
|
-
|
|
919
|
+
/** The release's asset list, so a name can be matched instead of constructed. */
|
|
920
|
+
export async function releaseAssets(
|
|
906
921
|
tool: ManagedTool,
|
|
907
922
|
version: string,
|
|
908
|
-
asset: string,
|
|
909
923
|
options: NetworkOptions = {},
|
|
910
|
-
): Promise<
|
|
924
|
+
): Promise<Array<{ name?: unknown; digest?: unknown }>> {
|
|
911
925
|
const tag = `${tool.tagPrefix}${version}`;
|
|
912
926
|
const url = `https://api.github.com/repos/${tool.repo}/releases/tags/${encodeURIComponent(tag)}`;
|
|
913
927
|
// The anonymous quota is 60 requests/hour per IP, shared with everything else
|
|
@@ -918,7 +932,17 @@ export async function fetchAssetDigest(
|
|
|
918
932
|
const response = await fetchWithRetries(url, { headers }, options);
|
|
919
933
|
if (!response.ok) throw new HttpError(response.status, `HTTP ${response.status} for ${url}`);
|
|
920
934
|
const payload = (await response.json()) as { assets?: Array<{ name?: unknown; digest?: unknown }> };
|
|
921
|
-
|
|
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);
|
|
922
946
|
if (!match || typeof match.digest !== "string") return undefined;
|
|
923
947
|
const separator = match.digest.indexOf(":");
|
|
924
948
|
if (separator < 0) return undefined;
|
|
@@ -988,6 +1012,26 @@ export async function verifyArchive(
|
|
|
988
1012
|
// Archives
|
|
989
1013
|
// =============================================================================
|
|
990
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
|
+
|
|
991
1035
|
function runExtraction(command: string, args: string[]): string | null {
|
|
992
1036
|
const result = spawnSync(command, args, { encoding: "utf-8", windowsHide: true });
|
|
993
1037
|
if (!result.error && result.status === 0) return null;
|
|
@@ -1005,7 +1049,7 @@ function windowsTar(): string {
|
|
|
1005
1049
|
return "tar.exe";
|
|
1006
1050
|
}
|
|
1007
1051
|
|
|
1008
|
-
function extractZip(archivePath: string, extractDir: string): void {
|
|
1052
|
+
function extractZip(archivePath: string, extractDir: string, binDir?: string): void {
|
|
1009
1053
|
const failures: string[] = [];
|
|
1010
1054
|
if (process.platform === "win32") {
|
|
1011
1055
|
const tarFailure = runExtraction(windowsTar(), ["xf", archivePath, "-C", extractDir]);
|
|
@@ -1027,12 +1071,37 @@ function extractZip(archivePath: string, extractDir: string): void {
|
|
|
1027
1071
|
if (!powershellFailure) return;
|
|
1028
1072
|
failures.push(powershellFailure);
|
|
1029
1073
|
} else {
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
const
|
|
1034
|
-
|
|
1035
|
-
|
|
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
|
+
}
|
|
1036
1105
|
}
|
|
1037
1106
|
throw new Error(`Failed to extract ${archivePath}: ${failures.join("; ")}`);
|
|
1038
1107
|
}
|
|
@@ -1209,6 +1278,31 @@ export interface InstallResult {
|
|
|
1209
1278
|
* non-atomic copy could leave a truncated binary where pi expects a working
|
|
1210
1279
|
* one.
|
|
1211
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
|
+
|
|
1212
1306
|
export async function installTool(
|
|
1213
1307
|
toolId: ToolId,
|
|
1214
1308
|
version: string,
|
|
@@ -1222,7 +1316,7 @@ export async function installTool(
|
|
|
1222
1316
|
throw new Error(`${tool.name}: no prebuilt release for ${plat}/${architecture}`);
|
|
1223
1317
|
}
|
|
1224
1318
|
|
|
1225
|
-
const asset = tool
|
|
1319
|
+
const asset = await resolveAsset(tool, version, target, options);
|
|
1226
1320
|
const url = downloadUrl(tool, version, asset);
|
|
1227
1321
|
const binDir = options.binDir;
|
|
1228
1322
|
mkdirSync(binDir, { recursive: true });
|
|
@@ -1251,10 +1345,10 @@ export async function installTool(
|
|
|
1251
1345
|
} else {
|
|
1252
1346
|
mkdirSync(extractDir, { recursive: true });
|
|
1253
1347
|
if (asset.endsWith(".tar.gz") || asset.endsWith(".tgz")) {
|
|
1254
|
-
const failure = runExtraction("tar", ["xzf", archivePath, "-C", extractDir]);
|
|
1348
|
+
const failure = runExtraction(systemToolPath("tar") ?? "tar", ["xzf", archivePath, "-C", extractDir]);
|
|
1255
1349
|
if (failure) throw new Error(`Failed to extract ${asset}: ${failure}`);
|
|
1256
1350
|
} else if (asset.endsWith(".zip")) {
|
|
1257
|
-
extractZip(archivePath, extractDir);
|
|
1351
|
+
extractZip(archivePath, extractDir, binDir);
|
|
1258
1352
|
} else {
|
|
1259
1353
|
throw new Error(`Unsupported archive format: ${asset}`);
|
|
1260
1354
|
}
|
|
@@ -1498,12 +1592,7 @@ export async function updateTools(
|
|
|
1498
1592
|
// A damaged binary is never "up to date", whatever version it claims. The
|
|
1499
1593
|
// state fallback supplies a version for a tool that cannot self-report, so
|
|
1500
1594
|
// without this check a broken gron would compare equal and never be fixed.
|
|
1501
|
-
if (
|
|
1502
|
-
!forced &&
|
|
1503
|
-
!wasDamaged &&
|
|
1504
|
-
report.version &&
|
|
1505
|
-
compareVersions(report.version, report.latest) >= 0
|
|
1506
|
-
) {
|
|
1595
|
+
if (!forced && !wasDamaged && !needsUpdate(tool, report.version, report.latest)) {
|
|
1507
1596
|
continue;
|
|
1508
1597
|
}
|
|
1509
1598
|
|
|
@@ -1629,7 +1718,20 @@ export function writeState(binDir: string, report: Report, options: { advance?:
|
|
|
1629
1718
|
// that cannot install a tool stops retrying it, but it must not move
|
|
1630
1719
|
// checkedAt: that would defer the next real attempt for a whole interval.
|
|
1631
1720
|
const checkedAt = options.advance === false ? (previous?.checkedAt ?? report.checkedAt) : report.checkedAt;
|
|
1632
|
-
|
|
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
|
+
};
|
|
1633
1735
|
const path = statePath(binDir);
|
|
1634
1736
|
const temporary = `${path}.${process.pid}.tmp`;
|
|
1635
1737
|
writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`);
|
|
@@ -1640,7 +1742,19 @@ export function writeState(binDir: string, report: Report, options: { advance?:
|
|
|
1640
1742
|
}
|
|
1641
1743
|
|
|
1642
1744
|
/**
|
|
1643
|
-
* Whether
|
|
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
|
|
1644
1758
|
* triggers a check: pi would otherwise download it itself with no version
|
|
1645
1759
|
* comparison at all.
|
|
1646
1760
|
*/
|
|
@@ -1738,3 +1852,372 @@ export function readSettings(env: NodeJS.ProcessEnv = process.env): ToolSettings
|
|
|
1738
1852
|
rewritePaths: !rewriteOff,
|
|
1739
1853
|
};
|
|
1740
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
|
+
}
|