@deepseek-ai/dsh-subprocess-local 0.2.2-alpha.3 → 0.2.2-rc.2

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.
Files changed (64) hide show
  1. package/README.i18n.yaml +4 -4
  2. package/README.md +2 -2
  3. package/README.zh.md +2 -2
  4. package/lib/index.js +27 -13
  5. package/lib/{runner-launch-B2zsQ1Dz.js → runner-launch-CKTiL8M8.js} +41 -14
  6. package/lib/runner.js +8 -12
  7. package/lib/types/bin.d.ts.map +1 -0
  8. package/lib/types/bin.js.map +1 -0
  9. package/lib/types/control-spawn.d.ts.map +1 -0
  10. package/lib/types/control-spawn.js.map +1 -0
  11. package/lib/types/index.d.ts.map +1 -0
  12. package/lib/types/index.js.map +1 -0
  13. package/lib/types/linux-execve.d.ts +1 -1
  14. package/lib/types/linux-execve.d.ts.map +1 -0
  15. package/lib/types/linux-execve.js.map +1 -0
  16. package/lib/types/linux-scope-selector.d.ts.map +1 -0
  17. package/lib/types/linux-scope-selector.js.map +1 -0
  18. package/lib/types/linux-scope.d.ts.map +1 -0
  19. package/lib/types/linux-scope.js.map +1 -0
  20. package/lib/types/managed-owner.d.ts.map +1 -0
  21. package/lib/types/managed-owner.js.map +1 -0
  22. package/lib/types/output.d.ts.map +1 -0
  23. package/lib/types/output.js.map +1 -0
  24. package/lib/types/process-inspector.d.ts +9 -5
  25. package/lib/types/process-inspector.d.ts.map +1 -0
  26. package/lib/types/process-inspector.js.map +1 -0
  27. package/lib/types/runner-launch.d.ts +1 -1
  28. package/lib/types/runner-launch.d.ts.map +1 -0
  29. package/lib/types/runner-launch.js.map +1 -0
  30. package/lib/types/runner-protocol.d.ts +2 -0
  31. package/lib/types/runner-protocol.d.ts.map +1 -0
  32. package/lib/types/runner-protocol.js.map +1 -0
  33. package/lib/types/shell-activity.d.ts.map +1 -0
  34. package/lib/types/shell-activity.js.map +1 -0
  35. package/lib/types/spawn-runner.d.ts +2 -1
  36. package/lib/types/spawn-runner.d.ts.map +1 -0
  37. package/lib/types/spawn-runner.js.map +1 -0
  38. package/lib/types/spawn.d.ts +2 -2
  39. package/lib/types/spawn.d.ts.map +1 -0
  40. package/lib/types/spawn.js.map +1 -0
  41. package/lib/types/terminal.d.ts.map +1 -0
  42. package/lib/types/terminal.js.map +1 -0
  43. package/lib/types/windows-inspector.d.ts.map +1 -0
  44. package/lib/types/windows-inspector.js.map +1 -0
  45. package/lib/types/windows-job.d.ts.map +1 -0
  46. package/lib/types/windows-job.js.map +1 -0
  47. package/package.json +14 -11
  48. package/src/bin.ts +25 -0
  49. package/src/control-spawn.ts +35 -0
  50. package/src/index.ts +387 -0
  51. package/src/linux-execve.ts +92 -0
  52. package/src/linux-scope-selector.ts +101 -0
  53. package/src/linux-scope.ts +726 -0
  54. package/src/managed-owner.ts +56 -0
  55. package/src/output.ts +313 -0
  56. package/src/process-inspector.ts +560 -0
  57. package/src/runner-launch.ts +315 -0
  58. package/src/runner-protocol.ts +281 -0
  59. package/src/shell-activity.ts +131 -0
  60. package/src/spawn-runner.ts +488 -0
  61. package/src/spawn.ts +500 -0
  62. package/src/terminal.ts +479 -0
  63. package/src/windows-inspector.ts +346 -0
  64. package/src/windows-job.ts +269 -0
@@ -0,0 +1,56 @@
1
+ /** Minimal managed-range ownership bound to one ordinary subprocess handle. */
2
+
3
+ import type { Duplex, Readable, Writable } from 'node:stream'
4
+ import type { SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
5
+
6
+ /** Platform owner used by termination and whole-range settlement. */
7
+ export interface BoundProcessOwner {
8
+ /** Signal the managed range; `cancellationReason` is used only before Windows target commit. */
9
+ signal(signal: 'SIGTERM' | 'SIGKILL', cancellationReason?: unknown): void
10
+ /** Wait for the same managed range to become empty; reject when it cannot be observed. */
11
+ waitForExit(): Promise<void>
12
+ /**
13
+ * Count tasks in the native range, including descendants outside the observable process tree.
14
+ * @returns the current count, or undefined when observation is unavailable.
15
+ */
16
+ inspectTaskCount?(): number | undefined
17
+ /** Synchronously force final termination during JavaScript-observable host exit. */
18
+ terminateForHostExit(): void
19
+ /** Release provider-private protocol artifacts after outcome and range settlement. */
20
+ cleanup?(): void
21
+ }
22
+
23
+ /** Platform launch facts consumed by the common stdio and result lifecycle. */
24
+ export interface ManagedProcessLaunch {
25
+ stdin: Writable | null
26
+ stdout: Readable | null
27
+ stderr: Readable | null
28
+ control?: Duplex | undefined
29
+ direct: Promise<SubprocessOutcome>
30
+ owner: BoundProcessOwner
31
+ }
32
+
33
+ /**
34
+ * Apply an optional abort bound to one shared wait promise.
35
+ * @param pending - managed-range wait shared by all callers.
36
+ * @param signal - optional caller cancellation signal.
37
+ * @returns whether the managed-range wait completed before cancellation.
38
+ */
39
+ export async function waitWithAbort(pending: Promise<void>, signal?: AbortSignal): Promise<boolean> {
40
+ if (signal?.aborted) {
41
+ void pending.catch(() => {})
42
+ return false
43
+ }
44
+ if (signal === undefined) {
45
+ await pending
46
+ return true
47
+ }
48
+ const aborted = Promise.withResolvers<boolean>()
49
+ const onAbort = (): void => { aborted.resolve(false) }
50
+ signal.addEventListener('abort', onAbort, { once: true })
51
+ try {
52
+ return await Promise.race([pending.then(() => true), aborted.promise])
53
+ } finally {
54
+ signal.removeEventListener('abort', onAbort)
55
+ }
56
+ }
package/src/output.ts ADDED
@@ -0,0 +1,313 @@
1
+ /** Bounded output tails and private spill files shared by process providers. */
2
+ import { randomBytes } from 'node:crypto'
3
+ import { closeSync, mkdtempSync, openSync, rmdirSync, unlinkSync, writeSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { tmpdir } from 'node:os'
6
+ import type { CollectedOutput } from '@deepseek-ai/dsh-subprocess'
7
+
8
+ /**
9
+ * Receives one spill failure so the owner can log it through its own logger.
10
+ * Called at most once per collector, after the spill has been discarded and
11
+ * the in-memory tail has kept collecting. A reporter that throws is contained
12
+ * and its failure written to stderr.
13
+ * @param error - the `node:fs` failure from opening or appending the spill file.
14
+ * @param label - the stream label of the collector that failed.
15
+ */
16
+ export type SpillFailureReporter = (error: unknown, label: string) => void
17
+
18
+ /** Spill storage for one collected stream; `undefined` means tail-only collection. */
19
+ export interface SpillOptions {
20
+ /** Whole-stream byte cap beyond which an incomplete spill is discarded. */
21
+ maxBytes: number
22
+ /** Private directory receiving the spill file. */
23
+ dir: string
24
+ /** Owner-side report of a spill open or write failure. */
25
+ onFailure: SpillFailureReporter
26
+ }
27
+
28
+ let spillCounter = 0
29
+ let defaultSpillDir: string | undefined
30
+
31
+ /**
32
+ * The default spill location: a private (0700) per-process directory under
33
+ * the OS tmpdir, created lazily. Predictable world-readable paths would let
34
+ * other local users read command output or pre-create symlinks. The directory
35
+ * is created once per process and never recreated: when an external
36
+ * temporary-file cleaner removes it while empty, the next spill open fails and
37
+ * the collector degrades to its in-memory tail. At a JavaScript-observable
38
+ * process exit the directory is removed only when it holds no completed spill
39
+ * file (spill files are retained as full-output recovery artifacts until an
40
+ * external cleanup).
41
+ */
42
+ function privateSpillDir(): string {
43
+ defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-subprocess-'))
44
+ return defaultSpillDir
45
+ }
46
+
47
+ // The per-process spill directory is removed at process exit when it holds no
48
+ // completed spill file: a directory that never spilled is empty and is safe to
49
+ // remove, while a directory holding completed spill files keeps them (their
50
+ // content is retained until an external cleanup). A SIGKILLed process cannot
51
+ // run this at all; its residue is left to OS temp hygiene.
52
+ /* v8 ignore next 4 -- exit listeners run after the coverage dump; removal is verified by the CI /tmp residue measurement. */
53
+ process.once('exit', () => {
54
+ if (defaultSpillDir === undefined) return
55
+ try { rmdirSync(defaultSpillDir) } catch { /* best-effort: ENOENT/ENOTEMPTY/EBUSY/EPERM must not change the exit code. */ }
56
+ })
57
+
58
+ /**
59
+ * The stderr reporter used when no owner supplies one: a bare
60
+ * {@link prepareManagedProcessBinding} caller has no plugin logger, and the
61
+ * failure must still reach the process diagnostics.
62
+ * @param error - the spill failure.
63
+ * @param label - the failed stream label.
64
+ */
65
+ function reportSpillFailureToStderr(error: unknown, label: string): void {
66
+ process.stderr.write(`dsh-subprocess-local: ${label} spill failed; only the in-memory tail is retained: ${String(error)}\n`)
67
+ }
68
+
69
+ /**
70
+ * Build the reporter an owner passes as {@link SpillOptions.onFailure}: one
71
+ * error-level log line naming the owner and stream, with the failure appended
72
+ * so its `code`, `syscall`, and `path` reach the log.
73
+ * @param logger - the owner's plugin logger.
74
+ * @param owner - the component named in the line.
75
+ * @returns the reporter.
76
+ */
77
+ export function logSpillFailure(logger: { error(message: string, ...detail: unknown[]): void }, owner: string): SpillFailureReporter {
78
+ return (error, label) => {
79
+ const removedDirectory = (error as NodeJS.ErrnoException).code === 'ENOENT'
80
+ logger.error(
81
+ `${owner} could not write the complete ${label} stream to its spill file; the result keeps only the in-memory tail and reports no full-output path.`
82
+ + (removedDirectory ? ' The spill directory no longer exists; a temporary-file cleaner removing it while empty is the usual cause.' : ''),
83
+ error,
84
+ )
85
+ }
86
+ }
87
+
88
+ /** Inputs a managed native process needs before its output streams are bound. */
89
+ export interface ManagedProcessBinding {
90
+ /** Directory receiving spill files. */
91
+ spillDir: string
92
+ /** Receives a spill open or write failure. */
93
+ onSpillFailure: SpillFailureReporter
94
+ }
95
+
96
+ /**
97
+ * Prepare fallible output storage before starting a managed native process.
98
+ * This is the explicit resolve step for spill inputs: the spill directory
99
+ * defaults to the private per-process directory, and the failure reporter
100
+ * defaults to a stderr line when the caller has no logger.
101
+ * @param internals - optional caller-owned spill directory and failure reporter.
102
+ * @returns binding inputs whose spill directory is ready for use.
103
+ */
104
+ export function prepareManagedProcessBinding(
105
+ internals: { spillDir?: string; onSpillFailure?: SpillFailureReporter } = {},
106
+ ): ManagedProcessBinding {
107
+ return {
108
+ spillDir: internals.spillDir ?? privateSpillDir(),
109
+ onSpillFailure: internals.onSpillFailure ?? reportSpillFailureToStderr,
110
+ }
111
+ }
112
+
113
+
114
+ /**
115
+ * Collects one stream with a bounded in-memory tail. With spill options, on
116
+ * first overflow a spill file is created and every chunk (including those
117
+ * already collected) is appended there while the full stream remains within
118
+ * the cap; without them, only the in-memory tail is ever retained (the
119
+ * diagnostic-tail shape — a language server's stderr).
120
+ *
121
+ * Spilling is best-effort: a spill open or write failure discards the spill,
122
+ * reports once through {@link SpillOptions.onFailure}, and never interrupts
123
+ * in-memory collection, because `push()` runs inside the stream's `'data'`
124
+ * listener where a thrown error would become an uncaught exception.
125
+ *
126
+ * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
127
+ * end of command output; the spill file covers the head.
128
+ */
129
+ export class OutputCollector {
130
+ private chunks: Buffer[] = []
131
+ private bytes = 0
132
+ private dropped = false
133
+ private spillFd: number | undefined
134
+ private spillFile: string | undefined
135
+ private spillDisabled: boolean
136
+ /** Total bytes ever pushed (not just retained). */
137
+ private total = 0
138
+
139
+ /**
140
+ * @param maxBytes - in-memory tail cap in bytes.
141
+ * @param label - stream label used in spill file names and failure reports.
142
+ * @param spill - spill storage; omit for tail-only collection.
143
+ */
144
+ constructor(
145
+ private readonly maxBytes: number,
146
+ private readonly label: string,
147
+ private readonly spill: SpillOptions | undefined,
148
+ ) {
149
+ this.spillDisabled = spill === undefined
150
+ }
151
+
152
+ /**
153
+ * Ingest one stream chunk, counting it toward the whole-stream total. On
154
+ * first overflow of the in-memory cap a spill file is opened (when spilling
155
+ * is enabled) and every chunk (already-collected ones included) is appended
156
+ * there from then on; the in-memory tail then drops whole chunks from its
157
+ * head (or the head of a single over-cap chunk) until it fits the cap again.
158
+ * @param chunk - the raw bytes from one stream 'data' event.
159
+ */
160
+ push(chunk: Buffer): void {
161
+ this.total += chunk.length
162
+ const overflows = this.bytes + chunk.length > this.maxBytes
163
+ const spill = this.spill
164
+ if (spill !== undefined && !this.spillDisabled && (overflows || this.spillFd !== undefined)) this.spillAll(spill, chunk)
165
+ this.chunks.push(chunk)
166
+ this.bytes += chunk.length
167
+ while (this.bytes > this.maxBytes) {
168
+ const head = this.chunks[0] as Buffer
169
+ const excess = this.bytes - this.maxBytes
170
+ if (head.length <= excess) {
171
+ // Drop the whole head chunk (length ≥ 1 is guaranteed while over cap).
172
+ this.chunks.shift()
173
+ this.bytes -= head.length
174
+ } else {
175
+ // Trim the head so the retained window is byte-exact at the cap — a
176
+ // diagnostic tail (an LSP server's stderr) must hold the LAST
177
+ // maxBytes regardless of how the stream was chunked.
178
+ this.chunks[0] = head.subarray(excess)
179
+ this.bytes -= excess
180
+ }
181
+ this.dropped = true
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Open the spill file lazily and append `chunk` (and any prior chunks once).
187
+ * Runs inside the stream's `'data'` listener, so every filesystem failure is
188
+ * contained here: the spill is discarded, reported once, and collection
189
+ * continues with the in-memory tail alone.
190
+ */
191
+ private spillAll(spill: SpillOptions, chunk: Buffer): void {
192
+ if (this.total > spill.maxBytes) {
193
+ this.discardSpill()
194
+ return
195
+ }
196
+ try {
197
+ if (this.spillFd === undefined) {
198
+ // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
199
+ // existing path, symlink or not) + owner-only mode: defeats spill-path
200
+ // prediction and symlink planting in shared tmp dirs. The path is
201
+ // published only once the open succeeded, so a failed open (EEXIST on a
202
+ // planted entry included) never lets discardSpill unlink a path this
203
+ // process did not create.
204
+ const file = join(
205
+ spill.dir,
206
+ `dsh-subprocess-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
207
+ )
208
+ const fd = openSync(file, 'wx', 0o600)
209
+ this.spillFile = file
210
+ this.spillFd = fd
211
+ for (const prior of this.chunks) writeSync(fd, prior)
212
+ }
213
+ writeSync(this.spillFd, chunk)
214
+ } catch (error) {
215
+ // ENOENT (spill directory removed by a temp cleaner), EACCES/EPERM,
216
+ // EMFILE, or ENOSPC: the spill file is a recovery aid, not a
217
+ // precondition of collection.
218
+ this.discardSpill()
219
+ try {
220
+ spill.onFailure(error, this.label)
221
+ } catch (reporterFailure) {
222
+ // The reporter runs inside the stream listener too; a failing logger
223
+ // must not become the uncaught exception this path exists to prevent.
224
+ process.stderr.write(`dsh-subprocess-local: spill failure reporter threw: ${String(reporterFailure)}\n`)
225
+ }
226
+ }
227
+ }
228
+
229
+ /** Stop spilling and remove the file once it can no longer hold the complete stream. */
230
+ private discardSpill(): void {
231
+ const fd = this.spillFd
232
+ const file = this.spillFile
233
+ this.spillFd = undefined
234
+ this.spillFile = undefined
235
+ this.spillDisabled = true
236
+ if (fd !== undefined) {
237
+ try {
238
+ closeSync(fd)
239
+ } catch {
240
+ // Retain the descriptor so finalize can retry the failed close.
241
+ this.spillFd = fd
242
+ }
243
+ }
244
+ if (file !== undefined) {
245
+ try {
246
+ unlinkSync(file)
247
+ } catch {
248
+ // A failed unlink leaves at most maxSpillBytes behind, never an unbounded file.
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Incremental read in whole-stream byte coordinates: returns everything
255
+ * pushed since `fromByte`. When `fromByte` has already slid out of the
256
+ * in-memory tail window, the read is `lossy` — it returns the whole
257
+ * retained tail and the gap is only recoverable from the spill file.
258
+ * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
259
+ * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
260
+ */
261
+ readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
262
+ const windowStart = this.total - this.bytes
263
+ const buffer = Buffer.concat(this.chunks)
264
+ const lossy = fromByte < windowStart
265
+ const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
266
+ return {
267
+ text: slice.toString('utf8'),
268
+ nextOffset: this.total,
269
+ lossy,
270
+ ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Copy the retained raw tail with its position in the complete observed stream.
276
+ * @returns independent tail bytes and the total byte count before truncation.
277
+ */
278
+ snapshot(): { bytes: Buffer; totalBytes: number } {
279
+ return { bytes: Buffer.concat(this.chunks), totalBytes: this.total }
280
+ }
281
+
282
+ /**
283
+ * Close the spill file once the stream has ended. A failed close (delayed
284
+ * writeback fault) stops advertising the spill path — the file may be
285
+ * missing its tail — while every in-memory read keeps working. Idempotent;
286
+ * the spawn path seals both collectors at settlement so reads after exit
287
+ * never point at a still-open file.
288
+ */
289
+ seal(): void {
290
+ if (this.spillFd === undefined) return
291
+ try {
292
+ closeSync(this.spillFd)
293
+ } catch {
294
+ // A delayed writeback failure makes the spill unreliable; keep the
295
+ // in-memory result but stop advertising that file.
296
+ this.spillFile = undefined
297
+ }
298
+ this.spillFd = undefined
299
+ }
300
+
301
+ /**
302
+ * Seal the spill file and return the final output.
303
+ * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
304
+ */
305
+ finalize(): CollectedOutput {
306
+ this.seal()
307
+ return {
308
+ text: Buffer.concat(this.chunks).toString('utf8'),
309
+ truncated: this.dropped,
310
+ ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
311
+ }
312
+ }
313
+ }