@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -3,6 +3,7 @@ import { execFileSync } from "node:child_process";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { monotonicNowMs } from "../time/monotonic.js";
6
7
  const windowsJobSupervisorPath = fileURLToPath(new URL("../../../runtime/windows-job-supervisor.ps1", import.meta.url));
7
8
  export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, resolvedArgs, platform = process.platform) {
8
9
  const env = request.env;
@@ -22,7 +23,8 @@ export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, res
22
23
  const payloadPath = `${metadataPath}.launch.json`;
23
24
  const readyPath = `${metadataPath}.provider-ready.json`;
24
25
  const startGrantPath = `${metadataPath}.provider-start-granted`;
25
- fs.writeFileSync(payloadPath, `${JSON.stringify({
26
+ const memoryTelemetryPath = `${metadataPath}.memory.json`;
27
+ const serializedPayload = `${JSON.stringify({
26
28
  command: resolvedCommand,
27
29
  args: resolvedArgs,
28
30
  cwd: request.cwd,
@@ -30,7 +32,10 @@ export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, res
30
32
  supervisorId,
31
33
  readyPath,
32
34
  startGrantPath,
33
- })}\n`, {
35
+ memoryTelemetryPath,
36
+ })}\n`;
37
+ const payloadSha256 = createHash("sha256").update(serializedPayload).digest("hex");
38
+ fs.writeFileSync(payloadPath, serializedPayload, {
34
39
  encoding: "utf8",
35
40
  flag: "wx",
36
41
  mode: 0o600,
@@ -49,12 +54,16 @@ export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, res
49
54
  "Outer",
50
55
  "-PayloadPath",
51
56
  payloadPath,
57
+ "-PayloadSha256",
58
+ payloadSha256,
52
59
  ],
53
60
  detached: false,
54
61
  supervisorId,
55
62
  strategy: "windows_job_object",
56
63
  metadataPath,
64
+ memoryTelemetryPath,
57
65
  payloadPath,
66
+ payloadSha256,
58
67
  readyPath,
59
68
  startGrantPath,
60
69
  commandDigest,
@@ -147,12 +156,7 @@ export function captureHostProcessIdentity(pid, platform = process.platform) {
147
156
  }
148
157
  export async function terminateHostProcessTree(child, launch, graceMs = 2_000) {
149
158
  if (!launch) {
150
- try {
151
- child.kill("SIGTERM");
152
- }
153
- catch {
154
- // The process already settled.
155
- }
159
+ await terminateUnsupervisedProcessTree(child, graceMs);
156
160
  return;
157
161
  }
158
162
  if (launch.strategy === "windows_job_object") {
@@ -189,9 +193,48 @@ export async function terminateHostProcessTree(child, launch, graceMs = 2_000) {
189
193
  const processGroupId = child.pid;
190
194
  if (!processGroupId || !signalUnixProcessGroup(processGroupId, "SIGTERM"))
191
195
  return;
192
- await new Promise(resolve => setTimeout(resolve, graceMs));
196
+ await waitForUnixProcessGroupExit(processGroupId, graceMs);
193
197
  if (unixProcessGroupExists(processGroupId)) {
194
198
  signalUnixProcessGroup(processGroupId, "SIGKILL");
199
+ await waitForUnixProcessGroupExit(processGroupId, graceMs);
200
+ }
201
+ if (unixProcessGroupExists(processGroupId)) {
202
+ throw new Error("host_process_supervisor_termination_failed: supervised Unix process group did not stop.");
203
+ }
204
+ }
205
+ async function terminateUnsupervisedProcessTree(child, graceMs) {
206
+ const rootPid = child.pid ?? 0;
207
+ if (!Number.isSafeInteger(rootPid) || rootPid <= 0) {
208
+ try {
209
+ child.kill("SIGTERM");
210
+ }
211
+ catch {
212
+ // The process already settled before a PID was assigned.
213
+ }
214
+ return;
215
+ }
216
+ if (process.platform === "win32") {
217
+ // Without a Job Object there is no trustworthy ancestry record after the
218
+ // root has already exited. Never target a potentially reused Windows PID.
219
+ if (child.exitCode !== null || child.signalCode !== null)
220
+ return;
221
+ const rootIdentity = captureHostProcessIdentity(rootPid, "win32");
222
+ forceWindowsProcessTree(rootPid);
223
+ await waitForExactProcessExit(rootPid, rootIdentity, graceMs, "win32");
224
+ if (exactProcessExists(rootPid, rootIdentity, "win32")) {
225
+ throw new Error("host_process_supervisor_termination_failed: unsupervised Windows provider tree did not stop.");
226
+ }
227
+ return;
228
+ }
229
+ if (!signalUnixProcessGroup(rootPid, "SIGTERM"))
230
+ return;
231
+ await waitForUnixProcessGroupExit(rootPid, graceMs);
232
+ if (unixProcessGroupExists(rootPid)) {
233
+ signalUnixProcessGroup(rootPid, "SIGKILL");
234
+ await waitForUnixProcessGroupExit(rootPid, graceMs);
235
+ }
236
+ if (unixProcessGroupExists(rootPid)) {
237
+ throw new Error("host_process_supervisor_termination_failed: unsupervised Unix provider tree did not stop.");
195
238
  }
196
239
  }
197
240
  function requiredEnvironment(env, name) {
@@ -207,7 +250,7 @@ function assertMetadataPath(logDirectory, metadataPath) {
207
250
  throw new Error("host_process_supervisor_invalid: metadata path must be inside FORGE_LOG_DIR.");
208
251
  }
209
252
  }
210
- function windowsPowerShellPath() {
253
+ export function windowsPowerShellPath() {
211
254
  const systemRoot = process.env.SystemRoot?.trim() || "C:\\Windows";
212
255
  const candidate = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
213
256
  return fs.existsSync(candidate) ? candidate : "powershell.exe";
@@ -234,6 +277,12 @@ function unixProcessGroupExists(processGroupId) {
234
277
  throw error;
235
278
  }
236
279
  }
280
+ async function waitForUnixProcessGroupExit(processGroupId, timeoutMs) {
281
+ const deadline = monotonicNowMs() + timeoutMs;
282
+ while (monotonicNowMs() < deadline && unixProcessGroupExists(processGroupId)) {
283
+ await new Promise(resolve => setTimeout(resolve, 25));
284
+ }
285
+ }
237
286
  function readSupervisorMetadata(metadataPath) {
238
287
  try {
239
288
  return JSON.parse(fs.readFileSync(metadataPath, "utf8"));
@@ -259,8 +308,8 @@ function processExists(pid) {
259
308
  }
260
309
  }
261
310
  async function waitForExactProcessExit(pid, identity, timeoutMs, platform) {
262
- const deadline = Date.now() + timeoutMs;
263
- while (Date.now() < deadline && exactProcessExists(pid, identity, platform)) {
311
+ const deadline = monotonicNowMs() + timeoutMs;
312
+ while (monotonicNowMs() < deadline && exactProcessExists(pid, identity, platform)) {
264
313
  await new Promise(resolve => setTimeout(resolve, 25));
265
314
  }
266
315
  }
@@ -0,0 +1,52 @@
1
+ export interface WindowsProcessEntry {
2
+ readonly pid: number;
3
+ readonly parentPid: number;
4
+ /** Creation time; a pid with a different one is a different process. */
5
+ readonly createdAt: string;
6
+ }
7
+ /** The process table and termination primitive, injectable for tests. */
8
+ export interface WindowsProcessTable {
9
+ list(): Promise<readonly WindowsProcessEntry[]>;
10
+ /** `taskkill /PID <pid> /T /F`: the process and the descendants Windows still links to it. */
11
+ killTree(pid: number): Promise<void>;
12
+ }
13
+ export declare const systemWindowsProcessTable: WindowsProcessTable;
14
+ /** What is known about the root's creation before it has been seen in the table. */
15
+ export type WindowsRootMarker =
16
+ /** Its recorded birth marker (Get-Process ticks): matched within a millisecond. */
17
+ {
18
+ readonly exactCreatedAt: string;
19
+ }
20
+ /** It was spawned no earlier than this (ticks): set synchronously at spawn. */
21
+ | {
22
+ readonly notBefore: string;
23
+ };
24
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
25
+ export declare function windowsTicksFromEpochMs(epochMs: number): string;
26
+ /** A Windows command's tracked tree; see the module comment. */
27
+ export declare class WindowsProcessTree {
28
+ private readonly rootPid;
29
+ private readonly table;
30
+ private readonly marker;
31
+ private readonly known;
32
+ /** The root's creation time as the process table reports it, once seen. */
33
+ private observedRoot;
34
+ private rootExited;
35
+ /**
36
+ * The root marker anchors the tree even if the root exits before the first
37
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
38
+ * created after it whose parent was the root are still found. A tree with
39
+ * no marker that never saw its root cannot be proven gone.
40
+ */
41
+ constructor(rootPid: number, table: WindowsProcessTable, marker?: WindowsRootMarker | null);
42
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
43
+ markRootExited(): void;
44
+ /** Records the root's current descendants; call while the command runs. */
45
+ track(): Promise<void>;
46
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
47
+ stop(deadlineMs: number): Promise<boolean>;
48
+ private rootAnchor;
49
+ private isRoot;
50
+ private absorb;
51
+ private alive;
52
+ }
@@ -0,0 +1,144 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { windowsPowerShellPath } from "./host-process-supervisor.js";
4
+ const execFileAsync = promisify(execFile);
5
+ export const systemWindowsProcessTable = {
6
+ async list() {
7
+ const { stdout } = await execFileAsync(windowsPowerShellPath(), [
8
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
9
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToUniversalTime().Ticks)\" }",
10
+ ], { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout: 30_000 });
11
+ return stdout.split(/\r?\n/u).flatMap(line => {
12
+ const [pid, parentPid, createdAt] = line.trim().split(" ");
13
+ return pid && parentPid && createdAt ? [{ pid: Number(pid), parentPid: Number(parentPid), createdAt }] : [];
14
+ });
15
+ },
16
+ async killTree(pid) {
17
+ await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 30_000 })
18
+ .catch(() => undefined);
19
+ },
20
+ };
21
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
22
+ export function windowsTicksFromEpochMs(epochMs) {
23
+ return ((BigInt(Math.floor(epochMs)) + 62135596800000n) * 10000n).toString();
24
+ }
25
+ /** A Windows command's tracked tree; see the module comment. */
26
+ export class WindowsProcessTree {
27
+ rootPid;
28
+ table;
29
+ marker;
30
+ known = new Map();
31
+ /** The root's creation time as the process table reports it, once seen. */
32
+ observedRoot = null;
33
+ rootExited = false;
34
+ /**
35
+ * The root marker anchors the tree even if the root exits before the first
36
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
37
+ * created after it whose parent was the root are still found. A tree with
38
+ * no marker that never saw its root cannot be proven gone.
39
+ */
40
+ constructor(rootPid, table, marker = null) {
41
+ this.rootPid = rootPid;
42
+ this.table = table;
43
+ this.marker = marker;
44
+ const anchor = this.rootAnchor();
45
+ if (anchor !== null)
46
+ this.known.set(rootPid, anchor);
47
+ }
48
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
49
+ markRootExited() {
50
+ this.rootExited = true;
51
+ }
52
+ /** Records the root's current descendants; call while the command runs. */
53
+ async track() {
54
+ const entries = await this.table.list().catch(() => null);
55
+ if (entries)
56
+ this.absorb(entries);
57
+ }
58
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
59
+ async stop(deadlineMs) {
60
+ for (;;) {
61
+ const entries = await this.table.list().catch(() => null);
62
+ if (!entries) {
63
+ if (Date.now() >= deadlineMs)
64
+ return false;
65
+ await delay(200);
66
+ continue;
67
+ }
68
+ this.absorb(entries);
69
+ // Without any anchor nothing proves which processes were the root's: fail closed.
70
+ if (!this.known.has(this.rootPid))
71
+ return false;
72
+ const alive = this.alive(entries);
73
+ if (alive.length === 0)
74
+ return true;
75
+ if (Date.now() >= deadlineMs)
76
+ return false;
77
+ for (const pid of alive)
78
+ await this.table.killTree(pid);
79
+ await delay(100);
80
+ }
81
+ }
82
+ rootAnchor() {
83
+ if (this.observedRoot !== null)
84
+ return this.observedRoot;
85
+ if (this.marker === null)
86
+ return null;
87
+ return "exactCreatedAt" in this.marker ? this.marker.exactCreatedAt : this.marker.notBefore;
88
+ }
89
+ isRoot(entry) {
90
+ if (entry.pid !== this.rootPid)
91
+ return false;
92
+ if (this.observedRoot !== null)
93
+ return entry.createdAt === this.observedRoot;
94
+ if (this.marker !== null && "exactCreatedAt" in this.marker)
95
+ return ticksClose(entry.createdAt, this.marker.exactCreatedAt);
96
+ // Before it exits, the root's pid cannot name anyone else.
97
+ if (this.rootExited)
98
+ return false;
99
+ return this.marker === null || compareTicks(entry.createdAt, this.marker.notBefore) >= 0;
100
+ }
101
+ absorb(entries) {
102
+ const root = entries.find(entry => this.isRoot(entry));
103
+ if (root && this.observedRoot === null)
104
+ this.observedRoot = root.createdAt;
105
+ const anchor = this.rootAnchor();
106
+ if (anchor !== null)
107
+ this.known.set(this.rootPid, anchor);
108
+ // Parents first: repeat until no new descendant of a known member appears.
109
+ let added = true;
110
+ while (added) {
111
+ added = false;
112
+ for (const entry of entries) {
113
+ if (this.known.has(entry.pid) || entry.pid === entry.parentPid)
114
+ continue;
115
+ const parentCreatedAt = this.known.get(entry.parentPid);
116
+ // A child is never older than its parent; an older one only reuses the parent's pid as its parent id.
117
+ if (parentCreatedAt === undefined || compareTicks(entry.createdAt, parentCreatedAt) < 0)
118
+ continue;
119
+ this.known.set(entry.pid, entry.createdAt);
120
+ added = true;
121
+ }
122
+ }
123
+ }
124
+ alive(entries) {
125
+ return entries
126
+ .filter(entry => entry.pid === this.rootPid ? this.isRoot(entry) : this.known.get(entry.pid) === entry.createdAt)
127
+ .map(entry => entry.pid);
128
+ }
129
+ }
130
+ function ticksClose(left, right) {
131
+ if (!/^\d+$/u.test(left) || !/^\d+$/u.test(right))
132
+ return left === right;
133
+ const difference = BigInt(left) - BigInt(right);
134
+ return (difference < 0n ? -difference : difference) <= 10000n;
135
+ }
136
+ function compareTicks(left, right) {
137
+ if (/^\d+$/u.test(left) && /^\d+$/u.test(right)) {
138
+ return left.length === right.length ? left.localeCompare(right) : left.length - right.length;
139
+ }
140
+ return left.localeCompare(right);
141
+ }
142
+ async function delay(ms) {
143
+ await new Promise(resolve => setTimeout(resolve, ms));
144
+ }
@@ -1,17 +1,86 @@
1
+ import { type WindowsProcessTable } from "./process-tree.js";
1
2
  export interface ProcessRunRequest {
2
3
  readonly command: string;
3
4
  readonly args: readonly string[];
4
5
  readonly cwd: string;
5
6
  readonly env?: NodeJS.ProcessEnv;
7
+ readonly rawOutput?: boolean;
8
+ readonly windowsVerbatimArguments?: boolean;
9
+ /**
10
+ * Stops the child (SIGTERM, then SIGKILL after a grace period) and rejects
11
+ * with an AbortError, but only once the child has exited, and with
12
+ * `processGroup` once its whole tree is proven gone: a caller that returns
13
+ * capacity on rejection never does so while the command still runs.
14
+ */
15
+ readonly signal?: AbortSignal;
16
+ /**
17
+ * Treat the command's whole process tree as the step: it is stopped as a
18
+ * whole (on abort, and whatever outlives the command when it exits) and the
19
+ * run settles only once no member is left. Unix: the command leads its own
20
+ * process group. Windows (no process groups): the tree is tracked while the
21
+ * command runs and stopped with `taskkill /T /F`; see process-tree.ts. If the
22
+ * tree cannot be proven gone the run rejects with ProcessTreeTerminationError.
23
+ */
24
+ readonly processGroup?: boolean;
25
+ /**
26
+ * Keeps at most this many characters of each stream: the tail, after a
27
+ * truncation notice. Unbounded when omitted.
28
+ */
29
+ readonly maxOutputChars?: number;
30
+ /** Called with the child's pid once it has spawned. */
31
+ readonly onSpawn?: (pid: number) => void;
6
32
  }
7
33
  export interface ProcessRunResult {
8
34
  readonly exitCode: number;
9
35
  readonly stdout: string;
10
36
  readonly stderr: string;
37
+ /** True when maxOutputChars dropped the head of either stream. */
38
+ readonly outputTruncated?: boolean;
11
39
  }
12
40
  export interface ProcessRunner {
13
41
  run(request: ProcessRunRequest): Promise<ProcessRunResult>;
14
42
  }
43
+ /**
44
+ * A command's process tree could not be proven gone after it was stopped.
45
+ * Whatever reserved capacity for it must keep that reservation.
46
+ */
47
+ export declare class ProcessTreeTerminationError extends Error {
48
+ readonly rootPid: number;
49
+ readonly command: string;
50
+ readonly stillGone: () => Promise<boolean>;
51
+ readonly code = "process_tree_termination_unconfirmed";
52
+ /**
53
+ * `stillGone` resolves true once the tree is proven gone (Unix: an existence
54
+ * check only, since its members were already SIGKILLed; Windows: another
55
+ * tracked stop), for callers that hold the reservation until then.
56
+ */
57
+ constructor(rootPid: number, command: string, stillGone: () => Promise<boolean>);
58
+ }
59
+ /**
60
+ * True when `error`, or anything it wraps (an AggregateError's errors, a cause
61
+ * chain, a sanitized copy that kept only the message), says a process tree
62
+ * could not be proven gone. Whoever holds capacity for that tree must keep it.
63
+ */
64
+ export declare function isProcessTreeTerminationUnproven(error: unknown, depth?: number): boolean;
65
+ export interface NodeProcessRunnerOptions {
66
+ /** How long a stopped command gets after SIGTERM before SIGKILL. */
67
+ readonly terminationGraceMs?: number;
68
+ /** How long to wait for a SIGKILLed tree to disappear before giving up. */
69
+ readonly killWaitMs?: number;
70
+ /** Test seams for the Windows tree path. */
71
+ readonly platform?: NodeJS.Platform;
72
+ readonly windowsProcesses?: WindowsProcessTable;
73
+ readonly windowsTrackIntervalMs?: number;
74
+ /** Test seam: whether a Unix process group still has members. */
75
+ readonly groupAlive?: (groupId: number) => boolean;
76
+ }
15
77
  export declare class NodeProcessRunner implements ProcessRunner {
78
+ private readonly graceMs;
79
+ private readonly killWaitMs;
80
+ private readonly platform;
81
+ private readonly windowsProcesses;
82
+ private readonly windowsTrackIntervalMs;
83
+ private readonly groupAlive;
84
+ constructor(options?: NodeProcessRunnerOptions);
16
85
  run(request: ProcessRunRequest): Promise<ProcessRunResult>;
17
86
  }
@@ -1,33 +1,240 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import readline from "node:readline";
3
+ import { systemWindowsProcessTable, windowsTicksFromEpochMs, WindowsProcessTree } from "./process-tree.js";
4
+ /**
5
+ * A command's process tree could not be proven gone after it was stopped.
6
+ * Whatever reserved capacity for it must keep that reservation.
7
+ */
8
+ export class ProcessTreeTerminationError extends Error {
9
+ rootPid;
10
+ command;
11
+ stillGone;
12
+ code = "process_tree_termination_unconfirmed";
13
+ /**
14
+ * `stillGone` resolves true once the tree is proven gone (Unix: an existence
15
+ * check only, since its members were already SIGKILLed; Windows: another
16
+ * tracked stop), for callers that hold the reservation until then.
17
+ */
18
+ constructor(rootPid, command, stillGone) {
19
+ super(`process_tree_termination_unconfirmed: ${command} (pid ${rootPid}) left processes that did not stop after SIGKILL; its host capacity stays reserved until they are gone.`);
20
+ this.rootPid = rootPid;
21
+ this.command = command;
22
+ this.stillGone = stillGone;
23
+ this.name = "ProcessTreeTerminationError";
24
+ }
25
+ }
26
+ /** Codes of every failure that means a process tree may still be running. */
27
+ const unprovenTerminationCodes = ["process_tree_termination_unconfirmed", "host_process_supervisor_termination_failed"];
28
+ /**
29
+ * True when `error`, or anything it wraps (an AggregateError's errors, a cause
30
+ * chain, a sanitized copy that kept only the message), says a process tree
31
+ * could not be proven gone. Whoever holds capacity for that tree must keep it.
32
+ */
33
+ export function isProcessTreeTerminationUnproven(error, depth = 0) {
34
+ if (depth > 8 || error === null || error === undefined)
35
+ return false;
36
+ if (error instanceof ProcessTreeTerminationError)
37
+ return true;
38
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
39
+ if (unprovenTerminationCodes.some(code => message.includes(code)))
40
+ return true;
41
+ if (error instanceof AggregateError && error.errors.some(inner => isProcessTreeTerminationUnproven(inner, depth + 1)))
42
+ return true;
43
+ return error instanceof Error && isProcessTreeTerminationUnproven(error.cause, depth + 1);
44
+ }
3
45
  export class NodeProcessRunner {
46
+ graceMs;
47
+ killWaitMs;
48
+ platform;
49
+ windowsProcesses;
50
+ windowsTrackIntervalMs;
51
+ groupAlive;
52
+ constructor(options = {}) {
53
+ this.graceMs = options.terminationGraceMs ?? 5_000;
54
+ this.killWaitMs = options.killWaitMs ?? 10_000;
55
+ this.platform = options.platform ?? process.platform;
56
+ this.windowsProcesses = options.windowsProcesses ?? systemWindowsProcessTable;
57
+ this.windowsTrackIntervalMs = options.windowsTrackIntervalMs ?? 2_000;
58
+ this.groupAlive = options.groupAlive ?? groupExists;
59
+ }
4
60
  async run(request) {
61
+ if (request.signal?.aborted)
62
+ throw abortError(request.signal);
63
+ const tree = request.processGroup === true ? (this.platform === "win32" ? "windows" : "unix") : null;
64
+ // Taken before the spawn: the root is created no earlier than this (less clock and
65
+ // precision slack), which anchors its Windows tree even if it exits before a snapshot.
66
+ const spawnedNotBefore = windowsTicksFromEpochMs(Date.now() - 2_000);
5
67
  return await new Promise((resolve, reject) => {
6
68
  const child = spawn(request.command, request.args, {
7
69
  cwd: request.cwd,
8
70
  env: request.env,
9
- stdio: ["ignore", "pipe", "pipe"]
71
+ stdio: ["ignore", "pipe", "pipe"],
72
+ windowsVerbatimArguments: request.windowsVerbatimArguments,
73
+ detached: tree === "unix",
74
+ });
75
+ const stdout = new OutputTail(request.maxOutputChars);
76
+ const stderr = new OutputTail(request.maxOutputChars);
77
+ let aborted = false;
78
+ let escalation = null;
79
+ let tracking = null;
80
+ // Resolves true once the tree is proven gone (trivially true without a tree).
81
+ let treeGone = Promise.resolve(true);
82
+ const windowsTree = tree === "windows" && child.pid
83
+ ? new WindowsProcessTree(child.pid, this.windowsProcesses, { notBefore: spawnedNotBefore })
84
+ : null;
85
+ const signalChild = (signal) => {
86
+ if (!child.pid)
87
+ return;
88
+ try {
89
+ process.kill(tree === "unix" ? -child.pid : child.pid, signal);
90
+ }
91
+ catch {
92
+ // ESRCH: already gone. Anything else surfaces as the child's own exit.
93
+ }
94
+ };
95
+ const onAbort = () => {
96
+ aborted = true;
97
+ if (windowsTree) {
98
+ // No signals on Windows: the tracked tree is stopped once the root exits.
99
+ void this.windowsProcesses.killTree(child.pid);
100
+ return;
101
+ }
102
+ signalChild("SIGTERM");
103
+ escalation = setTimeout(() => signalChild("SIGKILL"), this.graceMs);
104
+ escalation.unref?.();
105
+ };
106
+ const cleanup = () => {
107
+ request.signal?.removeEventListener("abort", onAbort);
108
+ if (escalation)
109
+ clearTimeout(escalation);
110
+ if (tracking)
111
+ clearInterval(tracking);
112
+ };
113
+ if (request.onSpawn)
114
+ child.once("spawn", () => { if (child.pid)
115
+ request.onSpawn(child.pid); });
116
+ if (windowsTree) {
117
+ void windowsTree.track();
118
+ tracking = setInterval(() => void windowsTree.track(), this.windowsTrackIntervalMs);
119
+ tracking.unref?.();
120
+ }
121
+ request.signal?.addEventListener("abort", onAbort, { once: true });
122
+ child.on("error", error => {
123
+ // A launch failure (ENOENT and the like): nothing is running.
124
+ if (child.pid === undefined) {
125
+ cleanup();
126
+ reject(error);
127
+ }
10
128
  });
11
- let stdout = "";
12
- let stderr = "";
13
- child.on("error", reject);
14
- const stdoutReader = readline.createInterface({ input: child.stdout });
15
- const stderrReader = readline.createInterface({ input: child.stderr });
16
- stdoutReader.on("line", (line) => {
17
- stdout += `${line}\n`;
129
+ // The command itself ended. Members of its tree that outlive it (a daemon or an
130
+ // orphaned script holding the pipes open) are stopped, so "close" can follow.
131
+ child.once("exit", () => {
132
+ if (!child.pid)
133
+ return;
134
+ if (tree === "unix")
135
+ treeGone = stopUnixGroup(child.pid, this.graceMs, this.killWaitMs, this.groupAlive);
136
+ if (windowsTree) {
137
+ windowsTree.markRootExited();
138
+ treeGone = windowsTree.stop(Date.now() + this.graceMs + this.killWaitMs);
139
+ }
18
140
  });
19
- stderrReader.on("line", (line) => {
20
- stderr += `${line}\n`;
141
+ const stdoutReader = request.rawOutput ? undefined : readline.createInterface({ input: child.stdout });
142
+ const stderrReader = request.rawOutput ? undefined : readline.createInterface({ input: child.stderr });
143
+ if (request.rawOutput) {
144
+ child.stdout.setEncoding("utf8").on("data", chunk => { stdout.append(chunk); });
145
+ child.stderr.setEncoding("utf8").on("data", chunk => { stderr.append(chunk); });
146
+ }
147
+ stdoutReader?.on("line", (line) => {
148
+ stdout.append(`${line}\n`);
149
+ });
150
+ stderrReader?.on("line", (line) => {
151
+ stderr.append(`${line}\n`);
21
152
  });
22
153
  child.on("close", (code) => {
23
- stdoutReader.close();
24
- stderrReader.close();
25
- resolve({
26
- exitCode: code ?? 1,
27
- stdout,
28
- stderr
154
+ stdoutReader?.close();
155
+ stderrReader?.close();
156
+ void treeGone.then(gone => {
157
+ cleanup();
158
+ // Never settle as finished while part of the tree may still run.
159
+ if (!gone) {
160
+ const pid = child.pid;
161
+ reject(new ProcessTreeTerminationError(pid, request.command, windowsTree
162
+ ? async () => await windowsTree.stop(Date.now() + this.graceMs)
163
+ : async () => !this.groupAlive(pid)));
164
+ return;
165
+ }
166
+ if (aborted) {
167
+ reject(abortError(request.signal));
168
+ return;
169
+ }
170
+ const truncated = stdout.truncated || stderr.truncated;
171
+ resolve({
172
+ exitCode: code ?? 1,
173
+ stdout: stdout.value(),
174
+ stderr: stderr.value(),
175
+ ...truncated ? { outputTruncated: true } : {},
176
+ });
29
177
  });
30
178
  });
31
179
  });
32
180
  }
33
181
  }
182
+ /** Keeps the last `limit` characters of a stream; unbounded without a limit. */
183
+ class OutputTail {
184
+ limit;
185
+ text = "";
186
+ truncated = false;
187
+ constructor(limit) {
188
+ this.limit = limit;
189
+ }
190
+ append(chunk) {
191
+ this.text += chunk;
192
+ // Trimmed in batches, so a noisy stream costs amortized linear time.
193
+ if (this.limit !== undefined && this.text.length > 2 * this.limit)
194
+ this.trim();
195
+ }
196
+ value() {
197
+ if (this.limit !== undefined && this.text.length > this.limit)
198
+ this.trim();
199
+ return this.truncated
200
+ ? `[output truncated: only the last ${this.limit} characters are kept]\n${this.text}`
201
+ : this.text;
202
+ }
203
+ trim() {
204
+ this.text = this.text.slice(-this.limit);
205
+ this.truncated = true;
206
+ }
207
+ }
208
+ /**
209
+ * SIGTERM, then SIGKILL, to what is left of a process group. True once the
210
+ * group is empty; false when members survive the SIGKILL wait.
211
+ */
212
+ async function stopUnixGroup(groupId, graceMs, killWaitMs, alive) {
213
+ for (const [signal, waitMs] of [["SIGTERM", graceMs], ["SIGKILL", killWaitMs]]) {
214
+ if (!alive(groupId))
215
+ return true;
216
+ try {
217
+ process.kill(-groupId, signal);
218
+ }
219
+ catch {
220
+ // ESRCH: the group emptied meanwhile; checked below.
221
+ }
222
+ const deadline = Date.now() + waitMs;
223
+ while (alive(groupId) && Date.now() < deadline)
224
+ await new Promise(resolve => setTimeout(resolve, 20));
225
+ }
226
+ // The deadline is a failed proof, not a success: a member may still run.
227
+ return !alive(groupId);
228
+ }
229
+ function groupExists(groupId) {
230
+ try {
231
+ process.kill(-groupId, 0);
232
+ return true;
233
+ }
234
+ catch (error) {
235
+ return error.code === "EPERM";
236
+ }
237
+ }
238
+ function abortError(signal) {
239
+ return Object.assign(new Error("The operation was aborted", { cause: signal.reason }), { name: "AbortError", code: "ABORT_ERR" });
240
+ }