@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.
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 +12 -9
  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,726 @@
1
+ /** Linux user-systemd scope launch and managed-range ownership. */
2
+
3
+ import { controlPipe } from './control-spawn.ts'
4
+ import { execFile, spawn, spawnSync } from 'node:child_process'
5
+ import { randomBytes } from 'node:crypto'
6
+ import { existsSync, readFileSync, statSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { setTimeout as sleepMs } from 'node:timers/promises'
9
+ import type {
10
+ SubprocessOutcome,
11
+ SubprocessSpawnSpec,
12
+ SubprocessTerminalSpawnSpec,
13
+ } from '@deepseek-ai/dsh-subprocess'
14
+ import { loadLinuxExecve } from './linux-execve.ts'
15
+ import type { BoundProcessOwner, ManagedProcessLaunch } from './managed-owner.ts'
16
+ import {
17
+ cleanupLinuxLaunchFiles,
18
+ createLinuxLaunchFiles,
19
+ deserializeRunnerError,
20
+ readLinuxStartupError,
21
+ } from './runner-protocol.ts'
22
+ import type { LinuxLaunchFiles } from './runner-protocol.ts'
23
+ import {
24
+ runnerEnvironment,
25
+ runnerInvocationAvailable,
26
+ runnerStdio,
27
+ spawnRunnerInvocation,
28
+ } from './runner-launch.ts'
29
+ import type { RunnerInvocation } from './runner-launch.ts'
30
+ import { childEnv } from './spawn.ts'
31
+
32
+ /** Test seams for systemd command execution. */
33
+ export interface LinuxScopeInternals {
34
+ spawn?: typeof spawn
35
+ spawnSync?: typeof spawnSync
36
+ systemctlQuery?: (command: string, args: readonly string[]) => Promise<SystemctlResult>
37
+ systemdRun?: string
38
+ systemctl?: string
39
+ runnerInvocation?: RunnerInvocation
40
+ resolveRunnerInvocation?: () => RunnerInvocation
41
+ runnerAvailable?: (invocation: RunnerInvocation) => boolean
42
+ loadLinuxExecve?: typeof loadLinuxExecve
43
+ sleep?: (delayMs: number, signal?: AbortSignal) => Promise<void>
44
+ /** Kernel unix socket table read by the user-manager confirmation; defaults to /proc/net/unix. */
45
+ unixSocketTable?: string
46
+ }
47
+
48
+ interface SystemctlResult {
49
+ status: number | null
50
+ stdout: string
51
+ stderr: string
52
+ error?: Error
53
+ }
54
+
55
+ const SYSTEMCTL_TIMEOUT_MS = 5_000
56
+ const SCOPE_INITIAL_POLL_INTERVAL_MS = 50
57
+ const MISSING_UNIT = /\bunit\b[^\r\n]*(?:could not be found|not found|not loaded)/iu
58
+ const LITERAL_ARGV_OPTION = '--expand-environment=no'
59
+ // systemd-run before v254 rejects the option; its scope mode passes argv to execvpe unexpanded.
60
+ const LITERAL_ARGV_OPTION_REJECTED = /unrecognized option\b.*expand-environment/u
61
+ // The spelling before systemctl v252 and an unambiguous prefix of the later `--kill-whom`.
62
+ const KILL_ALL_MEMBERS = '--kill-who=all'
63
+ /** Flags bit that /proc/net/unix sets on a listening socket (__SO_ACCEPTCON). */
64
+ const UNIX_SOCKET_ACCEPTING = 0x10000
65
+
66
+ /** systemd-run options that keep target argv literal; empty where scope mode never expands argv. */
67
+ export type LiteralArgvOptions = readonly string[]
68
+
69
+ function managerEnvironment(): NodeJS.ProcessEnv {
70
+ const environment = childEnv({ LC_ALL: 'C' })
71
+ delete environment.SYSTEMD_LOG_TARGET
72
+ return environment
73
+ }
74
+
75
+ function quietSystemdEnvironment(): NodeJS.ProcessEnv {
76
+ return childEnv({ LC_ALL: 'C', SYSTEMD_LOG_TARGET: 'null' })
77
+ }
78
+
79
+ function querySystemctl(command: string, args: readonly string[]): Promise<SystemctlResult> {
80
+ return new Promise((resolveResult) => {
81
+ execFile(command, [...args], {
82
+ encoding: 'utf8',
83
+ env: managerEnvironment(),
84
+ timeout: SYSTEMCTL_TIMEOUT_MS,
85
+ }, (error, stdout, stderr) => {
86
+ const code = error === null ? 0 : (error as Error & { code?: string | number }).code
87
+ resolveResult({
88
+ status: typeof code === 'number' ? code : null,
89
+ stdout,
90
+ stderr,
91
+ ...error === null ? {} : { error },
92
+ })
93
+ })
94
+ })
95
+ }
96
+
97
+ function unitStem(prefix: string): string {
98
+ return `${prefix}-${String(process.pid)}-${randomBytes(6).toString('hex')}`
99
+ }
100
+
101
+ function sleepWithAbort(delayMs: number, signal?: AbortSignal): Promise<void> {
102
+ return sleepMs(delayMs, undefined, { signal })
103
+ }
104
+
105
+ /**
106
+ * Confirm this exact runner entry and libc execve binding without a probe mode.
107
+ * @param internals - optional runner and libc-binding seams used by tests.
108
+ * @returns whether the bootstrap can enter the final target.
109
+ */
110
+ export function probeLinuxBootstrap(internals: LinuxScopeInternals = {}): boolean {
111
+ try {
112
+ ;(internals.loadLinuxExecve ?? loadLinuxExecve)()
113
+ const invocation = internals.runnerInvocation
114
+ ?? (internals.resolveRunnerInvocation ?? spawnRunnerInvocation)()
115
+ return (internals.runnerAvailable ?? runnerInvocationAvailable)(invocation)
116
+ } catch {
117
+ return false
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Confirm current literal-argv transient-scope support before selecting native launch.
123
+ * @param internals - optional systemd command seams used by tests.
124
+ * @returns the options that keep target argv literal, or undefined when the user manager cannot create the scope.
125
+ */
126
+ export function probeLinuxScope(internals: LinuxScopeInternals = {}): LiteralArgvOptions | undefined {
127
+ const attempt = (literalArgv: LiteralArgvOptions): { created: boolean; stderr: string } => {
128
+ const unitBase = unitStem('dsh-subprocess-probe')
129
+ const result = (internals.spawnSync ?? spawnSync)(internals.systemdRun ?? 'systemd-run', [
130
+ '--user',
131
+ '--scope',
132
+ '--quiet',
133
+ '--collect',
134
+ ...literalArgv,
135
+ `--unit=${unitBase}`,
136
+ '--',
137
+ internals.systemctl ?? 'systemctl',
138
+ '--user',
139
+ 'show',
140
+ `${unitBase}.scope`,
141
+ '--property=ActiveState',
142
+ '--value',
143
+ ], {
144
+ encoding: 'utf8',
145
+ env: quietSystemdEnvironment(),
146
+ stdio: ['ignore', 'ignore', 'pipe'],
147
+ timeout: SYSTEMCTL_TIMEOUT_MS,
148
+ })
149
+ return { created: result.error === undefined && result.status === 0, stderr: result.stderr }
150
+ }
151
+ const current = attempt([LITERAL_ARGV_OPTION])
152
+ if (current.created) return [LITERAL_ARGV_OPTION]
153
+ if (!LITERAL_ARGV_OPTION_REJECTED.test(current.stderr)) return undefined
154
+ return attempt([]).created ? [] : undefined
155
+ }
156
+
157
+ /**
158
+ * Check every Linux native prerequisite on each call.
159
+ * @param internals - optional native capability seams used by tests.
160
+ * @returns the literal-argv scope options when Linux native containment is available, otherwise undefined.
161
+ */
162
+ export function probeLinuxNative(internals: LinuxScopeInternals = {}): LiteralArgvOptions | undefined {
163
+ return probeLinuxBootstrap(internals) ? probeLinuxScope(internals) : undefined
164
+ }
165
+
166
+ /**
167
+ * Query the user manager once through systemctl.
168
+ * @param internals - optional systemctl seam used by tests.
169
+ * @returns whether the query succeeds.
170
+ */
171
+ export function probeLinuxManager(internals: LinuxScopeInternals = {}): boolean {
172
+ const result = (internals.spawnSync ?? spawnSync)(internals.systemctl ?? 'systemctl', [
173
+ '--user',
174
+ 'show',
175
+ '--property=Version',
176
+ '--value',
177
+ ], { env: managerEnvironment(), stdio: 'ignore', timeout: SYSTEMCTL_TIMEOUT_MS })
178
+ return result.error === undefined && result.status === 0
179
+ }
180
+
181
+ /**
182
+ * Find the socket a process in this network namespace listens on at path. The kernel lists a
183
+ * bound socket only while a process holds it open, so a socket file that a stopped or crashed
184
+ * listener left behind does not count.
185
+ */
186
+ function unixSocketListener(path: string, table: string): string | undefined {
187
+ let text: string
188
+ try {
189
+ text = readFileSync(table, 'utf8')
190
+ } catch (_unreadableSocketTable) {
191
+ // Without the socket table nothing is known, so callers fall back to systemctl or keep their verdict.
192
+ return undefined
193
+ }
194
+ const suffix = ` ${path}`
195
+ for (const line of text.split('\n')) {
196
+ if (!line.endsWith(suffix)) continue
197
+ const fields = line.trim().split(/\s+/u)
198
+ if (fields.slice(7).join(' ') === path && (Number.parseInt(String(fields[3]), 16) & UNIX_SOCKET_ACCEPTING) !== 0) {
199
+ return String(fields[6])
200
+ }
201
+ }
202
+ return undefined
203
+ }
204
+
205
+ /**
206
+ * Identify the user manager's listener on `$XDG_RUNTIME_DIR/systemd/private`, the socket
207
+ * `systemd-run --user` connects through.
208
+ * @param internals - optional socket-table seam used by tests.
209
+ * @returns the listening socket's inode from the kernel socket table, or undefined when
210
+ * XDG_RUNTIME_DIR is unset or nothing in this network namespace listens there.
211
+ */
212
+ export function linuxManagerListener(internals: LinuxScopeInternals = {}): string | undefined {
213
+ const runtimeDirectory = childEnv().XDG_RUNTIME_DIR
214
+ if (runtimeDirectory === undefined || runtimeDirectory === '') return undefined
215
+ return unixSocketListener(join(runtimeDirectory, 'systemd', 'private'), internals.unixSocketTable ?? '/proc/net/unix')
216
+ }
217
+
218
+ /**
219
+ * Identify the systemd-run binary that scope launches resolve through PATH, so a package upgrade
220
+ * that replaces it triggers another probe of its literal-argv options.
221
+ * @param internals - optional systemd-run seam used by tests.
222
+ * @returns the device, inode, size, and modification time of the first match, or undefined when none resolves.
223
+ */
224
+ export function systemdRunIdentity(internals: LinuxScopeInternals = {}): string | undefined {
225
+ const command = internals.systemdRun ?? 'systemd-run'
226
+ const candidates = command.includes('/')
227
+ ? [command]
228
+ : (childEnv().PATH ?? '').split(':').filter(directory => directory !== '').map(directory => join(directory, command))
229
+ for (const candidate of candidates) {
230
+ let stats: ReturnType<typeof statSync>
231
+ try {
232
+ stats = statSync(candidate, { throwIfNoEntry: false })
233
+ } catch (_unreadableCandidate) {
234
+ // A PATH entry that is not a searchable directory cannot hold systemd-run.
235
+ continue
236
+ }
237
+ if (stats?.isFile() === true) return `${String(stats.dev)}:${String(stats.ino)}:${String(stats.size)}:${String(stats.mtimeMs)}`
238
+ }
239
+ return undefined
240
+ }
241
+
242
+ /**
243
+ * Confirm the user manager before a scope launch. A listener on its private socket confirms it
244
+ * without a child process; otherwise one systemctl query decides. A hung manager that still
245
+ * listens passes, and its scope launch fails with LinuxScopeNotStartedError.
246
+ * @param internals - optional socket-table and systemctl seams used by tests.
247
+ * @returns whether a scope launch can reach the user manager.
248
+ */
249
+ export function confirmLinuxManager(internals: LinuxScopeInternals = {}): boolean {
250
+ return linuxManagerListener(internals) !== undefined || probeLinuxManager(internals)
251
+ }
252
+
253
+ interface DirectRange {
254
+ running(): boolean
255
+ /** True for group TERM delivery, direct signal submission, or proven direct-PID absence. */
256
+ signal(signal: 'SIGTERM' | 'SIGKILL'): boolean
257
+ /** Direct exit/error settlement, independent of output drain and managed-range completion. */
258
+ settled: Promise<unknown>
259
+ }
260
+
261
+ /** A scope launch whose bootstrap never consumed its launch request, so its target never ran. */
262
+ export class LinuxScopeNotStartedError extends Error {
263
+ override readonly name = 'LinuxScopeNotStartedError'
264
+ }
265
+
266
+ class LinuxScopeStartup {
267
+ readonly terminationSignals = new Set<NodeJS.Signals>()
268
+
269
+ constructor(readonly files: LinuxLaunchFiles, private readonly kind: 'subprocess' | 'terminal') {}
270
+
271
+ resolveOutcome(outcome: SubprocessOutcome): SubprocessOutcome {
272
+ const startup = readLinuxStartupError(this.files.startupErrorPath)
273
+ if (startup !== undefined) throw deserializeRunnerError(startup.error)
274
+ if (existsSync(this.files.requestPath)
275
+ && !(outcome.signal !== null && this.terminationSignals.has(outcome.signal))) {
276
+ throw new LinuxScopeNotStartedError(
277
+ `${this.kind} scope exited before its bootstrap consumed the launch request; the provider probes native containment again before its next command`,
278
+ )
279
+ }
280
+ return outcome
281
+ }
282
+ }
283
+
284
+ class SystemdScopeOwner implements BoundProcessOwner {
285
+ private establishment: 'pending' | 'established' = 'pending'
286
+ private stopped = false
287
+ private terminationRequested = false
288
+ private observation: Promise<void> | undefined
289
+ private killFailure: Error | undefined
290
+ private directKillSettlement: Promise<void> | undefined
291
+ private wakeGeneration = 0
292
+ private wakeWaiter: { generation: number; resolve: () => void } | undefined
293
+
294
+ constructor(
295
+ private readonly unit: string,
296
+ private readonly startup: LinuxScopeStartup,
297
+ private readonly direct: DirectRange,
298
+ private readonly systemctl: string,
299
+ private readonly runSync: typeof spawnSync,
300
+ private readonly query: (command: string, args: readonly string[]) => Promise<SystemctlResult>,
301
+ private readonly sleep: (delayMs: number, signal?: AbortSignal) => Promise<void>,
302
+ ) {}
303
+
304
+ inspectTaskCount(): number | undefined {
305
+ const result = this.runSync(this.systemctl, [
306
+ '--user', 'show', '--property=LoadState', '--property=ActiveState', '--property=TasksCurrent', this.unit,
307
+ ], { encoding: 'utf8', env: managerEnvironment(), timeout: SYSTEMCTL_TIMEOUT_MS })
308
+ if (result.error !== undefined || result.status !== 0 || typeof result.stdout !== 'string') return undefined
309
+ const state = this.parseUnitState(result.stdout)
310
+ return state.loadState === 'loaded' && state.activeState === 'active' ? state.tasksCurrent : undefined
311
+ }
312
+
313
+ signal(signal: 'SIGTERM' | 'SIGKILL'): void {
314
+ if (this.stopped) return
315
+ this.terminationRequested = true
316
+ if (this.direct.running()) this.startup.terminationSignals.add(signal)
317
+ this.observeRequestConsumption()
318
+ const directFallbackRequired = this.establishment === 'pending'
319
+ let directSignalled = false
320
+ if (directFallbackRequired && this.direct.running()) directSignalled = this.direct.signal(signal)
321
+ const result = this.runSync(this.systemctl, [
322
+ '--user',
323
+ 'kill',
324
+ KILL_ALL_MEMBERS,
325
+ `--signal=${signal}`,
326
+ this.unit,
327
+ ], { encoding: 'utf8', env: managerEnvironment(), timeout: SYSTEMCTL_TIMEOUT_MS })
328
+ this.wakeObservation()
329
+ if (result.error === undefined && result.status === 0) {
330
+ if (signal === 'SIGKILL') {
331
+ this.killFailure = undefined
332
+ this.directKillSettlement = undefined
333
+ }
334
+ return
335
+ }
336
+ if (!directFallbackRequired && this.direct.running()) directSignalled = this.direct.signal(signal)
337
+ if (signal === 'SIGKILL') {
338
+ const output = `${result.stdout}\n${result.stderr}`
339
+ if (!MISSING_UNIT.test(output)) {
340
+ this.killFailure = result.error ?? new Error(
341
+ `systemctl could not signal ${this.unit}: ${output.trim() || `exit ${String(result.status)}`}`,
342
+ )
343
+ // The direct outcome retains errors; this barrier only joins its physical settlement.
344
+ this.directKillSettlement = directSignalled
345
+ ? this.direct.settled.then(() => {}, () => {})
346
+ : undefined
347
+ }
348
+ }
349
+ }
350
+
351
+ terminateForHostExit(): void {
352
+ if (this.stopped) return
353
+ try {
354
+ if (this.direct.running()) this.direct.signal('SIGKILL')
355
+ } catch { /* Continue with the native owner. */ }
356
+ try {
357
+ this.runSync(this.systemctl, [
358
+ '--user',
359
+ 'kill',
360
+ KILL_ALL_MEMBERS,
361
+ '--signal=SIGKILL',
362
+ this.unit,
363
+ ], { env: managerEnvironment(), stdio: 'ignore', timeout: SYSTEMCTL_TIMEOUT_MS })
364
+ } catch {
365
+ // Host exit cannot report one range; the runtime continues with the rest.
366
+ }
367
+ }
368
+
369
+ private observeRequestConsumption(): void {
370
+ if (this.establishment === 'pending' && !existsSync(this.startup.files.requestPath)) {
371
+ this.establishment = 'established'
372
+ }
373
+ }
374
+
375
+ private absentUnit(): boolean {
376
+ this.observeRequestConsumption()
377
+ if (this.establishment === 'established') return false
378
+ if (!this.direct.running() && existsSync(this.startup.files.requestPath)) {
379
+ return false
380
+ }
381
+ if (this.killFailure !== undefined) throw this.killFailure
382
+ return true
383
+ }
384
+
385
+ /**
386
+ * Prove an active unit with no processes is the empty managed range rather
387
+ * than a launch still placing its payload. systemd ends a scope only on the
388
+ * populated-to-empty transition, so a payload killed before it entered the
389
+ * cgroup leaves the unit active forever. A departed client cannot add another
390
+ * payload; a consumed request proves the payload already entered the scope,
391
+ * even while its direct-process exit notification is pending.
392
+ */
393
+ private emptyRange(tasksCurrent: number | undefined): boolean {
394
+ return this.terminationRequested && tasksCurrent === 0
395
+ && (!this.direct.running() || !existsSync(this.startup.files.requestPath))
396
+ }
397
+
398
+ /** Release a leftover empty scope so the transient unit is collected and cannot accumulate. */
399
+ private releaseEmptyRange(): void {
400
+ try {
401
+ this.runSync(this.systemctl, ['--user', 'stop', this.unit], {
402
+ env: managerEnvironment(),
403
+ stdio: 'ignore',
404
+ timeout: SYSTEMCTL_TIMEOUT_MS,
405
+ })
406
+ } catch {
407
+ // The range is already empty; a failed cleanup leaves only the transient unit.
408
+ }
409
+ }
410
+
411
+ private parseUnitState(stdout: string): { loadState: string; activeState: string; tasksCurrent: number | undefined } {
412
+ const values = new Map<string, string>()
413
+ for (const line of stdout.split(/\r?\n/u)) {
414
+ if (line === '') continue
415
+ const separator = line.indexOf('=')
416
+ if (separator <= 0) {
417
+ throw new Error(`systemctl returned malformed state for ${this.unit}: ${JSON.stringify(stdout.trim())}`)
418
+ }
419
+ const name = line.slice(0, separator)
420
+ if (values.has(name)) {
421
+ throw new Error(`systemctl returned duplicate ${name} for ${this.unit}`)
422
+ }
423
+ values.set(name, line.slice(separator + 1))
424
+ }
425
+ const loadState = values.get('LoadState')
426
+ const activeState = values.get('ActiveState')
427
+ // The manager prints this sentinel for a property the unit does not carry.
428
+ const reportedTasks = values.get('TasksCurrent')
429
+ const tasksCurrent = reportedTasks === '[not set]' ? undefined : reportedTasks
430
+ if (values.size !== (reportedTasks === undefined ? 2 : 3)
431
+ || loadState === undefined || activeState === undefined) {
432
+ throw new Error(`systemctl returned incomplete state for ${this.unit}: ${JSON.stringify(stdout.trim())}`)
433
+ }
434
+ if (tasksCurrent !== undefined && !/^\d+$/u.test(tasksCurrent)) {
435
+ throw new Error(`systemctl returned a non-numeric TasksCurrent for ${this.unit}: ${JSON.stringify(tasksCurrent)}`)
436
+ }
437
+ return {
438
+ loadState,
439
+ activeState,
440
+ tasksCurrent: tasksCurrent === undefined ? undefined : Number(tasksCurrent),
441
+ }
442
+ }
443
+
444
+ private async rangeActive(): Promise<boolean> {
445
+ this.observeRequestConsumption()
446
+ const generation = this.wakeGeneration
447
+ const directRunning = this.direct.running()
448
+ const result = await this.query(this.systemctl, [
449
+ '--user',
450
+ 'show',
451
+ this.unit,
452
+ '--property=LoadState',
453
+ '--property=ActiveState',
454
+ '--property=TasksCurrent',
455
+ ])
456
+ // A signal invalidates state queried before its delivery and direct fallback.
457
+ if (generation !== this.wakeGeneration) return true
458
+ const output = `${result.stdout}\n${result.stderr}`
459
+ if (result.status === 0) {
460
+ const { loadState, activeState, tasksCurrent } = this.parseUnitState(result.stdout)
461
+ if (loadState === 'not-found' && activeState === 'inactive') return this.absentUnit()
462
+ if (loadState !== 'loaded') {
463
+ throw new Error(
464
+ `systemctl returned unknown state for ${this.unit}: ${JSON.stringify({ loadState, activeState })}`,
465
+ )
466
+ }
467
+ this.establishment = 'established'
468
+ if (activeState === 'inactive' || activeState === 'failed') return false
469
+ if (!['active', 'activating', 'reloading', 'deactivating'].includes(activeState)) {
470
+ throw new Error(`systemctl returned unknown ActiveState for ${this.unit}: ${JSON.stringify(activeState)}`)
471
+ }
472
+ if (this.emptyRange(tasksCurrent)) {
473
+ this.releaseEmptyRange()
474
+ return false
475
+ }
476
+ if (this.killFailure !== undefined) {
477
+ if (directRunning && this.directKillSettlement !== undefined) {
478
+ const settlement = this.directKillSettlement
479
+ this.directKillSettlement = undefined
480
+ await settlement
481
+ // A query preceding direct exit cannot prove that its signalled processes survived.
482
+ return this.rangeActive()
483
+ }
484
+ throw this.killFailure
485
+ }
486
+ return true
487
+ }
488
+ if (!MISSING_UNIT.test(output)) {
489
+ if (result.error !== undefined) throw result.error
490
+ throw new Error(`systemctl could not read ${this.unit}: ${output.trim() || `exit ${String(result.status)}`}`)
491
+ }
492
+ return this.absentUnit()
493
+ }
494
+
495
+ private wakeObservation(): void {
496
+ this.wakeGeneration += 1
497
+ this.wakeWaiter?.resolve()
498
+ this.wakeWaiter = undefined
499
+ }
500
+
501
+ private async waitForPoll(delayMs: number, generation: number): Promise<void> {
502
+ if (generation !== this.wakeGeneration) return
503
+ const wake = Promise.withResolvers<void>()
504
+ const waiter = { generation, resolve: wake.resolve }
505
+ const sleepController = new AbortController()
506
+ this.wakeWaiter = waiter
507
+ try {
508
+ await Promise.race([this.sleep(delayMs, sleepController.signal), wake.promise])
509
+ } finally {
510
+ sleepController.abort()
511
+ if (this.wakeWaiter === waiter) this.wakeWaiter = undefined
512
+ }
513
+ }
514
+
515
+ async waitForExit(): Promise<void> {
516
+ if (this.stopped) return
517
+ this.observation ??= (async () => {
518
+ let pollIntervalMs = SCOPE_INITIAL_POLL_INTERVAL_MS
519
+ let generation = this.wakeGeneration
520
+ while (await this.rangeActive()) {
521
+ await this.waitForPoll(pollIntervalMs, generation)
522
+ generation = this.wakeGeneration
523
+ // Keep establishment responsive, then reduce systemctl process churn
524
+ // while systemd remains the authoritative owner of an active range.
525
+ if (this.establishment === 'established') {
526
+ pollIntervalMs = Math.min(pollIntervalMs * 2, SYSTEMCTL_TIMEOUT_MS)
527
+ }
528
+ }
529
+ this.stopped = true
530
+ })().catch((error: unknown) => {
531
+ this.observation = undefined
532
+ throw error
533
+ })
534
+ await this.observation
535
+ }
536
+
537
+ cleanup(): void {
538
+ cleanupLinuxLaunchFiles(this.startup.files)
539
+ }
540
+ }
541
+
542
+ function scopeArgs(
543
+ unitBase: string,
544
+ literalArgv: LiteralArgvOptions,
545
+ invocation: RunnerInvocation,
546
+ argv: readonly string[],
547
+ ): string[] {
548
+ return [
549
+ '--user',
550
+ '--scope',
551
+ '--quiet',
552
+ '--collect',
553
+ ...literalArgv,
554
+ `--unit=${unitBase}`,
555
+ '--',
556
+ ...invocation,
557
+ '--',
558
+ ...argv,
559
+ ]
560
+ }
561
+
562
+ function directOutcome(
563
+ child: ReturnType<typeof spawn>,
564
+ startup: LinuxScopeStartup,
565
+ ): Promise<SubprocessOutcome> {
566
+ return new Promise((resolveOutcome, rejectOutcome) => {
567
+ let settled = false
568
+ child.once('error', (error) => {
569
+ if (settled) return
570
+ settled = true
571
+ rejectOutcome(error)
572
+ })
573
+ child.once('exit', (exitCode, signal) => {
574
+ if (settled) return
575
+ settled = true
576
+ try {
577
+ resolveOutcome(startup.resolveOutcome({ exitCode, signal }))
578
+ } catch (error) {
579
+ /* v8 ignore next -- Node filesystem operations throw Error instances. */
580
+ const failure = error instanceof Error ? error : new Error(String(error))
581
+ rejectOutcome(failure)
582
+ }
583
+ })
584
+ })
585
+ }
586
+
587
+ /**
588
+ * Send a direct-process signal, distinguishing an absent PID from failed delivery.
589
+ * @param pid - owned direct-process identity whose exit notification can still be pending.
590
+ * @param send - platform signal operation; true means the signal was submitted.
591
+ * @returns whether the signal was submitted or the owned PID is already absent.
592
+ */
593
+ export function signalLinuxDirectProcess(pid: number, send: () => boolean): boolean {
594
+ try {
595
+ if (send()) return true
596
+ } catch { /* A failed signal still permits an independent absence observation. */ }
597
+ try {
598
+ process.kill(pid, 0)
599
+ return false
600
+ } catch (error) {
601
+ return (error as NodeJS.ErrnoException).code === 'ESRCH'
602
+ }
603
+ }
604
+
605
+ function signalChildGroup(child: ReturnType<typeof spawn>, signal: 'SIGTERM' | 'SIGKILL'): boolean {
606
+ let groupSignalled = false
607
+ try {
608
+ groupSignalled = process.kill(-(child.pid as number), signal)
609
+ } catch { /* A missing or inaccessible group still permits a direct-process attempt. */ }
610
+ if (groupSignalled && signal === 'SIGTERM') return true
611
+ // Group success can reflect another member; joining direct exit requires its own SIGKILL submission.
612
+ // ChildProcess.kill can emit an error that settles directOutcome before the real exit.
613
+ return signalLinuxDirectProcess(child.pid as number, () => process.kill(child.pid as number, signal))
614
+ }
615
+
616
+ /** Linux PTY invocation and owner for the exact one-shot scope/bootstrap. */
617
+ export interface LinuxTerminalScopeLaunch {
618
+ command: string
619
+ args: string[]
620
+ cwd: string
621
+ env: NodeJS.ProcessEnv
622
+ bindOwner: (direct: DirectRange) => BoundProcessOwner
623
+ resolveOutcome: (outcome: SubprocessOutcome) => SubprocessOutcome
624
+ cleanup: () => void
625
+ }
626
+
627
+ /**
628
+ * Prepare one Linux PTY scope using the same launch request and bootstrap core.
629
+ * @param spec - terminal target request.
630
+ * @param targetEnv - validated complete target environment.
631
+ * @param literalArgv - options from the provider's positive scope probe.
632
+ * @param internals - optional runner and systemd seams used by tests.
633
+ * @returns invocation and ownership callbacks; requested termination preserves the observed signal even before bootstrap consumption.
634
+ */
635
+ export function prepareLinuxTerminalScope(
636
+ spec: SubprocessTerminalSpawnSpec,
637
+ targetEnv: Record<string, string>,
638
+ literalArgv: LiteralArgvOptions,
639
+ internals: LinuxScopeInternals = {},
640
+ ): LinuxTerminalScopeLaunch {
641
+ const invocation = internals.runnerInvocation ?? spawnRunnerInvocation()
642
+ const files = createLinuxLaunchFiles({ cwd: spec.cwd, env: targetEnv })
643
+ const startup = new LinuxScopeStartup(files, 'terminal')
644
+ const unitBase = unitStem('dsh-terminal')
645
+ return {
646
+ command: internals.systemdRun ?? 'systemd-run',
647
+ args: scopeArgs(unitBase, literalArgv, invocation, spec.argv),
648
+ cwd: process.cwd(),
649
+ env: runnerEnvironment(files.requestPath, invocation),
650
+ bindOwner: direct => new SystemdScopeOwner(
651
+ `${unitBase}.scope`,
652
+ startup,
653
+ direct,
654
+ internals.systemctl ?? 'systemctl',
655
+ internals.spawnSync ?? spawnSync,
656
+ internals.systemctlQuery ?? querySystemctl,
657
+ internals.sleep ?? sleepWithAbort,
658
+ ),
659
+ resolveOutcome: outcome => startup.resolveOutcome(outcome),
660
+ cleanup: () => { cleanupLinuxLaunchFiles(files) },
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Launch one ordinary target inside a transient user scope.
666
+ * @param spec - ordinary target request.
667
+ * @param targetEnv - validated complete target environment.
668
+ * @param literalArgv - options from the provider's positive scope probe.
669
+ * @param internals - optional runner and systemd seams used by tests.
670
+ * @returns streams, result, and scope owner; requested termination preserves the observed signal even before bootstrap consumption.
671
+ */
672
+ export function launchLinuxScope(
673
+ spec: SubprocessSpawnSpec,
674
+ targetEnv: Record<string, string>,
675
+ literalArgv: LiteralArgvOptions,
676
+ internals: LinuxScopeInternals = {},
677
+ ): ManagedProcessLaunch {
678
+ const invocation = internals.runnerInvocation ?? spawnRunnerInvocation()
679
+ const stdio = runnerStdio(spec, false)
680
+ const files = createLinuxLaunchFiles({
681
+ cwd: spec.cwd, env: targetEnv,
682
+ pipeFds: stdio.slice(0, 3).flatMap((disposition, fd) => disposition === 'pipe' ? [fd] : []),
683
+ ...spec.stdio.control === undefined ? {} : { control: spec.stdio.control },
684
+ })
685
+ const startup = new LinuxScopeStartup(files, 'subprocess')
686
+ const unitBase = unitStem('dsh-subprocess')
687
+ let child: ReturnType<typeof spawn>
688
+ try {
689
+ child = (internals.spawn ?? spawn)(internals.systemdRun ?? 'systemd-run', scopeArgs(
690
+ unitBase,
691
+ literalArgv,
692
+ invocation,
693
+ spec.argv,
694
+ ), {
695
+ cwd: process.cwd(),
696
+ env: runnerEnvironment(files.requestPath, invocation),
697
+ stdio,
698
+ detached: true,
699
+ })
700
+ } catch (error) {
701
+ cleanupLinuxLaunchFiles(files)
702
+ throw error
703
+ }
704
+ const direct = directOutcome(child, startup)
705
+ const owner = new SystemdScopeOwner(
706
+ `${unitBase}.scope`,
707
+ startup,
708
+ {
709
+ running: () => child.pid !== undefined && child.exitCode === null && child.signalCode === null,
710
+ signal: signal => signalChildGroup(child, signal),
711
+ settled: direct,
712
+ },
713
+ internals.systemctl ?? 'systemctl',
714
+ internals.spawnSync ?? spawnSync,
715
+ internals.systemctlQuery ?? querySystemctl,
716
+ internals.sleep ?? sleepWithAbort,
717
+ )
718
+ return {
719
+ stdin: child.stdin,
720
+ stdout: child.stdout,
721
+ stderr: child.stderr,
722
+ control: controlPipe(child, spec.stdio.control),
723
+ direct,
724
+ owner,
725
+ }
726
+ }