@linxin666/dsh-win-bash 0.4.13 → 0.4.14
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/README.i18n.yaml +2 -2
- package/README.md +26 -2
- package/README.zh.md +16 -1
- package/lib/index.js +438 -36
- package/lib/types/background.d.ts +7 -0
- package/lib/types/dsh-home.d.ts +16 -0
- package/lib/types/index.d.ts +11 -2
- package/lib/types/runtime.d.ts +118 -9
- package/lib/types/shell.d.ts +53 -1
- package/package.json +1 -1
- package/src/background.ts +19 -2
- package/src/dsh-home.ts +42 -0
- package/src/index.ts +56 -3
- package/src/runtime.ts +288 -26
- package/src/shell.ts +182 -6
- package/src/tool.ts +3 -1
package/lib/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { mkdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { rm } from "node:fs/promises";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
5
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
|
|
6
8
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
7
9
|
//#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
|
|
8
10
|
/** Return true when a value is `null` or `undefined`. */
|
|
@@ -1023,6 +1025,16 @@ const POLL_INTERVAL_MS = 15;
|
|
|
1023
1025
|
/** How long a freshly spawned shell gets to answer its startup handshake. */
|
|
1024
1026
|
const HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
1025
1027
|
/**
|
|
1028
|
+
* Name prefix of every private per-shell temp directory. The rest of the name
|
|
1029
|
+
* is the owning process id plus a random suffix, which is what lets a later
|
|
1030
|
+
* start tell an orphan from a directory a live shell is still using.
|
|
1031
|
+
*/
|
|
1032
|
+
const SHELL_TEMP_PREFIX = "dsh-win-bash-";
|
|
1033
|
+
/** Retries granted to one reclaim, for handles a child releases late. */
|
|
1034
|
+
const TEMP_REMOVE_RETRIES = 3;
|
|
1035
|
+
/** Backoff between those retries, in milliseconds. */
|
|
1036
|
+
const TEMP_REMOVE_RETRY_DELAY_MS = 100;
|
|
1037
|
+
/**
|
|
1026
1038
|
* The argv of one pinned shell: the payload's own bash by absolute path, no rc
|
|
1027
1039
|
* file and no profile, reading its commands from stdin. This tool never
|
|
1028
1040
|
* consults PATH, and every shell it starts — the session's persistent one and
|
|
@@ -1058,13 +1070,131 @@ function shellEnvironment(runtime, temp, base = process.env) {
|
|
|
1058
1070
|
}
|
|
1059
1071
|
/**
|
|
1060
1072
|
* Create one shell process's private temp directory.
|
|
1073
|
+
* @param base - the temp root to create it under; the machine's own by default.
|
|
1061
1074
|
* @returns the absolute directory, created if absent.
|
|
1062
1075
|
*/
|
|
1063
|
-
function shellTempDir() {
|
|
1064
|
-
const temp = join(
|
|
1076
|
+
function shellTempDir(base = tmpdir()) {
|
|
1077
|
+
const temp = join(base, SHELL_TEMP_PREFIX + process.pid.toString() + "-" + randomUUID().slice(0, 8));
|
|
1065
1078
|
mkdirSync(temp, { recursive: true });
|
|
1066
1079
|
return temp;
|
|
1067
1080
|
}
|
|
1081
|
+
/**
|
|
1082
|
+
* Delete one private temp directory, reporting failure to the caller.
|
|
1083
|
+
*
|
|
1084
|
+
* The retries are the Windows half of this: a child that just exited has not
|
|
1085
|
+
* necessarily released its own handles yet, and rm reports that as EBUSY/EPERM.
|
|
1086
|
+
* A few short retries turn that into a reclaim instead of a leftover.
|
|
1087
|
+
* @param temp - the directory to delete; a missing one is not an error.
|
|
1088
|
+
*/
|
|
1089
|
+
async function deleteShellTempDir(temp) {
|
|
1090
|
+
await rm(temp, {
|
|
1091
|
+
recursive: true,
|
|
1092
|
+
force: true,
|
|
1093
|
+
maxRetries: TEMP_REMOVE_RETRIES,
|
|
1094
|
+
retryDelay: TEMP_REMOVE_RETRY_DELAY_MS
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Delete one private temp directory, never letting the attempt throw.
|
|
1099
|
+
*
|
|
1100
|
+
* Teardown must not fail because a directory could not be reclaimed: the shell
|
|
1101
|
+
* is already gone, and whatever is left is named for this process's own pid, so
|
|
1102
|
+
* the next start's {@link sweepOrphanShellTempDirs} collects it once that pid is
|
|
1103
|
+
* gone.
|
|
1104
|
+
* @param temp - the directory that shell owned.
|
|
1105
|
+
*/
|
|
1106
|
+
async function removeShellTempDir(temp) {
|
|
1107
|
+
try {
|
|
1108
|
+
await deleteShellTempDir(temp);
|
|
1109
|
+
} catch {}
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Whether a process id still exists.
|
|
1113
|
+
*
|
|
1114
|
+
* Signal 0 performs the existence check without delivering anything. EPERM is
|
|
1115
|
+
* the one answer that means "alive": the pid is there, it just belongs to a
|
|
1116
|
+
* process this one may not signal.
|
|
1117
|
+
* @param pid - the process id taken from a directory name.
|
|
1118
|
+
* @returns whether that process is still running.
|
|
1119
|
+
*/
|
|
1120
|
+
function processAlive(pid) {
|
|
1121
|
+
try {
|
|
1122
|
+
process.kill(pid, 0);
|
|
1123
|
+
return true;
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
return error.code === "EPERM";
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* The owning pid of a shell temp directory, when the name is one.
|
|
1130
|
+
* @param name - a directory name inside the temp root.
|
|
1131
|
+
* @returns the pid, or undefined for every other name.
|
|
1132
|
+
*/
|
|
1133
|
+
function shellTempOwner(name) {
|
|
1134
|
+
const match = (/* @__PURE__ */ new RegExp("^dsh-win-bash-(\\d+)-[0-9a-f]{8}$")).exec(name);
|
|
1135
|
+
if (match === null) return void 0;
|
|
1136
|
+
const pid = Number.parseInt(match[1] ?? "", 10);
|
|
1137
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* List one temp root, reporting an unreadable root as empty.
|
|
1141
|
+
*
|
|
1142
|
+
* There is nothing to reclaim when the root cannot be read, and the next start
|
|
1143
|
+
* retries with the same rules; failing the mount over it would be worse.
|
|
1144
|
+
* @param root - the temp root to list.
|
|
1145
|
+
* @returns its entries, or none.
|
|
1146
|
+
*/
|
|
1147
|
+
function tempRootEntries(root) {
|
|
1148
|
+
try {
|
|
1149
|
+
return readdirSync(root, { withFileTypes: true });
|
|
1150
|
+
} catch {
|
|
1151
|
+
return [];
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Reclaim the private temp directories of shells that no longer exist.
|
|
1156
|
+
*
|
|
1157
|
+
* A crash or a hard kill ends this process before it can delete what its live
|
|
1158
|
+
* shells owned, and those directories are not small: whatever a command wrote
|
|
1159
|
+
* under TMP/TEMP/TMPDIR is still in them. Every name carries the pid that owned
|
|
1160
|
+
* it, so the ones whose pid is gone are garbage by construction, and the ones
|
|
1161
|
+
* whose pid still runs may belong to a live shell in this very process or to
|
|
1162
|
+
* another instance sharing the temp root - those are kept.
|
|
1163
|
+
*
|
|
1164
|
+
* One directory that cannot be deleted is reported and skipped; it must not
|
|
1165
|
+
* stop the round, because the usual cause (a long path, a locked file) is local
|
|
1166
|
+
* to that directory.
|
|
1167
|
+
* @param options - the seams; production passes none.
|
|
1168
|
+
* @returns what was removed, kept and failed.
|
|
1169
|
+
*/
|
|
1170
|
+
async function sweepOrphanShellTempDirs(options = {}) {
|
|
1171
|
+
const root = options.root ?? tmpdir();
|
|
1172
|
+
const isAlive = options.isAlive ?? processAlive;
|
|
1173
|
+
const remove = options.remove ?? deleteShellTempDir;
|
|
1174
|
+
const removed = [];
|
|
1175
|
+
const kept = [];
|
|
1176
|
+
const failed = [];
|
|
1177
|
+
for (const entry of tempRootEntries(root)) {
|
|
1178
|
+
if (!entry.isDirectory()) continue;
|
|
1179
|
+
const pid = shellTempOwner(entry.name);
|
|
1180
|
+
if (pid === void 0) continue;
|
|
1181
|
+
if (pid === process.pid || isAlive(pid)) {
|
|
1182
|
+
kept.push(entry.name);
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
try {
|
|
1186
|
+
await remove(join(root, entry.name));
|
|
1187
|
+
removed.push(entry.name);
|
|
1188
|
+
} catch {
|
|
1189
|
+
failed.push(entry.name);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
return {
|
|
1193
|
+
removed,
|
|
1194
|
+
kept,
|
|
1195
|
+
failed
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1068
1198
|
/** Failure raised when the shell cannot serve a call. */
|
|
1069
1199
|
var ShellUnavailableError = class extends Error {
|
|
1070
1200
|
/** Stable machine-readable reason. */
|
|
@@ -1240,6 +1370,7 @@ var ShellRegistry = class {
|
|
|
1240
1370
|
if (shell.exited) {
|
|
1241
1371
|
resume();
|
|
1242
1372
|
this.shells.delete(owner);
|
|
1373
|
+
await removeShellTempDir(shell.temp);
|
|
1243
1374
|
const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes);
|
|
1244
1375
|
if (shell.exitCode === null) throw new ShellUnavailableError("shell-exited", "The persistent bash shell exited without reporting a status, so this command did not complete. The next win_bash call starts a fresh shell in the session workspace with a new current directory and environment.");
|
|
1245
1376
|
const visibleErr = stderr.visible(budget.stderrBytes);
|
|
@@ -1293,6 +1424,7 @@ var ShellRegistry = class {
|
|
|
1293
1424
|
const existing = this.shells.get(owner);
|
|
1294
1425
|
if (existing !== void 0 && !existing.exited) return existing;
|
|
1295
1426
|
if (existing !== void 0) this.shells.delete(owner);
|
|
1427
|
+
const temp = shellTempDir();
|
|
1296
1428
|
const handle = this.subprocess.spawn({
|
|
1297
1429
|
argv: shellArgv(runtime),
|
|
1298
1430
|
cwd,
|
|
@@ -1308,10 +1440,11 @@ var ShellRegistry = class {
|
|
|
1308
1440
|
}
|
|
1309
1441
|
},
|
|
1310
1442
|
graceMs: GRACE_MS,
|
|
1311
|
-
env: shellEnvironment(runtime,
|
|
1443
|
+
env: shellEnvironment(runtime, temp)
|
|
1312
1444
|
});
|
|
1313
1445
|
const shell = {
|
|
1314
1446
|
handle,
|
|
1447
|
+
temp,
|
|
1315
1448
|
exited: false,
|
|
1316
1449
|
cursor: {
|
|
1317
1450
|
stdout: 0,
|
|
@@ -1428,12 +1561,20 @@ function recoverPartial(text, marker) {
|
|
|
1428
1561
|
const begin = text.lastIndexOf(marker.begin);
|
|
1429
1562
|
return begin < 0 ? text : text.slice(begin + marker.begin.length).replace(/^\n/, "");
|
|
1430
1563
|
}
|
|
1431
|
-
/**
|
|
1564
|
+
/**
|
|
1565
|
+
* Signal one shell's managed range and reclaim what it owned, never letting
|
|
1566
|
+
* teardown throw.
|
|
1567
|
+
*
|
|
1568
|
+
* The directory is deleted after the range is gone rather than before: it is
|
|
1569
|
+
* the shell's TMP/TEMP/TMPDIR, so deleting it under a live process would turn
|
|
1570
|
+
* every command still writing there into a failure.
|
|
1571
|
+
*/
|
|
1432
1572
|
async function terminate(shell, reason) {
|
|
1433
1573
|
try {
|
|
1434
1574
|
shell.handle.terminate();
|
|
1435
1575
|
await shell.handle.waitForExit();
|
|
1436
1576
|
} catch {}
|
|
1577
|
+
await removeShellTempDir(shell.temp);
|
|
1437
1578
|
}
|
|
1438
1579
|
//#endregion
|
|
1439
1580
|
//#region src/config.ts
|
|
@@ -2012,6 +2153,37 @@ function installPwshReplacement(ctx, options = {}) {
|
|
|
2012
2153
|
}, "dsh-win-bash: host pwsh replacement");
|
|
2013
2154
|
}
|
|
2014
2155
|
//#endregion
|
|
2156
|
+
//#region src/dsh-home.ts
|
|
2157
|
+
/**
|
|
2158
|
+
* DSH_HOME resolution shared by the plugin family's Host halves: the
|
|
2159
|
+
* environment override wins, the platform home fallback follows. Mirrors
|
|
2160
|
+
* what dsh-pet and dsh-liangshen each used to implement locally.
|
|
2161
|
+
*/
|
|
2162
|
+
/** Expand a leading ~ (or ~user) in a path, platform-style. */
|
|
2163
|
+
function expandHome(path, home = homedir()) {
|
|
2164
|
+
const j = home.startsWith("/") ? join$1 : join;
|
|
2165
|
+
if (path === "~") return home;
|
|
2166
|
+
if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
|
|
2167
|
+
return path;
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Resolve the DSH home directory.
|
|
2171
|
+
* @param env - process environment to read DSH_HOME from.
|
|
2172
|
+
* @param home - platform home directory fallback (test seam).
|
|
2173
|
+
* @returns the absolute DSH home path.
|
|
2174
|
+
*/
|
|
2175
|
+
function resolveDshHome(env = process.env, home = homedir()) {
|
|
2176
|
+
const isPosix = home.startsWith("/");
|
|
2177
|
+
const j = isPosix ? join$1 : join;
|
|
2178
|
+
const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
|
|
2179
|
+
const raw = env.DSH_HOME;
|
|
2180
|
+
if (raw !== void 0 && raw.trim() !== "") {
|
|
2181
|
+
const expanded = expandHome(raw.trim(), home);
|
|
2182
|
+
return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
|
|
2183
|
+
}
|
|
2184
|
+
return j(home, ".dsh");
|
|
2185
|
+
}
|
|
2186
|
+
//#endregion
|
|
2015
2187
|
//#region src/runtime.ts
|
|
2016
2188
|
/**
|
|
2017
2189
|
* Payload resolution and load-time integrity verification for the vendored
|
|
@@ -2020,12 +2192,26 @@ function installPwshReplacement(ctx, options = {}) {
|
|
|
2020
2192
|
* The package ships its own Git for Windows MinGit extraction under
|
|
2021
2193
|
* runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
|
|
2022
2194
|
* (a host Git for Windows install, WSL, or a stray MSYS), because the whole
|
|
2023
|
-
* point of vendoring is a shell whose version and bytes are pinned.
|
|
2195
|
+
* point of vendoring is a shell whose version and bytes are pinned. Three
|
|
2024
2196
|
* invariants implement that:
|
|
2025
2197
|
*
|
|
2026
|
-
* 1. the binary is addressed by absolute path
|
|
2198
|
+
* 1. the binary is addressed by absolute path, never by name,
|
|
2027
2199
|
* 2. every vendored byte is checked against the SHA256 manifest generated at
|
|
2028
|
-
* packaging time before
|
|
2200
|
+
* packaging time before it is used at all, and
|
|
2201
|
+
* 3. the tree that RUNS is a published copy under the DSH home, not the tree
|
|
2202
|
+
* inside the package.
|
|
2203
|
+
*
|
|
2204
|
+
* The third invariant is why this module publishes a cache: Windows refuses to
|
|
2205
|
+
* rename a directory whose executable is running, and pnpm imports a package by
|
|
2206
|
+
* renaming a staging directory over it, so a shell spawned from inside
|
|
2207
|
+
* node_modules makes every later update or uninstall of this package fail with
|
|
2208
|
+
* ERR_PNPM_EPERM until the host stops. A persistent shell is this package's
|
|
2209
|
+
* whole point, so the payload moves out of the package instead of the process
|
|
2210
|
+
* moving out of the payload. The copy is content-addressed by the shipped
|
|
2211
|
+
* manifest: the directory name is a digest of the payload's file identities, so
|
|
2212
|
+
* a release that changes only JavaScript reuses the copy already published, and
|
|
2213
|
+
* a copy whose bytes or manifest disagree with the shipped identity is never
|
|
2214
|
+
* used.
|
|
2029
2215
|
*
|
|
2030
2216
|
* A mismatch refuses the mount with a specific message. The alternative —
|
|
2031
2217
|
* mounting and hoping — would let a tampered or half-installed payload run
|
|
@@ -2037,23 +2223,58 @@ function installPwshReplacement(ctx, options = {}) {
|
|
|
2037
2223
|
const RUNTIME_DIR = "runtime/win32-x64";
|
|
2038
2224
|
/** Manifest file name inside {@link RUNTIME_DIR}. */
|
|
2039
2225
|
const CHECKSUM_FILE = "checksums.sha256";
|
|
2226
|
+
/**
|
|
2227
|
+
* Payload cache directories under the DSH home, in order.
|
|
2228
|
+
*
|
|
2229
|
+
* The cache lives OUTSIDE the package on purpose: a running shell holds its own
|
|
2230
|
+
* executable open, Windows refuses to rename a directory that holds a running
|
|
2231
|
+
* executable, and pnpm imports a package by renaming over it. A copy here is
|
|
2232
|
+
* also why a release that only changes JavaScript never has to move 16 MiB.
|
|
2233
|
+
*/
|
|
2234
|
+
const CACHE_DIR_PARTS = ["win-bash", "runtime"];
|
|
2235
|
+
/**
|
|
2236
|
+
* Name prefix of the staging directory one cache copy is built in. The rest of
|
|
2237
|
+
* the name is the payload key, this process's id and a random suffix, so a
|
|
2238
|
+
* half-written directory is never mistaken for a published payload.
|
|
2239
|
+
*/
|
|
2240
|
+
const CACHE_STAGING_PREFIX = ".staging-";
|
|
2040
2241
|
/** Absolute package root (the directory holding package.json). */
|
|
2041
2242
|
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
2042
|
-
/** Absolute payload root. */
|
|
2243
|
+
/** Absolute payload root inside one package root. */
|
|
2043
2244
|
function runtimeRoot(packageRoot = PACKAGE_ROOT) {
|
|
2044
2245
|
return join(packageRoot, RUNTIME_DIR);
|
|
2045
2246
|
}
|
|
2046
|
-
/** Absolute path of the vendored shell. */
|
|
2247
|
+
/** Absolute path of the vendored shell inside one payload root. */
|
|
2248
|
+
function bashIn(root) {
|
|
2249
|
+
return join(root, "usr", "bin", "bash.exe");
|
|
2250
|
+
}
|
|
2251
|
+
/** Absolute path of the vendored POSIX-shell alias inside one payload root. */
|
|
2252
|
+
function shIn(root) {
|
|
2253
|
+
return join(root, "usr", "bin", "sh.exe");
|
|
2254
|
+
}
|
|
2255
|
+
/** Absolute path of one payload root's usr/bin directory. */
|
|
2256
|
+
function binIn(root) {
|
|
2257
|
+
return join(root, "usr", "bin");
|
|
2258
|
+
}
|
|
2259
|
+
/** Absolute path of the packaged payload's shell. */
|
|
2047
2260
|
function bashPath(packageRoot = PACKAGE_ROOT) {
|
|
2048
|
-
return
|
|
2261
|
+
return bashIn(runtimeRoot(packageRoot));
|
|
2049
2262
|
}
|
|
2050
|
-
/** Absolute path of the
|
|
2263
|
+
/** Absolute path of the packaged payload's POSIX-shell alias. */
|
|
2051
2264
|
function shPath(packageRoot = PACKAGE_ROOT) {
|
|
2052
|
-
return
|
|
2265
|
+
return shIn(runtimeRoot(packageRoot));
|
|
2053
2266
|
}
|
|
2054
|
-
/**
|
|
2055
|
-
|
|
2056
|
-
|
|
2267
|
+
/**
|
|
2268
|
+
* Absolute root of the per-user payload cache.
|
|
2269
|
+
*
|
|
2270
|
+
* It follows the DSH home rather than the package, so an isolated
|
|
2271
|
+
* `DSH_HOME` (a probe instance, a test run) gets its own cache, and an update or
|
|
2272
|
+
* uninstall of this package never touches a byte the cache holds.
|
|
2273
|
+
* @param env - environment to read DSH_HOME from; the live one by default.
|
|
2274
|
+
* @returns the directory payload copies are published under.
|
|
2275
|
+
*/
|
|
2276
|
+
function cacheRoot(env = process.env) {
|
|
2277
|
+
return join(resolveDshHome(env), ...CACHE_DIR_PARTS);
|
|
2057
2278
|
}
|
|
2058
2279
|
/**
|
|
2059
2280
|
* Parse a sha256sum-style manifest: '<64 hex> <path>' per line. Blank lines
|
|
@@ -2082,6 +2303,18 @@ function sha256(bytes) {
|
|
|
2082
2303
|
return createHash("sha256").update(bytes).digest("hex");
|
|
2083
2304
|
}
|
|
2084
2305
|
/**
|
|
2306
|
+
* The content key of one payload: a digest over its manifest's file identities.
|
|
2307
|
+
*
|
|
2308
|
+
* Manifest formatting and row order do not move it, and any change to a
|
|
2309
|
+
* payload file does. That is what makes a cache directory name a statement
|
|
2310
|
+
* about the bytes inside it rather than about the release that shipped them.
|
|
2311
|
+
* @param entries - the parsed manifest rows.
|
|
2312
|
+
* @returns the 16-character key that names the cache directory.
|
|
2313
|
+
*/
|
|
2314
|
+
function payloadKey(entries) {
|
|
2315
|
+
return sha256(entries.map((entry) => entry.path + " " + entry.sha256).sort().join("\n")).slice(0, 16);
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2085
2318
|
* Verify every registered payload file against the shipped manifest.
|
|
2086
2319
|
*
|
|
2087
2320
|
* Reads and hashes the whole payload (about 16 MiB after the curated
|
|
@@ -2092,7 +2325,19 @@ function sha256(bytes) {
|
|
|
2092
2325
|
* @throws when the manifest itself is unreadable or malformed.
|
|
2093
2326
|
*/
|
|
2094
2327
|
function verifyPayload(packageRoot = PACKAGE_ROOT) {
|
|
2095
|
-
|
|
2328
|
+
return verifyPayloadRoot(runtimeRoot(packageRoot));
|
|
2329
|
+
}
|
|
2330
|
+
/**
|
|
2331
|
+
* Verify every payload file of one payload root against that root's manifest.
|
|
2332
|
+
*
|
|
2333
|
+
* The root is the directory holding `usr/` and `checksums.sha256`, which is
|
|
2334
|
+
* either the packaged payload or a published cache copy, so both go through the
|
|
2335
|
+
* same pass.
|
|
2336
|
+
* @param root - the payload root to verify.
|
|
2337
|
+
* @returns the count of verified files and every mismatch found.
|
|
2338
|
+
* @throws when the manifest itself is unreadable or malformed.
|
|
2339
|
+
*/
|
|
2340
|
+
function verifyPayloadRoot(root) {
|
|
2096
2341
|
const manifest = parseChecksums(readFileSync(join(root, CHECKSUM_FILE), "utf8"));
|
|
2097
2342
|
const mismatches = [];
|
|
2098
2343
|
let verified = 0;
|
|
@@ -2118,16 +2363,11 @@ function verifyPayload(packageRoot = PACKAGE_ROOT) {
|
|
|
2118
2363
|
};
|
|
2119
2364
|
}
|
|
2120
2365
|
/**
|
|
2121
|
-
*
|
|
2122
|
-
*
|
|
2123
|
-
* The order is deliberate: platform, then architecture, then presence, then
|
|
2124
|
-
* integrity. A checksum failure names the first mismatching path so an
|
|
2125
|
-
* operator can act on it, and no path here ever consults PATH.
|
|
2366
|
+
* Refuse a host that cannot run this payload at all.
|
|
2126
2367
|
* @param host - the running host's platform facts.
|
|
2127
|
-
* @
|
|
2128
|
-
* @returns the resolved shell paths, or the rejection reason.
|
|
2368
|
+
* @returns the rejection, or undefined when the host could serve the payload.
|
|
2129
2369
|
*/
|
|
2130
|
-
function
|
|
2370
|
+
function rejectHost(host) {
|
|
2131
2371
|
if (host.platform !== "win32") return {
|
|
2132
2372
|
code: "unsupported-platform",
|
|
2133
2373
|
message: "win_bash requires Windows: the vendored payload is a Git for Windows MinGit build for win32 and there is no PATH fallback."
|
|
@@ -2136,6 +2376,32 @@ function resolveRuntime(host, packageRoot = PACKAGE_ROOT) {
|
|
|
2136
2376
|
code: "unsupported-arch",
|
|
2137
2377
|
message: "win_bash currently ships only the x64 payload; this host is " + host.arch + "."
|
|
2138
2378
|
};
|
|
2379
|
+
}
|
|
2380
|
+
/** The three paths one payload root provides, tagged with where it came from. */
|
|
2381
|
+
function readyFrom(root, source) {
|
|
2382
|
+
return {
|
|
2383
|
+
bash: bashIn(root),
|
|
2384
|
+
bin: binIn(root),
|
|
2385
|
+
payloadRoot: root,
|
|
2386
|
+
source
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
/**
|
|
2390
|
+
* Resolve the PACKAGED shell for one host, or refuse the mount.
|
|
2391
|
+
*
|
|
2392
|
+
* The order is deliberate: platform, then architecture, then presence, then
|
|
2393
|
+
* integrity. A checksum failure names the first mismatching path so an
|
|
2394
|
+
* operator can act on it, and no path here ever consults PATH.
|
|
2395
|
+
*
|
|
2396
|
+
* This is the packaged tree, not the cache: callers that intend to RUN the
|
|
2397
|
+
* shell want {@link prepareRuntime}, which publishes a copy first.
|
|
2398
|
+
* @param host - the running host's platform facts.
|
|
2399
|
+
* @param packageRoot - package root holding the payload.
|
|
2400
|
+
* @returns the resolved shell paths, or the rejection reason.
|
|
2401
|
+
*/
|
|
2402
|
+
function resolveRuntime(host, packageRoot = PACKAGE_ROOT) {
|
|
2403
|
+
const refused = rejectHost(host);
|
|
2404
|
+
if (refused !== void 0) return refused;
|
|
2139
2405
|
const bash = bashPath(packageRoot);
|
|
2140
2406
|
try {
|
|
2141
2407
|
if (!statSync(bash).isFile()) throw new Error("not a file");
|
|
@@ -2161,10 +2427,130 @@ function resolveRuntime(host, packageRoot = PACKAGE_ROOT) {
|
|
|
2161
2427
|
message: "the vendored payload failed its SHA256 manifest: " + report.mismatches.length.toString() + " file(s) differ, first " + first.path + " (expected " + first.expected.slice(0, 12) + ", found " + first.actual.slice(0, 12) + "). Reinstall the package; win_bash will not run an unverified payload."
|
|
2162
2428
|
};
|
|
2163
2429
|
}
|
|
2164
|
-
return
|
|
2165
|
-
|
|
2166
|
-
|
|
2430
|
+
return readyFrom(runtimeRoot(packageRoot), "package");
|
|
2431
|
+
}
|
|
2432
|
+
/** The recursive copy one published payload is built with. */
|
|
2433
|
+
function copyTree(source, target) {
|
|
2434
|
+
cpSync(source, target, {
|
|
2435
|
+
recursive: true,
|
|
2436
|
+
force: true,
|
|
2437
|
+
preserveTimestamps: true
|
|
2438
|
+
});
|
|
2439
|
+
}
|
|
2440
|
+
/** One error's message, for an operator-facing line. */
|
|
2441
|
+
function describe(error) {
|
|
2442
|
+
return error instanceof Error ? error.message : String(error);
|
|
2443
|
+
}
|
|
2444
|
+
/** Delete a staging directory, never letting a failed reclaim escape. */
|
|
2445
|
+
function removeStaging(staging) {
|
|
2446
|
+
try {
|
|
2447
|
+
rmSync(staging, {
|
|
2448
|
+
recursive: true,
|
|
2449
|
+
force: true
|
|
2450
|
+
});
|
|
2451
|
+
} catch {}
|
|
2452
|
+
}
|
|
2453
|
+
/**
|
|
2454
|
+
* Whether one directory is a complete copy of the payload the key names.
|
|
2455
|
+
*
|
|
2456
|
+
* The copy's own manifest must reproduce the expected key before any byte is
|
|
2457
|
+
* executed, so a directory whose manifest was rewritten alongside its files is
|
|
2458
|
+
* a miss rather than a match.
|
|
2459
|
+
* @param root - the candidate payload root.
|
|
2460
|
+
* @param key - the key the shipped manifest produced.
|
|
2461
|
+
* @returns whether that directory can be spawned from.
|
|
2462
|
+
*/
|
|
2463
|
+
function cacheReady(root, key) {
|
|
2464
|
+
try {
|
|
2465
|
+
if (payloadKey(parseChecksums(readFileSync(join(root, "checksums.sha256"), "utf8"))) !== key) return false;
|
|
2466
|
+
if (!statSync(bashIn(root)).isFile()) return false;
|
|
2467
|
+
const report = verifyPayloadRoot(root);
|
|
2468
|
+
return report.verified > 0 && report.mismatches.length === 0;
|
|
2469
|
+
} catch {
|
|
2470
|
+
return false;
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
/**
|
|
2474
|
+
* Publish one payload copy under its key.
|
|
2475
|
+
*
|
|
2476
|
+
* The copy is built in a staging directory beside the target and renamed into
|
|
2477
|
+
* place, so the published name only ever refers to a complete tree. A rename
|
|
2478
|
+
* that loses a race against another host publishing the same key is not a
|
|
2479
|
+
* failure: both hosts copy the same bytes by construction.
|
|
2480
|
+
* @param source - the packaged payload root to copy.
|
|
2481
|
+
* @param target - the cache directory the key names.
|
|
2482
|
+
* @param key - the payload key, carried into the staging name.
|
|
2483
|
+
* @param copy - the copy itself.
|
|
2484
|
+
*/
|
|
2485
|
+
function publishPayload(source, target, key, copy) {
|
|
2486
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
2487
|
+
if (existsSync(target)) rmSync(target, {
|
|
2488
|
+
recursive: true,
|
|
2489
|
+
force: true
|
|
2490
|
+
});
|
|
2491
|
+
const staging = join(dirname(target), CACHE_STAGING_PREFIX + key + "-" + process.pid.toString() + "-" + randomUUID().slice(0, 8));
|
|
2492
|
+
try {
|
|
2493
|
+
copy(source, staging);
|
|
2494
|
+
renameSync(staging, target);
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
removeStaging(staging);
|
|
2497
|
+
if (cacheReady(target, key)) return;
|
|
2498
|
+
throw error;
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* Resolve the shell one host runs, publishing the payload outside the package.
|
|
2503
|
+
*
|
|
2504
|
+
* The verification order is the whole point: the shipped manifest identifies
|
|
2505
|
+
* the payload, a published copy of that identity is reused when it verifies,
|
|
2506
|
+
* and otherwise the packaged tree is verified first and only then copied. What
|
|
2507
|
+
* gets spawned is therefore always a tree whose bytes match the shipped
|
|
2508
|
+
* manifest, and it lives under the DSH home where an update or uninstall of
|
|
2509
|
+
* this package cannot be blocked by a running shell.
|
|
2510
|
+
*
|
|
2511
|
+
* A cache that cannot be written is not a reason to withhold the tool: the
|
|
2512
|
+
* verified packaged tree runs instead and the caller is told, through
|
|
2513
|
+
* {@link PrepareRuntimeOptions.warn}, that updates will need this host stopped.
|
|
2514
|
+
* A payload that fails its manifest is still a refusal — running unverified
|
|
2515
|
+
* bytes is the outcome the manifest exists to prevent, cache or no cache.
|
|
2516
|
+
* @param options - host facts, roots, and the seams tests drive.
|
|
2517
|
+
* @returns the shell paths to run, or the rejection reason.
|
|
2518
|
+
*/
|
|
2519
|
+
function prepareRuntime(options = {}) {
|
|
2520
|
+
const host = options.host ?? {
|
|
2521
|
+
platform: process.platform,
|
|
2522
|
+
arch: process.arch
|
|
2167
2523
|
};
|
|
2524
|
+
const refused = rejectHost(host);
|
|
2525
|
+
if (refused !== void 0) return refused;
|
|
2526
|
+
const packageRoot = options.packageRoot ?? PACKAGE_ROOT;
|
|
2527
|
+
const source = runtimeRoot(packageRoot);
|
|
2528
|
+
const cacheDir = options.cacheRoot ?? cacheRoot(options.env);
|
|
2529
|
+
const warn = options.warn ?? (() => {});
|
|
2530
|
+
let key;
|
|
2531
|
+
try {
|
|
2532
|
+
key = payloadKey(parseChecksums(readFileSync(join(source, CHECKSUM_FILE), "utf8")));
|
|
2533
|
+
} catch (error) {
|
|
2534
|
+
return {
|
|
2535
|
+
code: "manifest-unreadable",
|
|
2536
|
+
message: "the payload checksum manifest could not be read: " + describe(error)
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
const published = join(cacheDir, key);
|
|
2540
|
+
if (cacheReady(published, key)) return readyFrom(published, "cache");
|
|
2541
|
+
const shipped = resolveRuntime(host, packageRoot);
|
|
2542
|
+
if ("code" in shipped) return shipped;
|
|
2543
|
+
try {
|
|
2544
|
+
publishPayload(source, published, key, options.copy ?? copyTree);
|
|
2545
|
+
} catch (error) {
|
|
2546
|
+
warn("the verified payload could not be published to " + published + " (" + describe(error) + "), so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
|
|
2547
|
+
return shipped;
|
|
2548
|
+
}
|
|
2549
|
+
if (!cacheReady(published, key)) {
|
|
2550
|
+
warn("the payload copy at " + published + " did not verify against the shipped manifest, so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
|
|
2551
|
+
return shipped;
|
|
2552
|
+
}
|
|
2553
|
+
return readyFrom(published, "cache");
|
|
2168
2554
|
}
|
|
2169
2555
|
//#endregion
|
|
2170
2556
|
//#region src/background.ts
|
|
@@ -2264,7 +2650,7 @@ function startBackgroundJob(command) {
|
|
|
2264
2650
|
terminated = true;
|
|
2265
2651
|
process?.terminate();
|
|
2266
2652
|
},
|
|
2267
|
-
done: spawned === void 0 ? Promise.resolve(processOutcome(void 0, failedBeforeStart, false)) : spawned.done.then(async (outcome) => {
|
|
2653
|
+
done: (spawned === void 0 ? Promise.resolve(processOutcome(void 0, failedBeforeStart, false)) : spawned.done.then(async (outcome) => {
|
|
2268
2654
|
try {
|
|
2269
2655
|
await spawned.waitForExit();
|
|
2270
2656
|
} catch {}
|
|
@@ -2272,6 +2658,9 @@ function startBackgroundJob(command) {
|
|
|
2272
2658
|
}, (error) => {
|
|
2273
2659
|
failedBeforeStart = messageOf(error);
|
|
2274
2660
|
return processOutcome(void 0, failedBeforeStart, false);
|
|
2661
|
+
})).then(async (outcome) => {
|
|
2662
|
+
if (command.temp !== void 0) await removeShellTempDir(command.temp);
|
|
2663
|
+
return outcome;
|
|
2275
2664
|
})
|
|
2276
2665
|
};
|
|
2277
2666
|
}
|
|
@@ -2579,6 +2968,7 @@ function buildWinBashTool(ctx, config, runtime, shells) {
|
|
|
2579
2968
|
if (!config.enableRunInBackground) throw new Error("win_bash: run_in_background is disabled for this deployment (enableRunInBackground: false), so this call was not started.");
|
|
2580
2969
|
const registry = readJobRegistry(ctx);
|
|
2581
2970
|
if (registry === void 0) throw new Error("BACKGROUND_UNAVAILABLE: this deployment composes no background job registry (ctx.jobs), so win_bash cannot register a background command. This call was not run in the foreground instead. Run it without run_in_background, or start it in the background with the host pwsh tool, which is the native shell for this platform and stays available whenever win_bash cannot serve a call.");
|
|
2971
|
+
const temp = shellTempDir();
|
|
2582
2972
|
return {
|
|
2583
2973
|
stdout: "",
|
|
2584
2974
|
stderr: "",
|
|
@@ -2590,7 +2980,8 @@ function buildWinBashTool(ctx, config, runtime, shells) {
|
|
|
2590
2980
|
script: command,
|
|
2591
2981
|
argv: shellArgv(runtime),
|
|
2592
2982
|
cwd,
|
|
2593
|
-
env: shellEnvironment(runtime,
|
|
2983
|
+
env: shellEnvironment(runtime, temp),
|
|
2984
|
+
temp,
|
|
2594
2985
|
label: args.command,
|
|
2595
2986
|
stdoutBytes: BACKGROUND_STDOUT_BYTES,
|
|
2596
2987
|
stderrBytes: BACKGROUND_STDERR_BYTES
|
|
@@ -2733,9 +3124,14 @@ async function mountWithGate(ctx, config, runtime, options = {}) {
|
|
|
2733
3124
|
* @param config - the row's config, validated by {@link Config}.
|
|
2734
3125
|
*/
|
|
2735
3126
|
function apply(ctx, config) {
|
|
2736
|
-
const runtime =
|
|
2737
|
-
|
|
2738
|
-
|
|
3127
|
+
const runtime = prepareRuntime({
|
|
3128
|
+
host: {
|
|
3129
|
+
platform: process.platform,
|
|
3130
|
+
arch: process.arch
|
|
3131
|
+
},
|
|
3132
|
+
warn: (message) => {
|
|
3133
|
+
ctx.logger?.warn?.("dsh-win-bash: " + message);
|
|
3134
|
+
}
|
|
2739
3135
|
});
|
|
2740
3136
|
if ("code" in runtime) {
|
|
2741
3137
|
ctx.logger?.warn?.("dsh-win-bash: win_bash was not mounted (" + runtime.code + "): " + runtime.message);
|
|
@@ -2748,9 +3144,15 @@ function apply(ctx, config) {
|
|
|
2748
3144
|
ctx.logger?.error?.("dsh-win-bash: " + (error instanceof Error ? error.message : String(error)));
|
|
2749
3145
|
throw error;
|
|
2750
3146
|
}
|
|
3147
|
+
sweepOrphanShellTempDirs().then((sweep) => {
|
|
3148
|
+
if (sweep.removed.length > 0) ctx.logger?.info?.("dsh-win-bash: reclaimed " + sweep.removed.length.toString() + " orphaned shell temp directories left by earlier runs");
|
|
3149
|
+
if (sweep.failed.length > 0) ctx.logger?.warn?.("dsh-win-bash: " + sweep.failed.length.toString() + " orphaned shell temp directories could not be reclaimed and will be retried on the next start: " + sweep.failed.join(", "));
|
|
3150
|
+
}, (error) => {
|
|
3151
|
+
ctx.logger?.warn?.("dsh-win-bash: the orphaned shell temp directory sweep failed: " + (error instanceof Error ? error.message : String(error)));
|
|
3152
|
+
});
|
|
2751
3153
|
mountWithGate(ctx, resolved, runtime).catch((error) => {
|
|
2752
3154
|
ctx.logger?.error?.("dsh-win-bash: the mount continuation failed: " + (error instanceof Error ? error.message : String(error)));
|
|
2753
3155
|
});
|
|
2754
3156
|
}
|
|
2755
3157
|
//#endregion
|
|
2756
|
-
export { BACKGROUND_JOB_KIND, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, DEFAULT_SYNC_WITH_LIANGSHEN, GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, HOST_PWSH_TOOL, LIANGSHEN_PRESET_ID, SERVING_MODE, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashPath, buildFrame, declaresLiangShen, gateRefusalMessage, inject, installPwshReplacement, markerFor, mountWithGate, name, parseChecksums, parseFrame, readJobRegistry, readPresetRegistry, registerWinBash, renderResult, resolveRuntime, runtimeRoot, settleHostTree, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, startLiangShenGate, stripTerminalEscapes, truncationNotice, validateConfig, verifyPayload };
|
|
3158
|
+
export { BACKGROUND_JOB_KIND, CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, DEFAULT_SYNC_WITH_LIANGSHEN, GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, HOST_PWSH_TOOL, LIANGSHEN_PRESET_ID, SERVING_MODE, SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashIn, bashPath, binIn, buildFrame, cacheRoot, declaresLiangShen, gateRefusalMessage, inject, installPwshReplacement, markerFor, mountWithGate, name, parseChecksums, parseFrame, payloadKey, prepareRuntime, readJobRegistry, readPresetRegistry, registerWinBash, removeShellTempDir, renderResult, resolveRuntime, runtimeRoot, settleHostTree, shIn, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, startLiangShenGate, stripTerminalEscapes, sweepOrphanShellTempDirs, truncationNotice, validateConfig, verifyPayload, verifyPayloadRoot };
|
|
@@ -129,6 +129,13 @@ export interface BackgroundCommand {
|
|
|
129
129
|
readonly cwd: string;
|
|
130
130
|
/** Environment entries for the process. */
|
|
131
131
|
readonly env: NodeJS.ProcessEnv;
|
|
132
|
+
/**
|
|
133
|
+
* The private temp directory this job owns, when the caller created one (it is
|
|
134
|
+
* the TMP/TEMP/TMPDIR in {@link env}). Reclaimed when the job settles, on every
|
|
135
|
+
* path: the process's own exit, a kill through the hooks, and a starter that
|
|
136
|
+
* never spawned.
|
|
137
|
+
*/
|
|
138
|
+
readonly temp?: string;
|
|
132
139
|
/** Label shown for this job. */
|
|
133
140
|
readonly label: string;
|
|
134
141
|
/** In-memory capture ceiling for stdout, in bytes. */
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH_HOME resolution shared by the plugin family's Host halves: the
|
|
3
|
+
* environment override wins, the platform home fallback follows. Mirrors
|
|
4
|
+
* what dsh-pet and dsh-liangshen each used to implement locally.
|
|
5
|
+
*/
|
|
6
|
+
/** Expand a leading ~ (or ~user) in a path, platform-style. */
|
|
7
|
+
export declare function expandHome(path: string, home?: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Resolve the DSH home directory.
|
|
10
|
+
* @param env - process environment to read DSH_HOME from.
|
|
11
|
+
* @param home - platform home directory fallback (test seam).
|
|
12
|
+
* @returns the absolute DSH home path.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveDshHome(env?: NodeJS.ProcessEnv, home?: string): string;
|
|
15
|
+
/** Resolve the DSH home directory from the live environment. */
|
|
16
|
+
export declare function dshHome(): string;
|