@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.
@@ -13,6 +13,15 @@
13
13
  * and on a Windows host that is not x64, because no PATH bash is ever used as
14
14
  * a substitute.
15
15
  *
16
+ * Mount-time publication: the tree that is spawned is a verified copy under the
17
+ * DSH home, not the tree inside this package. A persistent shell holds its own
18
+ * executable open, and Windows refuses to rename a directory that holds a
19
+ * running executable, so a shell started inside node_modules makes pnpm's
20
+ * import of this package fail with ERR_PNPM_EPERM. Publishing the payload
21
+ * outside the package is what lets an update or uninstall run while sessions
22
+ * are live; a cache that cannot be written keeps the tool working from the
23
+ * packaged tree and logs that updates will need this host stopped.
24
+ *
16
25
  * Availability gate: win_bash serves sessions that run the LiangShen (梁神)
17
26
  * preset, so its registration follows that preset's DECLARATION in the
18
27
  * harness's agent-preset registry — declared means registered, undeclared
@@ -49,10 +58,10 @@ export { CONFIG_DEFAULTS, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND,
49
58
  export { HOST_PWSH_TOOL, SERVING_MODE, installPwshReplacement, type PwshReplacementOptions, type ScopedRestrictor, type SessionPolicyReader, } from './pwsh-replacement.ts';
50
59
  export { WIN_BASH_TOOL, renderResult, readJobRegistry, stripTerminalEscapes, truncationNotice } from './tool.ts';
51
60
  export type { RenderFacts } from './tool.ts';
52
- export { ShellRegistry, ShellUnavailableError, shellArgv, shellEnvironment, shellTempDir, } from './shell.ts';
61
+ export { SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, removeShellTempDir, shellArgv, shellEnvironment, shellTempDir, sweepOrphanShellTempDirs, type ShellTempSweep, type ShellTempSweepOptions, } from './shell.ts';
53
62
  export { buildFrame, markerFor, parseFrame } from './protocol.ts';
54
63
  export { GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, LIANGSHEN_PRESET_ID, declaresLiangShen, readPresetRegistry, settleHostTree, startLiangShenGate, type GateOptions, type GateOutcome, type GateReason, type PresetRosterReader, type PresetRosterRow, type SettleStatus, } from './gate.ts';
55
- export { bashPath, parseChecksums, resolveRuntime, runtimeRoot, shPath, verifyPayload, } from './runtime.ts';
64
+ export { CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, bashIn, bashPath, binIn, cacheRoot, parseChecksums, payloadKey, prepareRuntime, resolveRuntime, runtimeRoot, shIn, shPath, verifyPayload, verifyPayloadRoot, type CopyTree, type PrepareRuntimeOptions, } from './runtime.ts';
56
65
  /** Cordis plugin name; also the loader row id this package mounts under. */
57
66
  export declare const name = "dsh-win-bash";
58
67
  /** Required services: the tool registry and the managed subprocess seam. */
@@ -5,12 +5,26 @@
5
5
  * The package ships its own Git for Windows MinGit extraction under
6
6
  * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
7
7
  * (a host Git for Windows install, WSL, or a stray MSYS), because the whole
8
- * point of vendoring is a shell whose version and bytes are pinned. Two
8
+ * point of vendoring is a shell whose version and bytes are pinned. Three
9
9
  * invariants implement that:
10
10
  *
11
- * 1. the binary is addressed by absolute path inside the package, and
11
+ * 1. the binary is addressed by absolute path, never by name,
12
12
  * 2. every vendored byte is checked against the SHA256 manifest generated at
13
- * packaging time before the tool is mounted at all.
13
+ * packaging time before it is used at all, and
14
+ * 3. the tree that RUNS is a published copy under the DSH home, not the tree
15
+ * inside the package.
16
+ *
17
+ * The third invariant is why this module publishes a cache: Windows refuses to
18
+ * rename a directory whose executable is running, and pnpm imports a package by
19
+ * renaming a staging directory over it, so a shell spawned from inside
20
+ * node_modules makes every later update or uninstall of this package fail with
21
+ * ERR_PNPM_EPERM until the host stops. A persistent shell is this package's
22
+ * whole point, so the payload moves out of the package instead of the process
23
+ * moving out of the payload. The copy is content-addressed by the shipped
24
+ * manifest: the directory name is a digest of the payload's file identities, so
25
+ * a release that changes only JavaScript reuses the copy already published, and
26
+ * a copy whose bytes or manifest disagree with the shipped identity is never
27
+ * used.
14
28
  *
15
29
  * A mismatch refuses the mount with a specific message. The alternative —
16
30
  * mounting and hoping — would let a tampered or half-installed payload run
@@ -26,16 +40,47 @@ export declare const CHECKSUM_FILE = "checksums.sha256";
26
40
  export declare const RUNTIME_PLATFORM = "win32";
27
41
  /** The one architecture this payload supports. */
28
42
  export declare const RUNTIME_ARCH = "x64";
43
+ /**
44
+ * Payload cache directories under the DSH home, in order.
45
+ *
46
+ * The cache lives OUTSIDE the package on purpose: a running shell holds its own
47
+ * executable open, Windows refuses to rename a directory that holds a running
48
+ * executable, and pnpm imports a package by renaming over it. A copy here is
49
+ * also why a release that only changes JavaScript never has to move 16 MiB.
50
+ */
51
+ export declare const CACHE_DIR_PARTS: readonly ["win-bash", "runtime"];
52
+ /**
53
+ * Name prefix of the staging directory one cache copy is built in. The rest of
54
+ * the name is the payload key, this process's id and a random suffix, so a
55
+ * half-written directory is never mistaken for a published payload.
56
+ */
57
+ export declare const CACHE_STAGING_PREFIX = ".staging-";
29
58
  /** Absolute package root (the directory holding package.json). */
30
59
  export declare const PACKAGE_ROOT: string;
31
- /** Absolute payload root. */
60
+ /** Absolute payload root inside one package root. */
32
61
  export declare function runtimeRoot(packageRoot?: string): string;
33
- /** Absolute path of the vendored shell. */
62
+ /** Absolute path of the vendored shell inside one payload root. */
63
+ export declare function bashIn(root: string): string;
64
+ /** Absolute path of the vendored POSIX-shell alias inside one payload root. */
65
+ export declare function shIn(root: string): string;
66
+ /** Absolute path of one payload root's usr/bin directory. */
67
+ export declare function binIn(root: string): string;
68
+ /** Absolute path of the packaged payload's shell. */
34
69
  export declare function bashPath(packageRoot?: string): string;
35
- /** Absolute path of the vendored POSIX-shell alias of the same binary. */
70
+ /** Absolute path of the packaged payload's POSIX-shell alias. */
36
71
  export declare function shPath(packageRoot?: string): string;
37
- /** Absolute path of the vendored payload's usr/bin directory. */
72
+ /** Absolute path of the packaged payload's usr/bin directory. */
38
73
  export declare function binDir(packageRoot?: string): string;
74
+ /**
75
+ * Absolute root of the per-user payload cache.
76
+ *
77
+ * It follows the DSH home rather than the package, so an isolated
78
+ * `DSH_HOME` (a probe instance, a test run) gets its own cache, and an update or
79
+ * uninstall of this package never touches a byte the cache holds.
80
+ * @param env - environment to read DSH_HOME from; the live one by default.
81
+ * @returns the directory payload copies are published under.
82
+ */
83
+ export declare function cacheRoot(env?: NodeJS.ProcessEnv): string;
39
84
  /** One manifest row: a payload-relative path and its digest. */
40
85
  export interface ChecksumEntry {
41
86
  /** Payload-relative path, using forward slashes. */
@@ -70,6 +115,16 @@ export interface ChecksumReport {
70
115
  }
71
116
  /** SHA256 of a buffer or string, lowercase hex. */
72
117
  export declare function sha256(bytes: Buffer | string): string;
118
+ /**
119
+ * The content key of one payload: a digest over its manifest's file identities.
120
+ *
121
+ * Manifest formatting and row order do not move it, and any change to a
122
+ * payload file does. That is what makes a cache directory name a statement
123
+ * about the bytes inside it rather than about the release that shipped them.
124
+ * @param entries - the parsed manifest rows.
125
+ * @returns the 16-character key that names the cache directory.
126
+ */
127
+ export declare function payloadKey(entries: readonly ChecksumEntry[]): string;
73
128
  /**
74
129
  * Verify every registered payload file against the shipped manifest.
75
130
  *
@@ -81,6 +136,17 @@ export declare function sha256(bytes: Buffer | string): string;
81
136
  * @throws when the manifest itself is unreadable or malformed.
82
137
  */
83
138
  export declare function verifyPayload(packageRoot?: string): ChecksumReport;
139
+ /**
140
+ * Verify every payload file of one payload root against that root's manifest.
141
+ *
142
+ * The root is the directory holding `usr/` and `checksums.sha256`, which is
143
+ * either the packaged payload or a published cache copy, so both go through the
144
+ * same pass.
145
+ * @param root - the payload root to verify.
146
+ * @returns the count of verified files and every mismatch found.
147
+ * @throws when the manifest itself is unreadable or malformed.
148
+ */
149
+ export declare function verifyPayloadRoot(root: string): ChecksumReport;
84
150
  /** Why this deployment cannot serve the vendored shell. */
85
151
  export interface RuntimeRejection {
86
152
  /** Machine-readable reason. */
@@ -90,10 +156,14 @@ export interface RuntimeRejection {
90
156
  }
91
157
  /** Successful payload resolution. */
92
158
  export interface RuntimeReady {
93
- /** Absolute path of the vendored bash.exe. */
159
+ /** Absolute path of the vendored bash.exe that will be spawned. */
94
160
  readonly bash: string;
95
161
  /** Absolute path of the payload's usr/bin. */
96
162
  readonly bin: string;
163
+ /** Absolute payload root both paths above live in. */
164
+ readonly payloadRoot: string;
165
+ /** Whether that root is the published cache copy or the packaged tree. */
166
+ readonly source: 'cache' | 'package';
97
167
  }
98
168
  /** Whether the running host can serve this payload at all. */
99
169
  export interface HostPlatform {
@@ -103,13 +173,52 @@ export interface HostPlatform {
103
173
  readonly arch: string;
104
174
  }
105
175
  /**
106
- * Resolve the vendored shell for one host, or refuse the mount.
176
+ * Resolve the PACKAGED shell for one host, or refuse the mount.
107
177
  *
108
178
  * The order is deliberate: platform, then architecture, then presence, then
109
179
  * integrity. A checksum failure names the first mismatching path so an
110
180
  * operator can act on it, and no path here ever consults PATH.
181
+ *
182
+ * This is the packaged tree, not the cache: callers that intend to RUN the
183
+ * shell want {@link prepareRuntime}, which publishes a copy first.
111
184
  * @param host - the running host's platform facts.
112
185
  * @param packageRoot - package root holding the payload.
113
186
  * @returns the resolved shell paths, or the rejection reason.
114
187
  */
115
188
  export declare function resolveRuntime(host: HostPlatform, packageRoot?: string): RuntimeReady | RuntimeRejection;
189
+ /** One tree copy: the source payload root, the directory to fill. */
190
+ export type CopyTree = (source: string, target: string) => void;
191
+ /** Where payload publication can be redirected, and what it reports. */
192
+ export interface PrepareRuntimeOptions {
193
+ /** The running host's platform facts; this process's by default. */
194
+ readonly host?: HostPlatform;
195
+ /** Package root holding runtime/win32-x64; this package's own by default. */
196
+ readonly packageRoot?: string;
197
+ /** Cache root to publish into; the DSH home's own by default. */
198
+ readonly cacheRoot?: string;
199
+ /** Environment the default cache root resolves from; process.env by default. */
200
+ readonly env?: NodeJS.ProcessEnv;
201
+ /** Operator-facing notes; a copy that could not be published is reported here. */
202
+ readonly warn?: (message: string) => void;
203
+ /** The copy itself; a real recursive copy by default. */
204
+ readonly copy?: CopyTree;
205
+ }
206
+ /**
207
+ * Resolve the shell one host runs, publishing the payload outside the package.
208
+ *
209
+ * The verification order is the whole point: the shipped manifest identifies
210
+ * the payload, a published copy of that identity is reused when it verifies,
211
+ * and otherwise the packaged tree is verified first and only then copied. What
212
+ * gets spawned is therefore always a tree whose bytes match the shipped
213
+ * manifest, and it lives under the DSH home where an update or uninstall of
214
+ * this package cannot be blocked by a running shell.
215
+ *
216
+ * A cache that cannot be written is not a reason to withhold the tool: the
217
+ * verified packaged tree runs instead and the caller is told, through
218
+ * {@link PrepareRuntimeOptions.warn}, that updates will need this host stopped.
219
+ * A payload that fails its manifest is still a refusal — running unverified
220
+ * bytes is the outcome the manifest exists to prevent, cache or no cache.
221
+ * @param options - host facts, roots, and the seams tests drive.
222
+ * @returns the shell paths to run, or the rejection reason.
223
+ */
224
+ export declare function prepareRuntime(options?: PrepareRuntimeOptions): RuntimeReady | RuntimeRejection;
@@ -33,6 +33,12 @@ export declare const SHELL_STDERR_CAPTURE_BYTES: number;
33
33
  export declare const TIMEOUT_EXIT_CODE = 124;
34
34
  /** Environment variable names carrying the per-shell private temp directory. */
35
35
  export declare const TEMP_ENV_KEYS: readonly ["TMPDIR", "TMP", "TEMP"];
36
+ /**
37
+ * Name prefix of every private per-shell temp directory. The rest of the name
38
+ * is the owning process id plus a random suffix, which is what lets a later
39
+ * start tell an orphan from a directory a live shell is still using.
40
+ */
41
+ export declare const SHELL_TEMP_PREFIX = "dsh-win-bash-";
36
42
  /**
37
43
  * The argv of one pinned shell: the payload's own bash by absolute path, no rc
38
44
  * file and no profile, reading its commands from stdin. This tool never
@@ -57,9 +63,55 @@ export declare function shellEnvironment(runtime: {
57
63
  }, temp: string, base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
58
64
  /**
59
65
  * Create one shell process's private temp directory.
66
+ * @param base - the temp root to create it under; the machine's own by default.
60
67
  * @returns the absolute directory, created if absent.
61
68
  */
62
- export declare function shellTempDir(): string;
69
+ export declare function shellTempDir(base?: string): string;
70
+ /**
71
+ * Delete one private temp directory, never letting the attempt throw.
72
+ *
73
+ * Teardown must not fail because a directory could not be reclaimed: the shell
74
+ * is already gone, and whatever is left is named for this process's own pid, so
75
+ * the next start's {@link sweepOrphanShellTempDirs} collects it once that pid is
76
+ * gone.
77
+ * @param temp - the directory that shell owned.
78
+ */
79
+ export declare function removeShellTempDir(temp: string): Promise<void>;
80
+ /** What one orphan sweep found and did, for logging and for tests. */
81
+ export interface ShellTempSweep {
82
+ /** Directories this sweep deleted. */
83
+ readonly removed: string[];
84
+ /** Directories whose owning process is still alive. */
85
+ readonly kept: string[];
86
+ /** Directories that could not be deleted; the next start tries again. */
87
+ readonly failed: string[];
88
+ }
89
+ /** The seams one orphan sweep runs against. */
90
+ export interface ShellTempSweepOptions {
91
+ /** The temp root to scan; the machine's own by default. */
92
+ readonly root?: string;
93
+ /** Whether the process that owned a directory still exists. */
94
+ readonly isAlive?: (pid: number) => boolean;
95
+ /** How one directory is deleted; a rejection marks it failed. */
96
+ readonly remove?: (dir: string) => Promise<void>;
97
+ }
98
+ /**
99
+ * Reclaim the private temp directories of shells that no longer exist.
100
+ *
101
+ * A crash or a hard kill ends this process before it can delete what its live
102
+ * shells owned, and those directories are not small: whatever a command wrote
103
+ * under TMP/TEMP/TMPDIR is still in them. Every name carries the pid that owned
104
+ * it, so the ones whose pid is gone are garbage by construction, and the ones
105
+ * whose pid still runs may belong to a live shell in this very process or to
106
+ * another instance sharing the temp root - those are kept.
107
+ *
108
+ * One directory that cannot be deleted is reported and skipped; it must not
109
+ * stop the round, because the usual cause (a long path, a locked file) is local
110
+ * to that directory.
111
+ * @param options - the seams; production passes none.
112
+ * @returns what was removed, kept and failed.
113
+ */
114
+ export declare function sweepOrphanShellTempDirs(options?: ShellTempSweepOptions): Promise<ShellTempSweep>;
63
115
  /** One command's complete result, as the tool consumes it. */
64
116
  export interface ShellResult {
65
117
  /** The command's stdout, bounded to the visible budget. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-win-bash",
3
3
  "description": "Pinned private bash for Windows x64 DSH sessions: one persistent bash process per session behind the win_bash tool, carrying a digested Git for Windows MinGit payload and no PATH fallback.",
4
- "version": "0.4.13",
4
+ "version": "0.4.14",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
package/src/background.ts CHANGED
@@ -41,7 +41,7 @@
41
41
  */
42
42
 
43
43
  import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'
44
- import { DEFAULT_SPILL_BYTES, GRACE_MS, SHELL_STDERR_CAPTURE_BYTES } from './shell.ts'
44
+ import { DEFAULT_SPILL_BYTES, GRACE_MS, SHELL_STDERR_CAPTURE_BYTES, removeShellTempDir } from './shell.ts'
45
45
 
46
46
  /**
47
47
  * Producer kind of every job this plugin starts. It namespaces the ids the
@@ -137,6 +137,13 @@ export interface BackgroundCommand {
137
137
  readonly cwd: string
138
138
  /** Environment entries for the process. */
139
139
  readonly env: NodeJS.ProcessEnv
140
+ /**
141
+ * The private temp directory this job owns, when the caller created one (it is
142
+ * the TMP/TEMP/TMPDIR in {@link env}). Reclaimed when the job settles, on every
143
+ * path: the process's own exit, a kill through the hooks, and a starter that
144
+ * never spawned.
145
+ */
146
+ readonly temp?: string
140
147
  /** Label shown for this job. */
141
148
  readonly label: string
142
149
  /** In-memory capture ceiling for stdout, in bytes. */
@@ -230,7 +237,7 @@ export function startBackgroundJob(command: BackgroundCommand): string {
230
237
  failedBeforeStart = messageOf(error)
231
238
  }
232
239
  const spawned = process
233
- const done: Promise<JobOutcomeLike> = spawned === undefined
240
+ const settled: Promise<JobOutcomeLike> = spawned === undefined
234
241
  ? Promise.resolve(processOutcome(undefined, failedBeforeStart, false))
235
242
  : spawned.done.then(
236
243
  async (outcome) => {
@@ -251,6 +258,16 @@ export function startBackgroundJob(command: BackgroundCommand): string {
251
258
  return processOutcome(undefined, failedBeforeStart, false)
252
259
  },
253
260
  )
261
+ // The job owned its private temp directory for exactly as long as it ran.
262
+ // This runs on all three endings - own exit, kill through the hooks, and a
263
+ // starter that never spawned - because each of them leaves the directory
264
+ // with nothing left to use it. A reclaim that fails is contained: the
265
+ // directory is named for this process's pid, so the next start's orphan
266
+ // sweep collects it.
267
+ const done: Promise<JobOutcomeLike> = settled.then(async (outcome) => {
268
+ if (command.temp !== undefined) await removeShellTempDir(command.temp)
269
+ return outcome
270
+ })
254
271
  return {
255
272
  cancel: () => {
256
273
  if (terminated) return
@@ -0,0 +1,42 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/dsh-home.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
4
+ * environment override wins, the platform home fallback follows. Mirrors
5
+ * what dsh-pet and dsh-liangshen each used to implement locally.
6
+ */
7
+
8
+ import { homedir } from 'node:os'
9
+ import { isAbsolute, join } from 'node:path'
10
+ import { isAbsolute as posixIsAbsolute, join as posixJoin } from 'node:path/posix'
11
+
12
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
13
+ export function expandHome(path: string, home: string = homedir()): string {
14
+ const isPosix = home.startsWith('/')
15
+ const j = isPosix ? posixJoin : join
16
+ if (path === '~') return home
17
+ if (path.startsWith('~/') || path.startsWith('~\\')) return j(home, path.slice(2))
18
+ return path
19
+ }
20
+
21
+ /**
22
+ * Resolve the DSH home directory.
23
+ * @param env - process environment to read DSH_HOME from.
24
+ * @param home - platform home directory fallback (test seam).
25
+ * @returns the absolute DSH home path.
26
+ */
27
+ export function resolveDshHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
28
+ const isPosix = home.startsWith('/')
29
+ const j = isPosix ? posixJoin : join
30
+ const isAbs = isPosix ? posixIsAbsolute : isAbsolute
31
+ const raw = env.DSH_HOME
32
+ if (raw !== undefined && raw.trim() !== '') {
33
+ const expanded = expandHome(raw.trim(), home)
34
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded)
35
+ }
36
+ return j(home, '.dsh')
37
+ }
38
+
39
+ /** Resolve the DSH home directory from the live environment. */
40
+ export function dshHome(): string {
41
+ return resolveDshHome()
42
+ }
package/src/index.ts CHANGED
@@ -13,6 +13,15 @@
13
13
  * and on a Windows host that is not x64, because no PATH bash is ever used as
14
14
  * a substitute.
15
15
  *
16
+ * Mount-time publication: the tree that is spawned is a verified copy under the
17
+ * DSH home, not the tree inside this package. A persistent shell holds its own
18
+ * executable open, and Windows refuses to rename a directory that holds a
19
+ * running executable, so a shell started inside node_modules makes pnpm's
20
+ * import of this package fail with ERR_PNPM_EPERM. Publishing the payload
21
+ * outside the package is what lets an update or uninstall run while sessions
22
+ * are live; a cache that cannot be written keeps the tool working from the
23
+ * packaged tree and logs that updates will need this host stopped.
24
+ *
16
25
  * Availability gate: win_bash serves sessions that run the LiangShen (梁神)
17
26
  * preset, so its registration follows that preset's DECLARATION in the
18
27
  * harness's agent-preset registry — declared means registered, undeclared
@@ -46,8 +55,8 @@ import type {} from '@deepseek-ai/dsh-tools'
46
55
  import { Config, resolveConfig, type WinBashConfig, type WinBashConfigInput } from './config.ts'
47
56
  import { startLiangShenGate, LIANGSHEN_PRESET_ID, type GateOptions, type GateOutcome } from './gate.ts'
48
57
  import { installPwshReplacement } from './pwsh-replacement.ts'
49
- import { resolveRuntime, type RuntimeReady, type HostPlatform } from './runtime.ts'
50
- import { ShellRegistry } from './shell.ts'
58
+ import { prepareRuntime, type RuntimeReady, type HostPlatform } from './runtime.ts'
59
+ import { ShellRegistry, sweepOrphanShellTempDirs } from './shell.ts'
51
60
  import { buildWinBashTool } from './tool.ts'
52
61
 
53
62
  export { BACKGROUND_JOB_KIND, startBackgroundJob } from './background.ts'
@@ -82,11 +91,16 @@ export {
82
91
  export { WIN_BASH_TOOL, renderResult, readJobRegistry, stripTerminalEscapes, truncationNotice } from './tool.ts'
83
92
  export type { RenderFacts } from './tool.ts'
84
93
  export {
94
+ SHELL_TEMP_PREFIX,
85
95
  ShellRegistry,
86
96
  ShellUnavailableError,
97
+ removeShellTempDir,
87
98
  shellArgv,
88
99
  shellEnvironment,
89
100
  shellTempDir,
101
+ sweepOrphanShellTempDirs,
102
+ type ShellTempSweep,
103
+ type ShellTempSweepOptions,
90
104
  } from './shell.ts'
91
105
  export { buildFrame, markerFor, parseFrame } from './protocol.ts'
92
106
  export {
@@ -107,12 +121,23 @@ export {
107
121
  type SettleStatus,
108
122
  } from './gate.ts'
109
123
  export {
124
+ CACHE_DIR_PARTS,
125
+ CACHE_STAGING_PREFIX,
126
+ bashIn,
110
127
  bashPath,
128
+ binIn,
129
+ cacheRoot,
111
130
  parseChecksums,
131
+ payloadKey,
132
+ prepareRuntime,
112
133
  resolveRuntime,
113
134
  runtimeRoot,
135
+ shIn,
114
136
  shPath,
115
137
  verifyPayload,
138
+ verifyPayloadRoot,
139
+ type CopyTree,
140
+ type PrepareRuntimeOptions,
116
141
  } from './runtime.ts'
117
142
 
118
143
  /** Cordis plugin name; also the loader row id this package mounts under. */
@@ -254,7 +279,14 @@ export async function mountWithGate(
254
279
  */
255
280
  export function apply(ctx: Context, config?: WinBashConfigInput): void {
256
281
  const host: HostPlatform = { platform: process.platform, arch: process.arch }
257
- const runtime = resolveRuntime(host)
282
+ // The payload is published outside the package before the tool is built: a
283
+ // shell spawned from node_modules would make every later update or uninstall
284
+ // of this package fail with ERR_PNPM_EPERM while it runs. A cache that cannot
285
+ // be written keeps the tool working from the packaged tree and says so.
286
+ const runtime = prepareRuntime({
287
+ host,
288
+ warn: (message: string) => { ctx.logger?.warn?.('dsh-win-bash: ' + message) },
289
+ })
258
290
  if ('code' in runtime) {
259
291
  // Refusing the mount is the point: there is no fallback shell, and a
260
292
  // mounted tool that always errors is worse than an honest absence.
@@ -268,6 +300,27 @@ export function apply(ctx: Context, config?: WinBashConfigInput): void {
268
300
  ctx.logger?.error?.('dsh-win-bash: ' + (error instanceof Error ? error.message : String(error)))
269
301
  throw error
270
302
  }
303
+ // Every shell owns a private temp directory under the machine's temp root and
304
+ // deletes it when it stops. A crash or a hard kill ends this process first, and
305
+ // those directories are not small - whatever the commands wrote under TMP/TEMP
306
+ // is still in them. Their names carry the owning pid, so this start can tell
307
+ // which ones nobody owns any more; the sweep keeps the ones whose pid still
308
+ // runs. Detached like the mount continuation below, and self-contained, because
309
+ // an unreclaimed directory must never keep the plugin from mounting.
310
+ void sweepOrphanShellTempDirs().then((sweep) => {
311
+ if (sweep.removed.length > 0) {
312
+ ctx.logger?.info?.('dsh-win-bash: reclaimed ' + sweep.removed.length.toString()
313
+ + ' orphaned shell temp directories left by earlier runs')
314
+ }
315
+ if (sweep.failed.length > 0) {
316
+ ctx.logger?.warn?.('dsh-win-bash: ' + sweep.failed.length.toString()
317
+ + ' orphaned shell temp directories could not be reclaimed and will be retried on the next start: '
318
+ + sweep.failed.join(', '))
319
+ }
320
+ }, (error: unknown) => {
321
+ ctx.logger?.warn?.('dsh-win-bash: the orphaned shell temp directory sweep failed: '
322
+ + (error instanceof Error ? error.message : String(error)))
323
+ })
271
324
  // Deliberately detached (see mountWithGate), with a last-resort catch so no
272
325
  // defect above can surface as the unhandled rejection that kills the process.
273
326
  void mountWithGate(ctx, resolved, runtime).catch((error: unknown) => {