@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,315 @@
1
+ /** Parent-side invocation and bootstrap state for the private native runner. */
2
+
3
+ import type { StdioOptions } from 'node:child_process'
4
+ import { accessSync, constants as fsConstants, lstatSync, statSync } from 'node:fs'
5
+ import { extname, isAbsolute } from 'node:path'
6
+ import { inspect } from 'node:util'
7
+ import { fileURLToPath } from 'node:url'
8
+ import type { SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
9
+ import { childEnv } from './spawn.ts'
10
+ import { controlEnvironment } from './control-spawn.ts'
11
+ import { SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control'
12
+
13
+ /** The one private environment variable consumed before target state is restored. */
14
+ export const SUBPROCESS_RUNNER_ENV = 'DSH_SUBPROCESS_RUNNER' as const
15
+
16
+ /** Sentinel used by the packaged bootstrap for the Windows IPC runner. */
17
+ export const WINDOWS_RUNNER_SELECTION = 'windows' as const
18
+
19
+ /** Non-empty command tuple used to launch the private runner entry. */
20
+ export type RunnerInvocation = [string, ...string[]]
21
+
22
+ const SOURCE_TSCONFIG_PATH = fileURLToPath(new URL('../../../../tsconfig.base.json', import.meta.url))
23
+ const RUNNER_CONTROL_ENV_PREFIXES = ['NODE_', 'TSX_'] as const
24
+
25
+ /**
26
+ * Resolve the source, built, or packaged entry that calls the same runner core.
27
+ * @returns executable and arguments for the active runtime form.
28
+ */
29
+ export function spawnRunnerInvocation(): RunnerInvocation {
30
+ if ('pkg' in process) return [process.execPath]
31
+ /* v8 ignore next -- built-artifact smoke imports the emitted JavaScript runner entry;
32
+ * source-unit coverage cannot change import.meta.url. */
33
+ if (extname(fileURLToPath(import.meta.url)) !== '.ts') {
34
+ return [process.execPath, fileURLToPath(import.meta.resolve('@deepseek-ai/dsh-subprocess-local/runner'))]
35
+ }
36
+ return [
37
+ process.execPath,
38
+ '--import',
39
+ import.meta.resolve('tsx/esm'),
40
+ fileURLToPath(new URL('./bin.ts', import.meta.url)),
41
+ ]
42
+ }
43
+
44
+ /**
45
+ * Check the concrete runner executable and entry paths without executing a probe mode.
46
+ * @param invocation - resolved executable and runner-entry arguments.
47
+ * @returns whether every concrete executable or entry path is accessible.
48
+ */
49
+ export function runnerInvocationAvailable(invocation: RunnerInvocation = spawnRunnerInvocation()): boolean {
50
+ try {
51
+ if (isAbsolute(invocation[0])) accessSync(invocation[0], fsConstants.X_OK)
52
+ const entry = invocation.at(-1)
53
+ if (entry !== undefined && entry !== invocation[0] && isAbsolute(entry)) {
54
+ accessSync(entry, fsConstants.R_OK)
55
+ }
56
+ return true
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Build the bootstrap-safe environment; target overrides arrive through request/IPC.
64
+ * @param selection - private runner selector or Linux launch-request locator.
65
+ * @param invocation - resolved runner invocation whose source form needs the workspace paths map.
66
+ * @returns environment for the runner before target state is restored.
67
+ */
68
+ export function runnerEnvironment(
69
+ selection: string,
70
+ invocation?: RunnerInvocation,
71
+ ): NodeJS.ProcessEnv {
72
+ const entry = invocation?.at(-1)
73
+ const env = childEnv()
74
+ for (const name of Object.keys(env)) {
75
+ const normalized = name.toUpperCase()
76
+ if (RUNNER_CONTROL_ENV_PREFIXES.some(prefix => normalized.startsWith(prefix))) {
77
+ Reflect.deleteProperty(env, name)
78
+ }
79
+ }
80
+ return {
81
+ ...env,
82
+ [SUBPROCESS_RUNNER_ENV]: selection,
83
+ SYSTEMD_LOG_TARGET: 'null',
84
+ ...entry?.endsWith('.ts') === true ? { TSX_TSCONFIG_PATH: SOURCE_TSCONFIG_PATH } : {},
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Read and delete the private selector before importing or restoring target state.
90
+ * @param env - mutable environment containing the private selector.
91
+ * @returns the consumed selector, or undefined when no runner was requested.
92
+ */
93
+ export function consumeRunnerSelection(env: NodeJS.ProcessEnv = process.env): string | undefined {
94
+ const selection = env[SUBPROCESS_RUNNER_ENV]
95
+ Reflect.deleteProperty(env, SUBPROCESS_RUNNER_ENV)
96
+ return selection
97
+ }
98
+
99
+ /**
100
+ * Require the private argv delimiter and at least one target argv entry.
101
+ * @param argv - private runner arguments.
102
+ * @returns copied target argv after the private delimiter.
103
+ */
104
+ export function parseRunnerTargetArgv(argv: readonly string[]): string[] {
105
+ if (argv[0] !== '--' || argv.length < 2) {
106
+ throw new Error('subprocess runner requires target argv after a private -- delimiter')
107
+ }
108
+ return [...argv.slice(1)]
109
+ }
110
+
111
+ /**
112
+ * Build direct Linux target stdio, or isolated Windows runner stdio with IPC
113
+ * on fd 3 and target carriers on fd 4 through fd 6; optional control uses fd 7.
114
+ * @param spec - ordinary subprocess request whose stdio modes are preserved.
115
+ * @param ipc - whether to isolate the runner and add its private Node IPC descriptor.
116
+ * @param stdinCarrier - runner fd 4 carrier; Windows ignore passes an opened null-device fd.
117
+ * @returns child-process stdio options for the runner.
118
+ */
119
+ export function runnerStdio(
120
+ spec: SubprocessSpawnSpec,
121
+ ipc: boolean,
122
+ stdinCarrier: 'pipe' | number = 'pipe',
123
+ ): Exclude<StdioOptions, string> {
124
+ const targetStdio: StdioOptions = [
125
+ spec.stdio.stdin === 'ignore' ? 'ignore' : 'pipe',
126
+ spec.stdio.stdout === 'inherit' ? 'inherit' : 'pipe',
127
+ spec.stdio.stderr === 'inherit' ? 'inherit' : 'pipe',
128
+ ]
129
+ if (!ipc) {
130
+ if (spec.stdio.control === 'pipe') {
131
+ while (targetStdio.length < SUBPROCESS_CONTROL_FD) targetStdio.push('ignore')
132
+ targetStdio.push('overlapped')
133
+ }
134
+ return targetStdio
135
+ }
136
+ const runner: StdioOptions = [
137
+ 'ignore',
138
+ 'ignore',
139
+ 'ignore',
140
+ 'ipc',
141
+ stdinCarrier,
142
+ spec.stdio.stdout === 'inherit' ? 1 : 'pipe',
143
+ spec.stdio.stderr === 'inherit' ? 2 : 'pipe',
144
+ ]
145
+ if (spec.stdio.control === 'pipe') runner.push('overlapped')
146
+ return runner
147
+ }
148
+
149
+ function windowsEnvironmentValue(
150
+ env: Readonly<Record<string, string | undefined>>,
151
+ name: 'PATH' | 'NODEFAULTCURRENTDIRECTORYINEXEPATH',
152
+ ): string | undefined {
153
+ for (const key of Object.keys(env).sort()) {
154
+ if (key.toUpperCase() === name) return env[key]
155
+ }
156
+ return undefined
157
+ }
158
+
159
+ function executableCandidateExists(candidate: string): boolean {
160
+ try {
161
+ return !statSync(candidate).isDirectory()
162
+ } catch {
163
+ try {
164
+ const entry = lstatSync(candidate)
165
+ return entry.isFile() || entry.isSymbolicLink()
166
+ } catch {
167
+ return false
168
+ }
169
+ }
170
+ }
171
+
172
+ function windowsPathDirectories(path: string): string[] {
173
+ const directories: string[] = []
174
+ let start = 0
175
+ while (start < path.length) {
176
+ if (path.charAt(start) === ';') {
177
+ start += 1
178
+ continue
179
+ }
180
+ const quote = path.charAt(start)
181
+ const quoted = quote === '"' || quote === "'"
182
+ const quoteEnd = quoted
183
+ ? path.indexOf(quote, start + 1)
184
+ : -1
185
+ const separator = path.indexOf(';', quoted ? quoteEnd < 0 ? path.length : quoteEnd : start)
186
+ const end = separator < 0 ? path.length : separator
187
+ let directory = path.slice(start, end)
188
+ if (directory.startsWith('"') || directory.startsWith("'")) directory = directory.slice(1)
189
+ if (directory.endsWith('"') || directory.endsWith("'")) directory = directory.slice(0, -1)
190
+ if (directory.length > 0) directories.push(directory)
191
+ start = end + 1
192
+ }
193
+ return directories
194
+ }
195
+
196
+ function windowsFileNameStart(command: string): number {
197
+ let start = command.length
198
+ while (start > 0 && !/[\\/:]/u.test(command.charAt(start - 1))) start -= 1
199
+ return start
200
+ }
201
+
202
+ function windowsSearchPathJoin(directory: string, name: string, cwd: string): string {
203
+ let prefix = cwd
204
+ let adjustedDirectory = directory
205
+ const slash = (value: string): boolean => value === '\\' || value === '/'
206
+ if (directory.length > 2 && slash(directory.charAt(0)) && slash(directory.charAt(1))) {
207
+ prefix = ''
208
+ } else if (directory.length >= 1 && slash(directory.charAt(0))) {
209
+ prefix = cwd.slice(0, 2)
210
+ } else if (
211
+ directory.length >= 2
212
+ && directory.charAt(1) === ':'
213
+ && (directory.length < 3 || !slash(directory.charAt(2)))
214
+ ) {
215
+ if (cwd.length < 2 || cwd.slice(0, 2).toLowerCase() !== directory.slice(0, 2).toLowerCase()) {
216
+ prefix = ''
217
+ } else {
218
+ adjustedDirectory = directory.slice(2)
219
+ }
220
+ } else if (directory.length > 2 && directory.charAt(1) === ':') {
221
+ prefix = ''
222
+ }
223
+
224
+ const append = (base: string, part: string): string => {
225
+ if (base.length === 0 || part.length === 0) return base + part
226
+ return /[\\/:]$/u.test(base) ? base + part : `${base}\\${part}`
227
+ }
228
+ return append(append(prefix, adjustedDirectory), name)
229
+ }
230
+
231
+ function windowsExecutableNames(command: string, name: string): string[] {
232
+ const dot = name.indexOf('.')
233
+ const hasExtension = dot >= 0 && dot < name.length - 1
234
+ const separator = name.endsWith('.') ? '' : '.'
235
+ return [
236
+ ...hasExtension ? [command] : [],
237
+ `${command}${separator}com`,
238
+ `${command}${separator}exe`,
239
+ ]
240
+ }
241
+
242
+ /**
243
+ * Resolve the executable path with libuv/Node Windows spawn search order while
244
+ * preserving the caller's original command-line argv entry separately.
245
+ * @param command - original target argv[0].
246
+ * @param cwd - final target working directory used for relative search roots.
247
+ * @param env - final target environment containing the child PATH.
248
+ * @param exists - injectable non-directory candidate probe used by tests.
249
+ * @param currentEnv - runner environment supplying PATH fallback and cwd-search policy.
250
+ * @returns a resolved application name suitable for `CreateProcessW`, or undefined when no candidate exists.
251
+ */
252
+ export function resolveWindowsExecutable(
253
+ command: string,
254
+ cwd: string,
255
+ env: Readonly<Record<string, string>>,
256
+ exists: (candidate: string) => boolean = executableCandidateExists,
257
+ currentEnv: Readonly<Record<string, string | undefined>> = process.env,
258
+ ): string | undefined {
259
+ const nameStart = windowsFileNameStart(command)
260
+ const directory = command.slice(0, nameStart)
261
+ const name = command.slice(nameStart)
262
+ const hasPath = nameStart !== 0
263
+ const roots: string[] = []
264
+ if (hasPath) {
265
+ roots.push(directory)
266
+ } else {
267
+ if (windowsEnvironmentValue(currentEnv, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined) {
268
+ roots.push('')
269
+ }
270
+ const path = windowsEnvironmentValue(env, 'PATH') ?? windowsEnvironmentValue(currentEnv, 'PATH') ?? ''
271
+ roots.push(...windowsPathDirectories(path))
272
+ }
273
+
274
+ for (const root of roots) {
275
+ const base = windowsSearchPathJoin(root, name, cwd)
276
+ for (const candidate of windowsExecutableNames(base, name)) {
277
+ if (exists(candidate)) return candidate
278
+ }
279
+ }
280
+
281
+ return undefined
282
+ }
283
+
284
+ function throwNullByteError(property: string, value: string, argument: boolean): never {
285
+ const subject = argument ? `The argument '${property}'` : `The property '${property}'`
286
+ const error = new TypeError(`${subject} must be a string without null bytes. Received ${inspect(value)}`)
287
+ Object.assign(error, { code: 'ERR_INVALID_ARG_VALUE' })
288
+ throw error
289
+ }
290
+
291
+ function validateNoNullByte(property: string, value: string, argument = false): void {
292
+ if (value.includes('\0')) throwNullByteError(property, value, argument)
293
+ }
294
+
295
+ /**
296
+ * Materialize and synchronously validate the final target environment.
297
+ * @param spec - final target argv, cwd, and environment overrides.
298
+ * @returns complete target environment after Node-equivalent validation.
299
+ */
300
+ export function targetEnvironment(
301
+ spec: Pick<SubprocessSpawnSpec, 'argv' | 'cwd' | 'env'> & { stdio?: SubprocessSpawnSpec['stdio'] },
302
+ ): Record<string, string> {
303
+ spec.argv.forEach((value, index) => {
304
+ validateNoNullByte(index === 0 ? 'file' : `args[${String(index - 1)}]`, value, true)
305
+ })
306
+ validateNoNullByte('options.cwd', spec.cwd)
307
+ const env = Object.fromEntries(
308
+ Object.entries(childEnv(spec.env)).filter((entry): entry is [string, string] => entry[1] !== undefined),
309
+ )
310
+ for (const [key, value] of Object.entries(env)) {
311
+ validateNoNullByte(`options.env['${key}']`, key)
312
+ validateNoNullByte(`options.env['${key}']`, value)
313
+ }
314
+ return controlEnvironment(env, spec.stdio?.control)
315
+ }
@@ -0,0 +1,281 @@
1
+ /** Closed private transports shared by the native subprocess runner. */
2
+
3
+ import {
4
+ chmodSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdtempSync,
8
+ readFileSync,
9
+ rmdirSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ } from 'node:fs'
13
+ import { tmpdir } from 'node:os'
14
+ import { basename, dirname, isAbsolute, join } from 'node:path'
15
+
16
+ /** Target state restored by the Linux bootstrap after systemd establishes the scope. */
17
+ export interface LinuxLaunchRequest {
18
+ cwd: string
19
+ env: Record<string, string>
20
+ /** Only child-owned pipe endpoints may have their shared file status flags changed. */
21
+ pipeFds?: number[]
22
+ control?: 'pipe'
23
+ }
24
+
25
+ /** Bounded Node-shaped error fields allowed across a private runner boundary. */
26
+ export interface SerializedRunnerError {
27
+ name: string
28
+ message: string
29
+ code?: string
30
+ syscall?: string
31
+ path?: string
32
+ }
33
+
34
+ /** A Linux pre-exec failure published beside its consumed request. */
35
+ export type LinuxStartupError =
36
+ { type: 'error'; error: SerializedRunnerError }
37
+
38
+ /** The only parent-to-runner start message on Windows. */
39
+ export interface WindowsStartRequest {
40
+ type: 'start'
41
+ cwd: string
42
+ env: Record<string, string>
43
+ control?: 'pipe'
44
+ }
45
+
46
+ /** The only parent-to-runner control message on Windows. */
47
+ export interface WindowsTerminateRequest {
48
+ type: 'terminate'
49
+ }
50
+
51
+ /** Exactly one direct-result branch is sent by a connected Windows runner. */
52
+ export type WindowsRunnerResult =
53
+ | { type: 'target-exit'; exitCode: number }
54
+ | { type: 'error'; error: SerializedRunnerError }
55
+
56
+ /** Private paths owned by one Linux ordinary or PTY spawn. */
57
+ export interface LinuxLaunchFiles {
58
+ directory: string
59
+ requestPath: string
60
+ startupErrorPath: string
61
+ }
62
+
63
+ function isRecord(value: unknown): value is Record<string, unknown> {
64
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
65
+ }
66
+
67
+ function hasExactKeys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {
68
+ const allowed = new Set([...required, ...optional])
69
+ return required.every(key => Object.hasOwn(value, key))
70
+ && Object.keys(value).every(key => allowed.has(key))
71
+ }
72
+
73
+ function isStringRecord(value: unknown): value is Record<string, string> {
74
+ return isRecord(value) && Object.values(value).every(entry => typeof entry === 'string')
75
+ }
76
+
77
+ function isSerializedRunnerError(value: unknown): value is SerializedRunnerError {
78
+ if (!isRecord(value) || !hasExactKeys(
79
+ value,
80
+ ['name', 'message'],
81
+ ['code', 'syscall', 'path'],
82
+ )) return false
83
+ return typeof value.name === 'string'
84
+ && typeof value.message === 'string'
85
+ && (value.code === undefined || typeof value.code === 'string')
86
+ && (value.syscall === undefined || typeof value.syscall === 'string')
87
+ && (value.path === undefined || typeof value.path === 'string')
88
+ }
89
+
90
+ function parseErrorResult(value: Record<string, unknown>): LinuxStartupError {
91
+ if (!hasExactKeys(value, ['type', 'error']) || !isSerializedRunnerError(value.error)) {
92
+ throw new Error('subprocess runner emitted an invalid error result')
93
+ }
94
+ if (value.type !== 'error') {
95
+ throw new Error('subprocess runner emitted an unknown error result')
96
+ }
97
+ return { type: 'error', error: value.error }
98
+ }
99
+
100
+ /**
101
+ * Create a private 0700 directory and one complete 0600 launch request.
102
+ * @param request - target cwd and complete environment for the bootstrap.
103
+ * @returns private paths owned by this launch.
104
+ */
105
+ export function createLinuxLaunchFiles(request: LinuxLaunchRequest): LinuxLaunchFiles {
106
+ const directory = mkdtempSync(join(tmpdir(), 'dsh-subprocess-launch-'))
107
+ const files = {
108
+ directory,
109
+ requestPath: join(directory, 'launch-request.json'),
110
+ startupErrorPath: join(directory, 'startup-error.json'),
111
+ }
112
+ try {
113
+ chmodSync(directory, 0o700)
114
+ writeFileSync(files.requestPath, JSON.stringify(request), { flag: 'wx', mode: 0o600 })
115
+ return files
116
+ } catch (error) {
117
+ cleanupLinuxLaunchFiles(files)
118
+ throw error
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Derive the only permitted startup-error path from an absolute request locator.
124
+ * @param requestPath - absolute path to the private launch-request file.
125
+ * @returns validated sibling paths for this launch.
126
+ */
127
+ export function linuxLaunchFilesFromLocator(requestPath: string): LinuxLaunchFiles {
128
+ if (!isAbsolute(requestPath) || basename(requestPath) !== 'launch-request.json') {
129
+ throw new Error('subprocess runner received an invalid Linux launch-request locator')
130
+ }
131
+ const directory = dirname(requestPath)
132
+ return { directory, requestPath, startupErrorPath: join(directory, 'startup-error.json') }
133
+ }
134
+
135
+ /**
136
+ * Strictly read and remove a one-shot Linux launch request.
137
+ * @param requestPath - private launch-request path to consume.
138
+ * @returns validated target cwd and environment.
139
+ */
140
+ export function consumeLinuxLaunchRequest(requestPath: string): LinuxLaunchRequest {
141
+ const text = readFileSync(requestPath, 'utf8')
142
+ unlinkSync(requestPath)
143
+ const value: unknown = JSON.parse(text)
144
+ if (!isRecord(value) || !hasExactKeys(value, ['cwd', 'env'], ['control', 'pipeFds'])
145
+ || (value.pipeFds !== undefined && !isStdioFdList(value.pipeFds))
146
+ || typeof value.cwd !== 'string' || !isStringRecord(value.env)
147
+ || (value.control !== undefined && value.control !== 'pipe')) {
148
+ throw new Error('subprocess runner received an invalid Linux launch request')
149
+ }
150
+ return { cwd: value.cwd, env: value.env, ...value.pipeFds === undefined ? {} : { pipeFds: value.pipeFds },
151
+ ...value.control === 'pipe' ? { control: 'pipe' as const } : {} }
152
+ }
153
+
154
+ function isStdioFdList(value: unknown): value is number[] {
155
+ return Array.isArray(value) && value.every((fd: unknown) => fd === 0 || fd === 1 || fd === 2)
156
+ }
157
+
158
+ /**
159
+ * Publish one strict 0600 Linux pre-exec error.
160
+ * @param files - private paths for this launch.
161
+ * @param error - bounded spawn or runner failure to publish.
162
+ */
163
+ export function writeLinuxStartupError(files: LinuxLaunchFiles, error: LinuxStartupError): void {
164
+ writeFileSync(files.startupErrorPath, JSON.stringify(error), { flag: 'wx', mode: 0o600 })
165
+ }
166
+
167
+ /**
168
+ * Read the Linux pre-exec error, if the bootstrap published one.
169
+ * @param path - expected startup-error path.
170
+ * @returns the validated failure, or undefined when none was published.
171
+ */
172
+ export function readLinuxStartupError(path: string): LinuxStartupError | undefined {
173
+ if (!existsSync(path)) return undefined
174
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
175
+ if (!isRecord(value)) throw new Error('subprocess runner emitted an invalid startup error')
176
+ return parseErrorResult(value)
177
+ }
178
+
179
+ /**
180
+ * Strictly parse the single Windows start message.
181
+ * @param value - untrusted IPC payload.
182
+ * @returns validated target start request.
183
+ */
184
+ export function parseWindowsStartRequest(value: unknown): WindowsStartRequest {
185
+ if (!isRecord(value) || !hasExactKeys(value, ['type', 'cwd', 'env'], ['control'])
186
+ || value.type !== 'start' || typeof value.cwd !== 'string' || !isStringRecord(value.env)
187
+ || (value.control !== undefined && value.control !== 'pipe')) {
188
+ throw new Error('subprocess runner received an invalid Windows start request')
189
+ }
190
+ return { type: 'start', cwd: value.cwd, env: value.env, ...value.control === 'pipe' ? { control: 'pipe' as const } : {} }
191
+ }
192
+
193
+ /**
194
+ * Return true only for the exact, payload-free Windows terminate control.
195
+ * @param value - untrusted IPC payload.
196
+ * @returns whether the payload is the exact terminate request.
197
+ */
198
+ export function isWindowsTerminateRequest(value: unknown): value is WindowsTerminateRequest {
199
+ return isRecord(value) && hasExactKeys(value, ['type']) && value.type === 'terminate'
200
+ }
201
+
202
+ /**
203
+ * Strictly parse one of the two Windows direct-result branches.
204
+ * @param value - untrusted IPC payload.
205
+ * @returns validated direct-result message.
206
+ */
207
+ export function parseWindowsRunnerResult(value: unknown): WindowsRunnerResult {
208
+ if (!isRecord(value) || typeof value.type !== 'string') {
209
+ throw new Error('subprocess runner emitted an invalid Windows result')
210
+ }
211
+ if (value.type === 'error') return parseErrorResult(value)
212
+ if (value.type === 'target-exit') {
213
+ const validExitCode = typeof value.exitCode === 'number'
214
+ && Number.isSafeInteger(value.exitCode)
215
+ && value.exitCode >= 0
216
+ if (!hasExactKeys(value, ['type', 'exitCode']) || !validExitCode) {
217
+ throw new Error('subprocess runner emitted an invalid target-exit result')
218
+ }
219
+ return {
220
+ type: 'target-exit',
221
+ exitCode: value.exitCode as number,
222
+ }
223
+ }
224
+ throw new Error(`subprocess runner emitted an unknown Windows result: ${value.type}`)
225
+ }
226
+
227
+ /**
228
+ * Convert an unknown failure into the bounded cross-process error record.
229
+ * @param error - failure caught at the process boundary.
230
+ * @returns bounded serializable error fields.
231
+ */
232
+ export function serializeRunnerError(error: unknown): SerializedRunnerError {
233
+ const source = error instanceof Error ? error : new Error(String(error))
234
+ const node = source as NodeJS.ErrnoException & { path?: string }
235
+ return {
236
+ name: source.name,
237
+ message: source.message,
238
+ ...typeof node.code === 'string' ? { code: node.code } : {},
239
+ ...typeof node.syscall === 'string' ? { syscall: node.syscall } : {},
240
+ ...typeof node.path === 'string' ? { path: node.path } : {},
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Rebuild a Node-shaped Error from a strict runner record.
246
+ * @param serialized - validated bounded error fields.
247
+ * @returns reconstructed Error with supported Node fields.
248
+ */
249
+ export function deserializeRunnerError(serialized: SerializedRunnerError): Error {
250
+ const error = new Error(serialized.message)
251
+ error.name = serialized.name
252
+ return Object.assign(error, {
253
+ ...serialized.code === undefined ? {} : { code: serialized.code },
254
+ ...serialized.syscall === undefined ? {} : { syscall: serialized.syscall },
255
+ ...serialized.path === undefined ? {} : { path: serialized.path },
256
+ })
257
+ }
258
+
259
+ /**
260
+ * Best-effort removal of only the private paths created for this Linux spawn.
261
+ * @param files - exact private paths owned by this launch.
262
+ */
263
+ export function cleanupLinuxLaunchFiles(files: LinuxLaunchFiles): void {
264
+ try {
265
+ if (lstatSync(files.directory).isSymbolicLink()) {
266
+ unlinkSync(files.directory)
267
+ return
268
+ }
269
+ for (const path of [
270
+ files.requestPath,
271
+ files.startupErrorPath,
272
+ ]) {
273
+ try { unlinkSync(path) } catch (error) {
274
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
275
+ }
276
+ }
277
+ rmdirSync(files.directory)
278
+ } catch {
279
+ // Crash residue remains private and no later spawn reuses this directory.
280
+ }
281
+ }