@unieai/rabi-subprocess-local 0.0.0-stage → 0.2.2-rc.5

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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/index.js +1706 -0
  4. package/lib/output.js +239 -0
  5. package/lib/runner-launch-CKTiL8M8.js +1556 -0
  6. package/lib/runner.js +432 -0
  7. package/lib/types/bin.d.ts +7 -0
  8. package/lib/types/control-spawn.d.ts +19 -0
  9. package/lib/types/index.d.ts +59 -0
  10. package/lib/types/linux-execve.d.ts +9 -0
  11. package/lib/types/linux-scope-selector.d.ts +60 -0
  12. package/lib/types/linux-scope.d.ts +124 -0
  13. package/lib/types/managed-owner.d.ts +36 -0
  14. package/lib/types/output.d.ts +137 -0
  15. package/lib/types/process-inspector.d.ts +142 -0
  16. package/lib/types/runner-launch.d.ts +68 -0
  17. package/lib/types/runner-protocol.d.ts +113 -0
  18. package/lib/types/shell-activity.d.ts +37 -0
  19. package/lib/types/spawn-runner.d.ts +37 -0
  20. package/lib/types/spawn.d.ts +86 -0
  21. package/lib/types/terminal.d.ts +80 -0
  22. package/lib/types/windows-inspector.d.ts +79 -0
  23. package/lib/types/windows-job.d.ts +30 -0
  24. package/locale/de.json +6 -0
  25. package/locale/en.json +5 -0
  26. package/locale/es.json +6 -0
  27. package/locale/fr.json +6 -0
  28. package/locale/ja.json +6 -0
  29. package/locale/pt.json +6 -0
  30. package/locale/ru.json +6 -0
  31. package/locale/zh.json +6 -0
  32. package/package.json +54 -4
  33. package/scripts/ensure-spawn-helper.mjs +16 -0
  34. package/src/bin.ts +25 -0
  35. package/src/control-spawn.ts +35 -0
  36. package/src/index.ts +387 -0
  37. package/src/linux-execve.ts +92 -0
  38. package/src/linux-scope-selector.ts +101 -0
  39. package/src/linux-scope.ts +726 -0
  40. package/src/managed-owner.ts +56 -0
  41. package/src/output.ts +313 -0
  42. package/src/process-inspector.ts +560 -0
  43. package/src/runner-launch.ts +315 -0
  44. package/src/runner-protocol.ts +281 -0
  45. package/src/shell-activity.ts +131 -0
  46. package/src/spawn-runner.ts +488 -0
  47. package/src/spawn.ts +500 -0
  48. package/src/terminal.ts +479 -0
  49. package/src/windows-inspector.ts +346 -0
  50. package/src/windows-job.ts +269 -0
package/lib/index.js ADDED
@@ -0,0 +1,1706 @@
1
+ import { C as bindManagedProcess, D as createProcessInspector, E as validateSubprocessSpec, O as controlPipe, S as loadLinuxExecve, T as spawnSubprocess, _ as parseWindowsRunnerResult, c as runnerStdio, d as cleanupLinuxLaunchFiles, l as spawnRunnerInvocation, m as deserializeRunnerError, n as WINDOWS_RUNNER_SELECTION, o as runnerEnvironment, p as createLinuxLaunchFiles, s as runnerInvocationAvailable, u as targetEnvironment, w as childEnv, y as readLinuxStartupError } from "./runner-launch-CKTiL8M8.js";
2
+ import { logSpillFailure, prepareManagedProcessBinding } from "./output.js";
3
+ import { closeSync, constants, existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { access, stat } from "node:fs/promises";
5
+ import { constants as constants$1, devNull, tmpdir, userInfo } from "node:os";
6
+ import { basename, delimiter, extname, isAbsolute, join, resolve } from "node:path";
7
+ import { createLazyRequire } from "@unieai/rabi-lazy-require";
8
+ import { SubprocessError, SubprocessExecutableNotFoundError, SubprocessRuntime } from "@unieai/rabi-subprocess";
9
+ import { execFile, spawn, spawnSync } from "node:child_process";
10
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
+ import { randomBytes } from "node:crypto";
12
+ import { loadWin32ProcessBindings, probeCurrentTokenJobSupport } from "@unieai/rabi-win32-process";
13
+ import { Buffer } from "node:buffer";
14
+ import { PassThrough } from "node:stream";
15
+ //#region lib/types/linux-scope.js
16
+ /** Linux user-systemd scope launch and managed-range ownership. */
17
+ const SYSTEMCTL_TIMEOUT_MS = 5e3;
18
+ const SCOPE_INITIAL_POLL_INTERVAL_MS = 50;
19
+ const MISSING_UNIT = /\bunit\b[^\r\n]*(?:could not be found|not found|not loaded)/iu;
20
+ const LITERAL_ARGV_OPTION = "--expand-environment=no";
21
+ const LITERAL_ARGV_OPTION_REJECTED = /unrecognized option\b.*expand-environment/u;
22
+ const KILL_ALL_MEMBERS = "--kill-who=all";
23
+ /** Flags bit that /proc/net/unix sets on a listening socket (__SO_ACCEPTCON). */
24
+ const UNIX_SOCKET_ACCEPTING = 65536;
25
+ function managerEnvironment() {
26
+ const environment = childEnv({ LC_ALL: "C" });
27
+ delete environment.SYSTEMD_LOG_TARGET;
28
+ return environment;
29
+ }
30
+ function quietSystemdEnvironment() {
31
+ return childEnv({
32
+ LC_ALL: "C",
33
+ SYSTEMD_LOG_TARGET: "null"
34
+ });
35
+ }
36
+ function querySystemctl(command, args) {
37
+ return new Promise((resolveResult) => {
38
+ execFile(command, [...args], {
39
+ encoding: "utf8",
40
+ env: managerEnvironment(),
41
+ timeout: SYSTEMCTL_TIMEOUT_MS
42
+ }, (error, stdout, stderr) => {
43
+ const code = error === null ? 0 : error.code;
44
+ resolveResult({
45
+ status: typeof code === "number" ? code : null,
46
+ stdout,
47
+ stderr,
48
+ ...error === null ? {} : { error }
49
+ });
50
+ });
51
+ });
52
+ }
53
+ function unitStem(prefix) {
54
+ return `${prefix}-${String(process.pid)}-${randomBytes(6).toString("hex")}`;
55
+ }
56
+ function sleepWithAbort(delayMs, signal) {
57
+ return setTimeout$1(delayMs, void 0, { signal });
58
+ }
59
+ /**
60
+ * Confirm this exact runner entry and libc execve binding without a probe mode.
61
+ * @param internals - optional runner and libc-binding seams used by tests.
62
+ * @returns whether the bootstrap can enter the final target.
63
+ */
64
+ function probeLinuxBootstrap(internals = {}) {
65
+ try {
66
+ (internals.loadLinuxExecve ?? loadLinuxExecve)();
67
+ const invocation = internals.runnerInvocation ?? (internals.resolveRunnerInvocation ?? spawnRunnerInvocation)();
68
+ return (internals.runnerAvailable ?? runnerInvocationAvailable)(invocation);
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+ /**
74
+ * Confirm current literal-argv transient-scope support before selecting native launch.
75
+ * @param internals - optional systemd command seams used by tests.
76
+ * @returns the options that keep target argv literal, or undefined when the user manager cannot create the scope.
77
+ */
78
+ function probeLinuxScope(internals = {}) {
79
+ const attempt = (literalArgv) => {
80
+ const unitBase = unitStem("rabi-subprocess-probe");
81
+ const result = (internals.spawnSync ?? spawnSync)(internals.systemdRun ?? "systemd-run", [
82
+ "--user",
83
+ "--scope",
84
+ "--quiet",
85
+ "--collect",
86
+ ...literalArgv,
87
+ `--unit=${unitBase}`,
88
+ "--",
89
+ internals.systemctl ?? "systemctl",
90
+ "--user",
91
+ "show",
92
+ `${unitBase}.scope`,
93
+ "--property=ActiveState",
94
+ "--value"
95
+ ], {
96
+ encoding: "utf8",
97
+ env: quietSystemdEnvironment(),
98
+ stdio: [
99
+ "ignore",
100
+ "ignore",
101
+ "pipe"
102
+ ],
103
+ timeout: SYSTEMCTL_TIMEOUT_MS
104
+ });
105
+ return {
106
+ created: result.error === void 0 && result.status === 0,
107
+ stderr: result.stderr
108
+ };
109
+ };
110
+ const current = attempt([LITERAL_ARGV_OPTION]);
111
+ if (current.created) return [LITERAL_ARGV_OPTION];
112
+ if (!LITERAL_ARGV_OPTION_REJECTED.test(current.stderr)) return void 0;
113
+ return attempt([]).created ? [] : void 0;
114
+ }
115
+ /**
116
+ * Check every Linux native prerequisite on each call.
117
+ * @param internals - optional native capability seams used by tests.
118
+ * @returns the literal-argv scope options when Linux native containment is available, otherwise undefined.
119
+ */
120
+ function probeLinuxNative(internals = {}) {
121
+ return probeLinuxBootstrap(internals) ? probeLinuxScope(internals) : void 0;
122
+ }
123
+ /**
124
+ * Query the user manager once through systemctl.
125
+ * @param internals - optional systemctl seam used by tests.
126
+ * @returns whether the query succeeds.
127
+ */
128
+ function probeLinuxManager(internals = {}) {
129
+ const result = (internals.spawnSync ?? spawnSync)(internals.systemctl ?? "systemctl", [
130
+ "--user",
131
+ "show",
132
+ "--property=Version",
133
+ "--value"
134
+ ], {
135
+ env: managerEnvironment(),
136
+ stdio: "ignore",
137
+ timeout: SYSTEMCTL_TIMEOUT_MS
138
+ });
139
+ return result.error === void 0 && result.status === 0;
140
+ }
141
+ /**
142
+ * Find the socket a process in this network namespace listens on at path. The kernel lists a
143
+ * bound socket only while a process holds it open, so a socket file that a stopped or crashed
144
+ * listener left behind does not count.
145
+ */
146
+ function unixSocketListener(path, table) {
147
+ let text;
148
+ try {
149
+ text = readFileSync(table, "utf8");
150
+ } catch (_unreadableSocketTable) {
151
+ return;
152
+ }
153
+ const suffix = ` ${path}`;
154
+ for (const line of text.split("\n")) {
155
+ if (!line.endsWith(suffix)) continue;
156
+ const fields = line.trim().split(/\s+/u);
157
+ if (fields.slice(7).join(" ") === path && (Number.parseInt(String(fields[3]), 16) & UNIX_SOCKET_ACCEPTING) !== 0) return String(fields[6]);
158
+ }
159
+ }
160
+ /**
161
+ * Identify the user manager's listener on `$XDG_RUNTIME_DIR/systemd/private`, the socket
162
+ * `systemd-run --user` connects through.
163
+ * @param internals - optional socket-table seam used by tests.
164
+ * @returns the listening socket's inode from the kernel socket table, or undefined when
165
+ * XDG_RUNTIME_DIR is unset or nothing in this network namespace listens there.
166
+ */
167
+ function linuxManagerListener(internals = {}) {
168
+ const runtimeDirectory = childEnv().XDG_RUNTIME_DIR;
169
+ if (runtimeDirectory === void 0 || runtimeDirectory === "") return void 0;
170
+ return unixSocketListener(join(runtimeDirectory, "systemd", "private"), internals.unixSocketTable ?? "/proc/net/unix");
171
+ }
172
+ /**
173
+ * Identify the systemd-run binary that scope launches resolve through PATH, so a package upgrade
174
+ * that replaces it triggers another probe of its literal-argv options.
175
+ * @param internals - optional systemd-run seam used by tests.
176
+ * @returns the device, inode, size, and modification time of the first match, or undefined when none resolves.
177
+ */
178
+ function systemdRunIdentity(internals = {}) {
179
+ const command = internals.systemdRun ?? "systemd-run";
180
+ const candidates = command.includes("/") ? [command] : (childEnv().PATH ?? "").split(":").filter((directory) => directory !== "").map((directory) => join(directory, command));
181
+ for (const candidate of candidates) {
182
+ let stats;
183
+ try {
184
+ stats = statSync(candidate, { throwIfNoEntry: false });
185
+ } catch (_unreadableCandidate) {
186
+ continue;
187
+ }
188
+ if (stats?.isFile() === true) return `${String(stats.dev)}:${String(stats.ino)}:${String(stats.size)}:${String(stats.mtimeMs)}`;
189
+ }
190
+ }
191
+ /**
192
+ * Confirm the user manager before a scope launch. A listener on its private socket confirms it
193
+ * without a child process; otherwise one systemctl query decides. A hung manager that still
194
+ * listens passes, and its scope launch fails with LinuxScopeNotStartedError.
195
+ * @param internals - optional socket-table and systemctl seams used by tests.
196
+ * @returns whether a scope launch can reach the user manager.
197
+ */
198
+ function confirmLinuxManager(internals = {}) {
199
+ return linuxManagerListener(internals) !== void 0 || probeLinuxManager(internals);
200
+ }
201
+ /** A scope launch whose bootstrap never consumed its launch request, so its target never ran. */
202
+ var LinuxScopeNotStartedError = class extends Error {
203
+ name = "LinuxScopeNotStartedError";
204
+ };
205
+ var LinuxScopeStartup = class {
206
+ files;
207
+ kind;
208
+ terminationSignals = /* @__PURE__ */ new Set();
209
+ constructor(files, kind) {
210
+ this.files = files;
211
+ this.kind = kind;
212
+ }
213
+ resolveOutcome(outcome) {
214
+ const startup = readLinuxStartupError(this.files.startupErrorPath);
215
+ if (startup !== void 0) throw deserializeRunnerError(startup.error);
216
+ if (existsSync(this.files.requestPath) && !(outcome.signal !== null && this.terminationSignals.has(outcome.signal))) throw new LinuxScopeNotStartedError(`${this.kind} scope exited before its bootstrap consumed the launch request; the provider probes native containment again before its next command`);
217
+ return outcome;
218
+ }
219
+ };
220
+ var SystemdScopeOwner = class {
221
+ unit;
222
+ startup;
223
+ direct;
224
+ systemctl;
225
+ runSync;
226
+ query;
227
+ sleep;
228
+ establishment = "pending";
229
+ stopped = false;
230
+ terminationRequested = false;
231
+ observation;
232
+ killFailure;
233
+ directKillSettlement;
234
+ wakeGeneration = 0;
235
+ wakeWaiter;
236
+ constructor(unit, startup, direct, systemctl, runSync, query, sleep) {
237
+ this.unit = unit;
238
+ this.startup = startup;
239
+ this.direct = direct;
240
+ this.systemctl = systemctl;
241
+ this.runSync = runSync;
242
+ this.query = query;
243
+ this.sleep = sleep;
244
+ }
245
+ inspectTaskCount() {
246
+ const result = this.runSync(this.systemctl, [
247
+ "--user",
248
+ "show",
249
+ "--property=LoadState",
250
+ "--property=ActiveState",
251
+ "--property=TasksCurrent",
252
+ this.unit
253
+ ], {
254
+ encoding: "utf8",
255
+ env: managerEnvironment(),
256
+ timeout: SYSTEMCTL_TIMEOUT_MS
257
+ });
258
+ if (result.error !== void 0 || result.status !== 0 || typeof result.stdout !== "string") return void 0;
259
+ const state = this.parseUnitState(result.stdout);
260
+ return state.loadState === "loaded" && state.activeState === "active" ? state.tasksCurrent : void 0;
261
+ }
262
+ signal(signal) {
263
+ if (this.stopped) return;
264
+ this.terminationRequested = true;
265
+ if (this.direct.running()) this.startup.terminationSignals.add(signal);
266
+ this.observeRequestConsumption();
267
+ const directFallbackRequired = this.establishment === "pending";
268
+ let directSignalled = false;
269
+ if (directFallbackRequired && this.direct.running()) directSignalled = this.direct.signal(signal);
270
+ const result = this.runSync(this.systemctl, [
271
+ "--user",
272
+ "kill",
273
+ KILL_ALL_MEMBERS,
274
+ `--signal=${signal}`,
275
+ this.unit
276
+ ], {
277
+ encoding: "utf8",
278
+ env: managerEnvironment(),
279
+ timeout: SYSTEMCTL_TIMEOUT_MS
280
+ });
281
+ this.wakeObservation();
282
+ if (result.error === void 0 && result.status === 0) {
283
+ if (signal === "SIGKILL") {
284
+ this.killFailure = void 0;
285
+ this.directKillSettlement = void 0;
286
+ }
287
+ return;
288
+ }
289
+ if (!directFallbackRequired && this.direct.running()) directSignalled = this.direct.signal(signal);
290
+ if (signal === "SIGKILL") {
291
+ const output = `${result.stdout}\n${result.stderr}`;
292
+ if (!MISSING_UNIT.test(output)) {
293
+ this.killFailure = result.error ?? /* @__PURE__ */ new Error(`systemctl could not signal ${this.unit}: ${output.trim() || `exit ${String(result.status)}`}`);
294
+ this.directKillSettlement = directSignalled ? this.direct.settled.then(() => {}, () => {}) : void 0;
295
+ }
296
+ }
297
+ }
298
+ terminateForHostExit() {
299
+ if (this.stopped) return;
300
+ try {
301
+ if (this.direct.running()) this.direct.signal("SIGKILL");
302
+ } catch {}
303
+ try {
304
+ this.runSync(this.systemctl, [
305
+ "--user",
306
+ "kill",
307
+ KILL_ALL_MEMBERS,
308
+ "--signal=SIGKILL",
309
+ this.unit
310
+ ], {
311
+ env: managerEnvironment(),
312
+ stdio: "ignore",
313
+ timeout: SYSTEMCTL_TIMEOUT_MS
314
+ });
315
+ } catch {}
316
+ }
317
+ observeRequestConsumption() {
318
+ if (this.establishment === "pending" && !existsSync(this.startup.files.requestPath)) this.establishment = "established";
319
+ }
320
+ absentUnit() {
321
+ this.observeRequestConsumption();
322
+ if (this.establishment === "established") return false;
323
+ if (!this.direct.running() && existsSync(this.startup.files.requestPath)) return false;
324
+ if (this.killFailure !== void 0) throw this.killFailure;
325
+ return true;
326
+ }
327
+ /**
328
+ * Prove an active unit with no processes is the empty managed range rather
329
+ * than a launch still placing its payload. systemd ends a scope only on the
330
+ * populated-to-empty transition, so a payload killed before it entered the
331
+ * cgroup leaves the unit active forever. A departed client cannot add another
332
+ * payload; a consumed request proves the payload already entered the scope,
333
+ * even while its direct-process exit notification is pending.
334
+ */
335
+ emptyRange(tasksCurrent) {
336
+ return this.terminationRequested && tasksCurrent === 0 && (!this.direct.running() || !existsSync(this.startup.files.requestPath));
337
+ }
338
+ /** Release a leftover empty scope so the transient unit is collected and cannot accumulate. */
339
+ releaseEmptyRange() {
340
+ try {
341
+ this.runSync(this.systemctl, [
342
+ "--user",
343
+ "stop",
344
+ this.unit
345
+ ], {
346
+ env: managerEnvironment(),
347
+ stdio: "ignore",
348
+ timeout: SYSTEMCTL_TIMEOUT_MS
349
+ });
350
+ } catch {}
351
+ }
352
+ parseUnitState(stdout) {
353
+ const values = /* @__PURE__ */ new Map();
354
+ for (const line of stdout.split(/\r?\n/u)) {
355
+ if (line === "") continue;
356
+ const separator = line.indexOf("=");
357
+ if (separator <= 0) throw new Error(`systemctl returned malformed state for ${this.unit}: ${JSON.stringify(stdout.trim())}`);
358
+ const name = line.slice(0, separator);
359
+ if (values.has(name)) throw new Error(`systemctl returned duplicate ${name} for ${this.unit}`);
360
+ values.set(name, line.slice(separator + 1));
361
+ }
362
+ const loadState = values.get("LoadState");
363
+ const activeState = values.get("ActiveState");
364
+ const reportedTasks = values.get("TasksCurrent");
365
+ const tasksCurrent = reportedTasks === "[not set]" ? void 0 : reportedTasks;
366
+ if (values.size !== (reportedTasks === void 0 ? 2 : 3) || loadState === void 0 || activeState === void 0) throw new Error(`systemctl returned incomplete state for ${this.unit}: ${JSON.stringify(stdout.trim())}`);
367
+ if (tasksCurrent !== void 0 && !/^\d+$/u.test(tasksCurrent)) throw new Error(`systemctl returned a non-numeric TasksCurrent for ${this.unit}: ${JSON.stringify(tasksCurrent)}`);
368
+ return {
369
+ loadState,
370
+ activeState,
371
+ tasksCurrent: tasksCurrent === void 0 ? void 0 : Number(tasksCurrent)
372
+ };
373
+ }
374
+ async rangeActive() {
375
+ this.observeRequestConsumption();
376
+ const generation = this.wakeGeneration;
377
+ const directRunning = this.direct.running();
378
+ const result = await this.query(this.systemctl, [
379
+ "--user",
380
+ "show",
381
+ this.unit,
382
+ "--property=LoadState",
383
+ "--property=ActiveState",
384
+ "--property=TasksCurrent"
385
+ ]);
386
+ if (generation !== this.wakeGeneration) return true;
387
+ const output = `${result.stdout}\n${result.stderr}`;
388
+ if (result.status === 0) {
389
+ const { loadState, activeState, tasksCurrent } = this.parseUnitState(result.stdout);
390
+ if (loadState === "not-found" && activeState === "inactive") return this.absentUnit();
391
+ if (loadState !== "loaded") throw new Error(`systemctl returned unknown state for ${this.unit}: ${JSON.stringify({
392
+ loadState,
393
+ activeState
394
+ })}`);
395
+ this.establishment = "established";
396
+ if (activeState === "inactive" || activeState === "failed") return false;
397
+ if (![
398
+ "active",
399
+ "activating",
400
+ "reloading",
401
+ "deactivating"
402
+ ].includes(activeState)) throw new Error(`systemctl returned unknown ActiveState for ${this.unit}: ${JSON.stringify(activeState)}`);
403
+ if (this.emptyRange(tasksCurrent)) {
404
+ this.releaseEmptyRange();
405
+ return false;
406
+ }
407
+ if (this.killFailure !== void 0) {
408
+ if (directRunning && this.directKillSettlement !== void 0) {
409
+ const settlement = this.directKillSettlement;
410
+ this.directKillSettlement = void 0;
411
+ await settlement;
412
+ return this.rangeActive();
413
+ }
414
+ throw this.killFailure;
415
+ }
416
+ return true;
417
+ }
418
+ if (!MISSING_UNIT.test(output)) {
419
+ if (result.error !== void 0) throw result.error;
420
+ throw new Error(`systemctl could not read ${this.unit}: ${output.trim() || `exit ${String(result.status)}`}`);
421
+ }
422
+ return this.absentUnit();
423
+ }
424
+ wakeObservation() {
425
+ this.wakeGeneration += 1;
426
+ this.wakeWaiter?.resolve();
427
+ this.wakeWaiter = void 0;
428
+ }
429
+ async waitForPoll(delayMs, generation) {
430
+ if (generation !== this.wakeGeneration) return;
431
+ const wake = Promise.withResolvers();
432
+ const waiter = {
433
+ generation,
434
+ resolve: wake.resolve
435
+ };
436
+ const sleepController = new AbortController();
437
+ this.wakeWaiter = waiter;
438
+ try {
439
+ await Promise.race([this.sleep(delayMs, sleepController.signal), wake.promise]);
440
+ } finally {
441
+ sleepController.abort();
442
+ if (this.wakeWaiter === waiter) this.wakeWaiter = void 0;
443
+ }
444
+ }
445
+ async waitForExit() {
446
+ if (this.stopped) return;
447
+ this.observation ??= (async () => {
448
+ let pollIntervalMs = SCOPE_INITIAL_POLL_INTERVAL_MS;
449
+ let generation = this.wakeGeneration;
450
+ while (await this.rangeActive()) {
451
+ await this.waitForPoll(pollIntervalMs, generation);
452
+ generation = this.wakeGeneration;
453
+ if (this.establishment === "established") pollIntervalMs = Math.min(pollIntervalMs * 2, SYSTEMCTL_TIMEOUT_MS);
454
+ }
455
+ this.stopped = true;
456
+ })().catch((error) => {
457
+ this.observation = void 0;
458
+ throw error;
459
+ });
460
+ await this.observation;
461
+ }
462
+ cleanup() {
463
+ cleanupLinuxLaunchFiles(this.startup.files);
464
+ }
465
+ };
466
+ function scopeArgs(unitBase, literalArgv, invocation, argv) {
467
+ return [
468
+ "--user",
469
+ "--scope",
470
+ "--quiet",
471
+ "--collect",
472
+ ...literalArgv,
473
+ `--unit=${unitBase}`,
474
+ "--",
475
+ ...invocation,
476
+ "--",
477
+ ...argv
478
+ ];
479
+ }
480
+ function directOutcome(child, startup) {
481
+ return new Promise((resolveOutcome, rejectOutcome) => {
482
+ let settled = false;
483
+ child.once("error", (error) => {
484
+ if (settled) return;
485
+ settled = true;
486
+ rejectOutcome(error);
487
+ });
488
+ child.once("exit", (exitCode, signal) => {
489
+ if (settled) return;
490
+ settled = true;
491
+ try {
492
+ resolveOutcome(startup.resolveOutcome({
493
+ exitCode,
494
+ signal
495
+ }));
496
+ } catch (error) {
497
+ rejectOutcome(error instanceof Error ? error : new Error(String(error)));
498
+ }
499
+ });
500
+ });
501
+ }
502
+ /**
503
+ * Send a direct-process signal, distinguishing an absent PID from failed delivery.
504
+ * @param pid - owned direct-process identity whose exit notification can still be pending.
505
+ * @param send - platform signal operation; true means the signal was submitted.
506
+ * @returns whether the signal was submitted or the owned PID is already absent.
507
+ */
508
+ function signalLinuxDirectProcess(pid, send) {
509
+ try {
510
+ if (send()) return true;
511
+ } catch {}
512
+ try {
513
+ process.kill(pid, 0);
514
+ return false;
515
+ } catch (error) {
516
+ return error.code === "ESRCH";
517
+ }
518
+ }
519
+ function signalChildGroup(child, signal) {
520
+ let groupSignalled = false;
521
+ try {
522
+ groupSignalled = process.kill(-child.pid, signal);
523
+ } catch {}
524
+ if (groupSignalled && signal === "SIGTERM") return true;
525
+ return signalLinuxDirectProcess(child.pid, () => process.kill(child.pid, signal));
526
+ }
527
+ /**
528
+ * Prepare one Linux PTY scope using the same launch request and bootstrap core.
529
+ * @param spec - terminal target request.
530
+ * @param targetEnv - validated complete target environment.
531
+ * @param literalArgv - options from the provider's positive scope probe.
532
+ * @param internals - optional runner and systemd seams used by tests.
533
+ * @returns invocation and ownership callbacks; requested termination preserves the observed signal even before bootstrap consumption.
534
+ */
535
+ function prepareLinuxTerminalScope(spec, targetEnv, literalArgv, internals = {}) {
536
+ const invocation = internals.runnerInvocation ?? spawnRunnerInvocation();
537
+ const files = createLinuxLaunchFiles({
538
+ cwd: spec.cwd,
539
+ env: targetEnv
540
+ });
541
+ const startup = new LinuxScopeStartup(files, "terminal");
542
+ const unitBase = unitStem("rabi-terminal");
543
+ return {
544
+ command: internals.systemdRun ?? "systemd-run",
545
+ args: scopeArgs(unitBase, literalArgv, invocation, spec.argv),
546
+ cwd: process.cwd(),
547
+ env: runnerEnvironment(files.requestPath, invocation),
548
+ bindOwner: (direct) => new SystemdScopeOwner(`${unitBase}.scope`, startup, direct, internals.systemctl ?? "systemctl", internals.spawnSync ?? spawnSync, internals.systemctlQuery ?? querySystemctl, internals.sleep ?? sleepWithAbort),
549
+ resolveOutcome: (outcome) => startup.resolveOutcome(outcome),
550
+ cleanup: () => {
551
+ cleanupLinuxLaunchFiles(files);
552
+ }
553
+ };
554
+ }
555
+ /**
556
+ * Launch one ordinary target inside a transient user scope.
557
+ * @param spec - ordinary target request.
558
+ * @param targetEnv - validated complete target environment.
559
+ * @param literalArgv - options from the provider's positive scope probe.
560
+ * @param internals - optional runner and systemd seams used by tests.
561
+ * @returns streams, result, and scope owner; requested termination preserves the observed signal even before bootstrap consumption.
562
+ */
563
+ function launchLinuxScope(spec, targetEnv, literalArgv, internals = {}) {
564
+ const invocation = internals.runnerInvocation ?? spawnRunnerInvocation();
565
+ const stdio = runnerStdio(spec, false);
566
+ const files = createLinuxLaunchFiles({
567
+ cwd: spec.cwd,
568
+ env: targetEnv,
569
+ pipeFds: stdio.slice(0, 3).flatMap((disposition, fd) => disposition === "pipe" ? [fd] : []),
570
+ ...spec.stdio.control === void 0 ? {} : { control: spec.stdio.control }
571
+ });
572
+ const startup = new LinuxScopeStartup(files, "subprocess");
573
+ const unitBase = unitStem("rabi-subprocess");
574
+ let child;
575
+ try {
576
+ child = (internals.spawn ?? spawn)(internals.systemdRun ?? "systemd-run", scopeArgs(unitBase, literalArgv, invocation, spec.argv), {
577
+ cwd: process.cwd(),
578
+ env: runnerEnvironment(files.requestPath, invocation),
579
+ stdio,
580
+ detached: true
581
+ });
582
+ } catch (error) {
583
+ cleanupLinuxLaunchFiles(files);
584
+ throw error;
585
+ }
586
+ const direct = directOutcome(child, startup);
587
+ const owner = new SystemdScopeOwner(`${unitBase}.scope`, startup, {
588
+ running: () => child.pid !== void 0 && child.exitCode === null && child.signalCode === null,
589
+ signal: (signal) => signalChildGroup(child, signal),
590
+ settled: direct
591
+ }, internals.systemctl ?? "systemctl", internals.spawnSync ?? spawnSync, internals.systemctlQuery ?? querySystemctl, internals.sleep ?? sleepWithAbort);
592
+ return {
593
+ stdin: child.stdin,
594
+ stdout: child.stdout,
595
+ stderr: child.stderr,
596
+ control: controlPipe(child, spec.stdio.control),
597
+ direct,
598
+ owner
599
+ };
600
+ }
601
+ //#endregion
602
+ //#region lib/types/linux-scope-selector.js
603
+ /** Linux native containment decisions over injected host observations. */
604
+ /**
605
+ * Provider-lifetime Linux scope selection. A probe runs on the first selection and again only after
606
+ * a scope launch never started its target, a different user-manager listener appears under a
607
+ * negative verdict, or the systemd-run binary changes under a positive one. A positive verdict
608
+ * confirms the user manager on every selection. Selection is synchronous, so a decision stays
609
+ * valid for the launch that follows it.
610
+ */
611
+ var LinuxScopeSelector = class {
612
+ observe;
613
+ state = {
614
+ kind: "unprobed",
615
+ trigger: "first"
616
+ };
617
+ generation = 0;
618
+ /** @param observe - host checks consulted by each selection. */
619
+ constructor(observe) {
620
+ this.observe = observe;
621
+ }
622
+ /**
623
+ * Choose containment for one eligible launch.
624
+ * @returns the decision and the branch that produced it.
625
+ */
626
+ select() {
627
+ const state = this.state;
628
+ if (state.kind === "unprobed") return this.probe(state.trigger);
629
+ if (state.kind === "available") {
630
+ if (this.observe.launcherIdentity() !== state.launcher) return this.probe("launcher-changed");
631
+ return this.observe.confirmManager() ? {
632
+ kind: "scope",
633
+ reason: "manager-confirmed",
634
+ literalArgv: state.literalArgv,
635
+ generation: this.generation,
636
+ probe: void 0
637
+ } : {
638
+ kind: "fallback",
639
+ reason: "manager-unconfirmed",
640
+ probe: void 0
641
+ };
642
+ }
643
+ const listener = this.observe.managerListener();
644
+ if (listener === void 0) return {
645
+ kind: "fallback",
646
+ reason: "no-listener",
647
+ probe: void 0
648
+ };
649
+ if (listener === state.listener) return {
650
+ kind: "fallback",
651
+ reason: "same-listener",
652
+ probe: void 0
653
+ };
654
+ return this.probe("new-listener");
655
+ }
656
+ /**
657
+ * Record that a scope launched under generation exited before its bootstrap started the target,
658
+ * so the next selection probes again. Launches from a superseded probe are ignored.
659
+ * @param generation - generation of the scope decision that launched it.
660
+ */
661
+ scopeNotStarted(generation) {
662
+ if (generation === this.generation) this.state = {
663
+ kind: "unprobed",
664
+ trigger: "scope-not-started"
665
+ };
666
+ }
667
+ probe(trigger) {
668
+ this.generation += 1;
669
+ const listener = this.observe.managerListener();
670
+ const launcher = this.observe.launcherIdentity();
671
+ const literalArgv = this.observe.probe();
672
+ if (literalArgv === void 0) {
673
+ this.state = {
674
+ kind: "unavailable",
675
+ listener
676
+ };
677
+ return {
678
+ kind: "fallback",
679
+ reason: "probe-unavailable",
680
+ probe: trigger
681
+ };
682
+ }
683
+ this.state = {
684
+ kind: "available",
685
+ literalArgv,
686
+ launcher
687
+ };
688
+ return {
689
+ kind: "scope",
690
+ reason: "probe-available",
691
+ literalArgv,
692
+ generation: this.generation,
693
+ probe: trigger
694
+ };
695
+ }
696
+ };
697
+ //#endregion
698
+ //#region lib/types/windows-job.js
699
+ /** Windows parent-side launch and ownership for the private Job runner. */
700
+ /** Classify a failure on the private runner channel, keeping an already coded failure. */
701
+ function runnerIpcFailure(error) {
702
+ if (error instanceof SubprocessError) return error;
703
+ return new SubprocessError(`subprocess-local: Windows runner IPC failed: ${String(error)}`, "SUBPROCESS_RUNNER_IPC_FAILED", { cause: error });
704
+ }
705
+ function isWindowsStartCancellationError(error) {
706
+ return error.name === "Error" && error.message === "subprocess target start was cancelled" && error.code === void 0 && error.syscall === void 0 && error.path === void 0;
707
+ }
708
+ /**
709
+ * Re-check the runner entry, bindings, and current Job capability for every spawn.
710
+ * @param internals - optional runner and Win32 capability seams used by tests.
711
+ * @returns whether the Windows native containment path is currently available.
712
+ */
713
+ function probeWindowsJob(internals = {}) {
714
+ try {
715
+ const invocation = internals.runnerInvocation ?? (internals.resolveRunnerInvocation ?? spawnRunnerInvocation)();
716
+ if (!(internals.runnerAvailable ?? runnerInvocationAvailable)(invocation)) return false;
717
+ const api = (internals.loadWin32ProcessBindings ?? loadWin32ProcessBindings)();
718
+ (internals.probeCurrentTokenJobSupport ?? probeCurrentTokenJobSupport)(api);
719
+ return true;
720
+ } catch {
721
+ return false;
722
+ }
723
+ }
724
+ var WindowsJobOwner = class {
725
+ runner;
726
+ exited;
727
+ directResultType;
728
+ failInfrastructure;
729
+ cancellationReason;
730
+ cancellationReasonSet = false;
731
+ terminationSent = false;
732
+ constructor(runner, exited, directResultType, failInfrastructure) {
733
+ this.runner = runner;
734
+ this.exited = exited;
735
+ this.directResultType = directResultType;
736
+ this.failInfrastructure = failInfrastructure;
737
+ this.exited.catch(() => {});
738
+ }
739
+ signal(_signal, cancellationReason) {
740
+ if (!this.cancellationReasonSet) {
741
+ this.cancellationReason = cancellationReason;
742
+ this.cancellationReasonSet = true;
743
+ }
744
+ if (this.terminationSent || !this.runner.connected) return;
745
+ this.terminationSent = true;
746
+ try {
747
+ this.runner.send?.({ type: "terminate" }, (error) => {
748
+ if (error === null || this.directResultType() !== void 0) return;
749
+ this.failInfrastructure(error);
750
+ this.terminateForHostExit();
751
+ });
752
+ } catch (error) {
753
+ this.failInfrastructure(error);
754
+ this.terminateForHostExit();
755
+ }
756
+ }
757
+ mapStartFailure(failure, serialized) {
758
+ return this.cancellationReasonSet && isWindowsStartCancellationError(serialized) ? this.cancellationReason : failure;
759
+ }
760
+ async waitForExit() {
761
+ await this.exited;
762
+ }
763
+ terminateForHostExit() {
764
+ try {
765
+ this.runner.kill("SIGKILL");
766
+ } catch {}
767
+ }
768
+ };
769
+ /**
770
+ * Launch one target through a runner that uniquely owns its Job handle.
771
+ * @param spec - ordinary target request.
772
+ * @param targetEnv - validated complete target environment.
773
+ * @param internals - optional runner launch seams used by tests.
774
+ * @returns direct streams, result, and runner-owned managed range.
775
+ */
776
+ function launchWindowsJob(spec, targetEnv, internals = {}) {
777
+ const invocation = internals.runnerInvocation ?? spawnRunnerInvocation();
778
+ const [command, ...prefix] = invocation;
779
+ const ignoredStdinFd = spec.stdio.stdin === "ignore" ? openSync(devNull, "r") : void 0;
780
+ let child;
781
+ try {
782
+ child = (internals.spawn ?? spawn)(command, [
783
+ ...prefix,
784
+ "--",
785
+ ...spec.argv
786
+ ], {
787
+ cwd: process.cwd(),
788
+ windowsHide: true,
789
+ env: runnerEnvironment(WINDOWS_RUNNER_SELECTION, invocation),
790
+ stdio: runnerStdio(spec, true, ignoredStdinFd ?? "pipe")
791
+ });
792
+ } finally {
793
+ if (ignoredStdinFd !== void 0) closeSync(ignoredStdinFd);
794
+ }
795
+ const targetStdin = child.stdio[4];
796
+ const direct = Promise.withResolvers();
797
+ const rangeExit = Promise.withResolvers();
798
+ let directResultType;
799
+ let runnerSpawned = false;
800
+ let runnerExit;
801
+ let ipcDisconnected = false;
802
+ const failInfrastructure = (error) => {
803
+ direct.reject(error);
804
+ rangeExit.reject(error);
805
+ };
806
+ const settleRange = () => {
807
+ if (!runnerSpawned || runnerExit === void 0) return;
808
+ const { exitCode, signal } = runnerExit;
809
+ if (exitCode === 0 && signal === null) {
810
+ if (directResultType !== void 0) {
811
+ rangeExit.resolve();
812
+ return;
813
+ }
814
+ if (!ipcDisconnected) return;
815
+ }
816
+ failInfrastructure(new SubprocessError(`subprocess-local: Windows Job runner exited with ${signal !== null ? `signal ${signal}` : exitCode === null ? "without an exit status" : `exit code ${String(exitCode)}`} before proving its managed range empty`, "SUBPROCESS_RUNNER_FAILED"));
817
+ };
818
+ const owner = new WindowsJobOwner(child, rangeExit.promise, () => directResultType, failInfrastructure);
819
+ child.on("message", (value) => {
820
+ if (directResultType !== void 0) {
821
+ failInfrastructure(new SubprocessError("subprocess-local: Windows runner emitted more than one direct result", "SUBPROCESS_RUNNER_IPC_FAILED"));
822
+ owner.terminateForHostExit();
823
+ return;
824
+ }
825
+ let result;
826
+ try {
827
+ result = parseWindowsRunnerResult(value);
828
+ } catch (error) {
829
+ failInfrastructure(new SubprocessError(`subprocess-local: Windows runner emitted a malformed result: ${String(error)}`, "SUBPROCESS_RUNNER_IPC_FAILED", { cause: error }));
830
+ owner.terminateForHostExit();
831
+ return;
832
+ }
833
+ directResultType = result.type;
834
+ if (result.type === "target-exit") direct.resolve({
835
+ exitCode: result.exitCode,
836
+ signal: null
837
+ });
838
+ else direct.reject(owner.mapStartFailure(deserializeRunnerError(result.error), result.error));
839
+ settleRange();
840
+ });
841
+ child.once("spawn", () => {
842
+ runnerSpawned = true;
843
+ try {
844
+ if (child.send === void 0) throw new SubprocessError("subprocess-local: Windows runner has no IPC channel", "SUBPROCESS_RUNNER_IPC_FAILED");
845
+ child.send({
846
+ type: "start",
847
+ cwd: spec.cwd,
848
+ env: targetEnv,
849
+ ...spec.stdio.control === void 0 ? {} : { control: spec.stdio.control }
850
+ }, (error) => {
851
+ if (error === null) return;
852
+ failInfrastructure(runnerIpcFailure(error));
853
+ owner.terminateForHostExit();
854
+ });
855
+ } catch (error) {
856
+ failInfrastructure(runnerIpcFailure(error));
857
+ owner.terminateForHostExit();
858
+ }
859
+ });
860
+ child.once("error", (error) => {
861
+ if (!runnerSpawned) {
862
+ direct.reject(error);
863
+ rangeExit.resolve();
864
+ return;
865
+ }
866
+ failInfrastructure(new SubprocessError(`subprocess-local: Windows Job runner failed after it started: ${String(error)}`, "SUBPROCESS_RUNNER_FAILED", { cause: error }));
867
+ });
868
+ child.once("exit", (exitCode, signal) => {
869
+ runnerExit = {
870
+ exitCode,
871
+ signal
872
+ };
873
+ settleRange();
874
+ });
875
+ child.once("disconnect", () => {
876
+ ipcDisconnected = true;
877
+ settleRange();
878
+ });
879
+ return {
880
+ stdin: spec.stdio.stdin === "ignore" ? null : targetStdin,
881
+ stdout: child.stdio[5],
882
+ stderr: child.stdio[6],
883
+ control: controlPipe(child, spec.stdio.control),
884
+ direct: direct.promise,
885
+ owner
886
+ };
887
+ }
888
+ //#endregion
889
+ //#region lib/types/terminal.js
890
+ /** Local node-pty terminal-process implementation for the subprocess seam. */
891
+ function delay(ms, signal) {
892
+ return new Promise((resolve) => {
893
+ const finish = () => {
894
+ clearTimeout(timer);
895
+ signal?.removeEventListener("abort", finish);
896
+ resolve();
897
+ };
898
+ const timer = setTimeout(finish, ms);
899
+ signal?.addEventListener("abort", finish, { once: true });
900
+ });
901
+ }
902
+ async function raceWithDelay(operation, ms, timeout) {
903
+ const controller = new AbortController();
904
+ try {
905
+ return await Promise.race([operation, delay(ms, controller.signal).then(() => timeout)]);
906
+ } finally {
907
+ controller.abort();
908
+ }
909
+ }
910
+ function signalName(number) {
911
+ if (number === void 0 || number === 0) return null;
912
+ for (const [name, value] of Object.entries(constants$1.signals)) if (value === number) return name;
913
+ return null;
914
+ }
915
+ /**
916
+ * A local terminal whose native managed range or fallback process-session
917
+ * ownership stays below the PTY backend.
918
+ * The seam's terminate() promise — no write, inspection, or signal in flight
919
+ * after settlement — holds here without operation tracking only because every
920
+ * handle call completes synchronously under the hood (node-pty write, ps-based
921
+ * inspection). A first genuinely asynchronous step in any handle call must add
922
+ * the tracking a remote provider needs.
923
+ */
924
+ var LocalTerminalHandle = class {
925
+ terminal;
926
+ inspector;
927
+ graceMs;
928
+ platform;
929
+ managedOwner;
930
+ resolveManagedOutcome;
931
+ shellActivity;
932
+ onQuiescence;
933
+ observeShellExit;
934
+ pid;
935
+ output = new PassThrough();
936
+ done;
937
+ outcome = Promise.withResolvers();
938
+ dataDisposable;
939
+ exitDisposable;
940
+ cleanup;
941
+ managedOwnerCleaned = false;
942
+ exited = false;
943
+ outputPaused = false;
944
+ trackedDescendants = [];
945
+ activityRevision = 0;
946
+ activityKey = "";
947
+ quiescent = false;
948
+ managedRangeEmpty = false;
949
+ /** The spawned shell's start identity; scans stop adopting members once the root pid no longer carries it. */
950
+ rootIdentity;
951
+ /**
952
+ * @param terminal - allocated node-pty process.
953
+ * @param inspector - platform process/session operations.
954
+ * @param graceMs - TERM-to-KILL and exit-wait grace.
955
+ * @param platform - host platform; defaults to the running platform, injectable for deterministic tests.
956
+ */
957
+ constructor(terminal, inspector, graceMs, platform = process.platform, managedOwner, resolveManagedOutcome, shellActivity, onQuiescence, observeShellExit = false) {
958
+ this.terminal = terminal;
959
+ this.inspector = inspector;
960
+ this.graceMs = graceMs;
961
+ this.platform = platform;
962
+ this.managedOwner = managedOwner;
963
+ this.resolveManagedOutcome = resolveManagedOutcome;
964
+ this.shellActivity = shellActivity;
965
+ this.onQuiescence = onQuiescence;
966
+ this.observeShellExit = observeShellExit;
967
+ this.pid = terminal.pid;
968
+ try {
969
+ this.rootIdentity = inspector.snapshot().tree(this.pid).find((member) => member.pid === this.pid);
970
+ } catch (_rootIdentityUnavailable) {
971
+ this.rootIdentity = void 0;
972
+ }
973
+ this.done = this.outcome.promise;
974
+ const resume = () => {
975
+ if (!this.outputPaused) return;
976
+ this.outputPaused = false;
977
+ if (!this.exited) terminal.resume();
978
+ };
979
+ this.output.on("drain", resume);
980
+ this.output.once("close", () => {
981
+ this.output.off("drain", resume);
982
+ });
983
+ this.dataDisposable = terminal.onData((data) => {
984
+ if (!this.output.write(Buffer.from(data, "utf8")) && this.cleanup === void 0 && !this.outputPaused) {
985
+ this.outputPaused = true;
986
+ terminal.pause();
987
+ }
988
+ });
989
+ this.exitDisposable = terminal.onExit(({ exitCode, signal: exitSignal }) => {
990
+ if (this.exited) return;
991
+ this.exited = true;
992
+ if (this.managedOwner !== void 0 && this.observeShellExit) this.managedOwner.waitForExit().then(() => {
993
+ this.managedRangeEmpty = true;
994
+ }).catch(() => {});
995
+ this.output.end();
996
+ const outcome = {
997
+ exitCode: exitSignal === void 0 || exitSignal === 0 ? exitCode : null,
998
+ signal: signalName(exitSignal)
999
+ };
1000
+ try {
1001
+ this.outcome.resolve(this.resolveManagedOutcome?.(outcome) ?? outcome);
1002
+ } catch (error) {
1003
+ this.outcome.reject(error);
1004
+ }
1005
+ });
1006
+ }
1007
+ /** Whether node-pty has not yet published the top-level exit event. */
1008
+ get running() {
1009
+ return !this.exited;
1010
+ }
1011
+ async write(data) {
1012
+ if (this.exited) throw new Error("terminal process has exited");
1013
+ this.shellActivity?.invalidate();
1014
+ this.terminal.write(data);
1015
+ }
1016
+ async resize(cols, rows) {
1017
+ if (this.exited) throw new Error("terminal process has exited");
1018
+ this.terminal.resize(cols, rows);
1019
+ }
1020
+ async inspectForeground() {
1021
+ this.descendants(this.inspector.snapshot());
1022
+ const processGroupId = this.inspector.foregroundPgid(this.pid);
1023
+ if (processGroupId === void 0) return void 0;
1024
+ return {
1025
+ processGroupId,
1026
+ inputWaiting: this.inspector.isStdinWaiting(processGroupId, this.pid)
1027
+ };
1028
+ }
1029
+ async inspectActivity() {
1030
+ let state = this.quiescent ? "idle" : "unknown";
1031
+ let revision = 0;
1032
+ if (!this.quiescent) try {
1033
+ const shell = this.shellActivity?.inspect(this.pid) ?? {
1034
+ state: "unknown",
1035
+ revision: 0
1036
+ };
1037
+ revision = shell.revision;
1038
+ const observed = this.inspector.snapshot();
1039
+ const descendants = this.descendants(observed);
1040
+ const root = observed.tree(this.pid).find((member) => member.pid === this.pid);
1041
+ if (this.exited && this.managedRangeEmpty) state = "idle";
1042
+ else if (descendants.length > 0) state = "busy";
1043
+ else if (this.exited && this.managedOwner === void 0 && this.platform === "linux" && observed.complete === true && root === void 0) state = observed.session(this.pid).some((member) => observed.alive(member)) ? "busy" : "idle";
1044
+ else if (observed.complete === true && root?.started === this.rootIdentity?.started && root !== void 0) {
1045
+ const foreground = this.inspector.foregroundPgid(this.pid);
1046
+ state = foreground === void 0 ? "unknown" : foreground === this.pid ? shell.state : "busy";
1047
+ if (state === "idle" && this.managedOwner !== void 0) {
1048
+ const tasks = this.managedOwner.inspectTaskCount?.();
1049
+ state = tasks === void 0 || tasks < 1 ? "unknown" : tasks === 1 ? "idle" : "busy";
1050
+ }
1051
+ }
1052
+ } catch (_incompleteActivityObservation) {
1053
+ state = "unknown";
1054
+ }
1055
+ const key = `${revision}:${state}`;
1056
+ if (key !== this.activityKey) {
1057
+ this.activityKey = key;
1058
+ this.activityRevision++;
1059
+ }
1060
+ return {
1061
+ state,
1062
+ revision: this.activityRevision
1063
+ };
1064
+ }
1065
+ async signalForeground(signal) {
1066
+ this.shellActivity?.invalidate();
1067
+ const foreground = await this.inspectForeground();
1068
+ if (foreground === void 0) throw new Error(`cannot resolve foreground process group for terminal ${this.pid}`);
1069
+ if (signal === "SIGKILL" && foreground.processGroupId === this.pid) throw new Error("refusing to SIGKILL the terminal shell; terminate the terminal session instead");
1070
+ if (this.platform === "win32") {
1071
+ if (signal === "SIGINT") {
1072
+ this.terminal.write("");
1073
+ return foreground.processGroupId;
1074
+ }
1075
+ if (signal === "SIGTSTP" || signal === "SIGHUP") throw new Error(`signal ${signal} is unsupported on Windows; only SIGINT, SIGTERM, and SIGKILL are available`);
1076
+ }
1077
+ this.inspector.signalGroup(foreground.processGroupId, signal);
1078
+ return foreground.processGroupId;
1079
+ }
1080
+ terminate() {
1081
+ if (this.cleanup !== void 0) return this.cleanup;
1082
+ if (this.outputPaused) {
1083
+ this.outputPaused = false;
1084
+ this.terminal.resume();
1085
+ }
1086
+ const cleanup = this.closeOnce().then(() => {
1087
+ this.quiescent = true;
1088
+ this.shellActivity?.dispose();
1089
+ this.onQuiescence?.();
1090
+ });
1091
+ this.cleanup = cleanup;
1092
+ cleanup.catch(() => {
1093
+ this.cleanup = void 0;
1094
+ });
1095
+ return cleanup;
1096
+ }
1097
+ /**
1098
+ * Force-terminate the observable session synchronously during Node's exit
1099
+ * event. This does not claim quiescence and does not replace terminate().
1100
+ */
1101
+ terminateForHostExit() {
1102
+ this.forceStopDescendants();
1103
+ this.forceStopShell();
1104
+ this.forceStopDescendants();
1105
+ this.managedOwner?.terminateForHostExit();
1106
+ }
1107
+ forceStopShell() {
1108
+ if (this.exited) return;
1109
+ if (this.rootIdentity !== void 0) {
1110
+ try {
1111
+ this.inspector.signalProcess(this.rootIdentity, "SIGKILL");
1112
+ } catch (_rootExitedDuringHostExit) {}
1113
+ return;
1114
+ }
1115
+ try {
1116
+ this.terminal.kill("SIGKILL");
1117
+ } catch (_unidentifiedShellExitedDuringHostExit) {}
1118
+ }
1119
+ survivors(members, observed) {
1120
+ return members.filter((member) => observed.alive(member));
1121
+ }
1122
+ descendants(observed) {
1123
+ const tree = observed.tree(this.pid);
1124
+ const root = tree.find((member) => member.pid === this.pid);
1125
+ const rootVerified = this.rootIdentity !== void 0 && root !== void 0 && root.started === this.rootIdentity.started;
1126
+ this.trackedDescendants = this.survivors(this.unionMembers(this.trackedDescendants, ...rootVerified ? [tree, observed.session(this.pid)] : []).filter((member) => member.pid !== this.pid), observed);
1127
+ return this.trackedDescendants;
1128
+ }
1129
+ async waitForMembers(members) {
1130
+ if (members.length === 0) return [];
1131
+ const until = Date.now() + this.graceMs;
1132
+ let survivors = this.survivors(members, this.inspector.snapshot());
1133
+ while (survivors.length > 0 && Date.now() < until) {
1134
+ await delay(Math.min(25, Math.max(1, until - Date.now())));
1135
+ survivors = this.survivors(members, this.inspector.snapshot());
1136
+ }
1137
+ return survivors;
1138
+ }
1139
+ signalMembers(members, signal) {
1140
+ for (const member of members) try {
1141
+ this.inspector.signalProcess(member, signal);
1142
+ } catch (_alreadyExitedDuringSignal) {}
1143
+ }
1144
+ forceStopDescendants() {
1145
+ let members = this.trackedDescendants;
1146
+ try {
1147
+ members = this.descendants(this.inspector.snapshot());
1148
+ } catch (_processTableUnavailableDuringHostExit) {}
1149
+ this.signalMembers(members, "SIGKILL");
1150
+ }
1151
+ unionMembers(...groups) {
1152
+ const members = [];
1153
+ const seen = /* @__PURE__ */ new Set();
1154
+ for (const group of groups) for (const member of group) {
1155
+ const key = `${member.pid}:${member.started}`;
1156
+ if (seen.has(key)) continue;
1157
+ seen.add(key);
1158
+ members.push(member);
1159
+ }
1160
+ return members;
1161
+ }
1162
+ async stopDescendants() {
1163
+ const captured = this.descendants(this.inspector.snapshot());
1164
+ this.signalMembers(captured, "SIGTERM");
1165
+ const capturedSurvivors = await this.waitForMembers(captured);
1166
+ const members = this.unionMembers(capturedSurvivors, this.descendants(this.inspector.snapshot()));
1167
+ this.signalMembers(members, "SIGKILL");
1168
+ const survivors = await this.waitForMembers(members);
1169
+ const observed = this.inspector.snapshot();
1170
+ return this.survivors(this.unionMembers(survivors, this.descendants(observed)), observed);
1171
+ }
1172
+ async stopShell() {
1173
+ if (this.platform === "win32") {
1174
+ await this.stopShellWindows();
1175
+ return;
1176
+ }
1177
+ if (!this.exited) {
1178
+ try {
1179
+ this.terminal.kill("SIGTERM");
1180
+ } catch (_topLevelAlreadyExitedDuringTerm) {}
1181
+ await Promise.race([this.done.then(() => void 0), delay(this.graceMs)]);
1182
+ }
1183
+ if (!this.exited) {
1184
+ try {
1185
+ this.terminal.kill("SIGKILL");
1186
+ } catch (_topLevelAlreadyExitedDuringKill) {}
1187
+ await Promise.race([this.done.then(() => void 0), delay(this.graceMs)]);
1188
+ }
1189
+ if (!this.exited) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`);
1190
+ }
1191
+ async stopShellWindows() {
1192
+ const shellGone = () => this.exited || this.rootIdentity !== void 0 && !this.inspector.isAlive(this.rootIdentity);
1193
+ if (!shellGone() && this.rootIdentity !== void 0) {
1194
+ this.inspector.signalProcess(this.rootIdentity, "SIGTERM");
1195
+ await this.waitForWindowsShellExit();
1196
+ }
1197
+ if (!shellGone() && this.rootIdentity === void 0) {
1198
+ try {
1199
+ this.terminal.kill();
1200
+ } catch (_topLevelAlreadyExitedDuringKill) {}
1201
+ await Promise.race([this.done.then(() => void 0), delay(this.graceMs)]);
1202
+ }
1203
+ if (!shellGone() && this.rootIdentity !== void 0) {
1204
+ this.inspector.signalProcess(this.rootIdentity, "SIGKILL");
1205
+ await this.waitForWindowsShellExit();
1206
+ }
1207
+ if (!shellGone()) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`);
1208
+ }
1209
+ async waitForWindowsShellExit() {
1210
+ const until = Date.now() + this.graceMs;
1211
+ while (!this.exited && Date.now() < until) {
1212
+ if (this.rootIdentity !== void 0 && !this.inspector.isAlive(this.rootIdentity)) return;
1213
+ await delay(Math.min(25, Math.max(1, until - Date.now())));
1214
+ }
1215
+ }
1216
+ async closeOnce() {
1217
+ if (this.managedOwner !== void 0) {
1218
+ try {
1219
+ await this.closeManagedRange(this.managedOwner);
1220
+ this.dataDisposable.dispose();
1221
+ this.exitDisposable.dispose();
1222
+ } finally {
1223
+ this.done.finally(() => {
1224
+ this.cleanupManagedOwner(this.managedOwner);
1225
+ }).catch(() => {});
1226
+ }
1227
+ return;
1228
+ }
1229
+ let survivors = await this.stopDescendants();
1230
+ if (survivors.length > 0) throw new Error(`terminal cleanup failed; surviving pids: ${survivors.map((member) => member.pid).join(", ")}`);
1231
+ await this.stopShell();
1232
+ survivors = await this.stopDescendants();
1233
+ if (survivors.length > 0) throw new Error(`terminal cleanup failed; surviving pids: ${survivors.map((member) => member.pid).join(", ")}`);
1234
+ this.settleExitIfGone();
1235
+ this.dataDisposable.dispose();
1236
+ this.exitDisposable.dispose();
1237
+ }
1238
+ cleanupManagedOwner(owner) {
1239
+ if (this.managedOwnerCleaned) return;
1240
+ this.managedOwnerCleaned = true;
1241
+ owner.cleanup?.();
1242
+ }
1243
+ async closeManagedRange(owner) {
1244
+ owner.signal("SIGTERM");
1245
+ const observation = owner.waitForExit();
1246
+ const first = await raceWithDelay(observation.then(() => ({ kind: "stopped" }), (error) => ({
1247
+ kind: "failed",
1248
+ error
1249
+ })), this.graceMs, { kind: "timeout" });
1250
+ if (first.kind !== "stopped") {
1251
+ owner.signal("SIGKILL");
1252
+ if (first.kind === "failed") {
1253
+ try {
1254
+ await owner.waitForExit();
1255
+ } catch (finalError) {
1256
+ throw new AggregateError([first.error, finalError], "terminal managed-range cleanup failed");
1257
+ }
1258
+ throw first.error;
1259
+ }
1260
+ await observation;
1261
+ }
1262
+ if (!this.exited) await raceWithDelay(this.done.then(() => void 0), this.graceMs, void 0);
1263
+ if (!this.exited) throw new Error(`terminal cleanup failed; surviving pid: ${this.pid}`);
1264
+ }
1265
+ settleExitIfGone() {
1266
+ if (this.platform !== "win32") return;
1267
+ if (this.exited) return;
1268
+ /* v8 ignore next -- stopShellWindows() verified the shell is gone or threw;
1269
+ the identity re-check is a defensive fence for a future caller. */
1270
+ if (this.rootIdentity !== void 0 && this.inspector.isAlive(this.rootIdentity)) return;
1271
+ this.exited = true;
1272
+ this.output.end();
1273
+ this.outcome.resolve({
1274
+ exitCode: null,
1275
+ signal: null
1276
+ });
1277
+ }
1278
+ };
1279
+ //#endregion
1280
+ //#region lib/types/shell-activity.js
1281
+ /** Private shell lifecycle files; ordinary output never authorizes terminal reclamation. */
1282
+ function quote(value) {
1283
+ return `'${value.replaceAll("'", "'\\''")}'`;
1284
+ }
1285
+ /** Opt-in startup integration and revision tracking for one ordinary interactive shell. */
1286
+ var ShellActivity = class {
1287
+ directory;
1288
+ argv;
1289
+ env;
1290
+ revision = 0;
1291
+ observed = "";
1292
+ invalidated;
1293
+ state = "unknown";
1294
+ /**
1295
+ * @param directory - private startup and status file directory.
1296
+ * @param argv - shell launch preserving supported user startup files.
1297
+ * @param env - environment with any temporary startup redirect.
1298
+ */
1299
+ constructor(directory, argv, env) {
1300
+ this.directory = directory;
1301
+ this.argv = argv;
1302
+ this.env = env;
1303
+ }
1304
+ /** Invalidate prompt evidence before delivering input or a foreground signal. */
1305
+ invalidate() {
1306
+ this.invalidated = this.read();
1307
+ this.revision++;
1308
+ this.state = "unknown";
1309
+ }
1310
+ /**
1311
+ * Read the latest top-level shell transition, fenced against input since that transition.
1312
+ * @param pid - original shell process id.
1313
+ * @returns lifecycle evidence; process ownership must be checked separately.
1314
+ */
1315
+ inspect(pid) {
1316
+ const record = this.read();
1317
+ if (record !== this.observed) {
1318
+ this.observed = record;
1319
+ this.revision++;
1320
+ }
1321
+ const match = /^(\d+):(\d+):(idle|busy)\n?$/u.exec(record);
1322
+ this.state = record === this.invalidated || match?.[1] !== String(pid) ? "unknown" : match[3];
1323
+ return {
1324
+ state: this.state,
1325
+ revision: this.revision
1326
+ };
1327
+ }
1328
+ /** Remove private startup and status files after process quiescence. */
1329
+ dispose() {
1330
+ rmSync(this.directory, {
1331
+ recursive: true,
1332
+ force: true
1333
+ });
1334
+ }
1335
+ read() {
1336
+ try {
1337
+ return readFileSync(join(this.directory, "state"), "utf8");
1338
+ } catch (_unavailableShellObservation) {
1339
+ return "";
1340
+ }
1341
+ }
1342
+ };
1343
+ /**
1344
+ * Prepare optional Bash or Zsh integration for a plain, non-login interactive launch.
1345
+ * @param spec - terminal request; custom arguments and wrapped executables remain unmodified.
1346
+ * @param env - scrubbed target environment.
1347
+ * @param platform - execution platform.
1348
+ * @returns private integration, or undefined for unsupported launches.
1349
+ */
1350
+ function prepareShellActivity(spec, env, platform) {
1351
+ if (spec.shellActivity !== true || platform === "win32" || spec.argv.length !== 2 || spec.argv[1] !== "-i") return void 0;
1352
+ const shell = basename(spec.argv[0]);
1353
+ if (shell !== "bash" && shell !== "zsh") return void 0;
1354
+ const directory = mkdtempSync(join(tmpdir(), "rabi-shell-"));
1355
+ const state = quote(join(directory, "state"));
1356
+ const guards = quote(join(directory, "guards"));
1357
+ try {
1358
+ if (shell === "bash") {
1359
+ const rc = join(directory, "bashrc");
1360
+ writeFileSync(rc, [
1361
+ "[[ ! -r ~/.bashrc ]] || builtin source ~/.bashrc",
1362
+ "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",
1363
+ " __rabi_shell_pid=$BASHPID; __rabi_shell_sequence=0",
1364
+ " __rabi_shell_idle() {",
1365
+ " local result=$?",
1366
+ " if [[ $BASHPID == \"$__rabi_shell_pid\" ]]; then",
1367
+ " (( ++__rabi_shell_sequence ))",
1368
+ " local activity=idle",
1369
+ ` builtin trap -p >| ${guards}`,
1370
+ ` [[ ! -s ${guards} ]] || activity=unknown`,
1371
+ ` builtin printf '%s:%s:%s\\n' "$BASHPID" "$__rabi_shell_sequence" "$activity" >| ${state}`,
1372
+ " fi",
1373
+ " return \"$result\"",
1374
+ " }",
1375
+ " if [[ $(declare -p PROMPT_COMMAND 2>/dev/null) == \"declare -a \"* ]]; then",
1376
+ " PROMPT_COMMAND+=(__rabi_shell_idle)",
1377
+ " else",
1378
+ " PROMPT_COMMAND=\"${PROMPT_COMMAND}\"$'\\n'\"__rabi_shell_idle\"",
1379
+ " fi",
1380
+ ` PS0+=${quote(`$(builtin printf '%s:%s:busy' "$__rabi_shell_pid" "$__rabi_shell_sequence" >| ${state})`)}`,
1381
+ "fi",
1382
+ ""
1383
+ ].join("\n"), {
1384
+ mode: 384,
1385
+ flag: "wx"
1386
+ });
1387
+ return new ShellActivity(directory, [
1388
+ spec.argv[0],
1389
+ "--rcfile",
1390
+ rc,
1391
+ "-i"
1392
+ ], env);
1393
+ }
1394
+ writeFileSync(join(directory, ".zshenv"), [
1395
+ env.ZDOTDIR === void 0 ? "unset ZDOTDIR" : `ZDOTDIR=${quote(env.ZDOTDIR)}`,
1396
+ "[[ ! -r ${ZDOTDIR:-$HOME}/.zshenv ]] || builtin source \"${ZDOTDIR:-$HOME}/.zshenv\"",
1397
+ "typeset -g __rabi_shell_pid=$$ __rabi_shell_sequence=0",
1398
+ "__rabi_shell_activity() {",
1399
+ " (( ZSH_SUBSHELL == 0 && $$ == __rabi_shell_pid )) || return",
1400
+ " (( ++__rabi_shell_sequence ))",
1401
+ ` builtin printf '%s:%s:%s\\n' "$$" "$__rabi_shell_sequence" "$1" >| ${state}`,
1402
+ " return 0",
1403
+ "}",
1404
+ "__rabi_shell_idle() {",
1405
+ ` { builtin trap; zle -F; } >| ${guards}`,
1406
+ " if [[ $CONTEXT != start || -n $BUFFER ]]; then __rabi_shell_activity busy",
1407
+ ` elif [[ -s ${guards} || -n \${(k)functions[(I)TRAP*]} ]]; then __rabi_shell_activity unknown`,
1408
+ " else __rabi_shell_activity idle; fi",
1409
+ "}",
1410
+ "__rabi_shell_busy() { __rabi_shell_activity busy }",
1411
+ "__rabi_shell_init() {",
1412
+ " autoload -Uz add-zle-hook-widget add-zsh-hook",
1413
+ " add-zle-hook-widget line-init __rabi_shell_idle",
1414
+ " add-zle-hook-widget line-finish __rabi_shell_busy",
1415
+ " add-zsh-hook preexec __rabi_shell_busy",
1416
+ " precmd_functions=(${precmd_functions:#__rabi_shell_init})",
1417
+ "}",
1418
+ "typeset -ga precmd_functions",
1419
+ "precmd_functions+=(__rabi_shell_init)",
1420
+ ""
1421
+ ].join("\n"), {
1422
+ mode: 384,
1423
+ flag: "wx"
1424
+ });
1425
+ return new ShellActivity(directory, spec.argv, {
1426
+ ...env,
1427
+ ZDOTDIR: directory
1428
+ });
1429
+ } catch (error) {
1430
+ rmSync(directory, {
1431
+ recursive: true,
1432
+ force: true
1433
+ });
1434
+ throw error;
1435
+ }
1436
+ }
1437
+ //#endregion
1438
+ //#region lib/types/index.js
1439
+ /**
1440
+ * Local Service Provider for the subprocess capability seam. Each spawn owns a
1441
+ * platform-selected managed range with the spec's per-stream stdio dispositions.
1442
+ * Normal disposal terminates and joins live ranges; Node's synchronous exit
1443
+ * phase force-stops any ranges the service still owns. It has no config: every
1444
+ * disposition and limit arrives on the spec, so deployment-varying choices
1445
+ * stay with the caller's config (the bash executor's, the LSP host's, …).
1446
+ * @module @unieai/rabi-subprocess-local
1447
+ */
1448
+ const requireNodePty = createLazyRequire("node-pty", import.meta.url);
1449
+ /** Load node-pty, reporting a missing or unloadable native module as `SUBPROCESS_PTY_UNAVAILABLE`. */
1450
+ function loadNodePty() {
1451
+ try {
1452
+ return requireNodePty();
1453
+ } catch (error) {
1454
+ throw new SubprocessError(`subprocess-local: terminals are unavailable because node-pty cannot be loaded: ${String(error)}`, "SUBPROCESS_PTY_UNAVAILABLE", { cause: error });
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Local subprocess service: platform-selected managed ranges, Node-shaped stdio
1459
+ * dispositions (raw pipes, inherit, bounded tail-keep collection with spill
1460
+ * files), credential-scrubbed environment, and provider-owned range signalling.
1461
+ * POSIX paths stage TERM before KILL; Windows paths terminate immediately.
1462
+ * JavaScript-observable host exit also performs synchronous final termination.
1463
+ */
1464
+ var LocalSubprocessRuntime = class extends SubprocessRuntime {
1465
+ /** Live handles retained for normal disposal and synchronous host-exit finalization. */
1466
+ live = /* @__PURE__ */ new Set();
1467
+ /** Live terminals retained through normal quiescence or host-exit finalization. */
1468
+ terminals = /* @__PURE__ */ new Set();
1469
+ /** Caller endpoints retained until close, independently of managed process lifetime. */
1470
+ controlChannels = /* @__PURE__ */ new Set();
1471
+ /** Test hook: process, spill, and platform operations forwarded to spawnSubprocess. */
1472
+ internals = {};
1473
+ /** Provider-lifetime latch suppressing repeated weaker-containment warnings. */
1474
+ fallbackWarningIssued = false;
1475
+ /**
1476
+ * Linux native containment decisions. Each probe is a spawnSync that blocks the event loop and forks the
1477
+ * host, so the selector reruns it only after an event invalidates the previous verdict.
1478
+ */
1479
+ linuxScope = new LinuxScopeSelector({
1480
+ probe: () => probeLinuxNative(),
1481
+ managerListener: () => linuxManagerListener(),
1482
+ confirmManager: () => confirmLinuxManager(),
1483
+ launcherIdentity: () => systemdRunIdentity()
1484
+ });
1485
+ /** Scope decision of the launch in progress; selectContainmentMode sets it immediately before the launch reads it. */
1486
+ linuxScopeDecision;
1487
+ /** Test hook for platform process inspection; production resolves lazily on terminal spawn. */
1488
+ terminalInspector;
1489
+ constructor(ctx) {
1490
+ super(ctx);
1491
+ ctx.effect(() => {
1492
+ const onHostExit = () => {
1493
+ this.terminateForHostExit();
1494
+ };
1495
+ process.prependListener("exit", onHostExit);
1496
+ return async () => {
1497
+ await this.disposeManagedProcesses();
1498
+ process.off("exit", onHostExit);
1499
+ };
1500
+ }, "local subprocess teardown");
1501
+ }
1502
+ /** Spill failures reach the plugin logger; the log line is the only trace of why a result has no spill path. */
1503
+ reportSpillFailure = logSpillFailure(this.ctx.logger, "subprocess-local");
1504
+ terminateForHostExit() {
1505
+ for (const handle of this.live) try {
1506
+ handle.terminateForHostExit();
1507
+ } catch (_ordinaryRangeTerminationFailed) {}
1508
+ for (const terminal of this.terminals) try {
1509
+ terminal.terminateForHostExit();
1510
+ } catch (_terminalTerminationFailed) {}
1511
+ }
1512
+ async disposeManagedProcesses() {
1513
+ const pending = [];
1514
+ for (const handle of this.live) {
1515
+ handle.terminate();
1516
+ pending.push(Promise.all([handle.done.catch(() => {}), handle.waitForExit()]).then(() => {
1517
+ this.live.delete(handle);
1518
+ }));
1519
+ }
1520
+ for (const terminal of this.terminals) pending.push(terminal.terminate().then(() => {
1521
+ this.terminals.delete(terminal);
1522
+ }));
1523
+ const outcomes = await Promise.allSettled(pending);
1524
+ await Promise.all([...this.controlChannels].map((control) => new Promise((resolveClose) => {
1525
+ control.once("close", () => {
1526
+ resolveClose();
1527
+ });
1528
+ control.destroy();
1529
+ })));
1530
+ this.controlChannels.clear();
1531
+ const failures = [];
1532
+ for (const outcome of outcomes) if (outcome.status === "rejected") failures.push(outcome.reason);
1533
+ if (failures.length > 0) this.terminateForHostExit();
1534
+ if (failures.length === 1) throw failures[0];
1535
+ if (failures.length > 1) throw new AggregateError(failures, "local subprocess teardown failed");
1536
+ }
1537
+ async resolveExecutable(command, env, signal) {
1538
+ if (command.length === 0) throw new Error("subprocess-local: executable must be non-empty");
1539
+ signal?.throwIfAborted();
1540
+ const environment = childEnv(env);
1541
+ const absolute = isAbsolute(command);
1542
+ if (!absolute && (command.includes("/") || process.platform === "win32" && command.includes("\\"))) throw new Error(`subprocess-local: command ${JSON.stringify(command)} is a relative path; use an absolute path or a bare PATH name`);
1543
+ const candidates = absolute ? [command] : this.executableCandidates(command, environment);
1544
+ for (const candidate of candidates) {
1545
+ signal?.throwIfAborted();
1546
+ try {
1547
+ if (!(await stat(candidate)).isFile()) continue;
1548
+ await access(candidate, constants.X_OK);
1549
+ signal?.throwIfAborted();
1550
+ return candidate;
1551
+ } catch {}
1552
+ }
1553
+ signal?.throwIfAborted();
1554
+ throw new SubprocessExecutableNotFoundError(absolute ? `subprocess-local: command ${JSON.stringify(command)} is not an executable file` : `subprocess-local: command ${JSON.stringify(command)} was not found on PATH`);
1555
+ }
1556
+ executableCandidates(command, env) {
1557
+ const path = environmentValue(env, "PATH") ?? "";
1558
+ const extensions = process.platform === "win32" && extname(command) === "" ? (environmentValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
1559
+ return path.split(delimiter).flatMap((directory) => extensions.map((extension) => resolve(process.cwd(), directory, command + extension)));
1560
+ }
1561
+ spawn(spec) {
1562
+ validateSubprocessSpec(spec);
1563
+ const env = targetEnvironment(spec);
1564
+ const containmentMode = this.selectContainmentMode("ordinary");
1565
+ let handle;
1566
+ const internals = {
1567
+ ...this.internals,
1568
+ onSpillFailure: this.reportSpillFailure
1569
+ };
1570
+ if (containmentMode === "fallback") handle = spawnSubprocess(spec, internals);
1571
+ else {
1572
+ const binding = prepareManagedProcessBinding(internals);
1573
+ const linuxScope = containmentMode === "linux-scope" ? this.linuxScopeDecision : void 0;
1574
+ handle = bindManagedProcess(spec, linuxScope === void 0 ? launchWindowsJob(spec, env) : launchLinuxScope(spec, env, linuxScope.literalArgv), binding);
1575
+ if (linuxScope !== void 0) this.watchLinuxScopeStart(handle.done, linuxScope.generation);
1576
+ }
1577
+ this.live.add(handle);
1578
+ const control = handle.control;
1579
+ if (control !== void 0) {
1580
+ this.controlChannels.add(control);
1581
+ control.once("close", () => {
1582
+ this.controlChannels.delete(control);
1583
+ });
1584
+ }
1585
+ const release = () => handle.waitForExit().then(() => {
1586
+ this.live.delete(handle);
1587
+ });
1588
+ handle.done.then(release, release).catch(() => {});
1589
+ return handle;
1590
+ }
1591
+ /** Probe again before the next launch when a scope launched under generation never started its target. */
1592
+ watchLinuxScopeStart(done, generation) {
1593
+ done.catch((error) => {
1594
+ if (error instanceof LinuxScopeNotStartedError) this.linuxScope.scopeNotStarted(generation);
1595
+ });
1596
+ }
1597
+ selectContainmentMode(kind) {
1598
+ const platform = this.internals.platform ?? process.platform;
1599
+ let fallbackReason;
1600
+ if (platform === "linux") {
1601
+ const decision = this.linuxScope.select();
1602
+ const probe = decision.probe === void 0 ? "" : `, probed after ${decision.probe}`;
1603
+ this.ctx.logger.debug(`linux native containment: ${decision.kind} (${decision.reason}${probe})`);
1604
+ if (decision.kind === "scope") {
1605
+ this.linuxScopeDecision = decision;
1606
+ return "linux-scope";
1607
+ }
1608
+ fallbackReason = "the current user-systemd scope or private bootstrap is unavailable";
1609
+ }
1610
+ if (kind === "ordinary" && platform === "win32") {
1611
+ if (probeWindowsJob()) return "windows-job";
1612
+ }
1613
+ this.warnFallback(platform, kind, fallbackReason);
1614
+ return "fallback";
1615
+ }
1616
+ warnFallback(platform, kind, selectedReason) {
1617
+ if (this.fallbackWarningIssued) return;
1618
+ this.fallbackWarningIssued = true;
1619
+ const reason = selectedReason ?? (platform === "darwin" ? "macOS has no supported persistent process-range owner" : platform === "win32" ? kind === "terminal" ? "Windows ConPTY remains outside Job containment" : "the Win32 Job runner is unavailable" : `platform ${platform} has no native managed range`);
1620
+ this.ctx.logger.warn(`subprocess-local is using weaker process-tree containment because ${reason}; descendants that escape the process group or direct-parent tree are not guaranteed to terminate or delay waitForExit()`);
1621
+ }
1622
+ /** @inheritdoc */
1623
+ async terminalEnvironment(signal) {
1624
+ signal?.throwIfAborted();
1625
+ const platform = process.platform === "win32" ? "windows" : "posix";
1626
+ const defaultShell = platform === "windows" ? process.env.ComSpec || void 0 : process.env.SHELL || userInfo().shell || void 0;
1627
+ return {
1628
+ platform,
1629
+ ...defaultShell === void 0 ? {} : { defaultShell }
1630
+ };
1631
+ }
1632
+ async spawnTerminal(spec) {
1633
+ const file = spec.argv[0];
1634
+ if (file === void 0 || file.length === 0) throw new SubprocessError("subprocess-local: terminal argv must contain a program", "SUBPROCESS_INVALID_ARGV");
1635
+ spec.signal?.throwIfAborted();
1636
+ const inspector = this.terminalInspector ?? createProcessInspector();
1637
+ const containmentMode = this.selectContainmentMode("terminal");
1638
+ const env = targetEnvironment(spec);
1639
+ const platform = this.internals.platform ?? process.platform;
1640
+ const activity = prepareShellActivity(spec, env, platform);
1641
+ const launch = activity === void 0 ? spec : {
1642
+ ...spec,
1643
+ argv: activity.argv,
1644
+ env: activity.env
1645
+ };
1646
+ const options = {
1647
+ name: spec.terminalType,
1648
+ rows: spec.rows,
1649
+ cols: spec.cols,
1650
+ cwd: spec.cwd,
1651
+ env: {
1652
+ ...activity?.env ?? env,
1653
+ TERM: spec.terminalType
1654
+ },
1655
+ ...platform === "win32" ? { useConptyDll: true } : {}
1656
+ };
1657
+ const linuxScope = containmentMode === "linux-scope" ? this.linuxScopeDecision : void 0;
1658
+ let scope;
1659
+ let terminal;
1660
+ try {
1661
+ scope = linuxScope === void 0 ? void 0 : prepareLinuxTerminalScope(launch, {
1662
+ ...activity?.env ?? env,
1663
+ PWD: spec.cwd,
1664
+ TERM: spec.terminalType
1665
+ }, linuxScope.literalArgv);
1666
+ if (scope !== void 0) {
1667
+ options.cwd = scope.cwd;
1668
+ options.env = scope.env;
1669
+ }
1670
+ terminal = loadNodePty().spawn(scope?.command ?? file, scope?.args ?? [...launch.argv.slice(1)], options);
1671
+ } catch (error) {
1672
+ scope?.cleanup();
1673
+ activity?.dispose();
1674
+ throw error;
1675
+ }
1676
+ let handle;
1677
+ const directSettlement = Promise.withResolvers();
1678
+ const owner = scope?.bindOwner({
1679
+ running: () => handle?.running ?? true,
1680
+ settled: directSettlement.promise,
1681
+ signal: (signal) => signalLinuxDirectProcess(terminal.pid, () => process.kill(terminal.pid, signal))
1682
+ });
1683
+ handle = new LocalTerminalHandle(terminal, inspector, spec.graceMs, platform, owner, scope?.resolveOutcome, activity, () => {
1684
+ this.terminals.delete(handle);
1685
+ }, spec.shellActivity === true);
1686
+ this.terminals.add(handle);
1687
+ if (linuxScope !== void 0) this.watchLinuxScopeStart(handle.done, linuxScope.generation);
1688
+ const release = async () => {
1689
+ directSettlement.resolve();
1690
+ if (spec.shellActivity === true) return;
1691
+ await handle.terminate();
1692
+ this.terminals.delete(handle);
1693
+ };
1694
+ handle.done.then(release, release).catch(() => {});
1695
+ return handle;
1696
+ }
1697
+ };
1698
+ /** Read a Windows environment key using the platform's case-insensitive semantics. */
1699
+ function environmentValue(env, name) {
1700
+ const exact = env[name];
1701
+ if (exact !== void 0 || process.platform !== "win32") return exact;
1702
+ const normalized = name.toUpperCase();
1703
+ return Object.entries(env).find(([key]) => key.toUpperCase() === normalized)?.[1];
1704
+ }
1705
+ //#endregion
1706
+ export { LocalSubprocessRuntime, LocalSubprocessRuntime as default };