@deepseek-ai/dsh-win32-process 0.2.2-rc.1 → 0.2.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/process.ts ADDED
@@ -0,0 +1,641 @@
1
+ /** Typed Win32 process operations over the shared binding table. */
2
+
3
+ import * as abi from './abi.ts'
4
+ import { inheritedControlStdio } from './control-stdio.ts'
5
+ import {
6
+ allocProcessInfo,
7
+ allocPtrSlot,
8
+ allocStartupInfo,
9
+ allocUint32,
10
+ decodeProcessInfo,
11
+ decodePtr,
12
+ decodeUint32,
13
+ encodeStartupInfo,
14
+ isNullPtr,
15
+ throwLastError,
16
+ throwWin32,
17
+ } from './ffi.ts'
18
+ import type { CurrentTokenProcessBindings, NativePtr, Win32ProcessBindings } from './ffi.ts'
19
+ import { requireKoffi } from './koffi.ts'
20
+
21
+ /**
22
+ * Quote one argument according to CommandLineToArgvW parsing.
23
+ * @param argument - one argv entry.
24
+ * @returns bare or quoted command-line segment.
25
+ */
26
+ export function quoteArg(argument: string): string {
27
+ if (argument === '') return '""'
28
+ if (!/[\s"]/u.test(argument)) return argument
29
+ let quoted = '"'
30
+ for (let index = 0; index < argument.length; index++) {
31
+ let backslashes = 0
32
+ while (index < argument.length && argument.charAt(index) === '\\') {
33
+ backslashes += 1
34
+ index += 1
35
+ }
36
+ if (index === argument.length) {
37
+ quoted += '\\'.repeat(backslashes * 2)
38
+ } else if (argument.charAt(index) === '"') {
39
+ quoted += '\\'.repeat(backslashes * 2 + 1) + '"'
40
+ } else {
41
+ quoted += '\\'.repeat(backslashes) + argument.charAt(index)
42
+ }
43
+ }
44
+ return quoted + '"'
45
+ }
46
+
47
+ /**
48
+ * Build the mutable command line accepted by CreateProcessAsUserW.
49
+ * @param program - executable argv entry.
50
+ * @param args - remaining argv entries.
51
+ * @returns joined Win32 command line.
52
+ */
53
+ export function buildCommandLine(program: string, args: readonly string[]): string {
54
+ return [program, ...args].map(quoteArg).join(' ')
55
+ }
56
+
57
+ function compareWindowsEnvironmentKeys(
58
+ [left]: readonly [string, string],
59
+ [right]: readonly [string, string],
60
+ ): number {
61
+ const foldedLeft = left.toUpperCase()
62
+ const foldedRight = right.toUpperCase()
63
+ return foldedLeft < foldedRight ? -1 : foldedLeft > foldedRight ? 1 : 0
64
+ }
65
+
66
+ function encodeWindowsEnvironment(env: Readonly<Record<string, string>>): Buffer {
67
+ const entries = Object.entries(env).sort(compareWindowsEnvironmentKeys)
68
+ const strings = entries.map(([key, value]) => `${key}=${value}`)
69
+ return Buffer.from(`${strings.join('\0')}\0\0`, 'utf16le')
70
+ }
71
+
72
+ interface ProcessSpawnOptions {
73
+ /** Executable argv entry passed through CreateProcess. */
74
+ command: string
75
+ /** Arguments excluding the executable. */
76
+ args: readonly string[]
77
+ /** Existing child working directory. */
78
+ cwd: string
79
+ }
80
+
81
+ /** Ordinary process creation inputs used by the local Win32 runner. */
82
+ export interface CurrentTokenProcessSpawnOptions extends ProcessSpawnOptions {
83
+ /** Resolved executable path passed separately from the preserved argv entry. */
84
+ applicationName: string
85
+ /** Complete target environment passed without mutating the runner. */
86
+ env: Readonly<Record<string, string>>
87
+ /** Runner CRT descriptors carrying target stdin, stdout, and stderr. */
88
+ stdio: CurrentTokenStdioFileDescriptors
89
+ }
90
+
91
+ /** Runner CRT descriptors whose OS handles become the target standard handles. */
92
+ export interface CurrentTokenStdioFileDescriptors {
93
+ stdin: number
94
+ stdout: number
95
+ stderr: number
96
+ /** Optional carrier and target descriptor for the inherited control pipe. */
97
+ control?: 7
98
+ }
99
+
100
+ /** Restricted-token process creation inputs owned by the Windows ACL sandbox. */
101
+ export interface RestrictedProcessSpawnOptions extends ProcessSpawnOptions {
102
+ /** Restricted primary token supplied by sandbox policy. */
103
+ token: NativePtr
104
+ /** Optional control pipe inherited at the same descriptor in the payload. */
105
+ controlFileDescriptor?: 7
106
+ }
107
+
108
+ /** Piped child resources whose process and read handles remain caller-owned. */
109
+ export interface SpawnedPipedProcess {
110
+ /** Direct child process id. */
111
+ pid: number
112
+ /** Process handle closed by waitForProcessExit. */
113
+ process: NativePtr
114
+ /** Stdout pipe read end closed by drainPipe. */
115
+ stdoutRead: NativePtr
116
+ /** Stderr pipe read end closed by drainPipe. */
117
+ stderrRead: NativePtr
118
+ }
119
+
120
+ /** Suspended child assigned to one caller-owned kill-on-close Job before resume. */
121
+ export interface SpawnedJobProcess {
122
+ /** Direct child process id. */
123
+ pid: number
124
+ /** Process handle closed by waitForProcessExit. */
125
+ process: NativePtr
126
+ /** Job handle closed by the lifecycle owner. */
127
+ job: NativePtr
128
+ }
129
+
130
+ interface PipePair {
131
+ read: NativePtr
132
+ write: NativePtr
133
+ }
134
+
135
+ function freeNative(pointer: NativePtr | undefined): void {
136
+ if (pointer !== undefined) requireKoffi().free(pointer)
137
+ }
138
+
139
+ function closeBestEffort(api: Win32ProcessBindings, handle: NativePtr | null | undefined): void {
140
+ if (!isNullPtr(handle)) api.closeHandle(handle)
141
+ }
142
+
143
+ function createPipe(api: Win32ProcessBindings, owned: Set<NativePtr>): PipePair {
144
+ const readSlot = allocPtrSlot()
145
+ let writeSlot: NativePtr | undefined
146
+ try {
147
+ writeSlot = allocPtrSlot()
148
+ if (api.createPipe(readSlot, writeSlot, null, 0) === 0) throwLastError(api, 'CreatePipe')
149
+ const read = decodePtr(readSlot)
150
+ const write = decodePtr(writeSlot)
151
+ if (read === null || write === null) {
152
+ closeBestEffort(api, read)
153
+ closeBestEffort(api, write)
154
+ throwLastError(api, 'CreatePipe', 'null pipe handle')
155
+ }
156
+ owned.add(read)
157
+ owned.add(write)
158
+ return { read, write }
159
+ } finally {
160
+ freeNative(writeSlot)
161
+ requireKoffi().free(readSlot)
162
+ }
163
+ }
164
+
165
+ function closeOwned(api: Win32ProcessBindings, owned: Set<NativePtr>, handle: NativePtr): void {
166
+ /* v8 ignore next -- each successfully decoded pipe end is uniquely owned. */
167
+ if (!owned.delete(handle)) return
168
+ api.closeHandle(handle)
169
+ }
170
+
171
+ function closeAllOwned(api: Win32ProcessBindings, owned: Set<NativePtr>): void {
172
+ for (const handle of owned) api.closeHandle(handle)
173
+ owned.clear()
174
+ }
175
+
176
+ function createRestrictedProcess(
177
+ api: Win32ProcessBindings,
178
+ options: RestrictedProcessSpawnOptions,
179
+ commandLine: string,
180
+ creationFlags: number,
181
+ startupInfo: NativePtr,
182
+ processInfo: NativePtr,
183
+ ): number {
184
+ // The sandbox mutates its process environment before this call. Passing an
185
+ // explicit block through Koffi makes CreateProcessAsUserW reject the request
186
+ // with ERROR_INVALID_PARAMETER, so lpEnvironment remains NULL.
187
+ return api.createProcessAsUserW(
188
+ options.token,
189
+ null,
190
+ commandLine,
191
+ null,
192
+ null,
193
+ 1,
194
+ creationFlags,
195
+ null,
196
+ options.cwd,
197
+ startupInfo,
198
+ processInfo,
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Spawn a process with anonymous-pipe stdout/stderr and immediate stdin EOF.
204
+ * New console windows start hidden without changing console inheritance.
205
+ * @param api - active binding table.
206
+ * @param options - command, cwd, args, and restricted primary token.
207
+ * @returns caller-owned process and pipe read handles.
208
+ */
209
+ export function spawnPipedProcess(
210
+ api: Win32ProcessBindings,
211
+ options: RestrictedProcessSpawnOptions,
212
+ ): SpawnedPipedProcess {
213
+ const owned = new Set<NativePtr>()
214
+ let startupInfo: NativePtr | undefined
215
+ let processInfo: NativePtr | undefined
216
+ try {
217
+ const stdIn = createPipe(api, owned)
218
+ const stdOut = createPipe(api, owned)
219
+ const stdErr = createPipe(api, owned)
220
+ for (const [handle, label] of [
221
+ [stdIn.read, 'stdin read end'],
222
+ [stdOut.write, 'stdout write end'],
223
+ [stdErr.write, 'stderr write end'],
224
+ ] as const) {
225
+ if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
226
+ throwLastError(api, 'SetHandleInformation', label)
227
+ }
228
+ }
229
+ startupInfo = allocStartupInfo()
230
+ encodeStartupInfo(startupInfo, {
231
+ cb: abi.STARTUPINFOW_SIZE,
232
+ dwFlags: abi.STARTF_USESTDHANDLES | abi.STARTF_USESHOWWINDOW,
233
+ wShowWindow: abi.SW_HIDE,
234
+ hStdInput: stdIn.read,
235
+ hStdOutput: stdOut.write,
236
+ hStdError: stdErr.write,
237
+ })
238
+ processInfo = allocProcessInfo()
239
+ const created = createRestrictedProcess(
240
+ api,
241
+ options,
242
+ buildCommandLine(options.command, options.args),
243
+ 0,
244
+ startupInfo,
245
+ processInfo,
246
+ )
247
+ if (created === 0) {
248
+ const win32Code = api.getLastError()
249
+ throwWin32(api, 'CreateProcessAsUserW', win32Code, `command: ${options.command}, cwd: ${options.cwd}`)
250
+ }
251
+ const info = decodeProcessInfo(processInfo)
252
+ if (info.hProcess === null || info.hThread === null) {
253
+ if (info.hProcess !== null) api.terminateProcess(info.hProcess, 1)
254
+ closeBestEffort(api, info.hThread)
255
+ closeBestEffort(api, info.hProcess)
256
+ throw new Error(`CreateProcessAsUserW succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
257
+ }
258
+ closeOwned(api, owned, stdIn.read)
259
+ closeOwned(api, owned, stdIn.write)
260
+ closeOwned(api, owned, stdOut.write)
261
+ closeOwned(api, owned, stdErr.write)
262
+ closeBestEffort(api, info.hThread)
263
+ owned.delete(stdOut.read)
264
+ owned.delete(stdErr.read)
265
+ return {
266
+ pid: info.dwProcessId,
267
+ process: info.hProcess,
268
+ stdoutRead: stdOut.read,
269
+ stderrRead: stdErr.read,
270
+ }
271
+ } catch (error) {
272
+ closeAllOwned(api, owned)
273
+ throw error
274
+ } finally {
275
+ freeNative(processInfo)
276
+ freeNative(startupInfo)
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Drain one anonymous pipe until the writer closes it.
282
+ * @param api - active binding table.
283
+ * @param handle - caller-owned pipe read end.
284
+ * @returns complete bytes read before EOF; the handle is always closed.
285
+ * @throws when a Win32 pipe operation fails.
286
+ */
287
+ export async function drainPipe(
288
+ api: Win32ProcessBindings,
289
+ handle: NativePtr,
290
+ ): Promise<Buffer> {
291
+ const chunks: Buffer[] = []
292
+ let countSlot: NativePtr | undefined
293
+ try {
294
+ countSlot = allocUint32()
295
+ for (;;) {
296
+ const peeked = api.peekNamedPipe(handle, null, 0, null, countSlot, null)
297
+ if (peeked === 0) {
298
+ const win32Code = api.getLastError()
299
+ if (win32Code === abi.ERROR_BROKEN_PIPE || win32Code === abi.ERROR_NO_DATA) break
300
+ throwLastError(api, 'PeekNamedPipe', `drain failure after ${chunks.length} chunk(s)`)
301
+ }
302
+ const available = decodeUint32(countSlot)
303
+ if (available > 0) {
304
+ const chunk = Buffer.alloc(available)
305
+ if (api.readFile(handle, chunk, chunk.length, countSlot, null) === 0) {
306
+ throwLastError(api, 'ReadFile', `drain failure after ${chunks.length} chunk(s)`)
307
+ }
308
+ chunks.push(chunk.subarray(0, decodeUint32(countSlot)))
309
+ }
310
+ await new Promise<void>(resolve => setTimeout(resolve, 1))
311
+ }
312
+ return Buffer.concat(chunks)
313
+ } finally {
314
+ freeNative(countSlot)
315
+ api.closeHandle(handle)
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Wait for a process and always close its handle.
321
+ * @param api - active binding table.
322
+ * @param process - caller-owned process handle.
323
+ * @returns direct process exit code.
324
+ */
325
+ export function waitForProcessExit(api: Win32ProcessBindings, process: NativePtr): number {
326
+ let exitCodeSlot: NativePtr | undefined
327
+ try {
328
+ if (api.waitForSingleObject(process, abi.INFINITE) === 0xFFFFFFFF) {
329
+ throwLastError(api, 'WaitForSingleObject')
330
+ }
331
+ exitCodeSlot = allocUint32()
332
+ if (api.getExitCodeProcess(process, exitCodeSlot) === 0) throwLastError(api, 'GetExitCodeProcess')
333
+ return decodeUint32(exitCodeSlot)
334
+ } finally {
335
+ freeNative(exitCodeSlot)
336
+ api.closeHandle(process)
337
+ }
338
+ }
339
+
340
+ function createKillOnCloseJob(api: Win32ProcessBindings): NativePtr {
341
+ const job = api.createJobObjectW(null, null)
342
+ if (isNullPtr(job)) throwLastError(api, 'CreateJobObjectW')
343
+ const information = Buffer.alloc(abi.JOBOBJECT_EXTENDED_LIMIT_SIZE)
344
+ information.writeUInt32LE(
345
+ abi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
346
+ abi.JOBOBJECT_EXTENDED_LIMIT_FLAGS_OFFSET,
347
+ )
348
+ if (api.setInformationJobObject(
349
+ job,
350
+ abi.JobObjectExtendedLimitInformation,
351
+ information,
352
+ information.length,
353
+ ) === 0) {
354
+ const win32Code = api.getLastError()
355
+ api.closeHandle(job)
356
+ throwWin32(api, 'SetInformationJobObject', win32Code)
357
+ }
358
+ return job
359
+ }
360
+
361
+ interface ProcessStandardHandles {
362
+ stdin: NativePtr
363
+ stdout: NativePtr
364
+ stderr: NativePtr
365
+ control?: { fileDescriptor: 7; handle: NativePtr }
366
+ }
367
+
368
+ // Koffi exposes PVOID as an unsigned 64-bit bigint on supported Windows hosts.
369
+ const UV_INVALID_OS_FILE_HANDLE = 0xffff_ffff_ffff_ffffn
370
+ const UV_INVALID_FILE_DESCRIPTOR = 0xffff_ffff_ffff_fffen
371
+
372
+ function inheritedStandardHandles(api: Win32ProcessBindings, controlFileDescriptor?: 7): ProcessStandardHandles {
373
+ const get = (selector: number, label: string): NativePtr => {
374
+ const handle = api.getStdHandle(selector)
375
+ if (!isNullPtr(handle)) return handle
376
+ throwLastError(api, 'GetStdHandle', `null ${label} handle`)
377
+ }
378
+ return {
379
+ stdin: get(abi.STD_INPUT_HANDLE, 'stdin'),
380
+ stdout: get(abi.STD_OUTPUT_HANDLE, 'stdout'),
381
+ stderr: get(abi.STD_ERROR_HANDLE, 'stderr'),
382
+ ...controlFileDescriptor === undefined ? {} : {
383
+ control: { fileDescriptor: controlFileDescriptor, handle: descriptorHandle(api, controlFileDescriptor, 'control') },
384
+ },
385
+ }
386
+ }
387
+
388
+ function descriptorHandle(api: Win32ProcessBindings, fileDescriptor: number, label: string): NativePtr {
389
+ const handle = api.uvGetOsfhandle(fileDescriptor)
390
+ if (
391
+ isNullPtr(handle)
392
+ || handle === UV_INVALID_OS_FILE_HANDLE
393
+ || handle === UV_INVALID_FILE_DESCRIPTOR
394
+ ) {
395
+ throw new Error(`uv_get_osfhandle returned an invalid handle for target ${label} fd ${String(fileDescriptor)}`)
396
+ }
397
+ return handle
398
+ }
399
+
400
+ function targetCarrierHandles(
401
+ api: CurrentTokenProcessBindings,
402
+ descriptors: CurrentTokenStdioFileDescriptors,
403
+ ): ProcessStandardHandles {
404
+ return {
405
+ stdin: descriptorHandle(api, descriptors.stdin, 'stdin'),
406
+ stdout: descriptorHandle(api, descriptors.stdout, 'stdout'),
407
+ stderr: descriptorHandle(api, descriptors.stderr, 'stderr'),
408
+ ...descriptors.control === undefined ? {} : {
409
+ control: { fileDescriptor: descriptors.control, handle: descriptorHandle(api, descriptors.control, 'control') },
410
+ },
411
+ }
412
+ }
413
+
414
+ /** Shared suspended-create, Job-assignment, and resume lifecycle. */
415
+ function spawnJobProcess(
416
+ api: Win32ProcessBindings,
417
+ options: ProcessSpawnOptions,
418
+ resolveStdio: () => ProcessStandardHandles,
419
+ createName: 'CreateProcessAsUserW' | 'CreateProcessW',
420
+ create: (startupInfo: NativePtr, processInfo: NativePtr) => number,
421
+ ): SpawnedJobProcess {
422
+ const job = createKillOnCloseJob(api)
423
+ const enabled: NativePtr[] = []
424
+ let startupInfo: NativePtr | undefined
425
+ let processInfo: NativePtr | undefined
426
+ let controlDescriptorBlock: { pointer: NativePtr; length: number } | undefined
427
+ let created = 0
428
+ let createFailureCode = 0
429
+ try {
430
+ const stdio = resolveStdio()
431
+ const inherited: Array<readonly [NativePtr, string]> = [
432
+ [stdio.stdin, 'stdin'],
433
+ [stdio.stdout, 'stdout'],
434
+ [stdio.stderr, 'stderr'],
435
+ ]
436
+ if (stdio.control !== undefined) inherited.push([stdio.control.handle, 'control'])
437
+ for (const [handle, label] of inherited) {
438
+ if (api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, abi.HANDLE_FLAG_INHERIT) === 0) {
439
+ throwLastError(api, 'SetHandleInformation', `${label} (enable inherit)`)
440
+ }
441
+ enabled.push(handle)
442
+ }
443
+ const controlBytes = stdio.control === undefined
444
+ ? undefined
445
+ : inheritedControlStdio(api, { ...stdio, control: stdio.control })
446
+ if (controlBytes !== undefined) {
447
+ const koffi = requireKoffi()
448
+ controlDescriptorBlock = { pointer: koffi.alloc('uint8', controlBytes.length) as NativePtr, length: controlBytes.length }
449
+ koffi.encode(controlDescriptorBlock.pointer, 'uint8', controlBytes, controlBytes.length)
450
+ }
451
+ startupInfo = allocStartupInfo()
452
+ encodeStartupInfo(startupInfo, {
453
+ cb: abi.STARTUPINFOW_SIZE,
454
+ // Preserve console inheritance: CREATE_NO_WINDOW can fail restricted-token DLL initialization.
455
+ dwFlags: abi.STARTF_USESTDHANDLES | abi.STARTF_USESHOWWINDOW,
456
+ wShowWindow: abi.SW_HIDE,
457
+ hStdInput: stdio.stdin,
458
+ hStdOutput: stdio.stdout,
459
+ hStdError: stdio.stderr,
460
+ ...controlDescriptorBlock === undefined ? {} : {
461
+ cbReserved2: controlDescriptorBlock.length,
462
+ lpReserved2: controlDescriptorBlock.pointer,
463
+ },
464
+ })
465
+ processInfo = allocProcessInfo()
466
+ created = create(startupInfo, processInfo)
467
+ if (created === 0) createFailureCode = api.getLastError()
468
+ } catch (error) {
469
+ freeNative(processInfo)
470
+ api.closeHandle(job)
471
+ throw error
472
+ } finally {
473
+ freeNative(startupInfo)
474
+ freeNative(controlDescriptorBlock?.pointer)
475
+ for (const handle of enabled) {
476
+ // The runner spawns nothing else; cleanup failure must not mask the child.
477
+ api.setHandleInformation(handle, abi.HANDLE_FLAG_INHERIT, 0)
478
+ }
479
+ }
480
+ if (created === 0) {
481
+ freeNative(processInfo)
482
+ api.closeHandle(job)
483
+ throwWin32(
484
+ api,
485
+ createName,
486
+ createFailureCode,
487
+ `command: ${options.command}, cwd: ${options.cwd}`,
488
+ )
489
+ }
490
+ let info: ReturnType<typeof decodeProcessInfo>
491
+ try {
492
+ info = decodeProcessInfo(processInfo)
493
+ } finally {
494
+ freeNative(processInfo)
495
+ }
496
+ if (info.hProcess === null || info.hThread === null) {
497
+ if (info.hProcess !== null) api.terminateProcess(info.hProcess, 1)
498
+ api.closeHandle(job)
499
+ closeBestEffort(api, info.hThread)
500
+ closeBestEffort(api, info.hProcess)
501
+ throw new Error(`${createName} succeeded but returned null process/thread handles (pid ${info.dwProcessId})`)
502
+ }
503
+ if (api.assignProcessToJobObject(job, info.hProcess) === 0) {
504
+ const win32Code = api.getLastError()
505
+ api.terminateProcess(info.hProcess, 1)
506
+ closeBestEffort(api, info.hThread)
507
+ closeBestEffort(api, info.hProcess)
508
+ api.closeHandle(job)
509
+ throwWin32(api, 'AssignProcessToJobObject', win32Code, `pid ${info.dwProcessId}`)
510
+ }
511
+ if (api.resumeThread(info.hThread) === 0xFFFFFFFF) {
512
+ const win32Code = api.getLastError()
513
+ closeBestEffort(api, info.hThread)
514
+ closeBestEffort(api, info.hProcess)
515
+ api.closeHandle(job)
516
+ throwWin32(api, 'ResumeThread', win32Code, `pid ${info.dwProcessId}`)
517
+ }
518
+ closeBestEffort(api, info.hThread)
519
+ return { pid: info.dwProcessId, process: info.hProcess, job }
520
+ }
521
+
522
+ /**
523
+ * Spawn a restricted-token process suspended with hidden initial windows, assign its Job, then resume it.
524
+ * @param api - active binding table.
525
+ * @param options - command, cwd, args, and restricted primary token.
526
+ * @returns caller-owned process and Job handles after successful resume.
527
+ * @remarks Node clears stdio handle inheritability at startup through
528
+ * uv_disable_stdio_inheritance. This operation temporarily restores the bits
529
+ * required by STARTF_USESTDHANDLES. Restoring them afterward is best-effort:
530
+ * failure must not replace the already-created child's outcome.
531
+ */
532
+ export function spawnInheritedJobProcess(
533
+ api: Win32ProcessBindings,
534
+ options: RestrictedProcessSpawnOptions,
535
+ ): SpawnedJobProcess {
536
+ const commandLine = buildCommandLine(options.command, options.args)
537
+ return spawnJobProcess(api, options, () => inheritedStandardHandles(api, options.controlFileDescriptor), 'CreateProcessAsUserW', (startupInfo, processInfo) =>
538
+ createRestrictedProcess(
539
+ api,
540
+ options,
541
+ commandLine,
542
+ abi.CREATE_SUSPENDED,
543
+ startupInfo,
544
+ processInfo,
545
+ ))
546
+ }
547
+
548
+ /**
549
+ * Spawn an ordinary process suspended with hidden initial windows, assign its Job, then resume it.
550
+ * @param api - active binding table.
551
+ * @param options - command, cwd, argv, and target carrier descriptors.
552
+ * @returns caller-owned process and Job handles after successful resume.
553
+ */
554
+ export function spawnCurrentTokenJobProcess(
555
+ api: CurrentTokenProcessBindings,
556
+ options: CurrentTokenProcessSpawnOptions,
557
+ ): SpawnedJobProcess {
558
+ const commandLine = buildCommandLine(options.command, options.args)
559
+ const environment = encodeWindowsEnvironment(options.env)
560
+ return spawnJobProcess(api, options, () => targetCarrierHandles(api, options.stdio), 'CreateProcessW', (startupInfo, processInfo) =>
561
+ api.createProcessW(
562
+ options.applicationName,
563
+ commandLine,
564
+ null,
565
+ null,
566
+ 1,
567
+ abi.CREATE_SUSPENDED | abi.CREATE_UNICODE_ENVIRONMENT,
568
+ environment,
569
+ options.cwd,
570
+ startupInfo,
571
+ processInfo,
572
+ ))
573
+ }
574
+
575
+ /**
576
+ * Verify that an unnamed kill-on-close Job can be created and released now.
577
+ * @param api - active binding table.
578
+ */
579
+ export function probeCurrentTokenJobSupport(api: CurrentTokenProcessBindings): void {
580
+ const job = createKillOnCloseJob(api)
581
+ closeHandleChecked(api, job, 'current-token Job capability probe')
582
+ }
583
+
584
+ /**
585
+ * Poll one process handle without blocking the runner event loop.
586
+ * @param api - active binding table.
587
+ * @param process - caller-owned process handle.
588
+ * @returns the direct exit code when signalled, or undefined while running.
589
+ */
590
+ export function pollProcessExit(api: Win32ProcessBindings, process: NativePtr): number | undefined {
591
+ const waitResult = api.waitForSingleObject(process, 0)
592
+ if (waitResult === abi.WAIT_TIMEOUT) return undefined
593
+ if (waitResult === 0xFFFFFFFF) throwLastError(api, 'WaitForSingleObject')
594
+ const exitCodeSlot = allocUint32()
595
+ try {
596
+ if (api.getExitCodeProcess(process, exitCodeSlot) === 0) throwLastError(api, 'GetExitCodeProcess')
597
+ return decodeUint32(exitCodeSlot)
598
+ } finally {
599
+ requireKoffi().free(exitCodeSlot)
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Return whether a Job has no active processes.
605
+ * @param api - active binding table.
606
+ * @param job - caller-owned Job handle.
607
+ * @returns true once the Job reports zero active processes.
608
+ */
609
+ export function isJobEmpty(api: Win32ProcessBindings, job: NativePtr): boolean {
610
+ const information = Buffer.alloc(abi.JOBOBJECT_BASIC_ACCOUNTING_SIZE)
611
+ if (api.queryInformationJobObject(
612
+ job,
613
+ abi.JobObjectBasicAccountingInformation,
614
+ information,
615
+ information.length,
616
+ null,
617
+ ) === 0) {
618
+ throwLastError(api, 'QueryInformationJobObject', 'active process count')
619
+ }
620
+ return information.readUInt32LE(abi.JOBOBJECT_BASIC_ACCOUNTING_ACTIVE_PROCESSES_OFFSET) === 0
621
+ }
622
+
623
+ /**
624
+ * Terminate every process in a Job.
625
+ * @param api - active binding table.
626
+ * @param job - caller-owned Job handle.
627
+ * @param exitCode - direct Windows exit code assigned to members.
628
+ */
629
+ export function terminateJob(api: Win32ProcessBindings, job: NativePtr, exitCode: number): void {
630
+ if (api.terminateJobObject(job, exitCode) === 0) throwLastError(api, 'TerminateJobObject')
631
+ }
632
+
633
+ /**
634
+ * Close a caller-owned handle and report a labelled Win32 failure.
635
+ * @param api - active binding table.
636
+ * @param handle - handle to close.
637
+ * @param detail - lifecycle label for diagnostics.
638
+ */
639
+ export function closeHandleChecked(api: Win32ProcessBindings, handle: NativePtr, detail: string): void {
640
+ if (api.closeHandle(handle) === 0) throwLastError(api, 'CloseHandle', detail)
641
+ }