@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.
- 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 +14 -11
- 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,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows process-table operations for terminal readiness, signalling, and
|
|
3
|
+
* teardown: Toolhelp32 snapshot enumeration with GetProcessTimes creation-time
|
|
4
|
+
* identity and process-handle wait-state liveness, the shell pid as a pseudo
|
|
5
|
+
* process group (Windows has no POSIX groups), and taskkill tree signalling.
|
|
6
|
+
* The koffi bindings load lazily so
|
|
7
|
+
* non-Windows processes never touch Win32 libraries; all decision logic takes
|
|
8
|
+
* an injectable internals boundary so suites can pin it on any host.
|
|
9
|
+
* @module dsh-subprocess-local/windows-inspector
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { spawnSync } from 'node:child_process'
|
|
13
|
+
import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess'
|
|
14
|
+
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
|
|
15
|
+
import type { ProcessIdentity, ProcessInspector, ProcessSnapshot } from './process-inspector.ts'
|
|
16
|
+
|
|
17
|
+
type Koffi = typeof import('koffi')['default']
|
|
18
|
+
type KoffiType = ReturnType<Koffi['pointer']>
|
|
19
|
+
|
|
20
|
+
const requireKoffi = createLazyRequire<Koffi>('koffi', import.meta.url)
|
|
21
|
+
|
|
22
|
+
/** One Toolhelp32 process-table row. */
|
|
23
|
+
export interface ProcessEntry {
|
|
24
|
+
pid: number
|
|
25
|
+
parentPid: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Creation identity plus the process object's current wait state. */
|
|
29
|
+
export interface WindowsProcessState {
|
|
30
|
+
/** GetProcessTimes creation identity used to fence PID reuse. */
|
|
31
|
+
started: string
|
|
32
|
+
/** Whether a zero-time process-handle wait reports the process still running. */
|
|
33
|
+
active: boolean
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Injectable Windows process operations used by one local PTY session. */
|
|
37
|
+
export interface WindowsProcessInspectorInternals {
|
|
38
|
+
/** Enumerate the current process table (pid/parent pairs). */
|
|
39
|
+
snapshot(): ProcessEntry[]
|
|
40
|
+
/** Return one process's creation identity and wait state, or undefined when unreadable. */
|
|
41
|
+
processState(pid: number): WindowsProcessState | undefined
|
|
42
|
+
/** Terminate one process tree; `force` maps to taskkill `/F`. */
|
|
43
|
+
taskkill(pid: number, force: boolean): void
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Walk a process table from one root in children-first order, retaining only
|
|
48
|
+
* members whose start identity is readable (unreadable members are detector
|
|
49
|
+
* misses, exactly like an unreadable `/proc` entry on Linux).
|
|
50
|
+
* @param entries - the process table snapshot.
|
|
51
|
+
* @param rootPid - the tree root to descend from.
|
|
52
|
+
* @param started - creation-time identity resolver for one member.
|
|
53
|
+
* @returns the root and its current transitive descendants, children first.
|
|
54
|
+
*/
|
|
55
|
+
/* jscpd:ignore-start -- the Windows inspector deliberately mirrors process-inspector.ts:
|
|
56
|
+
the decision logic (tree walk, identity fencing, group signalling) is the same contract over
|
|
57
|
+
Win32 primitives, per the persistent-pty note 2026-08-11-pwsh-persistent-pty. */
|
|
58
|
+
export function windowsProcessTree(
|
|
59
|
+
entries: ProcessEntry[],
|
|
60
|
+
rootPid: number,
|
|
61
|
+
started: (pid: number) => string | undefined,
|
|
62
|
+
): ProcessIdentity[] {
|
|
63
|
+
const byPid = new Map(entries.map(entry => [entry.pid, entry]))
|
|
64
|
+
const root = byPid.get(rootPid)
|
|
65
|
+
if (root === undefined) return []
|
|
66
|
+
const byParent = new Map<number, ProcessEntry[]>()
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
const children = byParent.get(entry.parentPid) ?? []
|
|
69
|
+
children.push(entry)
|
|
70
|
+
byParent.set(entry.parentPid, children)
|
|
71
|
+
}
|
|
72
|
+
const visited = new Set<number>()
|
|
73
|
+
const result: ProcessIdentity[] = []
|
|
74
|
+
const visit = (entry: ProcessEntry): void => {
|
|
75
|
+
if (visited.has(entry.pid)) return
|
|
76
|
+
visited.add(entry.pid)
|
|
77
|
+
for (const child of byParent.get(entry.pid) ?? []) visit(child)
|
|
78
|
+
const identity = started(entry.pid)
|
|
79
|
+
if (identity !== undefined) result.push({ pid: entry.pid, started: identity })
|
|
80
|
+
}
|
|
81
|
+
visit(root)
|
|
82
|
+
return result
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Windows {@link ProcessInspector}. The shell pid stands in for a foreground
|
|
87
|
+
* process group: it is a stable pseudo-group that lets the prompt-marker
|
|
88
|
+
* readiness path compare foreground identities, while every actual signal
|
|
89
|
+
* targets the console-wide tree through taskkill (SIGINT is delivered by the
|
|
90
|
+
* terminal handle as a `\x03` input write and never reaches this layer).
|
|
91
|
+
*/
|
|
92
|
+
export class WindowsProcessInspector implements ProcessInspector {
|
|
93
|
+
constructor(
|
|
94
|
+
private readonly internals: WindowsProcessInspectorInternals = defaultWindowsProcessInternals(),
|
|
95
|
+
) {}
|
|
96
|
+
|
|
97
|
+
foregroundPgid(shellPid: number): number {
|
|
98
|
+
return shellPid
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
isStdinWaiting(_pgid: number, _shellPid: number): boolean {
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
isAlive(identity: ProcessIdentity): boolean {
|
|
106
|
+
const state = this.internals.processState(identity.pid)
|
|
107
|
+
return state?.active === true && state.started === identity.started
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
snapshot(): ProcessSnapshot {
|
|
111
|
+
// Enumerated on the first question that reads the table. Liveness never
|
|
112
|
+
// does — wait state is a per-handle question here — so the Windows
|
|
113
|
+
// teardown poll, which asks only for liveness, pays no Toolhelp32 walk.
|
|
114
|
+
let entries: ProcessEntry[] | undefined
|
|
115
|
+
return {
|
|
116
|
+
tree: rootPid => windowsProcessTree(
|
|
117
|
+
entries ??= this.internals.snapshot(),
|
|
118
|
+
rootPid,
|
|
119
|
+
pid => this.internals.processState(pid)?.started,
|
|
120
|
+
),
|
|
121
|
+
// Windows has no POSIX sessions; the shell pid stands in as a pseudo group.
|
|
122
|
+
session: () => [],
|
|
123
|
+
alive: identity => this.isAlive(identity),
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
signalGroup(pgid: number, signal: SubprocessTerminalSignal): void {
|
|
128
|
+
this.internals.taskkill(pgid, signal === 'SIGKILL')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void {
|
|
132
|
+
if (this.isAlive(identity)) this.internals.taskkill(identity.pid, signal === 'SIGKILL')
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/* jscpd:ignore-end */
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Create the Windows process inspector.
|
|
139
|
+
* @param internals - injectable process operations; defaults to the koffi-backed table.
|
|
140
|
+
* @returns the Windows inspector.
|
|
141
|
+
*/
|
|
142
|
+
export function createWindowsProcessInspector(
|
|
143
|
+
internals: WindowsProcessInspectorInternals = defaultWindowsProcessInternals(),
|
|
144
|
+
): WindowsProcessInspector {
|
|
145
|
+
return new WindowsProcessInspector(internals)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Terminate one Windows process tree with taskkill, contained like POSIX group signalling. */
|
|
149
|
+
function taskkillTree(pid: number, force: boolean): void {
|
|
150
|
+
if (pid <= 0) return
|
|
151
|
+
// Outcome deliberately unchecked: an already-absent tree, exit races, and a
|
|
152
|
+
// missing taskkill binary are as tolerable here as ESRCH is for POSIX.
|
|
153
|
+
spawnSync('taskkill', ['/PID', String(pid), '/T', ...(force ? ['/F'] : [])], {
|
|
154
|
+
stdio: 'ignore',
|
|
155
|
+
windowsHide: true,
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
declare const nativePtr: unique symbol
|
|
160
|
+
/** Koffi 3 native pointer (a BigInt address), branded so it cannot silently enter numeric contexts. */
|
|
161
|
+
export type NativePtr = bigint & { readonly [nativePtr]: true }
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* True for NULL and INVALID_HANDLE_VALUE returns from Win32 handle APIs.
|
|
165
|
+
* @param value - a handle as koffi may hand it back (pointer, null, or 0n).
|
|
166
|
+
* @returns whether the value signals an invalid handle.
|
|
167
|
+
*/
|
|
168
|
+
export function isInvalidHandle(value: NativePtr | null | undefined): boolean {
|
|
169
|
+
if (value === null || value === undefined) return true
|
|
170
|
+
const asBigInt = value as bigint
|
|
171
|
+
return asBigInt === 0n || asBigInt === 0xFFFFFFFFFFFFFFFFn || asBigInt === -1n
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The lazy koffi binding table: every Win32 call the Windows inspector uses. */
|
|
175
|
+
interface Win32Bindings {
|
|
176
|
+
createToolhelp32Snapshot(flags: number, processId: number): NativePtr
|
|
177
|
+
process32FirstW(snapshot: NativePtr, entry: NativePtr): number
|
|
178
|
+
process32NextW(snapshot: NativePtr, entry: NativePtr): number
|
|
179
|
+
openProcess(desiredAccess: number, inheritHandle: number, pid: number): NativePtr
|
|
180
|
+
getProcessTimes(
|
|
181
|
+
process: NativePtr,
|
|
182
|
+
creation: NativePtr,
|
|
183
|
+
exit: NativePtr,
|
|
184
|
+
kernel: NativePtr,
|
|
185
|
+
user: NativePtr,
|
|
186
|
+
): number
|
|
187
|
+
waitForSingleObject(handle: NativePtr, milliseconds: number): number
|
|
188
|
+
closeHandle(handle: NativePtr): number
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Resolve the koffi Win32 struct types once. Registration is lazy and cached
|
|
193
|
+
* because koffi's type registry is global per process: test runners that
|
|
194
|
+
* re-evaluate this module (a hoisted `vi.mock` re-imports the graph) must not
|
|
195
|
+
* re-register the names.
|
|
196
|
+
*/
|
|
197
|
+
function win32Structs(): { PVOID: KoffiType; PROCESSENTRY32W: ReturnType<Koffi['struct']>; FILETIME: ReturnType<Koffi['struct']> } {
|
|
198
|
+
if (cachedStructs !== undefined) return cachedStructs
|
|
199
|
+
const koffi = requireKoffi()
|
|
200
|
+
const PVOID = koffi.pointer('void')
|
|
201
|
+
// koffi PROCESSENTRY32W layout (tlhelp32.h); the size assert pins the x64 layout.
|
|
202
|
+
const PROCESSENTRY32W = koffi.struct('PROCESSENTRY32W', {
|
|
203
|
+
dwSize: 'uint32',
|
|
204
|
+
cntUsage: 'uint32',
|
|
205
|
+
th32ProcessID: 'uint32',
|
|
206
|
+
th32DefaultHeapID: PVOID,
|
|
207
|
+
th32ModuleID: 'uint32',
|
|
208
|
+
cCntThreads: 'uint32',
|
|
209
|
+
th32ParentProcessID: 'uint32',
|
|
210
|
+
pcPriClassBase: 'int32',
|
|
211
|
+
dwFlags: 'uint32',
|
|
212
|
+
szExeFile: koffi.array('char16', 260),
|
|
213
|
+
})
|
|
214
|
+
// koffi FILETIME layout (minwinbase.h): two 32-bit halves of the 64-bit timestamp.
|
|
215
|
+
const FILETIME = koffi.struct('FILETIME', {
|
|
216
|
+
dwLowDateTime: 'uint32',
|
|
217
|
+
dwHighDateTime: 'uint32',
|
|
218
|
+
})
|
|
219
|
+
/* v8 ignore start -- a layout-mismatch guard fires only on ABI breakage; the windows-native suites exercise the real struct. */
|
|
220
|
+
if (PROCESSENTRY32W.size !== 568) {
|
|
221
|
+
throw new Error(`PROCESSENTRY32W layout mismatch: koffi computed ${PROCESSENTRY32W.size}, Windows headers say 568`)
|
|
222
|
+
}
|
|
223
|
+
/* v8 ignore stop */
|
|
224
|
+
cachedStructs = { PVOID, PROCESSENTRY32W, FILETIME }
|
|
225
|
+
return cachedStructs
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
let cachedStructs: ReturnType<typeof win32Structs> | undefined
|
|
229
|
+
|
|
230
|
+
const TH32CS_SNAPPROCESS = 0x2
|
|
231
|
+
const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
232
|
+
const SYNCHRONIZE = 0x00100000
|
|
233
|
+
const WAIT_OBJECT_0 = 0
|
|
234
|
+
const WAIT_TIMEOUT = 0x102
|
|
235
|
+
|
|
236
|
+
let cachedBindings: Win32Bindings | undefined
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Resolve the lazy Win32 bindings (throws the first binding failure, fail-closed).
|
|
240
|
+
* @returns the cached binding table.
|
|
241
|
+
*/
|
|
242
|
+
function win32Bindings(): Win32Bindings {
|
|
243
|
+
if (cachedBindings !== undefined) return cachedBindings
|
|
244
|
+
const koffi = requireKoffi()
|
|
245
|
+
const { PVOID, PROCESSENTRY32W, FILETIME } = win32Structs()
|
|
246
|
+
const kernel32 = koffi.load('kernel32.dll')
|
|
247
|
+
const bind = (
|
|
248
|
+
name: string,
|
|
249
|
+
result: ReturnType<typeof koffi.pointer> | string,
|
|
250
|
+
args: Array<ReturnType<typeof koffi.pointer> | string>,
|
|
251
|
+
): unknown => kernel32.func('__stdcall', name, result, args)
|
|
252
|
+
cachedBindings = {
|
|
253
|
+
createToolhelp32Snapshot: bind('CreateToolhelp32Snapshot', PVOID, ['uint32', 'uint32']),
|
|
254
|
+
process32FirstW: bind('Process32FirstW', 'int', [PVOID, koffi.pointer(PROCESSENTRY32W)]),
|
|
255
|
+
process32NextW: bind('Process32NextW', 'int', [PVOID, koffi.pointer(PROCESSENTRY32W)]),
|
|
256
|
+
openProcess: bind('OpenProcess', PVOID, ['uint32', 'int', 'uint32']),
|
|
257
|
+
getProcessTimes: bind('GetProcessTimes', 'int', [
|
|
258
|
+
PVOID,
|
|
259
|
+
koffi.pointer(FILETIME),
|
|
260
|
+
koffi.pointer(FILETIME),
|
|
261
|
+
koffi.pointer(FILETIME),
|
|
262
|
+
koffi.pointer(FILETIME),
|
|
263
|
+
]),
|
|
264
|
+
waitForSingleObject: bind('WaitForSingleObject', 'uint32', [PVOID, 'uint32']),
|
|
265
|
+
closeHandle: bind('CloseHandle', 'int', [PVOID]),
|
|
266
|
+
} as Win32Bindings
|
|
267
|
+
return cachedBindings
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Allocate koffi memory as a branded {@link NativePtr}; koffi's TS types are
|
|
272
|
+
* `any`, so the cast goes through `unknown` to keep the unsafe surface here.
|
|
273
|
+
* @param type - the koffi type to allocate.
|
|
274
|
+
* @param count - element count.
|
|
275
|
+
* @returns the branded allocation pointer.
|
|
276
|
+
*/
|
|
277
|
+
function allocNative(type: Parameters<Koffi['alloc']>[0], count: number): NativePtr {
|
|
278
|
+
const koffi = requireKoffi()
|
|
279
|
+
const value: unknown = koffi.alloc(type, count)
|
|
280
|
+
return value as NativePtr
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Enumerate the current process table through Toolhelp32. */
|
|
284
|
+
function snapshotWindowsProcesses(bindings: Win32Bindings): ProcessEntry[] {
|
|
285
|
+
const koffi = requireKoffi()
|
|
286
|
+
const { PROCESSENTRY32W } = win32Structs()
|
|
287
|
+
const snapshot = bindings.createToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
|
|
288
|
+
/* v8 ignore next -- an invalid snapshot for the process flag is not producible through the public API;
|
|
289
|
+
the guard mirrors POSIX's unreadable-proc tolerance and isInvalidHandle is unit-tested. */
|
|
290
|
+
if (isInvalidHandle(snapshot)) return []
|
|
291
|
+
const entries: ProcessEntry[] = []
|
|
292
|
+
try {
|
|
293
|
+
const entry = allocNative(PROCESSENTRY32W, 1)
|
|
294
|
+
koffi.encode(entry, 'uint32', PROCESSENTRY32W.size)
|
|
295
|
+
let ok = bindings.process32FirstW(snapshot, entry)
|
|
296
|
+
while (ok !== 0) {
|
|
297
|
+
const record = koffi.decode(entry, PROCESSENTRY32W) as {
|
|
298
|
+
th32ProcessID: number
|
|
299
|
+
th32ParentProcessID: number
|
|
300
|
+
}
|
|
301
|
+
entries.push({ pid: record.th32ProcessID, parentPid: record.th32ParentProcessID })
|
|
302
|
+
ok = bindings.process32NextW(snapshot, entry)
|
|
303
|
+
}
|
|
304
|
+
} finally {
|
|
305
|
+
bindings.closeHandle(snapshot)
|
|
306
|
+
}
|
|
307
|
+
return entries
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Read one process's creation identity and current wait state. */
|
|
311
|
+
function windowsProcessState(bindings: Win32Bindings, pid: number): WindowsProcessState | undefined {
|
|
312
|
+
const koffi = requireKoffi()
|
|
313
|
+
const { FILETIME } = win32Structs()
|
|
314
|
+
const handle = bindings.openProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid)
|
|
315
|
+
if (isInvalidHandle(handle)) return undefined
|
|
316
|
+
try {
|
|
317
|
+
const creation = allocNative(FILETIME, 1)
|
|
318
|
+
const exit = allocNative(FILETIME, 1)
|
|
319
|
+
const kernel = allocNative(FILETIME, 1)
|
|
320
|
+
const user = allocNative(FILETIME, 1)
|
|
321
|
+
/* v8 ignore next -- a GetProcessTimes failure after a successful open races process exit and
|
|
322
|
+
cannot be staged deterministically; the absent-process path is covered and the caller
|
|
323
|
+
treats undefined as a detector miss. */
|
|
324
|
+
if (bindings.getProcessTimes(handle, creation, exit, kernel, user) === 0) return undefined
|
|
325
|
+
const record = koffi.decode(creation, FILETIME) as { dwLowDateTime: number; dwHighDateTime: number }
|
|
326
|
+
const wait = bindings.waitForSingleObject(handle, 0)
|
|
327
|
+
/* v8 ignore next -- an opened process handle has exactly one of these two
|
|
328
|
+
zero-time wait states; an unexpected Win32 failure is an unreadable process. */
|
|
329
|
+
if (wait !== WAIT_OBJECT_0 && wait !== WAIT_TIMEOUT) return undefined
|
|
330
|
+
return {
|
|
331
|
+
started: `${record.dwHighDateTime}:${record.dwLowDateTime}`,
|
|
332
|
+
active: wait === WAIT_TIMEOUT,
|
|
333
|
+
}
|
|
334
|
+
} finally {
|
|
335
|
+
bindings.closeHandle(handle)
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The koffi-backed default internals; bindings resolve lazily on first use. */
|
|
340
|
+
function defaultWindowsProcessInternals(): WindowsProcessInspectorInternals {
|
|
341
|
+
return {
|
|
342
|
+
snapshot: () => snapshotWindowsProcesses(win32Bindings()),
|
|
343
|
+
processState: pid => windowsProcessState(win32Bindings(), pid),
|
|
344
|
+
taskkill: taskkillTree,
|
|
345
|
+
}
|
|
346
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/** Windows parent-side launch and ownership for the private Job runner. */
|
|
2
|
+
|
|
3
|
+
import { controlPipe } from './control-spawn.ts'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import { closeSync, openSync } from 'node:fs'
|
|
6
|
+
import { devNull } from 'node:os'
|
|
7
|
+
import type { Readable, Writable } from 'node:stream'
|
|
8
|
+
import { SubprocessError } from '@deepseek-ai/dsh-subprocess'
|
|
9
|
+
import type { SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
|
|
10
|
+
import {
|
|
11
|
+
loadWin32ProcessBindings,
|
|
12
|
+
probeCurrentTokenJobSupport,
|
|
13
|
+
} from '@deepseek-ai/dsh-win32-process'
|
|
14
|
+
import type { BoundProcessOwner, ManagedProcessLaunch } from './managed-owner.ts'
|
|
15
|
+
import {
|
|
16
|
+
type SerializedRunnerError,
|
|
17
|
+
type WindowsRunnerResult,
|
|
18
|
+
deserializeRunnerError,
|
|
19
|
+
parseWindowsRunnerResult,
|
|
20
|
+
} from './runner-protocol.ts'
|
|
21
|
+
import {
|
|
22
|
+
runnerEnvironment,
|
|
23
|
+
runnerInvocationAvailable,
|
|
24
|
+
runnerStdio,
|
|
25
|
+
spawnRunnerInvocation,
|
|
26
|
+
WINDOWS_RUNNER_SELECTION,
|
|
27
|
+
} from './runner-launch.ts'
|
|
28
|
+
import type { RunnerInvocation } from './runner-launch.ts'
|
|
29
|
+
|
|
30
|
+
/** Classify a failure on the private runner channel, keeping an already coded failure. */
|
|
31
|
+
function runnerIpcFailure(error: unknown): SubprocessError {
|
|
32
|
+
if (error instanceof SubprocessError) return error
|
|
33
|
+
return new SubprocessError(
|
|
34
|
+
`subprocess-local: Windows runner IPC failed: ${String(error)}`,
|
|
35
|
+
'SUBPROCESS_RUNNER_IPC_FAILED',
|
|
36
|
+
{ cause: error },
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Test seams for runner launch and dynamic capability checks. */
|
|
41
|
+
export interface WindowsJobInternals {
|
|
42
|
+
spawn?: typeof spawn
|
|
43
|
+
runnerInvocation?: RunnerInvocation
|
|
44
|
+
resolveRunnerInvocation?: () => RunnerInvocation
|
|
45
|
+
runnerAvailable?: (invocation: RunnerInvocation) => boolean
|
|
46
|
+
loadWin32ProcessBindings?: typeof loadWin32ProcessBindings
|
|
47
|
+
probeCurrentTokenJobSupport?: typeof probeCurrentTokenJobSupport
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type RunnerProcess = Omit<ReturnType<typeof spawn>, 'send' | 'stdio'> & {
|
|
51
|
+
send?: ReturnType<typeof spawn>['send']
|
|
52
|
+
stdio: Array<Readable | Writable | null>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isWindowsStartCancellationError(error: SerializedRunnerError): boolean {
|
|
56
|
+
return error.name === 'Error'
|
|
57
|
+
&& error.message === 'subprocess target start was cancelled'
|
|
58
|
+
&& error.code === undefined
|
|
59
|
+
&& error.syscall === undefined
|
|
60
|
+
&& error.path === undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Re-check the runner entry, bindings, and current Job capability for every spawn.
|
|
65
|
+
* @param internals - optional runner and Win32 capability seams used by tests.
|
|
66
|
+
* @returns whether the Windows native containment path is currently available.
|
|
67
|
+
*/
|
|
68
|
+
export function probeWindowsJob(internals: WindowsJobInternals = {}): boolean {
|
|
69
|
+
try {
|
|
70
|
+
const invocation = internals.runnerInvocation
|
|
71
|
+
?? (internals.resolveRunnerInvocation ?? spawnRunnerInvocation)()
|
|
72
|
+
if (!(internals.runnerAvailable ?? runnerInvocationAvailable)(invocation)) return false
|
|
73
|
+
const api = (internals.loadWin32ProcessBindings ?? loadWin32ProcessBindings)()
|
|
74
|
+
;(internals.probeCurrentTokenJobSupport ?? probeCurrentTokenJobSupport)(api)
|
|
75
|
+
return true
|
|
76
|
+
} catch {
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
class WindowsJobOwner implements BoundProcessOwner {
|
|
82
|
+
private cancellationReason: unknown
|
|
83
|
+
private cancellationReasonSet = false
|
|
84
|
+
private terminationSent = false
|
|
85
|
+
|
|
86
|
+
constructor(
|
|
87
|
+
private readonly runner: RunnerProcess,
|
|
88
|
+
private readonly exited: Promise<void>,
|
|
89
|
+
private readonly directResultType: () => WindowsRunnerResult['type'] | undefined,
|
|
90
|
+
private readonly failInfrastructure: (error: unknown) => void,
|
|
91
|
+
) {
|
|
92
|
+
void this.exited.catch(() => {})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
signal(_signal: 'SIGTERM' | 'SIGKILL', cancellationReason?: unknown): void {
|
|
96
|
+
if (!this.cancellationReasonSet) {
|
|
97
|
+
this.cancellationReason = cancellationReason
|
|
98
|
+
this.cancellationReasonSet = true
|
|
99
|
+
}
|
|
100
|
+
if (this.terminationSent || !this.runner.connected) return
|
|
101
|
+
this.terminationSent = true
|
|
102
|
+
try {
|
|
103
|
+
this.runner.send?.({ type: 'terminate' }, (error) => {
|
|
104
|
+
if (error === null || this.directResultType() !== undefined) return
|
|
105
|
+
this.failInfrastructure(error)
|
|
106
|
+
this.terminateForHostExit()
|
|
107
|
+
})
|
|
108
|
+
} catch (error) {
|
|
109
|
+
this.failInfrastructure(error)
|
|
110
|
+
this.terminateForHostExit()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
mapStartFailure(failure: unknown, serialized: SerializedRunnerError): unknown {
|
|
115
|
+
return this.cancellationReasonSet && isWindowsStartCancellationError(serialized)
|
|
116
|
+
? this.cancellationReason
|
|
117
|
+
: failure
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async waitForExit(): Promise<void> {
|
|
121
|
+
await this.exited
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
terminateForHostExit(): void {
|
|
125
|
+
try { this.runner.kill('SIGKILL') } catch { /* Host exit continues with other live runners. */ }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Launch one target through a runner that uniquely owns its Job handle.
|
|
131
|
+
* @param spec - ordinary target request.
|
|
132
|
+
* @param targetEnv - validated complete target environment.
|
|
133
|
+
* @param internals - optional runner launch seams used by tests.
|
|
134
|
+
* @returns direct streams, result, and runner-owned managed range.
|
|
135
|
+
*/
|
|
136
|
+
export function launchWindowsJob(
|
|
137
|
+
spec: SubprocessSpawnSpec,
|
|
138
|
+
targetEnv: Record<string, string>,
|
|
139
|
+
internals: WindowsJobInternals = {},
|
|
140
|
+
): ManagedProcessLaunch {
|
|
141
|
+
const invocation = internals.runnerInvocation ?? spawnRunnerInvocation()
|
|
142
|
+
const [command, ...prefix] = invocation
|
|
143
|
+
const ignoredStdinFd = spec.stdio.stdin === 'ignore' ? openSync(devNull, 'r') : undefined
|
|
144
|
+
let child: RunnerProcess
|
|
145
|
+
try {
|
|
146
|
+
child = (internals.spawn ?? spawn)(command, [
|
|
147
|
+
...prefix,
|
|
148
|
+
'--',
|
|
149
|
+
...spec.argv,
|
|
150
|
+
], {
|
|
151
|
+
cwd: process.cwd(),
|
|
152
|
+
windowsHide: true,
|
|
153
|
+
env: runnerEnvironment(WINDOWS_RUNNER_SELECTION, invocation),
|
|
154
|
+
stdio: runnerStdio(spec, true, ignoredStdinFd ?? 'pipe'),
|
|
155
|
+
}) as RunnerProcess
|
|
156
|
+
} finally {
|
|
157
|
+
if (ignoredStdinFd !== undefined) closeSync(ignoredStdinFd)
|
|
158
|
+
}
|
|
159
|
+
const targetStdin = child.stdio[4] as Writable | null
|
|
160
|
+
|
|
161
|
+
const direct = Promise.withResolvers<SubprocessOutcome>()
|
|
162
|
+
const rangeExit = Promise.withResolvers<void>()
|
|
163
|
+
let directResultType: WindowsRunnerResult['type'] | undefined
|
|
164
|
+
let runnerSpawned = false
|
|
165
|
+
let runnerExit: { exitCode: number | null; signal: NodeJS.Signals | null } | undefined
|
|
166
|
+
let ipcDisconnected = false
|
|
167
|
+
const failInfrastructure = (error: unknown): void => {
|
|
168
|
+
direct.reject(error)
|
|
169
|
+
rangeExit.reject(error)
|
|
170
|
+
}
|
|
171
|
+
const settleRange = (): void => {
|
|
172
|
+
if (!runnerSpawned || runnerExit === undefined) return
|
|
173
|
+
const { exitCode, signal } = runnerExit
|
|
174
|
+
if (exitCode === 0 && signal === null) {
|
|
175
|
+
if (directResultType !== undefined) {
|
|
176
|
+
rangeExit.resolve()
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
// The private IPC result may arrive after the process-exit notification.
|
|
180
|
+
if (!ipcDisconnected) return
|
|
181
|
+
}
|
|
182
|
+
const status = signal !== null
|
|
183
|
+
? `signal ${signal}`
|
|
184
|
+
: exitCode === null ? 'without an exit status' : `exit code ${String(exitCode)}`
|
|
185
|
+
failInfrastructure(new SubprocessError(
|
|
186
|
+
`subprocess-local: Windows Job runner exited with ${status} before proving its managed range empty`,
|
|
187
|
+
'SUBPROCESS_RUNNER_FAILED',
|
|
188
|
+
))
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const owner = new WindowsJobOwner(
|
|
192
|
+
child,
|
|
193
|
+
rangeExit.promise,
|
|
194
|
+
() => directResultType,
|
|
195
|
+
failInfrastructure,
|
|
196
|
+
)
|
|
197
|
+
child.on('message', (value: unknown) => {
|
|
198
|
+
if (directResultType !== undefined) {
|
|
199
|
+
const error = new SubprocessError('subprocess-local: Windows runner emitted more than one direct result', 'SUBPROCESS_RUNNER_IPC_FAILED')
|
|
200
|
+
failInfrastructure(error)
|
|
201
|
+
owner.terminateForHostExit()
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
let result: ReturnType<typeof parseWindowsRunnerResult>
|
|
205
|
+
try {
|
|
206
|
+
result = parseWindowsRunnerResult(value)
|
|
207
|
+
} catch (error) {
|
|
208
|
+
failInfrastructure(new SubprocessError(
|
|
209
|
+
`subprocess-local: Windows runner emitted a malformed result: ${String(error)}`,
|
|
210
|
+
'SUBPROCESS_RUNNER_IPC_FAILED',
|
|
211
|
+
{ cause: error },
|
|
212
|
+
))
|
|
213
|
+
owner.terminateForHostExit()
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
directResultType = result.type
|
|
217
|
+
if (result.type === 'target-exit') {
|
|
218
|
+
direct.resolve({ exitCode: result.exitCode, signal: null })
|
|
219
|
+
} else {
|
|
220
|
+
direct.reject(owner.mapStartFailure(deserializeRunnerError(result.error), result.error))
|
|
221
|
+
}
|
|
222
|
+
settleRange()
|
|
223
|
+
})
|
|
224
|
+
child.once('spawn', () => {
|
|
225
|
+
runnerSpawned = true
|
|
226
|
+
try {
|
|
227
|
+
if (child.send === undefined) {
|
|
228
|
+
throw new SubprocessError('subprocess-local: Windows runner has no IPC channel', 'SUBPROCESS_RUNNER_IPC_FAILED')
|
|
229
|
+
}
|
|
230
|
+
child.send({ type: 'start', cwd: spec.cwd, env: targetEnv, ...spec.stdio.control === undefined ? {} : { control: spec.stdio.control } }, (error) => {
|
|
231
|
+
if (error === null) return
|
|
232
|
+
failInfrastructure(runnerIpcFailure(error))
|
|
233
|
+
owner.terminateForHostExit()
|
|
234
|
+
})
|
|
235
|
+
} catch (error) {
|
|
236
|
+
failInfrastructure(runnerIpcFailure(error))
|
|
237
|
+
owner.terminateForHostExit()
|
|
238
|
+
}
|
|
239
|
+
})
|
|
240
|
+
child.once('error', (error) => {
|
|
241
|
+
if (!runnerSpawned) {
|
|
242
|
+
direct.reject(error)
|
|
243
|
+
rangeExit.resolve()
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
failInfrastructure(new SubprocessError(
|
|
247
|
+
`subprocess-local: Windows Job runner failed after it started: ${String(error)}`,
|
|
248
|
+
'SUBPROCESS_RUNNER_FAILED',
|
|
249
|
+
{ cause: error },
|
|
250
|
+
))
|
|
251
|
+
})
|
|
252
|
+
child.once('exit', (exitCode, signal) => {
|
|
253
|
+
runnerExit = { exitCode, signal }
|
|
254
|
+
settleRange()
|
|
255
|
+
})
|
|
256
|
+
child.once('disconnect', () => {
|
|
257
|
+
ipcDisconnected = true
|
|
258
|
+
settleRange()
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
stdin: spec.stdio.stdin === 'ignore' ? null : targetStdin,
|
|
263
|
+
stdout: child.stdio[5] as Readable | null,
|
|
264
|
+
stderr: child.stdio[6] as Readable | null,
|
|
265
|
+
control: controlPipe(child, spec.stdio.control),
|
|
266
|
+
direct: direct.promise,
|
|
267
|
+
owner,
|
|
268
|
+
}
|
|
269
|
+
}
|