@linxin666/dsh-win-bash 0.4.13 → 0.4.15

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/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,