@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/src/runtime.ts CHANGED
@@ -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
@@ -19,10 +33,11 @@
19
33
  * @module @linxin666/dsh-win-bash/runtime
20
34
  */
21
35
 
22
- import { createHash } from 'node:crypto'
23
- import { readFileSync, statSync } from 'node:fs'
36
+ import { createHash, randomUUID } from 'node:crypto'
37
+ import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
24
38
  import { dirname, join, resolve } from 'node:path'
25
39
  import { fileURLToPath } from 'node:url'
40
+ import { resolveDshHome } from './dsh-home.ts'
26
41
 
27
42
  /** Directory holding the shipped payload, relative to the package root. */
28
43
  export const RUNTIME_DIR = 'runtime/win32-x64'
@@ -36,27 +51,72 @@ export const RUNTIME_PLATFORM = 'win32'
36
51
  /** The one architecture this payload supports. */
37
52
  export const RUNTIME_ARCH = 'x64'
38
53
 
54
+ /**
55
+ * Payload cache directories under the DSH home, in order.
56
+ *
57
+ * The cache lives OUTSIDE the package on purpose: a running shell holds its own
58
+ * executable open, Windows refuses to rename a directory that holds a running
59
+ * executable, and pnpm imports a package by renaming over it. A copy here is
60
+ * also why a release that only changes JavaScript never has to move 16 MiB.
61
+ */
62
+ export const CACHE_DIR_PARTS = ['win-bash', 'runtime'] as const
63
+
64
+ /**
65
+ * Name prefix of the staging directory one cache copy is built in. The rest of
66
+ * the name is the payload key, this process's id and a random suffix, so a
67
+ * half-written directory is never mistaken for a published payload.
68
+ */
69
+ export const CACHE_STAGING_PREFIX = '.staging-'
70
+
39
71
  /** Absolute package root (the directory holding package.json). */
40
72
  export const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
41
73
 
42
- /** Absolute payload root. */
74
+ /** Absolute payload root inside one package root. */
43
75
  export function runtimeRoot(packageRoot: string = PACKAGE_ROOT): string {
44
76
  return join(packageRoot, RUNTIME_DIR)
45
77
  }
46
78
 
47
- /** Absolute path of the vendored shell. */
79
+ /** Absolute path of the vendored shell inside one payload root. */
80
+ export function bashIn(root: string): string {
81
+ return join(root, 'usr', 'bin', 'bash.exe')
82
+ }
83
+
84
+ /** Absolute path of the vendored POSIX-shell alias inside one payload root. */
85
+ export function shIn(root: string): string {
86
+ return join(root, 'usr', 'bin', 'sh.exe')
87
+ }
88
+
89
+ /** Absolute path of one payload root's usr/bin directory. */
90
+ export function binIn(root: string): string {
91
+ return join(root, 'usr', 'bin')
92
+ }
93
+
94
+ /** Absolute path of the packaged payload's shell. */
48
95
  export function bashPath(packageRoot: string = PACKAGE_ROOT): string {
49
- return join(runtimeRoot(packageRoot), 'usr', 'bin', 'bash.exe')
96
+ return bashIn(runtimeRoot(packageRoot))
50
97
  }
51
98
 
52
- /** Absolute path of the vendored POSIX-shell alias of the same binary. */
99
+ /** Absolute path of the packaged payload's POSIX-shell alias. */
53
100
  export function shPath(packageRoot: string = PACKAGE_ROOT): string {
54
- return join(runtimeRoot(packageRoot), 'usr', 'bin', 'sh.exe')
101
+ return shIn(runtimeRoot(packageRoot))
55
102
  }
56
103
 
57
- /** Absolute path of the vendored payload's usr/bin directory. */
104
+ /** Absolute path of the packaged payload's usr/bin directory. */
58
105
  export function binDir(packageRoot: string = PACKAGE_ROOT): string {
59
- return join(runtimeRoot(packageRoot), 'usr', 'bin')
106
+ return binIn(runtimeRoot(packageRoot))
107
+ }
108
+
109
+ /**
110
+ * Absolute root of the per-user payload cache.
111
+ *
112
+ * It follows the DSH home rather than the package, so an isolated
113
+ * `DSH_HOME` (a probe instance, a test run) gets its own cache, and an update or
114
+ * uninstall of this package never touches a byte the cache holds.
115
+ * @param env - environment to read DSH_HOME from; the live one by default.
116
+ * @returns the directory payload copies are published under.
117
+ */
118
+ export function cacheRoot(env: NodeJS.ProcessEnv = process.env): string {
119
+ return join(resolveDshHome(env), ...CACHE_DIR_PARTS)
60
120
  }
61
121
 
62
122
  /** One manifest row: a payload-relative path and its digest. */
@@ -110,6 +170,19 @@ export function sha256(bytes: Buffer | string): string {
110
170
  return createHash('sha256').update(bytes).digest('hex')
111
171
  }
112
172
 
173
+ /**
174
+ * The content key of one payload: a digest over its manifest's file identities.
175
+ *
176
+ * Manifest formatting and row order do not move it, and any change to a
177
+ * payload file does. That is what makes a cache directory name a statement
178
+ * about the bytes inside it rather than about the release that shipped them.
179
+ * @param entries - the parsed manifest rows.
180
+ * @returns the 16-character key that names the cache directory.
181
+ */
182
+ export function payloadKey(entries: readonly ChecksumEntry[]): string {
183
+ return sha256(entries.map(entry => entry.path + ' ' + entry.sha256).sort().join('\n')).slice(0, 16)
184
+ }
185
+
113
186
  /**
114
187
  * Verify every registered payload file against the shipped manifest.
115
188
  *
@@ -121,7 +194,20 @@ export function sha256(bytes: Buffer | string): string {
121
194
  * @throws when the manifest itself is unreadable or malformed.
122
195
  */
123
196
  export function verifyPayload(packageRoot: string = PACKAGE_ROOT): ChecksumReport {
124
- const root = runtimeRoot(packageRoot)
197
+ return verifyPayloadRoot(runtimeRoot(packageRoot))
198
+ }
199
+
200
+ /**
201
+ * Verify every payload file of one payload root against that root's manifest.
202
+ *
203
+ * The root is the directory holding `usr/` and `checksums.sha256`, which is
204
+ * either the packaged payload or a published cache copy, so both go through the
205
+ * same pass.
206
+ * @param root - the payload root to verify.
207
+ * @returns the count of verified files and every mismatch found.
208
+ * @throws when the manifest itself is unreadable or malformed.
209
+ */
210
+ export function verifyPayloadRoot(root: string): ChecksumReport {
125
211
  const manifest = parseChecksums(readFileSync(join(root, CHECKSUM_FILE), 'utf8'))
126
212
  const mismatches: ChecksumMismatch[] = []
127
213
  let verified = 0
@@ -157,10 +243,14 @@ export interface RuntimeRejection {
157
243
 
158
244
  /** Successful payload resolution. */
159
245
  export interface RuntimeReady {
160
- /** Absolute path of the vendored bash.exe. */
246
+ /** Absolute path of the vendored bash.exe that will be spawned. */
161
247
  readonly bash: string
162
248
  /** Absolute path of the payload's usr/bin. */
163
249
  readonly bin: string
250
+ /** Absolute payload root both paths above live in. */
251
+ readonly payloadRoot: string
252
+ /** Whether that root is the published cache copy or the packaged tree. */
253
+ readonly source: 'cache' | 'package'
164
254
  }
165
255
 
166
256
  /** Whether the running host can serve this payload at all. */
@@ -172,19 +262,11 @@ export interface HostPlatform {
172
262
  }
173
263
 
174
264
  /**
175
- * Resolve the vendored shell for one host, or refuse the mount.
176
- *
177
- * The order is deliberate: platform, then architecture, then presence, then
178
- * integrity. A checksum failure names the first mismatching path so an
179
- * operator can act on it, and no path here ever consults PATH.
265
+ * Refuse a host that cannot run this payload at all.
180
266
  * @param host - the running host's platform facts.
181
- * @param packageRoot - package root holding the payload.
182
- * @returns the resolved shell paths, or the rejection reason.
267
+ * @returns the rejection, or undefined when the host could serve the payload.
183
268
  */
184
- export function resolveRuntime(
185
- host: HostPlatform,
186
- packageRoot: string = PACKAGE_ROOT,
187
- ): RuntimeReady | RuntimeRejection {
269
+ function rejectHost(host: HostPlatform): RuntimeRejection | undefined {
188
270
  if (host.platform !== RUNTIME_PLATFORM) {
189
271
  return {
190
272
  code: 'unsupported-platform',
@@ -200,6 +282,33 @@ export function resolveRuntime(
200
282
  message: 'win_bash currently ships only the ' + RUNTIME_ARCH + ' payload; this host is ' + host.arch + '.',
201
283
  }
202
284
  }
285
+ return undefined
286
+ }
287
+
288
+ /** The three paths one payload root provides, tagged with where it came from. */
289
+ function readyFrom(root: string, source: RuntimeReady['source']): RuntimeReady {
290
+ return { bash: bashIn(root), bin: binIn(root), payloadRoot: root, source }
291
+ }
292
+
293
+ /**
294
+ * Resolve the PACKAGED shell for one host, or refuse the mount.
295
+ *
296
+ * The order is deliberate: platform, then architecture, then presence, then
297
+ * integrity. A checksum failure names the first mismatching path so an
298
+ * operator can act on it, and no path here ever consults PATH.
299
+ *
300
+ * This is the packaged tree, not the cache: callers that intend to RUN the
301
+ * shell want {@link prepareRuntime}, which publishes a copy first.
302
+ * @param host - the running host's platform facts.
303
+ * @param packageRoot - package root holding the payload.
304
+ * @returns the resolved shell paths, or the rejection reason.
305
+ */
306
+ export function resolveRuntime(
307
+ host: HostPlatform,
308
+ packageRoot: string = PACKAGE_ROOT,
309
+ ): RuntimeReady | RuntimeRejection {
310
+ const refused = rejectHost(host)
311
+ if (refused !== undefined) return refused
203
312
  const bash = bashPath(packageRoot)
204
313
  try {
205
314
  if (!statSync(bash).isFile()) throw new Error('not a file')
@@ -236,5 +345,158 @@ export function resolveRuntime(
236
345
  + '). Reinstall the package; win_bash will not run an unverified payload.',
237
346
  }
238
347
  }
239
- return { bash, bin: binDir(packageRoot) }
348
+ return readyFrom(runtimeRoot(packageRoot), 'package')
349
+ }
350
+
351
+ /** One tree copy: the source payload root, the directory to fill. */
352
+ export type CopyTree = (source: string, target: string) => void
353
+
354
+ /** Where payload publication can be redirected, and what it reports. */
355
+ export interface PrepareRuntimeOptions {
356
+ /** The running host's platform facts; this process's by default. */
357
+ readonly host?: HostPlatform
358
+ /** Package root holding runtime/win32-x64; this package's own by default. */
359
+ readonly packageRoot?: string
360
+ /** Cache root to publish into; the DSH home's own by default. */
361
+ readonly cacheRoot?: string
362
+ /** Environment the default cache root resolves from; process.env by default. */
363
+ readonly env?: NodeJS.ProcessEnv
364
+ /** Operator-facing notes; a copy that could not be published is reported here. */
365
+ readonly warn?: (message: string) => void
366
+ /** The copy itself; a real recursive copy by default. */
367
+ readonly copy?: CopyTree
368
+ }
369
+
370
+ /** The recursive copy one published payload is built with. */
371
+ function copyTree(source: string, target: string): void {
372
+ cpSync(source, target, { recursive: true, force: true, preserveTimestamps: true })
373
+ }
374
+
375
+ /** One error's message, for an operator-facing line. */
376
+ function describe(error: unknown): string {
377
+ return error instanceof Error ? error.message : String(error)
378
+ }
379
+
380
+ /** Delete a staging directory, never letting a failed reclaim escape. */
381
+ function removeStaging(staging: string): void {
382
+ try {
383
+ rmSync(staging, { recursive: true, force: true })
384
+ } catch {
385
+ // An unreclaimed staging directory is inert: its name is not a payload key,
386
+ // so no mount can mistake it for a published copy.
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Whether one directory is a complete copy of the payload the key names.
392
+ *
393
+ * The copy's own manifest must reproduce the expected key before any byte is
394
+ * executed, so a directory whose manifest was rewritten alongside its files is
395
+ * a miss rather than a match.
396
+ * @param root - the candidate payload root.
397
+ * @param key - the key the shipped manifest produced.
398
+ * @returns whether that directory can be spawned from.
399
+ */
400
+ function cacheReady(root: string, key: string): boolean {
401
+ try {
402
+ if (payloadKey(parseChecksums(readFileSync(join(root, CHECKSUM_FILE), 'utf8'))) !== key) return false
403
+ if (!statSync(bashIn(root)).isFile()) return false
404
+ const report = verifyPayloadRoot(root)
405
+ return report.verified > 0 && report.mismatches.length === 0
406
+ } catch {
407
+ return false
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Publish one payload copy under its key.
413
+ *
414
+ * The copy is built in a staging directory beside the target and renamed into
415
+ * place, so the published name only ever refers to a complete tree. A rename
416
+ * that loses a race against another host publishing the same key is not a
417
+ * failure: both hosts copy the same bytes by construction.
418
+ * @param source - the packaged payload root to copy.
419
+ * @param target - the cache directory the key names.
420
+ * @param key - the payload key, carried into the staging name.
421
+ * @param copy - the copy itself.
422
+ */
423
+ function publishPayload(source: string, target: string, key: string, copy: CopyTree): void {
424
+ mkdirSync(dirname(target), { recursive: true })
425
+ // A directory already sitting at the key has failed its verification (the
426
+ // caller only publishes on a miss), so it is unusable and has to go before a
427
+ // rename can land. A copy a live shell still holds open refuses the delete on
428
+ // Windows, and that refusal reaches the caller as an honest fallback.
429
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true })
430
+ const staging = join(
431
+ dirname(target),
432
+ CACHE_STAGING_PREFIX + key + '-' + process.pid.toString() + '-' + randomUUID().slice(0, 8),
433
+ )
434
+ try {
435
+ copy(source, staging)
436
+ renameSync(staging, target)
437
+ } catch (error) {
438
+ removeStaging(staging)
439
+ if (cacheReady(target, key)) return
440
+ throw error
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Resolve the shell one host runs, publishing the payload outside the package.
446
+ *
447
+ * The verification order is the whole point: the shipped manifest identifies
448
+ * the payload, a published copy of that identity is reused when it verifies,
449
+ * and otherwise the packaged tree is verified first and only then copied. What
450
+ * gets spawned is therefore always a tree whose bytes match the shipped
451
+ * manifest, and it lives under the DSH home where an update or uninstall of
452
+ * this package cannot be blocked by a running shell.
453
+ *
454
+ * A cache that cannot be written is not a reason to withhold the tool: the
455
+ * verified packaged tree runs instead and the caller is told, through
456
+ * {@link PrepareRuntimeOptions.warn}, that updates will need this host stopped.
457
+ * A payload that fails its manifest is still a refusal — running unverified
458
+ * bytes is the outcome the manifest exists to prevent, cache or no cache.
459
+ * @param options - host facts, roots, and the seams tests drive.
460
+ * @returns the shell paths to run, or the rejection reason.
461
+ */
462
+ export function prepareRuntime(options: PrepareRuntimeOptions = {}): RuntimeReady | RuntimeRejection {
463
+ const host = options.host ?? { platform: process.platform, arch: process.arch }
464
+ const refused = rejectHost(host)
465
+ if (refused !== undefined) return refused
466
+ const packageRoot = options.packageRoot ?? PACKAGE_ROOT
467
+ const source = runtimeRoot(packageRoot)
468
+ const cacheDir = options.cacheRoot ?? cacheRoot(options.env)
469
+ const warn = options.warn ?? ((): void => {})
470
+
471
+ let key: string
472
+ try {
473
+ key = payloadKey(parseChecksums(readFileSync(join(source, CHECKSUM_FILE), 'utf8')))
474
+ } catch (error) {
475
+ return {
476
+ code: 'manifest-unreadable',
477
+ message: 'the payload checksum manifest could not be read: ' + describe(error),
478
+ }
479
+ }
480
+
481
+ const published = join(cacheDir, key)
482
+ if (cacheReady(published, key)) return readyFrom(published, 'cache')
483
+
484
+ const shipped = resolveRuntime(host, packageRoot)
485
+ if ('code' in shipped) return shipped
486
+
487
+ try {
488
+ publishPayload(source, published, key, options.copy ?? copyTree)
489
+ } catch (error) {
490
+ warn('the verified payload could not be published to ' + published + ' (' + describe(error)
491
+ + '), so this host runs the shell from ' + source + '; while it runs, updating or uninstalling'
492
+ + ' this package can fail with ERR_PNPM_EPERM')
493
+ return shipped
494
+ }
495
+ if (!cacheReady(published, key)) {
496
+ warn('the payload copy at ' + published + ' did not verify against the shipped manifest, so this host'
497
+ + ' runs the shell from ' + source + '; while it runs, updating or uninstalling this package can fail'
498
+ + ' with ERR_PNPM_EPERM')
499
+ return shipped
500
+ }
501
+ return readyFrom(published, 'cache')
240
502
  }
package/src/shell.ts CHANGED
@@ -18,7 +18,8 @@
18
18
  */
19
19
 
20
20
  import { randomUUID } from 'node:crypto'
21
- import { mkdirSync } from 'node:fs'
21
+ import { mkdirSync, readdirSync, type Dirent } from 'node:fs'
22
+ import { rm } from 'node:fs/promises'
22
23
  import { tmpdir } from 'node:os'
23
24
  import { join } from 'node:path'
24
25
  import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'
@@ -54,6 +55,19 @@ export const TIMEOUT_EXIT_CODE = 124
54
55
  /** Environment variable names carrying the per-shell private temp directory. */
55
56
  export const TEMP_ENV_KEYS = ['TMPDIR', 'TMP', 'TEMP'] as const
56
57
 
58
+ /**
59
+ * Name prefix of every private per-shell temp directory. The rest of the name
60
+ * is the owning process id plus a random suffix, which is what lets a later
61
+ * start tell an orphan from a directory a live shell is still using.
62
+ */
63
+ export const SHELL_TEMP_PREFIX = 'dsh-win-bash-'
64
+
65
+ /** Retries granted to one reclaim, for handles a child releases late. */
66
+ const TEMP_REMOVE_RETRIES = 3
67
+
68
+ /** Backoff between those retries, in milliseconds. */
69
+ const TEMP_REMOVE_RETRY_DELAY_MS = 100
70
+
57
71
  /**
58
72
  * The argv of one pinned shell: the payload's own bash by absolute path, no rc
59
73
  * file and no profile, reading its commands from stdin. This tool never
@@ -102,14 +116,158 @@ export function shellEnvironment(
102
116
 
103
117
  /**
104
118
  * Create one shell process's private temp directory.
119
+ * @param base - the temp root to create it under; the machine's own by default.
105
120
  * @returns the absolute directory, created if absent.
106
121
  */
107
- export function shellTempDir(): string {
108
- const temp = join(tmpdir(), 'dsh-win-bash-' + process.pid.toString() + '-' + randomUUID().slice(0, 8))
122
+ export function shellTempDir(base: string = tmpdir()): string {
123
+ const temp = join(base, SHELL_TEMP_PREFIX + process.pid.toString() + '-' + randomUUID().slice(0, 8))
109
124
  mkdirSync(temp, { recursive: true })
110
125
  return temp
111
126
  }
112
127
 
128
+ /**
129
+ * Delete one private temp directory, reporting failure to the caller.
130
+ *
131
+ * The retries are the Windows half of this: a child that just exited has not
132
+ * necessarily released its own handles yet, and rm reports that as EBUSY/EPERM.
133
+ * A few short retries turn that into a reclaim instead of a leftover.
134
+ * @param temp - the directory to delete; a missing one is not an error.
135
+ */
136
+ async function deleteShellTempDir(temp: string): Promise<void> {
137
+ await rm(temp, {
138
+ recursive: true,
139
+ force: true,
140
+ maxRetries: TEMP_REMOVE_RETRIES,
141
+ retryDelay: TEMP_REMOVE_RETRY_DELAY_MS,
142
+ })
143
+ }
144
+
145
+ /**
146
+ * Delete one private temp directory, never letting the attempt throw.
147
+ *
148
+ * Teardown must not fail because a directory could not be reclaimed: the shell
149
+ * is already gone, and whatever is left is named for this process's own pid, so
150
+ * the next start's {@link sweepOrphanShellTempDirs} collects it once that pid is
151
+ * gone.
152
+ * @param temp - the directory that shell owned.
153
+ */
154
+ export async function removeShellTempDir(temp: string): Promise<void> {
155
+ try {
156
+ await deleteShellTempDir(temp)
157
+ } catch {
158
+ // Deliberately swallowed; see the doc comment above.
159
+ }
160
+ }
161
+
162
+ /** What one orphan sweep found and did, for logging and for tests. */
163
+ export interface ShellTempSweep {
164
+ /** Directories this sweep deleted. */
165
+ readonly removed: string[]
166
+ /** Directories whose owning process is still alive. */
167
+ readonly kept: string[]
168
+ /** Directories that could not be deleted; the next start tries again. */
169
+ readonly failed: string[]
170
+ }
171
+
172
+ /** The seams one orphan sweep runs against. */
173
+ export interface ShellTempSweepOptions {
174
+ /** The temp root to scan; the machine's own by default. */
175
+ readonly root?: string
176
+ /** Whether the process that owned a directory still exists. */
177
+ readonly isAlive?: (pid: number) => boolean
178
+ /** How one directory is deleted; a rejection marks it failed. */
179
+ readonly remove?: (dir: string) => Promise<void>
180
+ }
181
+
182
+ /**
183
+ * Whether a process id still exists.
184
+ *
185
+ * Signal 0 performs the existence check without delivering anything. EPERM is
186
+ * the one answer that means "alive": the pid is there, it just belongs to a
187
+ * process this one may not signal.
188
+ * @param pid - the process id taken from a directory name.
189
+ * @returns whether that process is still running.
190
+ */
191
+ function processAlive(pid: number): boolean {
192
+ try {
193
+ process.kill(pid, 0)
194
+ return true
195
+ } catch (error) {
196
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
197
+ }
198
+ }
199
+
200
+ /**
201
+ * The owning pid of a shell temp directory, when the name is one.
202
+ * @param name - a directory name inside the temp root.
203
+ * @returns the pid, or undefined for every other name.
204
+ */
205
+ function shellTempOwner(name: string): number | undefined {
206
+ const match = new RegExp('^' + SHELL_TEMP_PREFIX + '(\\d+)-[0-9a-f]{8}$').exec(name)
207
+ if (match === null) return undefined
208
+ const pid = Number.parseInt(match[1] ?? '', 10)
209
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined
210
+ }
211
+
212
+ /**
213
+ * List one temp root, reporting an unreadable root as empty.
214
+ *
215
+ * There is nothing to reclaim when the root cannot be read, and the next start
216
+ * retries with the same rules; failing the mount over it would be worse.
217
+ * @param root - the temp root to list.
218
+ * @returns its entries, or none.
219
+ */
220
+ function tempRootEntries(root: string): Dirent[] {
221
+ try {
222
+ return readdirSync(root, { withFileTypes: true })
223
+ } catch {
224
+ return []
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Reclaim the private temp directories of shells that no longer exist.
230
+ *
231
+ * A crash or a hard kill ends this process before it can delete what its live
232
+ * shells owned, and those directories are not small: whatever a command wrote
233
+ * under TMP/TEMP/TMPDIR is still in them. Every name carries the pid that owned
234
+ * it, so the ones whose pid is gone are garbage by construction, and the ones
235
+ * whose pid still runs may belong to a live shell in this very process or to
236
+ * another instance sharing the temp root - those are kept.
237
+ *
238
+ * One directory that cannot be deleted is reported and skipped; it must not
239
+ * stop the round, because the usual cause (a long path, a locked file) is local
240
+ * to that directory.
241
+ * @param options - the seams; production passes none.
242
+ * @returns what was removed, kept and failed.
243
+ */
244
+ export async function sweepOrphanShellTempDirs(options: ShellTempSweepOptions = {}): Promise<ShellTempSweep> {
245
+ const root = options.root ?? tmpdir()
246
+ const isAlive = options.isAlive ?? processAlive
247
+ const remove = options.remove ?? deleteShellTempDir
248
+ const removed: string[] = []
249
+ const kept: string[] = []
250
+ const failed: string[] = []
251
+ for (const entry of tempRootEntries(root)) {
252
+ if (!entry.isDirectory()) continue
253
+ const pid = shellTempOwner(entry.name)
254
+ if (pid === undefined) continue
255
+ // This process's own pid is alive by definition, and a directory of its own
256
+ // may be in use by a shell nothing has disposed yet.
257
+ if (pid === process.pid || isAlive(pid)) {
258
+ kept.push(entry.name)
259
+ continue
260
+ }
261
+ try {
262
+ await remove(join(root, entry.name))
263
+ removed.push(entry.name)
264
+ } catch {
265
+ failed.push(entry.name)
266
+ }
267
+ }
268
+ return { removed, kept, failed }
269
+ }
270
+
113
271
  /** One command's complete result, as the tool consumes it. */
114
272
  export interface ShellResult {
115
273
  /** The command's stdout, bounded to the visible budget. */
@@ -165,6 +323,12 @@ export class ShellUnavailableError extends Error {
165
323
  interface LiveShell {
166
324
  /** The spawned process handle. */
167
325
  readonly handle: SubprocessHandle
326
+ /**
327
+ * The private temp directory this shell owns (its TMP/TEMP/TMPDIR). Recorded
328
+ * on the shell rather than recomputed at teardown, because teardown is the
329
+ * only moment this process knows the directory became garbage.
330
+ */
331
+ readonly temp: string
168
332
  /** Set once the handle's outcome settles, so a dead shell is never reused. */
169
333
  exited: boolean
170
334
  /**
@@ -395,6 +559,9 @@ export class ShellRegistry {
395
559
  // to report but the teardown itself.
396
560
  resume()
397
561
  this.shells.delete(owner)
562
+ // The process ended on its own, so dispose never runs for it: its
563
+ // private temp directory is reclaimed here or nowhere.
564
+ await removeShellTempDir(shell.temp)
398
565
  const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes)
399
566
  if (shell.exitCode === null) {
400
567
  throw new ShellUnavailableError(
@@ -460,6 +627,7 @@ export class ShellRegistry {
460
627
  const existing = this.shells.get(owner)
461
628
  if (existing !== undefined && !existing.exited) return existing
462
629
  if (existing !== undefined) this.shells.delete(owner)
630
+ const temp = shellTempDir()
463
631
  const handle = this.subprocess.spawn({
464
632
  argv: shellArgv(runtime),
465
633
  cwd,
@@ -469,9 +637,9 @@ export class ShellRegistry {
469
637
  stderr: { maxBytes: SHELL_STDERR_CAPTURE_BYTES, spill: { maxBytes: DEFAULT_SPILL_BYTES } },
470
638
  },
471
639
  graceMs: GRACE_MS,
472
- env: shellEnvironment(runtime, shellTempDir()),
640
+ env: shellEnvironment(runtime, temp),
473
641
  })
474
- const shell: LiveShell = { handle, exited: false, cursor: { stdout: 0, stderr: 0 }, exitCode: null }
642
+ const shell: LiveShell = { handle, temp, exited: false, cursor: { stdout: 0, stderr: 0 }, exitCode: null }
475
643
  const markExited = (outcome: { exitCode: number | null }): void => {
476
644
  shell.exitCode = outcome.exitCode
477
645
  shell.exited = true
@@ -617,7 +785,14 @@ function recoverPartial(text: string, marker: FrameMarker): string {
617
785
  return begin < 0 ? text : text.slice(begin + marker.begin.length).replace(/^\n/, '')
618
786
  }
619
787
 
620
- /** Signal and await one shell's managed range, never letting teardown throw. */
788
+ /**
789
+ * Signal one shell's managed range and reclaim what it owned, never letting
790
+ * teardown throw.
791
+ *
792
+ * The directory is deleted after the range is gone rather than before: it is
793
+ * the shell's TMP/TEMP/TMPDIR, so deleting it under a live process would turn
794
+ * every command still writing there into a failure.
795
+ */
621
796
  async function terminate(shell: LiveShell, reason: string): Promise<void> {
622
797
  void reason
623
798
  try {
@@ -627,4 +802,5 @@ async function terminate(shell: LiveShell, reason: string): Promise<void> {
627
802
  // A provider that can no longer observe its range must not block teardown:
628
803
  // the process was signalled and the registry entry is already gone.
629
804
  }
805
+ await removeShellTempDir(shell.temp)
630
806
  }
package/src/tool.ts CHANGED
@@ -430,6 +430,7 @@ export function buildWinBashTool(
430
430
  + ' this platform and stays available whenever win_bash cannot serve a call.',
431
431
  )
432
432
  }
433
+ const temp = shellTempDir()
433
434
  const jobId = startBackgroundJob({
434
435
  subprocess: ctx.subprocess,
435
436
  jobs: registry,
@@ -437,7 +438,8 @@ export function buildWinBashTool(
437
438
  script: command,
438
439
  argv: shellArgv(runtime),
439
440
  cwd,
440
- env: shellEnvironment(runtime, shellTempDir()),
441
+ env: shellEnvironment(runtime, temp),
442
+ temp,
441
443
  label: args.command,
442
444
  stdoutBytes: BACKGROUND_STDOUT_BYTES,
443
445
  stderrBytes: BACKGROUND_STDERR_BYTES,