@deepseek-ai/dsh-subprocess-local 0.2.2-rc.1 → 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.
- package/README.i18n.yaml +4 -4
- package/README.md +2 -2
- package/README.zh.md +2 -2
- package/lib/index.js +27 -13
- package/lib/{runner-launch-B2zsQ1Dz.js → runner-launch-CKTiL8M8.js} +41 -14
- package/lib/runner.js +8 -12
- package/lib/types/bin.d.ts.map +1 -0
- package/lib/types/bin.js.map +1 -0
- package/lib/types/control-spawn.d.ts.map +1 -0
- package/lib/types/control-spawn.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/linux-execve.d.ts +1 -1
- package/lib/types/linux-execve.d.ts.map +1 -0
- package/lib/types/linux-execve.js.map +1 -0
- package/lib/types/linux-scope-selector.d.ts.map +1 -0
- package/lib/types/linux-scope-selector.js.map +1 -0
- package/lib/types/linux-scope.d.ts.map +1 -0
- package/lib/types/linux-scope.js.map +1 -0
- package/lib/types/managed-owner.d.ts.map +1 -0
- package/lib/types/managed-owner.js.map +1 -0
- package/lib/types/output.d.ts.map +1 -0
- package/lib/types/output.js.map +1 -0
- package/lib/types/process-inspector.d.ts +9 -5
- package/lib/types/process-inspector.d.ts.map +1 -0
- package/lib/types/process-inspector.js.map +1 -0
- package/lib/types/runner-launch.d.ts +1 -1
- package/lib/types/runner-launch.d.ts.map +1 -0
- package/lib/types/runner-launch.js.map +1 -0
- package/lib/types/runner-protocol.d.ts +2 -0
- package/lib/types/runner-protocol.d.ts.map +1 -0
- package/lib/types/runner-protocol.js.map +1 -0
- package/lib/types/shell-activity.d.ts.map +1 -0
- package/lib/types/shell-activity.js.map +1 -0
- package/lib/types/spawn-runner.d.ts +2 -1
- package/lib/types/spawn-runner.d.ts.map +1 -0
- package/lib/types/spawn-runner.js.map +1 -0
- package/lib/types/spawn.d.ts +2 -2
- package/lib/types/spawn.d.ts.map +1 -0
- package/lib/types/spawn.js.map +1 -0
- package/lib/types/terminal.d.ts.map +1 -0
- package/lib/types/terminal.js.map +1 -0
- package/lib/types/windows-inspector.d.ts.map +1 -0
- package/lib/types/windows-inspector.js.map +1 -0
- package/lib/types/windows-job.d.ts.map +1 -0
- package/lib/types/windows-job.js.map +1 -0
- package/package.json +12 -9
- package/src/bin.ts +25 -0
- package/src/control-spawn.ts +35 -0
- package/src/index.ts +387 -0
- package/src/linux-execve.ts +92 -0
- package/src/linux-scope-selector.ts +101 -0
- package/src/linux-scope.ts +726 -0
- package/src/managed-owner.ts +56 -0
- package/src/output.ts +313 -0
- package/src/process-inspector.ts +560 -0
- package/src/runner-launch.ts +315 -0
- package/src/runner-protocol.ts +281 -0
- package/src/shell-activity.ts +131 -0
- package/src/spawn-runner.ts +488 -0
- package/src/spawn.ts +500 -0
- package/src/terminal.ts +479 -0
- package/src/windows-inspector.ts +346 -0
- package/src/windows-job.ts +269 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/** Private shell lifecycle files; ordinary output never authorizes terminal reclamation. */
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { basename, join } from 'node:path'
|
|
5
|
+
import type { SubprocessTerminalActivity, SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess'
|
|
6
|
+
|
|
7
|
+
function quote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'` }
|
|
8
|
+
|
|
9
|
+
/** Opt-in startup integration and revision tracking for one ordinary interactive shell. */
|
|
10
|
+
export class ShellActivity {
|
|
11
|
+
private revision = 0
|
|
12
|
+
private observed = ''
|
|
13
|
+
private invalidated: string | undefined
|
|
14
|
+
private state: SubprocessTerminalActivity['state'] = 'unknown'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param directory - private startup and status file directory.
|
|
18
|
+
* @param argv - shell launch preserving supported user startup files.
|
|
19
|
+
* @param env - environment with any temporary startup redirect.
|
|
20
|
+
*/
|
|
21
|
+
constructor(private readonly directory: string, readonly argv: readonly string[], readonly env: Record<string, string>) {}
|
|
22
|
+
|
|
23
|
+
/** Invalidate prompt evidence before delivering input or a foreground signal. */
|
|
24
|
+
invalidate(): void {
|
|
25
|
+
this.invalidated = this.read()
|
|
26
|
+
this.revision++
|
|
27
|
+
this.state = 'unknown'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Read the latest top-level shell transition, fenced against input since that transition.
|
|
32
|
+
* @param pid - original shell process id.
|
|
33
|
+
* @returns lifecycle evidence; process ownership must be checked separately.
|
|
34
|
+
*/
|
|
35
|
+
inspect(pid: number): SubprocessTerminalActivity {
|
|
36
|
+
const record = this.read()
|
|
37
|
+
if (record !== this.observed) { this.observed = record; this.revision++ }
|
|
38
|
+
const match = /^(\d+):(\d+):(idle|busy)\n?$/u.exec(record)
|
|
39
|
+
this.state = record === this.invalidated || match?.[1] !== String(pid) ? 'unknown'
|
|
40
|
+
: match[3] as 'idle' | 'busy'
|
|
41
|
+
return { state: this.state, revision: this.revision }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Remove private startup and status files after process quiescence. */
|
|
45
|
+
dispose(): void { rmSync(this.directory, { recursive: true, force: true }) }
|
|
46
|
+
|
|
47
|
+
private read(): string {
|
|
48
|
+
try { return readFileSync(join(this.directory, 'state'), 'utf8') }
|
|
49
|
+
catch (_unavailableShellObservation) { return '' }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Prepare optional Bash or Zsh integration for a plain, non-login interactive launch.
|
|
55
|
+
* @param spec - terminal request; custom arguments and wrapped executables remain unmodified.
|
|
56
|
+
* @param env - scrubbed target environment.
|
|
57
|
+
* @param platform - execution platform.
|
|
58
|
+
* @returns private integration, or undefined for unsupported launches.
|
|
59
|
+
*/
|
|
60
|
+
export function prepareShellActivity(
|
|
61
|
+
spec: SubprocessTerminalSpawnSpec, env: Record<string, string>, platform: NodeJS.Platform,
|
|
62
|
+
): ShellActivity | undefined {
|
|
63
|
+
if (spec.shellActivity !== true || platform === 'win32' || spec.argv.length !== 2 || spec.argv[1] !== '-i') return undefined
|
|
64
|
+
const shell = basename(spec.argv[0] as string)
|
|
65
|
+
if (shell !== 'bash' && shell !== 'zsh') return undefined
|
|
66
|
+
const directory = mkdtempSync(join(tmpdir(), 'dsh-shell-'))
|
|
67
|
+
const state = quote(join(directory, 'state'))
|
|
68
|
+
const guards = quote(join(directory, 'guards'))
|
|
69
|
+
try {
|
|
70
|
+
if (shell === 'bash') {
|
|
71
|
+
const rc = join(directory, 'bashrc')
|
|
72
|
+
writeFileSync(rc, [
|
|
73
|
+
'[[ ! -r ~/.bashrc ]] || builtin source ~/.bashrc',
|
|
74
|
+
'if (( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) && [[ ! $(declare -p PROMPT_COMMAND PS0 2>/dev/null) =~ declare\\ -[^[:space:]]*r ]]; then',
|
|
75
|
+
' __dsh_shell_pid=$BASHPID; __dsh_shell_sequence=0',
|
|
76
|
+
' __dsh_shell_idle() {',
|
|
77
|
+
' local result=$?',
|
|
78
|
+
' if [[ $BASHPID == "$__dsh_shell_pid" ]]; then',
|
|
79
|
+
' (( ++__dsh_shell_sequence ))',
|
|
80
|
+
' local activity=idle',
|
|
81
|
+
` builtin trap -p >| ${guards}`,
|
|
82
|
+
` [[ ! -s ${guards} ]] || activity=unknown`,
|
|
83
|
+
` builtin printf '%s:%s:%s\\n' "$BASHPID" "$__dsh_shell_sequence" "$activity" >| ${state}`,
|
|
84
|
+
' fi',
|
|
85
|
+
' return "$result"',
|
|
86
|
+
' }',
|
|
87
|
+
' if [[ $(declare -p PROMPT_COMMAND 2>/dev/null) == "declare -a "* ]]; then',
|
|
88
|
+
' PROMPT_COMMAND+=(__dsh_shell_idle)',
|
|
89
|
+
' else',
|
|
90
|
+
' PROMPT_COMMAND="${PROMPT_COMMAND}"$\'\\n\'"__dsh_shell_idle"',
|
|
91
|
+
' fi',
|
|
92
|
+
` PS0+=${quote(`$(builtin printf '%s:%s:busy' "$__dsh_shell_pid" "$__dsh_shell_sequence" >| ${state})`)}`,
|
|
93
|
+
'fi',
|
|
94
|
+
'',
|
|
95
|
+
].join('\n'), { mode: 0o600, flag: 'wx' })
|
|
96
|
+
return new ShellActivity(directory, [spec.argv[0] as string, '--rcfile', rc, '-i'], env)
|
|
97
|
+
}
|
|
98
|
+
writeFileSync(join(directory, '.zshenv'), [
|
|
99
|
+
env.ZDOTDIR === undefined ? 'unset ZDOTDIR' : `ZDOTDIR=${quote(env.ZDOTDIR)}`,
|
|
100
|
+
'[[ ! -r ${ZDOTDIR:-$HOME}/.zshenv ]] || builtin source "${ZDOTDIR:-$HOME}/.zshenv"',
|
|
101
|
+
'typeset -g __dsh_shell_pid=$$ __dsh_shell_sequence=0',
|
|
102
|
+
'__dsh_shell_activity() {',
|
|
103
|
+
' (( ZSH_SUBSHELL == 0 && $$ == __dsh_shell_pid )) || return',
|
|
104
|
+
' (( ++__dsh_shell_sequence ))',
|
|
105
|
+
` builtin printf '%s:%s:%s\\n' "$$" "$__dsh_shell_sequence" "$1" >| ${state}`,
|
|
106
|
+
' return 0',
|
|
107
|
+
'}',
|
|
108
|
+
'__dsh_shell_idle() {',
|
|
109
|
+
` { builtin trap; zle -F; } >| ${guards}`,
|
|
110
|
+
' if [[ $CONTEXT != start || -n $BUFFER ]]; then __dsh_shell_activity busy',
|
|
111
|
+
` elif [[ -s ${guards}` + ' || -n ${(k)functions[(I)TRAP*]} ]]; then __dsh_shell_activity unknown',
|
|
112
|
+
' else __dsh_shell_activity idle; fi',
|
|
113
|
+
'}',
|
|
114
|
+
'__dsh_shell_busy() { __dsh_shell_activity busy }',
|
|
115
|
+
'__dsh_shell_init() {',
|
|
116
|
+
' autoload -Uz add-zle-hook-widget add-zsh-hook',
|
|
117
|
+
' add-zle-hook-widget line-init __dsh_shell_idle',
|
|
118
|
+
' add-zle-hook-widget line-finish __dsh_shell_busy',
|
|
119
|
+
' add-zsh-hook preexec __dsh_shell_busy',
|
|
120
|
+
' precmd_functions=(${precmd_functions:#__dsh_shell_init})',
|
|
121
|
+
'}',
|
|
122
|
+
'typeset -ga precmd_functions',
|
|
123
|
+
'precmd_functions+=(__dsh_shell_init)',
|
|
124
|
+
'',
|
|
125
|
+
].join('\n'), { mode: 0o600, flag: 'wx' })
|
|
126
|
+
return new ShellActivity(directory, spec.argv, { ...env, ZDOTDIR: directory })
|
|
127
|
+
} catch (error) {
|
|
128
|
+
rmSync(directory, { recursive: true, force: true })
|
|
129
|
+
throw error
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
/** One-shot Linux exec bootstrap and Windows Job-owning subprocess runner. */
|
|
2
|
+
|
|
3
|
+
import { SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control'
|
|
4
|
+
import { closeSync } from 'node:fs'
|
|
5
|
+
import {
|
|
6
|
+
closeHandleChecked,
|
|
7
|
+
isJobEmpty,
|
|
8
|
+
loadWin32ProcessBindings,
|
|
9
|
+
pollProcessExit,
|
|
10
|
+
spawnCurrentTokenJobProcess,
|
|
11
|
+
terminateJob,
|
|
12
|
+
Win32Error,
|
|
13
|
+
} from '@deepseek-ai/dsh-win32-process'
|
|
14
|
+
import type {
|
|
15
|
+
CurrentTokenProcessBindings,
|
|
16
|
+
NativePtr,
|
|
17
|
+
} from '@deepseek-ai/dsh-win32-process'
|
|
18
|
+
import { loadLinuxExecve } from './linux-execve.ts'
|
|
19
|
+
import {
|
|
20
|
+
consumeLinuxLaunchRequest,
|
|
21
|
+
isWindowsTerminateRequest,
|
|
22
|
+
linuxLaunchFilesFromLocator,
|
|
23
|
+
parseWindowsStartRequest,
|
|
24
|
+
serializeRunnerError,
|
|
25
|
+
writeLinuxStartupError,
|
|
26
|
+
} from './runner-protocol.ts'
|
|
27
|
+
import type {
|
|
28
|
+
LinuxLaunchFiles,
|
|
29
|
+
LinuxLaunchRequest,
|
|
30
|
+
SerializedRunnerError,
|
|
31
|
+
WindowsRunnerResult,
|
|
32
|
+
WindowsStartRequest,
|
|
33
|
+
} from './runner-protocol.ts'
|
|
34
|
+
import {
|
|
35
|
+
parseRunnerTargetArgv,
|
|
36
|
+
resolveWindowsExecutable,
|
|
37
|
+
SUBPROCESS_RUNNER_ENV,
|
|
38
|
+
WINDOWS_RUNNER_SELECTION,
|
|
39
|
+
} from './runner-launch.ts'
|
|
40
|
+
|
|
41
|
+
type RunnerHost = Pick<NodeJS.Process, 'env' | 'exitCode' | 'connected' | 'cwd' | 'chdir' | 'on' | 'off' | 'once' | 'disconnect'> & {
|
|
42
|
+
send?: NodeJS.Process['send']
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Injectable operations used by the protocol-owner tests. */
|
|
46
|
+
export interface SpawnRunnerInternals {
|
|
47
|
+
execve: ReturnType<typeof loadLinuxExecve>
|
|
48
|
+
loadWin32ProcessBindings(): CurrentTokenProcessBindings
|
|
49
|
+
spawnCurrentTokenJobProcess: typeof spawnCurrentTokenJobProcess
|
|
50
|
+
closeFileDescriptor(fileDescriptor: number): void
|
|
51
|
+
resolveWindowsExecutable: typeof resolveWindowsExecutable
|
|
52
|
+
pollProcessExit: typeof pollProcessExit
|
|
53
|
+
isJobEmpty: typeof isJobEmpty
|
|
54
|
+
terminateJob: typeof terminateJob
|
|
55
|
+
closeHandleChecked: typeof closeHandleChecked
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const defaultInternals: SpawnRunnerInternals = {
|
|
59
|
+
/* v8 ignore next -- source/built/packaged subprocess smoke executes this only in a replaceable child process. */
|
|
60
|
+
execve: (...args) => loadLinuxExecve()(...args),
|
|
61
|
+
loadWin32ProcessBindings,
|
|
62
|
+
spawnCurrentTokenJobProcess,
|
|
63
|
+
closeFileDescriptor: closeSync,
|
|
64
|
+
resolveWindowsExecutable,
|
|
65
|
+
pollProcessExit,
|
|
66
|
+
isJobEmpty,
|
|
67
|
+
terminateJob,
|
|
68
|
+
closeHandleChecked,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const NODE_SPAWN_DETAIL_CODES = new Set(['EACCES', 'ENOENT'])
|
|
72
|
+
const WINDOWS_SPAWN_ERROR_CODES = new Map<number, string>([
|
|
73
|
+
[2, 'ENOENT'],
|
|
74
|
+
[3, 'ENOENT'],
|
|
75
|
+
[267, 'ENOENT'],
|
|
76
|
+
[5, 'EPERM'],
|
|
77
|
+
[193, 'EFTYPE'],
|
|
78
|
+
[740, 'EACCES'],
|
|
79
|
+
])
|
|
80
|
+
|
|
81
|
+
function nodeSpawnError(
|
|
82
|
+
syscall: string,
|
|
83
|
+
code: string,
|
|
84
|
+
path?: string,
|
|
85
|
+
): SerializedRunnerError {
|
|
86
|
+
const message = `${syscall} ${code}`
|
|
87
|
+
return {
|
|
88
|
+
name: 'Error',
|
|
89
|
+
message,
|
|
90
|
+
code,
|
|
91
|
+
syscall,
|
|
92
|
+
...path === undefined ? {} : { path },
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function asSpawnError(
|
|
97
|
+
error: unknown,
|
|
98
|
+
program: string,
|
|
99
|
+
): SerializedRunnerError {
|
|
100
|
+
const serialized = serializeRunnerError(error)
|
|
101
|
+
if (!(error instanceof Win32Error)) {
|
|
102
|
+
return serialized.code === undefined
|
|
103
|
+
? serialized
|
|
104
|
+
: nodeSpawnError(`spawn ${program}`, serialized.code, program)
|
|
105
|
+
}
|
|
106
|
+
const code = WINDOWS_SPAWN_ERROR_CODES.get(error.win32Code) ?? 'UNKNOWN'
|
|
107
|
+
if (NODE_SPAWN_DETAIL_CODES.has(code)) {
|
|
108
|
+
return nodeSpawnError(`spawn ${program}`, code, program)
|
|
109
|
+
}
|
|
110
|
+
return nodeSpawnError('spawn', code)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function windowsPathNotFoundError(program: string): SerializedRunnerError {
|
|
114
|
+
return nodeSpawnError(`spawn ${program}`, 'ENOENT', program)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function windowsStartCancelledError(): SerializedRunnerError {
|
|
118
|
+
return {
|
|
119
|
+
name: 'Error',
|
|
120
|
+
message: 'subprocess target start was cancelled',
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function linuxPathNotFoundError(program: string): NodeJS.ErrnoException {
|
|
125
|
+
return Object.assign(new Error(`spawn ${program} ENOENT`), {
|
|
126
|
+
code: 'ENOENT',
|
|
127
|
+
errno: -2,
|
|
128
|
+
syscall: `spawn ${program}`,
|
|
129
|
+
path: program,
|
|
130
|
+
spawnargs: [] as string[],
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function execLinuxFile(
|
|
135
|
+
file: string,
|
|
136
|
+
argv: string[],
|
|
137
|
+
request: LinuxLaunchRequest,
|
|
138
|
+
internals: SpawnRunnerInternals,
|
|
139
|
+
): never {
|
|
140
|
+
try {
|
|
141
|
+
return internals.execve(file, argv, request.env, request.control, request.pipeFds)
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOEXEC') throw error
|
|
144
|
+
return internals.execve('/bin/sh', ['/bin/sh', file, ...argv.slice(1)], request.env, request.control, request.pipeFds)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function execLinuxTarget(
|
|
149
|
+
request: LinuxLaunchRequest,
|
|
150
|
+
argv: string[],
|
|
151
|
+
internals: SpawnRunnerInternals,
|
|
152
|
+
): never {
|
|
153
|
+
const program = argv[0] as string
|
|
154
|
+
if (program.includes('/')) return execLinuxFile(program, argv, request, internals)
|
|
155
|
+
const path = request.env.PATH ?? '/usr/bin:/bin'
|
|
156
|
+
let permissionFailure: Error | undefined
|
|
157
|
+
for (const directory of path.split(':')) {
|
|
158
|
+
const root = directory.startsWith('/')
|
|
159
|
+
? directory
|
|
160
|
+
: `${request.cwd}${request.cwd.endsWith('/') ? '' : '/'}${directory}`
|
|
161
|
+
const candidate = `${root}${root.endsWith('/') ? '' : '/'}${program}`
|
|
162
|
+
try {
|
|
163
|
+
return execLinuxFile(candidate, argv, request, internals)
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
166
|
+
if (code === 'EACCES') {
|
|
167
|
+
permissionFailure ??= error as Error
|
|
168
|
+
continue
|
|
169
|
+
}
|
|
170
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') continue
|
|
171
|
+
throw error
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
throw permissionFailure ?? linuxPathNotFoundError(program)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function runLinux(
|
|
178
|
+
locator: string,
|
|
179
|
+
argv: string[],
|
|
180
|
+
host: RunnerHost,
|
|
181
|
+
internals: SpawnRunnerInternals,
|
|
182
|
+
): void {
|
|
183
|
+
const files = linuxLaunchFilesFromLocator(locator)
|
|
184
|
+
let request: ReturnType<typeof consumeLinuxLaunchRequest>
|
|
185
|
+
try {
|
|
186
|
+
request = consumeLinuxLaunchRequest(files.requestPath)
|
|
187
|
+
} catch (error) {
|
|
188
|
+
writeLinuxStartupError(files, { type: 'error', error: serializeRunnerError(error) })
|
|
189
|
+
host.exitCode = 127
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
host.chdir(request.cwd)
|
|
194
|
+
execLinuxTarget({ ...request, cwd: host.cwd() }, argv, internals)
|
|
195
|
+
} catch (error) {
|
|
196
|
+
writeLinuxStartupError(files, {
|
|
197
|
+
type: 'error',
|
|
198
|
+
error: asSpawnError(error, argv[0] as string),
|
|
199
|
+
})
|
|
200
|
+
host.exitCode = 127
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function sendMessage(host: RunnerHost, result: WindowsRunnerResult): Promise<void> {
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
if (!host.connected || host.send === undefined) {
|
|
207
|
+
reject(new Error('subprocess runner IPC is not connected'))
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
host.send(result, (error) => {
|
|
212
|
+
if (error === null) resolve()
|
|
213
|
+
else reject(error)
|
|
214
|
+
})
|
|
215
|
+
} catch (error) {
|
|
216
|
+
/* v8 ignore next -- process.send throws Error instances. */
|
|
217
|
+
const failure = error instanceof Error ? error : new Error(String(error))
|
|
218
|
+
reject(failure)
|
|
219
|
+
}
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
class WindowsJobRunner {
|
|
224
|
+
private api: CurrentTokenProcessBindings | undefined
|
|
225
|
+
private processHandle: NativePtr | undefined
|
|
226
|
+
private jobHandle: NativePtr | undefined
|
|
227
|
+
private pollTimer: ReturnType<typeof setInterval> | undefined
|
|
228
|
+
private startSeen = false
|
|
229
|
+
private terminateRequested = false
|
|
230
|
+
private resultStarted = false
|
|
231
|
+
private resultDelivered = false
|
|
232
|
+
private finished = false
|
|
233
|
+
private readonly completion = Promise.withResolvers<void>()
|
|
234
|
+
|
|
235
|
+
constructor(
|
|
236
|
+
private readonly argv: string[],
|
|
237
|
+
private readonly host: RunnerHost,
|
|
238
|
+
private readonly internals: SpawnRunnerInternals,
|
|
239
|
+
) {}
|
|
240
|
+
|
|
241
|
+
run(): Promise<void> {
|
|
242
|
+
if (!this.host.connected || this.host.send === undefined) {
|
|
243
|
+
this.finish(127)
|
|
244
|
+
return this.completion.promise
|
|
245
|
+
}
|
|
246
|
+
this.host.on('message', this.onMessage)
|
|
247
|
+
this.host.once('disconnect', this.onDisconnect)
|
|
248
|
+
return this.completion.promise
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private readonly onMessage = (value: unknown): void => {
|
|
252
|
+
if (this.finished) return
|
|
253
|
+
if (isWindowsTerminateRequest(value)) {
|
|
254
|
+
this.requestTermination()
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
if (this.startSeen) {
|
|
258
|
+
void this.runnerFailure(new Error('subprocess runner received more than one Windows start request'))
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
let request: WindowsStartRequest
|
|
262
|
+
try {
|
|
263
|
+
request = parseWindowsStartRequest(value)
|
|
264
|
+
} catch (error) {
|
|
265
|
+
void this.runnerFailure(error)
|
|
266
|
+
return
|
|
267
|
+
}
|
|
268
|
+
this.startSeen = true
|
|
269
|
+
void this.start(request)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private readonly onDisconnect = (): void => {
|
|
273
|
+
if (this.finished) return
|
|
274
|
+
this.releaseOwnedJob()
|
|
275
|
+
this.finish(127, false)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private async start(request: WindowsStartRequest): Promise<void> {
|
|
279
|
+
if (this.terminateRequested) {
|
|
280
|
+
await this.publishTerminalResult({ type: 'error', error: windowsStartCancelledError() }, 0)
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
await new Promise<void>((resolveImmediate) => { setImmediate(resolveImmediate) })
|
|
284
|
+
if (this.finished) return
|
|
285
|
+
// IPC may set this field while start() is suspended above.
|
|
286
|
+
// oxlint-disable-next-line typescript/no-unnecessary-condition
|
|
287
|
+
if (this.terminateRequested) {
|
|
288
|
+
await this.publishTerminalResult({ type: 'error', error: windowsStartCancelledError() }, 0)
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
const [command, ...args] = this.argv
|
|
293
|
+
const applicationName = this.internals.resolveWindowsExecutable(
|
|
294
|
+
command as string,
|
|
295
|
+
request.cwd,
|
|
296
|
+
request.env,
|
|
297
|
+
undefined,
|
|
298
|
+
{ ...this.host.env },
|
|
299
|
+
)
|
|
300
|
+
if (applicationName === undefined) {
|
|
301
|
+
await this.publishTerminalResult({
|
|
302
|
+
type: 'error',
|
|
303
|
+
error: windowsPathNotFoundError(command as string),
|
|
304
|
+
}, 0)
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
this.api = this.internals.loadWin32ProcessBindings()
|
|
308
|
+
const spawned = this.internals.spawnCurrentTokenJobProcess(this.api, {
|
|
309
|
+
command: command as string,
|
|
310
|
+
applicationName,
|
|
311
|
+
args,
|
|
312
|
+
cwd: request.cwd,
|
|
313
|
+
env: request.env,
|
|
314
|
+
stdio: { stdin: 4, stdout: 5, stderr: 6, ...request.control === 'pipe' ? { control: SUBPROCESS_CONTROL_FD } : {} },
|
|
315
|
+
})
|
|
316
|
+
this.processHandle = spawned.process
|
|
317
|
+
this.jobHandle = spawned.job
|
|
318
|
+
for (const fileDescriptor of request.control === 'pipe' ? [4, 5, 6, SUBPROCESS_CONTROL_FD] : [4, 5, 6]) {
|
|
319
|
+
this.internals.closeFileDescriptor(fileDescriptor)
|
|
320
|
+
}
|
|
321
|
+
this.pollTimer = setInterval(() => { this.poll() }, 10)
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if (this.jobHandle === undefined && error instanceof Win32Error && error.api === 'CreateProcessW') {
|
|
324
|
+
await this.publishTerminalResult({
|
|
325
|
+
type: 'error',
|
|
326
|
+
error: asSpawnError(error, this.argv[0] as string),
|
|
327
|
+
}, 0)
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
await this.runnerFailure(error)
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private requestTermination(): void {
|
|
335
|
+
if (this.terminateRequested) return
|
|
336
|
+
this.terminateRequested = true
|
|
337
|
+
try {
|
|
338
|
+
this.terminateOwnedJob()
|
|
339
|
+
} catch (error) {
|
|
340
|
+
void this.runnerFailure(error)
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
private terminateOwnedJob(): void {
|
|
345
|
+
const job = this.jobHandle
|
|
346
|
+
if (job === undefined) return
|
|
347
|
+
/* v8 ignore next -- a Job handle is assigned only after the bindings are loaded;
|
|
348
|
+
* the guard above is the only reachable empty-owner state. */
|
|
349
|
+
if (this.api === undefined) return
|
|
350
|
+
this.internals.terminateJob(this.api, job, 1)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private poll(): void {
|
|
354
|
+
if (this.finished) return
|
|
355
|
+
/* v8 ignore next -- poll is installed only after start() stores the bindings; retained as a defensive invariant guard. */
|
|
356
|
+
if (this.api === undefined) return
|
|
357
|
+
try {
|
|
358
|
+
if (this.processHandle !== undefined) {
|
|
359
|
+
const exitCode = this.internals.pollProcessExit(this.api, this.processHandle)
|
|
360
|
+
if (exitCode !== undefined) {
|
|
361
|
+
this.internals.closeHandleChecked(this.api, this.processHandle, 'ordinary direct process')
|
|
362
|
+
this.processHandle = undefined
|
|
363
|
+
void this.publishTerminalResult({ type: 'target-exit', exitCode })
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (this.jobHandle !== undefined && this.internals.isJobEmpty(this.api, this.jobHandle)) {
|
|
367
|
+
this.internals.closeHandleChecked(this.api, this.jobHandle, 'ordinary process Job')
|
|
368
|
+
this.jobHandle = undefined
|
|
369
|
+
if (this.resultDelivered) this.finish(0)
|
|
370
|
+
}
|
|
371
|
+
} catch (error) {
|
|
372
|
+
void this.runnerFailure(error)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
private async publishTerminalResult(result: WindowsRunnerResult, exitCode?: number): Promise<void> {
|
|
377
|
+
/* v8 ignore next -- each state transition has a single result call site; the guard contains only re-entrant internal defects. */
|
|
378
|
+
if (this.finished || this.resultStarted) return
|
|
379
|
+
this.resultStarted = true
|
|
380
|
+
try {
|
|
381
|
+
await sendMessage(this.host, result)
|
|
382
|
+
this.resultDelivered = true
|
|
383
|
+
} catch {
|
|
384
|
+
this.releaseOwnedJob()
|
|
385
|
+
this.finish(127, false)
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
if (exitCode !== undefined) {
|
|
389
|
+
this.finish(exitCode)
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
if (this.jobHandle === undefined) this.finish(0)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private async runnerFailure(error: unknown): Promise<void> {
|
|
396
|
+
/* v8 ignore next -- callers stop/detach on finish; this guard contains only an already-queued internal callback. */
|
|
397
|
+
if (this.finished) return
|
|
398
|
+
if (!this.resultStarted) {
|
|
399
|
+
this.resultStarted = true
|
|
400
|
+
try {
|
|
401
|
+
await sendMessage(this.host, { type: 'error', error: serializeRunnerError(error) })
|
|
402
|
+
this.resultDelivered = true
|
|
403
|
+
} catch {
|
|
404
|
+
// The disconnected parent observes runner infrastructure failure.
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
this.releaseOwnedJob()
|
|
408
|
+
this.finish(127)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private releaseOwnedJob(): void {
|
|
412
|
+
if (this.pollTimer !== undefined) clearInterval(this.pollTimer)
|
|
413
|
+
this.pollTimer = undefined
|
|
414
|
+
const api = this.api
|
|
415
|
+
if (api === undefined) return
|
|
416
|
+
if (this.jobHandle !== undefined) {
|
|
417
|
+
try { this.internals.terminateJob(api, this.jobHandle, 1) } catch { /* Continue to kill-on-close. */ }
|
|
418
|
+
try { this.internals.closeHandleChecked(api, this.jobHandle, 'ordinary process Job cleanup') } catch { /* Best effort after failure. */ }
|
|
419
|
+
this.jobHandle = undefined
|
|
420
|
+
}
|
|
421
|
+
if (this.processHandle !== undefined) {
|
|
422
|
+
try { this.internals.closeHandleChecked(api, this.processHandle, 'ordinary direct process cleanup') } catch { /* Best effort after failure. */ }
|
|
423
|
+
this.processHandle = undefined
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
private finish(exitCode: number, disconnect = true): void {
|
|
428
|
+
if (this.finished) return
|
|
429
|
+
this.finished = true
|
|
430
|
+
if (this.pollTimer !== undefined) clearInterval(this.pollTimer)
|
|
431
|
+
this.pollTimer = undefined
|
|
432
|
+
this.host.off('message', this.onMessage)
|
|
433
|
+
this.host.off('disconnect', this.onDisconnect)
|
|
434
|
+
this.host.exitCode = exitCode
|
|
435
|
+
if (disconnect && this.host.connected) this.host.disconnect()
|
|
436
|
+
this.completion.resolve()
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Execute the selected Linux bootstrap or Windows Job runner.
|
|
442
|
+
* @param selection - Windows sentinel or Linux launch-request locator.
|
|
443
|
+
* @param argv - private runner arguments beginning with the target delimiter.
|
|
444
|
+
* @param host - process transport and lifecycle host.
|
|
445
|
+
* @param internals - native and filesystem operations used by the runner.
|
|
446
|
+
*/
|
|
447
|
+
export async function runSpawnRunner(
|
|
448
|
+
selection: string,
|
|
449
|
+
argv: readonly string[],
|
|
450
|
+
host: RunnerHost = process,
|
|
451
|
+
internals: SpawnRunnerInternals = defaultInternals,
|
|
452
|
+
): Promise<void> {
|
|
453
|
+
Reflect.deleteProperty(host.env, SUBPROCESS_RUNNER_ENV)
|
|
454
|
+
const targetArgv = parseRunnerTargetArgv(argv)
|
|
455
|
+
if (selection === WINDOWS_RUNNER_SELECTION) {
|
|
456
|
+
await new WindowsJobRunner(targetArgv, host, internals).run()
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
runLinux(selection, targetArgv, host, internals)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Best-effort reporting for failures before the selected runner established its owner.
|
|
464
|
+
* @param selection - Windows sentinel, Linux launch-request locator, or no selection.
|
|
465
|
+
* @param error - failure raised before normal runner settlement.
|
|
466
|
+
* @param host - process transport and lifecycle host.
|
|
467
|
+
*/
|
|
468
|
+
export async function reportSpawnRunnerFailure(
|
|
469
|
+
selection: string | undefined,
|
|
470
|
+
error: unknown,
|
|
471
|
+
host: RunnerHost = process,
|
|
472
|
+
): Promise<void> {
|
|
473
|
+
if (selection === WINDOWS_RUNNER_SELECTION) {
|
|
474
|
+
try { await sendMessage(host, { type: 'error', error: serializeRunnerError(error) }) } catch { /* No transport remains. */ }
|
|
475
|
+
host.exitCode = 127
|
|
476
|
+
if (host.connected) host.disconnect()
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
if (selection !== undefined) {
|
|
480
|
+
try {
|
|
481
|
+
const files: LinuxLaunchFiles = linuxLaunchFilesFromLocator(selection)
|
|
482
|
+
writeLinuxStartupError(files, { type: 'error', error: serializeRunnerError(error) })
|
|
483
|
+
} catch {
|
|
484
|
+
// The parent will report an unconsumed request or missing runner result.
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
host.exitCode = 127
|
|
488
|
+
}
|