@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.028808a841c8

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 (243) hide show
  1. package/README.md +165 -1
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -1
  5. package/dist/bridge/bridge.service.d.ts +140 -3
  6. package/dist/bridge/bridge.service.js +2471 -68
  7. package/dist/bridge/bridge.types.d.ts +224 -2
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +14 -2
  21. package/dist/cleanup/cleanup.service.js +496 -3
  22. package/dist/cleanup/cleanup.types.d.ts +10 -0
  23. package/dist/cleanup/index.d.ts +1 -1
  24. package/dist/cleanup/index.js +1 -1
  25. package/dist/cleanup/internals.d.ts +2 -2
  26. package/dist/cleanup/internals.js +1 -1
  27. package/dist/cli/cli.help.d.ts +2 -0
  28. package/dist/cli/cli.help.js +217 -0
  29. package/dist/cli/cli.service.d.ts +55 -7
  30. package/dist/cli/cli.service.js +429 -219
  31. package/dist/cli/local-config.d.ts +7 -0
  32. package/dist/cli/local-config.js +51 -3
  33. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  34. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  35. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  36. package/dist/runtime/attempt-database-broker.js +390 -0
  37. package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
  38. package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
  39. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  40. package/dist/runtime/attempt-path-operation.js +94 -0
  41. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  42. package/dist/runtime/attempt-private-directory.js +54 -0
  43. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  44. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  45. package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
  46. package/dist/runtime/attempt-process-supervisor.js +471 -0
  47. package/dist/runtime/canonical-source-file.d.ts +3 -0
  48. package/dist/runtime/canonical-source-file.js +54 -0
  49. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  50. package/dist/runtime/docker-engine-probe.js +333 -0
  51. package/dist/runtime/generated-output-reset.d.ts +20 -0
  52. package/dist/runtime/generated-output-reset.js +157 -0
  53. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  54. package/dist/runtime/host-database-capability-boundary.js +63 -0
  55. package/dist/runtime/host-diagnostics.d.ts +11 -0
  56. package/dist/runtime/host-diagnostics.js +192 -0
  57. package/dist/runtime/host-execution-root.d.ts +4 -0
  58. package/dist/runtime/host-execution-root.js +39 -0
  59. package/dist/runtime/host-facts.d.ts +35 -0
  60. package/dist/runtime/host-facts.js +95 -0
  61. package/dist/runtime/host-listener-inspector.d.ts +51 -0
  62. package/dist/runtime/host-listener-inspector.js +385 -0
  63. package/dist/runtime/host-load-sampler.d.ts +83 -0
  64. package/dist/runtime/host-load-sampler.js +164 -0
  65. package/dist/runtime/host-port-broker.d.ts +76 -0
  66. package/dist/runtime/host-port-broker.js +333 -0
  67. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  68. package/dist/runtime/host-pressure-stall.js +121 -0
  69. package/dist/runtime/host-runtime-contract.d.ts +59 -0
  70. package/dist/runtime/host-runtime-contract.js +815 -0
  71. package/dist/runtime/host-runtime-lease.d.ts +217 -0
  72. package/dist/runtime/host-runtime-lease.js +2533 -0
  73. package/dist/runtime/host-runtime-promotion.d.ts +32 -0
  74. package/dist/runtime/host-runtime-promotion.js +206 -0
  75. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  76. package/dist/runtime/managed-command-teardown.js +607 -0
  77. package/dist/runtime/memory-capacity.d.ts +70 -0
  78. package/dist/runtime/memory-capacity.js +123 -0
  79. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  80. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  81. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  82. package/dist/runtime/node-host-runtime-adapter.js +286 -0
  83. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  84. package/dist/runtime/pinned-directory-process.js +61 -0
  85. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  86. package/dist/runtime/pinned-source-directory.js +94 -0
  87. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  88. package/dist/runtime/playwright-browser-cache.js +227 -0
  89. package/dist/runtime/playwright-host-runtime-adapter.d.ts +32 -0
  90. package/dist/runtime/playwright-host-runtime-adapter.js +262 -0
  91. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  92. package/dist/runtime/prepared-runtime-identity.js +218 -0
  93. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  94. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  95. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  96. package/dist/runtime/runtime-isolation-lease.js +161 -0
  97. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  98. package/dist/runtime/workspace-resource-estimator.js +174 -0
  99. package/dist/sandbox/command-runner.d.ts +4 -0
  100. package/dist/sandbox/command-runner.js +47 -0
  101. package/dist/sandbox/contract.d.ts +5 -0
  102. package/dist/sandbox/contract.js +276 -0
  103. package/dist/sandbox/event-budget.d.ts +11 -0
  104. package/dist/sandbox/event-budget.js +27 -0
  105. package/dist/sandbox/image-policy.d.ts +35 -0
  106. package/dist/sandbox/image-policy.js +247 -0
  107. package/dist/sandbox/index.d.ts +5 -0
  108. package/dist/sandbox/index.js +5 -0
  109. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  110. package/dist/sandbox/lease-watchdog.js +67 -0
  111. package/dist/sandbox/preflight.d.ts +84 -0
  112. package/dist/sandbox/preflight.js +521 -0
  113. package/dist/sandbox/process.d.ts +20 -0
  114. package/dist/sandbox/process.js +209 -0
  115. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  116. package/dist/sandbox/provider-auth/codex.js +212 -0
  117. package/dist/sandbox/repository-lock.d.ts +6 -0
  118. package/dist/sandbox/repository-lock.js +129 -0
  119. package/dist/sandbox/runtime.d.ts +302 -0
  120. package/dist/sandbox/runtime.js +2368 -0
  121. package/dist/sandbox/sandbox.types.d.ts +93 -0
  122. package/dist/sandbox/sandbox.types.js +1 -0
  123. package/dist/sandbox/smoke.d.ts +76 -0
  124. package/dist/sandbox/smoke.js +380 -0
  125. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  126. package/dist/sandbox/worker-supervisor.js +36 -0
  127. package/dist/sandbox/worker.d.ts +1 -0
  128. package/dist/sandbox/worker.js +225 -0
  129. package/dist/sandbox/workspace.service.d.ts +13 -0
  130. package/dist/sandbox/workspace.service.js +74 -0
  131. package/dist/session/managed-attempt-tools.d.ts +53 -0
  132. package/dist/session/managed-attempt-tools.js +1213 -0
  133. package/dist/session/managed-build-coordinator.d.ts +5 -0
  134. package/dist/session/managed-build-coordinator.js +109 -0
  135. package/dist/session/managed-build-receipt.d.ts +21 -0
  136. package/dist/session/managed-build-receipt.js +337 -0
  137. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  138. package/dist/session/managed-verification-timeouts.js +17 -0
  139. package/dist/session/phase-completion.artifacts.d.ts +27 -0
  140. package/dist/session/phase-completion.artifacts.js +833 -0
  141. package/dist/session/phase-completion.d.ts +53 -42
  142. package/dist/session/phase-completion.helpers.d.ts +117 -0
  143. package/dist/session/phase-completion.helpers.js +707 -0
  144. package/dist/session/phase-completion.js +125 -3007
  145. package/dist/session/phase-completion.prompts.d.ts +14 -0
  146. package/dist/session/phase-completion.prompts.js +233 -0
  147. package/dist/session/phase-completion.runtime.d.ts +49 -0
  148. package/dist/session/phase-completion.runtime.js +845 -0
  149. package/dist/session/phase-completion.schemas.d.ts +3 -0
  150. package/dist/session/phase-completion.schemas.js +859 -0
  151. package/dist/session/phase-completion.validation.d.ts +38 -0
  152. package/dist/session/phase-completion.validation.js +918 -0
  153. package/dist/session/pre-publication-process.d.ts +20 -0
  154. package/dist/session/pre-publication-process.js +97 -0
  155. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  156. package/dist/session/pre-publication-skipped-tests.js +109 -0
  157. package/dist/session/pre-publication-validation.d.ts +75 -0
  158. package/dist/session/pre-publication-validation.js +631 -0
  159. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  160. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  161. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  162. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  163. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
  164. package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
  165. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  166. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  167. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  168. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  169. package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
  170. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  171. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  172. package/dist/session/provider-cli/provider-cli.process.d.ts +128 -0
  173. package/dist/session/provider-cli/provider-cli.process.js +1140 -0
  174. package/dist/session/provider-cli/provider-cli.prompts.d.ts +57 -0
  175. package/dist/session/provider-cli/provider-cli.prompts.js +730 -0
  176. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  177. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  178. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  179. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  180. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -0
  181. package/dist/session/provider-cli/provider-cli.runtime.js +92 -0
  182. package/dist/session/provider-cli/provider-cli.service.d.ts +47 -53
  183. package/dist/session/provider-cli/provider-cli.service.js +1344 -2506
  184. package/dist/session/provider-cli/provider-cli.types.d.ts +8 -0
  185. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  186. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  187. package/dist/session/provider-cli/provider-output-state.d.ts +38 -0
  188. package/dist/session/provider-cli/provider-output-state.js +826 -0
  189. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  190. package/dist/session/provider-cli/provider-usage.js +28 -5
  191. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  192. package/dist/session/publishable-worktree-changes.js +193 -0
  193. package/dist/session/session-redaction.d.ts +3 -0
  194. package/dist/session/session-redaction.js +448 -0
  195. package/dist/session/session.base.d.ts +6 -1
  196. package/dist/session/session.service.d.ts +8 -2
  197. package/dist/session/session.service.js +586 -59
  198. package/dist/session/session.types.d.ts +324 -3
  199. package/dist/session/session.types.js +951 -10
  200. package/dist/session/unreferenced-exports.d.ts +12 -0
  201. package/dist/session/unreferenced-exports.js +59 -0
  202. package/dist/shared/format/format-bytes.d.ts +1 -0
  203. package/dist/shared/format/format-bytes.js +9 -0
  204. package/dist/shared/git/git.js +2 -1
  205. package/dist/shared/path/path.d.ts +1 -0
  206. package/dist/shared/path/path.js +21 -1
  207. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  208. package/dist/shared/process/dotnet-toolchain.js +307 -0
  209. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  210. package/dist/shared/process/host-process-recovery.js +79 -0
  211. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  212. package/dist/shared/process/host-process-supervisor.js +331 -0
  213. package/dist/shared/process/process.d.ts +3 -0
  214. package/dist/shared/process/process.js +13 -7
  215. package/dist/shared/process/windows-launch.d.ts +8 -0
  216. package/dist/shared/process/windows-launch.js +41 -0
  217. package/dist/shared/provider-capabilities.d.ts +4 -0
  218. package/dist/shared/provider-capabilities.js +88 -0
  219. package/dist/shared/redaction/redaction.d.ts +1 -0
  220. package/dist/shared/redaction/redaction.js +47 -4
  221. package/dist/shared/time/monotonic.d.ts +1 -0
  222. package/dist/shared/time/monotonic.js +8 -0
  223. package/dist/version.d.ts +1 -1
  224. package/dist/version.js +1 -1
  225. package/dist/worktree/artifact-injector.d.ts +3 -2
  226. package/dist/worktree/artifact-injector.js +82 -10
  227. package/dist/worktree/dependency-warmer.d.ts +53 -1
  228. package/dist/worktree/dependency-warmer.js +693 -11
  229. package/dist/worktree/index.d.ts +2 -1
  230. package/dist/worktree/index.js +1 -0
  231. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  232. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  233. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  234. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  235. package/dist/worktree/worktree-paths.d.ts +4 -0
  236. package/dist/worktree/worktree-paths.js +30 -0
  237. package/dist/worktree/worktree.base.d.ts +3 -0
  238. package/dist/worktree/worktree.service.d.ts +16 -3
  239. package/dist/worktree/worktree.service.js +334 -54
  240. package/dist/worktree/worktree.types.d.ts +9 -1
  241. package/package.json +12 -7
  242. package/runtime/windows-job-supervisor.ps1 +722 -0
  243. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,1140 @@
1
+ import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import readline from "node:readline";
7
+ import { promisify } from "node:util";
8
+ import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
+ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunch, terminateHostProcessTree, } from "../../shared/process/host-process-supervisor.js";
10
+ import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
11
+ import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
+ import { ForgeFailureError } from "../session.types.js";
13
+ import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
14
+ const execFileAsync = promisify(execFile);
15
+ // Provider processes can emit many gigabytes over a long-running session. The
16
+ // line handlers stream that output to Forge as it arrives; the completed result
17
+ // only needs a bounded diagnostic tail for failure classification.
18
+ export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
19
+ const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
20
+ // A provider that keeps starting turns after its first successful one (background-task
21
+ // notifications) is still stopped once this much time without supervised work in flight
22
+ // has passed since that first success.
23
+ const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
24
+ // How often the end-of-turn timers re-check whether supervised work is still in flight.
25
+ const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
26
+ const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
27
+ /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
28
+ * relaunch needs a new fenced child generation and exclusive launch files. */
29
+ export function recoveringProviderProcessRunner(inner) {
30
+ return new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner));
31
+ }
32
+ /**
33
+ * Codex Desktop and an independently installed Codex CLI can briefly disagree
34
+ * about the shared models-cache schema during a rolling upgrade. Recover only
35
+ * that exact failure by quarantining the bounded cache file and retrying once;
36
+ * auth, config, sessions, and every other CODEX_HOME entry remain untouched.
37
+ */
38
+ export class CodexModelsCacheRecoveringProcessRunner {
39
+ inner;
40
+ constructor(inner) {
41
+ this.inner = inner;
42
+ }
43
+ async run(request, handlers, signal) {
44
+ const first = await this.inner.run(request, handlers, signal);
45
+ if (first.exitCode === 0
46
+ || signal?.aborted
47
+ || !isCodexCommand(request.command)
48
+ || !isCodexModelsCacheSchemaFailure(first)) {
49
+ return first;
50
+ }
51
+ const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
52
+ if (!recovered || signal?.aborted)
53
+ return first;
54
+ return await this.inner.run(request, handlers, signal);
55
+ }
56
+ }
57
+ /**
58
+ * Some Codex CLI builds can start new turns but cannot resume an older thread
59
+ * because the backing app does not implement the paginated thread lookup RPC.
60
+ * Preserve the prepared worktree and prompt, then retry once as a fresh turn.
61
+ */
62
+ export class CodexResumeRecoveringProcessRunner {
63
+ inner;
64
+ constructor(inner) {
65
+ this.inner = inner;
66
+ }
67
+ async run(request, handlers, signal) {
68
+ const first = await this.inner.run(request, handlers, signal);
69
+ if (first.exitCode === 0
70
+ || signal?.aborted
71
+ || !isCodexCommand(request.command)
72
+ || !isRecoverableCodexResumeFailure(request.command, first)) {
73
+ return first;
74
+ }
75
+ const fallback = codexFreshTurnRequest(request);
76
+ return fallback ? await this.inner.run(fallback, handlers, signal) : first;
77
+ }
78
+ }
79
+ function isRecoverableCodexResumeFailure(command, result) {
80
+ const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
81
+ return (output.includes("thread/resume failed")
82
+ && output.includes("paginated_threads is not supported yet"))
83
+ || isTransientCodexProviderNotFoundFailure(command, result);
84
+ }
85
+ /**
86
+ * Recognizes the exact nonzero Codex service response at the provider-process
87
+ * boundary. Provider stdout is deliberately excluded because it can contain
88
+ * arbitrary tool/command output and therefore cannot mint retry authority.
89
+ */
90
+ export function isTransientCodexProviderNotFoundFailure(command, result) {
91
+ if (result.exitCode === 0 || !isCodexCommand(command))
92
+ return false;
93
+ return result.stderr
94
+ .split(/\r?\n/u)
95
+ .map(line => line.trim().toLowerCase())
96
+ .some(line => line === "not found: status code '404'"
97
+ || line === 'not found: status code "404"');
98
+ }
99
+ function codexFreshTurnRequest(request) {
100
+ const args = [...request.args];
101
+ const resumeIndex = args.indexOf("resume");
102
+ if (resumeIndex < 0 || args.length < 2)
103
+ return null;
104
+ // buildProviderCliCommand always places the thread id immediately before
105
+ // the prompt. Remove it before moving exec-level --cd back out of the
106
+ // resume subcommand shape.
107
+ args.splice(args.length - 2, 1);
108
+ args.splice(resumeIndex, 1);
109
+ const cdIndex = args.indexOf("--cd");
110
+ if (cdIndex >= 0 && cdIndex + 1 < args.length) {
111
+ const cd = args.splice(cdIndex, 2);
112
+ args.splice(args.length - 1, 0, ...cd);
113
+ }
114
+ return { ...request, args };
115
+ }
116
+ function isCodexCommand(command) {
117
+ return path.parse(command).name.toLowerCase() === "codex";
118
+ }
119
+ function isCodexModelsCacheSchemaFailure(result) {
120
+ const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
121
+ return output.includes("base_instructions")
122
+ && output.includes("missing field")
123
+ && (output.includes("models_cache") || output.includes("models cache") || output.includes("model cache"));
124
+ }
125
+ async function quarantineIncompatibleCodexModelsCache(requestEnv) {
126
+ const configuredHome = readEnvironmentValue(requestEnv ?? {}, "CODEX_HOME")
127
+ ?? readEnvironmentValue(process.env, "CODEX_HOME")
128
+ ?? readEnvironmentValue(process.env, "FORGE_CODEX_HOME");
129
+ const codexHome = path.resolve(configuredHome ?? path.join(os.homedir(), ".codex"));
130
+ if (!path.isAbsolute(codexHome) || codexHome === path.parse(codexHome).root)
131
+ return false;
132
+ const cachePath = path.join(codexHome, "models_cache.json");
133
+ const cacheStat = await fs.promises.lstat(cachePath).catch(error => {
134
+ if (error.code === "ENOENT")
135
+ return null;
136
+ throw error;
137
+ });
138
+ if (!cacheStat
139
+ || !cacheStat.isFile()
140
+ || cacheStat.isSymbolicLink()
141
+ || cacheStat.nlink !== 1
142
+ || cacheStat.size <= 0
143
+ || cacheStat.size > maximumRecoverableCodexModelsCacheBytes) {
144
+ return false;
145
+ }
146
+ const quarantinePath = path.join(codexHome, `models_cache.forge-incompatible-${Date.now()}-${randomUUID()}.json`);
147
+ await fs.promises.rename(cachePath, quarantinePath);
148
+ return true;
149
+ }
150
+ const allowedProviderParentEnvNames = [
151
+ "PATH",
152
+ "HOME",
153
+ "USERPROFILE",
154
+ "TMPDIR",
155
+ "TEMP",
156
+ "TMP",
157
+ "LANG",
158
+ "CLAUDE_CONFIG_DIR"
159
+ ];
160
+ const windowsAllowedProviderParentEnvNames = [
161
+ "SystemRoot",
162
+ "SystemDrive",
163
+ "ComSpec",
164
+ "PATHEXT",
165
+ "APPDATA",
166
+ "LOCALAPPDATA",
167
+ "USERNAME",
168
+ "USERDOMAIN",
169
+ "HOMEDRIVE",
170
+ "HOMEPATH",
171
+ "ProgramData",
172
+ "ProgramFiles",
173
+ "ProgramFiles(x86)",
174
+ "ProgramW6432",
175
+ "DOTNET_ROOT",
176
+ "DOTNET_ROOT(x86)",
177
+ "DOTNET_CLI_HOME",
178
+ "NUGET_PACKAGES",
179
+ "NUGET_HTTP_CACHE_PATH",
180
+ "CLAUDE_CODE_GIT_BASH_PATH"
181
+ ];
182
+ export function buildProviderChildEnvironment(requestEnv, options = {}) {
183
+ const parentEnv = options.parentEnv ?? process.env;
184
+ const platform = options.platform ?? process.platform;
185
+ const env = {};
186
+ for (const [key, value] of Object.entries(parentEnv)) {
187
+ if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
188
+ env[key] = value;
189
+ }
190
+ }
191
+ if (requestEnv) {
192
+ for (const [key, value] of Object.entries(requestEnv)) {
193
+ const trimmedKey = key.trim();
194
+ if (trimmedKey.length > 0) {
195
+ env[trimmedKey] = value;
196
+ }
197
+ }
198
+ }
199
+ if (platform === "win32") {
200
+ normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
201
+ }
202
+ normalizeProviderBuildEnvironment(env);
203
+ return env;
204
+ }
205
+ function normalizeProviderBuildEnvironment(env) {
206
+ // Provider sessions are long lived and commonly run many dotnet builds. Persistent
207
+ // MSBuild and Roslyn compiler servers otherwise survive individual commands and can
208
+ // retain more memory than the active Forge lane. Keep those caches process-scoped by
209
+ // default on every runner OS; an explicitly supplied request value still wins.
210
+ setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
211
+ setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
212
+ setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
213
+ }
214
+ function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
215
+ // The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
216
+ // property names are case-insensitive on every OS. Collapse request aliases to
217
+ // one canonical key so the explicit value wins without producing ambiguity.
218
+ const exact = env[name];
219
+ const alias = Object.entries(env).find(([key, candidate]) => key !== name
220
+ && key.toLowerCase() === name.toLowerCase()
221
+ && typeof candidate === "string"
222
+ && candidate.trim().length > 0)?.[1];
223
+ const resolved = typeof exact === "string" && exact.trim().length > 0
224
+ ? exact
225
+ : alias ?? value;
226
+ for (const key of Object.keys(env)) {
227
+ if (key !== name && key.toLowerCase() === name.toLowerCase()) {
228
+ delete env[key];
229
+ }
230
+ }
231
+ env[name] = resolved;
232
+ }
233
+ function isAllowedProviderParentEnv(key, platform = process.platform) {
234
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
235
+ || key.toUpperCase().startsWith("LC_")
236
+ || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
237
+ }
238
+ function isAllowedProviderParentEnvName(key, allowedNames) {
239
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
240
+ }
241
+ function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
242
+ const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
243
+ const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
244
+ setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
245
+ setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
246
+ setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
247
+ setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
248
+ const resolvedSystemDrive = readEnvironmentValue(env, "SystemDrive") ?? systemDrive;
249
+ const defaultProgramFiles = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files");
250
+ const defaultProgramFilesX86 = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files (x86)");
251
+ const defaultProgramData = path.win32.join(`${resolvedSystemDrive}\\`, "ProgramData");
252
+ const programFiles = readEnvironmentValue(env, "ProgramFiles")
253
+ ?? readEnvironmentValue(parentEnv, "ProgramFiles")
254
+ ?? defaultProgramFiles;
255
+ setEnvironmentValueIfMissing(env, "ProgramFiles", programFiles);
256
+ setEnvironmentValueIfMissing(env, "ProgramW6432", readEnvironmentValue(parentEnv, "ProgramW6432") ?? defaultProgramFiles);
257
+ setEnvironmentValueIfMissing(env, "ProgramFiles(x86)", readEnvironmentValue(parentEnv, "ProgramFiles(x86)") ?? defaultProgramFilesX86);
258
+ setEnvironmentValueIfMissing(env, "ProgramData", readEnvironmentValue(parentEnv, "ProgramData") ?? defaultProgramData);
259
+ const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
260
+ if (userProfile) {
261
+ setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
262
+ setEnvironmentValueIfMissing(env, "HOME", userProfile);
263
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
264
+ setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
265
+ const parsed = path.win32.parse(userProfile);
266
+ if (parsed.root) {
267
+ setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
268
+ setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
269
+ }
270
+ }
271
+ const appData = readEnvironmentValue(env, "APPDATA")
272
+ ?? readEnvironmentValue(parentEnv, "APPDATA")
273
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
274
+ const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
275
+ ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
276
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
277
+ if (appData) {
278
+ setEnvironmentValueIfMissing(env, "APPDATA", appData);
279
+ }
280
+ if (localAppData) {
281
+ setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
282
+ setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
283
+ }
284
+ setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
285
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
286
+ setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
287
+ setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
288
+ }
289
+ function resolveWindowsUserProfile(env, parentEnv, homeDir) {
290
+ const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
291
+ if (existing) {
292
+ return existing;
293
+ }
294
+ const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
295
+ if (home && path.win32.isAbsolute(home)) {
296
+ return home;
297
+ }
298
+ const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
299
+ const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
300
+ if (homeDrive && homePath) {
301
+ return `${homeDrive}${homePath}`;
302
+ }
303
+ if (homeDir && path.win32.isAbsolute(homeDir)) {
304
+ return homeDir;
305
+ }
306
+ const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
307
+ const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
308
+ return username ? path.win32.join(systemDrive, "Users", username) : undefined;
309
+ }
310
+ function readEnvironmentValue(env, name) {
311
+ const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
312
+ const value = entry?.[1];
313
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
314
+ }
315
+ function setEnvironmentValueIfMissing(env, name, value) {
316
+ if (readEnvironmentValue(env, name)) {
317
+ return;
318
+ }
319
+ env[name] = value;
320
+ }
321
+ export class StreamingProviderProcessRunner {
322
+ terminalExitGraceMs;
323
+ terminalSuccessCeilingMs;
324
+ terminalWorkPollMs;
325
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
326
+ this.terminalExitGraceMs = terminalExitGraceMs;
327
+ this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
328
+ this.terminalWorkPollMs = terminalWorkPollMs;
329
+ }
330
+ async run(request, handlers = {}, signal) {
331
+ assertHostDatabaseCapabilityBoundary();
332
+ const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
333
+ const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
334
+ // An unsupervised Unix provider still gets a dedicated process group so a
335
+ // cancellation can stop descendants instead of only the CLI root.
336
+ const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
337
+ const childEnvironment = buildProviderChildEnvironment(request.env);
338
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
339
+ // silent stdin after ~3s), but the provider must not run before Forge has
340
+ // recorded its start. Off Windows, hold the launch behind a start gate in
341
+ // the same process: the prompt is written immediately and buffers in the
342
+ // pipe, and the gate execs the provider only once onStarted succeeds.
343
+ const startGated = process.platform !== "win32"
344
+ && supervisedLaunch?.strategy !== "windows_job_object"
345
+ && request.stdin !== undefined
346
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
347
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
348
+ const spawnLaunch = startGated
349
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
350
+ : launch;
351
+ return await new Promise((resolve, reject) => {
352
+ const rootCreatedAt = new Date().toISOString();
353
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
354
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
355
+ cwd: request.cwd,
356
+ env: childEnvironment,
357
+ stdio: startGated
358
+ ? [stdinMode, "pipe", "pipe", "pipe"]
359
+ : [stdinMode, "pipe", "pipe"],
360
+ windowsHide: true,
361
+ detached: launch.detached,
362
+ });
363
+ const memoryObserver = supervisedLaunch
364
+ ? new HostProcessTreeMemoryObserver(supervisedLaunch, child.pid ?? 0)
365
+ : null;
366
+ let termination = null;
367
+ const terminate = () => {
368
+ termination ??= terminateHostProcessTree(child, supervisedLaunch);
369
+ return termination;
370
+ };
371
+ const childStdout = child.stdout;
372
+ const childStderr = child.stderr;
373
+ if (!childStdout || !childStderr) {
374
+ const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
375
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
376
+ return;
377
+ }
378
+ const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
379
+ const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
380
+ let settled = false;
381
+ let closed = false;
382
+ let cancellationRequested = false;
383
+ let cancelledBeforeClose = false;
384
+ let terminalTerminationStarted = false;
385
+ let terminalStopReason = null;
386
+ // Idle time (no supervised work in flight) accrued against the end-of-turn grace and
387
+ // the success ceiling; null while that timer is not armed.
388
+ let graceIdleMs = null;
389
+ let ceilingIdleMs = null;
390
+ let terminalSuccessCount = 0;
391
+ let replayedTurnCeilingSkipped = false;
392
+ let terminalWorkTimer = null;
393
+ let terminalWorkTickAt = 0;
394
+ let terminalWorkTickRunning = false;
395
+ let latestTurnFailed = false;
396
+ let readiness = null;
397
+ const cleanup = () => {
398
+ stopTerminalWorkTimer();
399
+ graceIdleMs = null;
400
+ ceilingIdleMs = null;
401
+ signal?.removeEventListener("abort", abort);
402
+ };
403
+ const fail = (error) => {
404
+ if (settled) {
405
+ return;
406
+ }
407
+ settled = true;
408
+ cleanup();
409
+ // Do not release the caller's reservation/worktree/port ownership until
410
+ // descendant termination has completed (or failed with explicit proof).
411
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
412
+ };
413
+ const abort = () => {
414
+ if (!closed)
415
+ cancelledBeforeClose = true;
416
+ cancellationRequested = true;
417
+ // Cancellation is not a launch failure when the supervised tree can be
418
+ // proven stopped. Let the close handler settle the command after exact
419
+ // termination; only a failed termination proof rejects the run.
420
+ void terminate().catch(fail);
421
+ };
422
+ if (signal?.aborted) {
423
+ abort();
424
+ }
425
+ else {
426
+ signal?.addEventListener("abort", abort, { once: true });
427
+ }
428
+ child.on("error", fail);
429
+ const startGrant = startGated ? child.stdio[3] : null;
430
+ if (startGated && !startGrant) {
431
+ fail(new Error("Provider start-grant stream was not piped."));
432
+ return;
433
+ }
434
+ startGrant?.on("error", error => {
435
+ // A broken grant pipe means the gate already exited (terminated before
436
+ // its grant, or it died on its own). Its close event carries the real
437
+ // exit status, so an EPIPE here must not replace that result.
438
+ if (isBrokenPipeError(error))
439
+ return;
440
+ fail(error);
441
+ });
442
+ const grantUnixProviderStart = () => {
443
+ if (!startGrant)
444
+ return;
445
+ // Never release a provider whose launch was cancelled or already failed.
446
+ if (closed || settled || cancellationRequested || signal?.aborted)
447
+ return;
448
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
449
+ };
450
+ child.once("spawn", () => {
451
+ readiness = (async () => {
452
+ const providerReady = supervisedLaunch?.strategy === "windows_job_object"
453
+ ? await waitForWindowsProviderReady(supervisedLaunch, signal, () => closed)
454
+ : undefined;
455
+ if (supervisedLaunch) {
456
+ persistHostProcessSupervisorMetadata(supervisedLaunch, request, child.pid ?? 0, rootCreatedAt, providerReady);
457
+ }
458
+ await handlers.onStarted?.();
459
+ if (supervisedLaunch?.strategy === "windows_job_object") {
460
+ grantWindowsProviderStart(supervisedLaunch);
461
+ }
462
+ else if (startGated) {
463
+ grantUnixProviderStart();
464
+ }
465
+ })();
466
+ void readiness.catch(error => {
467
+ if (!closed && !signal?.aborted)
468
+ fail(error);
469
+ });
470
+ });
471
+ const writeProviderInput = () => {
472
+ if (request.stdin === undefined)
473
+ return;
474
+ if (!child.stdin) {
475
+ void terminate();
476
+ fail(new Error("Provider process stdin stream was not piped."));
477
+ return;
478
+ }
479
+ child.stdin.on("error", (error) => {
480
+ // A prompt still buffered when Forge stops the process (cancellation,
481
+ // or a refused start grant) cannot be delivered; that broken pipe is
482
+ // not a failure. Any other stdin error still is.
483
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
484
+ return;
485
+ void terminate();
486
+ fail(error);
487
+ });
488
+ child.stdin.end(request.stdin, "utf8");
489
+ };
490
+ if (request.stdin !== undefined) {
491
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
492
+ // The outer supervisor / Unix start gate must receive stdin before it
493
+ // can launch the provider. Its start grant fences prompt processing.
494
+ writeProviderInput();
495
+ }
496
+ else {
497
+ child.once("spawn", () => {
498
+ void readiness?.then(writeProviderInput).catch(fail);
499
+ });
500
+ }
501
+ }
502
+ const finishAfterTerminalSuccess = (reason) => {
503
+ if (closed || settled || cancellationRequested || terminalTerminationStarted)
504
+ return;
505
+ terminalTerminationStarted = true;
506
+ terminalStopReason = reason;
507
+ stopTerminalWorkTimer();
508
+ void terminate().catch(fail);
509
+ };
510
+ const workInFlight = async () => {
511
+ try {
512
+ if (handlers.isToolCallInFlight?.())
513
+ return true;
514
+ }
515
+ catch {
516
+ // A failing probe must not keep the provider open or stop it early on its own.
517
+ }
518
+ return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
519
+ };
520
+ // The grace and the ceiling only count time in which no supervised work is in flight:
521
+ // a provider waiting on an MCP tool call or on a managed command it started is not
522
+ // finished, even when its turn has ended. The grace restarts once that work is done.
523
+ const terminalWorkTick = async () => {
524
+ if (terminalWorkTickRunning)
525
+ return;
526
+ terminalWorkTickRunning = true;
527
+ try {
528
+ const inFlight = await workInFlight();
529
+ const now = performance.now();
530
+ const elapsed = Math.max(0, now - terminalWorkTickAt);
531
+ terminalWorkTickAt = now;
532
+ if (closed || settled || terminalTerminationStarted)
533
+ return;
534
+ if (inFlight) {
535
+ if (graceIdleMs !== null)
536
+ graceIdleMs = 0;
537
+ return;
538
+ }
539
+ if (graceIdleMs !== null)
540
+ graceIdleMs += elapsed;
541
+ if (ceilingIdleMs !== null)
542
+ ceilingIdleMs += elapsed;
543
+ if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
544
+ finishAfterTerminalSuccess("turn_exit_grace");
545
+ }
546
+ else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
547
+ finishAfterTerminalSuccess("success_ceiling");
548
+ }
549
+ }
550
+ finally {
551
+ terminalWorkTickRunning = false;
552
+ if (graceIdleMs === null && ceilingIdleMs === null)
553
+ stopTerminalWorkTimer();
554
+ }
555
+ };
556
+ function stopTerminalWorkTimer() {
557
+ if (terminalWorkTimer) {
558
+ clearInterval(terminalWorkTimer);
559
+ terminalWorkTimer = null;
560
+ }
561
+ }
562
+ const startTerminalWorkTimer = () => {
563
+ if (terminalWorkTimer)
564
+ return;
565
+ terminalWorkTickAt = performance.now();
566
+ const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
567
+ terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
568
+ terminalWorkTimer.unref?.();
569
+ };
570
+ const armTerminalExit = () => {
571
+ terminalSuccessCount += 1;
572
+ graceIdleMs = 0;
573
+ // Later turns may postpone the grace period, but never past this ceiling.
574
+ ceilingIdleMs ??= 0;
575
+ startTerminalWorkTimer();
576
+ };
577
+ const readers = [
578
+ readProcessLines(childStdout, (line) => {
579
+ if (request.captureOutput !== false)
580
+ stdout.appendLine(line);
581
+ const handled = handlers.onStdoutLine?.(line);
582
+ if (!terminalTerminationStarted) {
583
+ if (isProviderTerminalSuccess(line)) {
584
+ latestTurnFailed = false;
585
+ armTerminalExit();
586
+ }
587
+ else if (isProviderTerminalFailure(line)) {
588
+ // A later turn that fails reports its failure even after an earlier success.
589
+ latestTurnFailed = true;
590
+ }
591
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
592
+ // A terminal event ends a turn, not necessarily the provider. Claude Code
593
+ // stays resident while background tasks it started are pending and begins a
594
+ // new turn when one reports. A provider that is working again is not finished;
595
+ // the grace period restarts at its next terminal event.
596
+ graceIdleMs = null;
597
+ // A resumed session can replay a queued notification turn before the
598
+ // prompt's own turn. That replayed turn must not start the ceiling, or the
599
+ // resumed agent is stopped mid-work; the prompt's turn arms it instead.
600
+ if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
601
+ replayedTurnCeilingSkipped = true;
602
+ ceilingIdleMs = null;
603
+ }
604
+ }
605
+ }
606
+ return handled;
607
+ }),
608
+ readProcessLines(childStderr, (line) => {
609
+ if (request.captureOutput !== false)
610
+ stderr.appendLine(line);
611
+ return handlers.onStderrLine?.(line);
612
+ })
613
+ ];
614
+ for (const reader of readers) {
615
+ void reader.catch(fail);
616
+ }
617
+ child.on("close", (code) => {
618
+ closed = true;
619
+ Promise.allSettled(readers).then(async (readerResults) => {
620
+ await readiness?.catch(() => undefined);
621
+ const rejected = readerResults.find((result) => result.status === "rejected");
622
+ if (rejected?.status === "rejected") {
623
+ fail(rejected.reason);
624
+ return;
625
+ }
626
+ if (settled) {
627
+ return;
628
+ }
629
+ try {
630
+ memoryObserver?.sample();
631
+ if (supervisedLaunch?.strategy === "unix_process_group" || !supervisedLaunch) {
632
+ await terminate();
633
+ }
634
+ else if (termination) {
635
+ await termination;
636
+ }
637
+ }
638
+ catch (error) {
639
+ fail(error);
640
+ return;
641
+ }
642
+ settled = true;
643
+ cleanup();
644
+ const memory = memoryObserver?.complete();
645
+ resolve({
646
+ // A structured terminal-success event is the provider protocol's
647
+ // authoritative completion signal. If the CLI stays resident after
648
+ // that event, terminate the supervised tree after a short grace
649
+ // period and preserve the successful handoff so the existing
650
+ // artifact, commit, and publication gates can run.
651
+ // A provider stopped after a successful turn keeps that success. Whenever the
652
+ // most recent turn failed, the run fails, however the process ended.
653
+ exitCode: latestTurnFailed
654
+ ? code && code !== 0 ? code : 1
655
+ : terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
656
+ stdout: stdout.toString(),
657
+ stderr: stderr.toString(),
658
+ ...(memory ?? {}),
659
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
660
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
661
+ });
662
+ }).catch(fail);
663
+ });
664
+ });
665
+ }
666
+ }
667
+ /**
668
+ * The typed failure for a provider run that ended without calling its required Forge
669
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
670
+ * is not mistaken for an agent that simply ended its turn.
671
+ */
672
+ export function providerCompletionToolMissingFailure(message, result) {
673
+ if (result?.terminalStopReason === "success_ceiling") {
674
+ return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
675
+ }
676
+ return new ForgeFailureError("provider_completion_tool_missing", message);
677
+ }
678
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
679
+ function isProviderTurnActivity(line) {
680
+ const trimmed = line.trim();
681
+ if (!trimmed.startsWith("{"))
682
+ return false;
683
+ try {
684
+ const event = JSON.parse(trimmed);
685
+ return event.type === "assistant"
686
+ || event.type === "user"
687
+ || (event.type === "system" && event.subtype === "init")
688
+ || event.type === "turn.started"
689
+ || event.type === "item.started";
690
+ }
691
+ catch {
692
+ return false;
693
+ }
694
+ }
695
+ function isProviderTerminalFailure(line) {
696
+ const trimmed = line.trim();
697
+ if (!trimmed.startsWith("{"))
698
+ return false;
699
+ try {
700
+ const event = JSON.parse(trimmed);
701
+ // The same events the output parsers report as provider errors.
702
+ return event.type === "turn.failed"
703
+ || event.type === "error"
704
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
705
+ }
706
+ catch {
707
+ return false;
708
+ }
709
+ }
710
+ function isProviderTerminalSuccess(line) {
711
+ const trimmed = line.trim();
712
+ if (!trimmed.startsWith("{"))
713
+ return false;
714
+ try {
715
+ const event = JSON.parse(trimmed);
716
+ return event.type === "turn.completed"
717
+ || (event.type === "result" && event.subtype === "success" && event.is_error !== true);
718
+ }
719
+ catch {
720
+ return false;
721
+ }
722
+ }
723
+ class HostProcessTreeMemoryObserver {
724
+ launch;
725
+ processGroupId;
726
+ peakMemoryBytes = 0;
727
+ sampleCount = 0;
728
+ observedAt = null;
729
+ timer;
730
+ constructor(launch, processGroupId) {
731
+ this.launch = launch;
732
+ this.processGroupId = processGroupId;
733
+ if (launch.strategy === "unix_process_group" && processGroupId > 0) {
734
+ this.sample();
735
+ this.timer = setInterval(() => this.sample(), 1_000);
736
+ this.timer.unref?.();
737
+ }
738
+ else {
739
+ this.timer = null;
740
+ }
741
+ }
742
+ sample() {
743
+ if (this.launch.strategy !== "unix_process_group" || this.processGroupId <= 0)
744
+ return;
745
+ const bytes = processGroupResidentMemoryBytes(this.processGroupId);
746
+ if (bytes === null)
747
+ return;
748
+ this.sampleCount += 1;
749
+ this.peakMemoryBytes = Math.max(this.peakMemoryBytes, bytes);
750
+ this.observedAt = new Date().toISOString();
751
+ }
752
+ complete() {
753
+ if (this.timer)
754
+ clearInterval(this.timer);
755
+ if (this.launch.strategy === "windows_job_object") {
756
+ return readWindowsJobMemoryTelemetry(this.launch.memoryTelemetryPath);
757
+ }
758
+ if (this.peakMemoryBytes <= 0 || this.sampleCount <= 0 || !this.observedAt)
759
+ return undefined;
760
+ return {
761
+ peakMemoryBytes: this.peakMemoryBytes,
762
+ memorySampleCount: this.sampleCount,
763
+ memorySource: process.platform === "linux"
764
+ ? "linux_process_group_rss"
765
+ : "unix_process_group_rss",
766
+ memoryObservedAt: this.observedAt,
767
+ };
768
+ }
769
+ }
770
+ /** Returns aggregate resident bytes for the exact supervised Unix process group. */
771
+ export function processGroupResidentMemoryBytes(processGroupId, platform = process.platform, procRoot = "/proc") {
772
+ if (!Number.isSafeInteger(processGroupId) || processGroupId <= 0)
773
+ return null;
774
+ if (platform === "linux") {
775
+ let totalKilobytes = 0;
776
+ let matched = 0;
777
+ try {
778
+ for (const entry of fs.readdirSync(procRoot, { withFileTypes: true })) {
779
+ if (!entry.isDirectory() || !/^\d+$/u.test(entry.name))
780
+ continue;
781
+ try {
782
+ const stat = fs.readFileSync(path.join(procRoot, entry.name, "stat"), "utf8");
783
+ const close = stat.lastIndexOf(")");
784
+ const fields = close >= 0 ? stat.slice(close + 2).trim().split(/\s+/u) : [];
785
+ if (Number.parseInt(fields[2] ?? "", 10) !== processGroupId)
786
+ continue;
787
+ const status = fs.readFileSync(path.join(procRoot, entry.name, "status"), "utf8");
788
+ const rss = /^VmRSS:\s+(\d+)\s+kB$/mu.exec(status);
789
+ if (!rss)
790
+ continue;
791
+ totalKilobytes += Number.parseInt(rss[1], 10);
792
+ matched += 1;
793
+ }
794
+ catch {
795
+ // Processes can exit between the directory, stat, and status reads.
796
+ }
797
+ }
798
+ return matched > 0 ? totalKilobytes * 1024 : null;
799
+ }
800
+ catch {
801
+ return null;
802
+ }
803
+ }
804
+ if (platform !== "win32") {
805
+ try {
806
+ const output = execFileSync("ps", ["-axo", "pgid=,rss="], {
807
+ encoding: "utf8",
808
+ timeout: 5_000,
809
+ stdio: ["ignore", "pipe", "ignore"],
810
+ });
811
+ let totalKilobytes = 0;
812
+ let matched = 0;
813
+ for (const line of output.split(/\r?\n/u)) {
814
+ const fields = line.trim().split(/\s+/u);
815
+ if (Number.parseInt(fields[0] ?? "", 10) !== processGroupId)
816
+ continue;
817
+ const rss = Number.parseInt(fields[1] ?? "", 10);
818
+ if (!Number.isSafeInteger(rss) || rss < 0)
819
+ continue;
820
+ totalKilobytes += rss;
821
+ matched += 1;
822
+ }
823
+ return matched > 0 ? totalKilobytes * 1024 : null;
824
+ }
825
+ catch {
826
+ return null;
827
+ }
828
+ }
829
+ return null;
830
+ }
831
+ function readWindowsJobMemoryTelemetry(target) {
832
+ if (!target)
833
+ return undefined;
834
+ try {
835
+ const value = JSON.parse(fs.readFileSync(target, "utf8"));
836
+ const peakMemoryBytes = value.peakMemoryBytes;
837
+ const sampleCount = value.sampleCount;
838
+ const source = value.source;
839
+ const observedAt = value.observedAt;
840
+ if (!Number.isSafeInteger(peakMemoryBytes) || peakMemoryBytes <= 0
841
+ || !Number.isSafeInteger(sampleCount) || sampleCount <= 0
842
+ || typeof source !== "string" || source.length === 0
843
+ || typeof observedAt !== "string" || !Number.isFinite(Date.parse(observedAt))) {
844
+ return undefined;
845
+ }
846
+ return {
847
+ peakMemoryBytes: peakMemoryBytes,
848
+ memorySampleCount: sampleCount,
849
+ memorySource: source,
850
+ memoryObservedAt: observedAt,
851
+ };
852
+ }
853
+ catch {
854
+ return undefined;
855
+ }
856
+ }
857
+ class BoundedOutputTail {
858
+ maxChars;
859
+ value = "";
860
+ constructor(maxChars) {
861
+ this.maxChars = maxChars;
862
+ }
863
+ appendLine(line) {
864
+ const chunk = `${line}\n`;
865
+ if (chunk.length >= this.maxChars) {
866
+ this.value = chunk.slice(-this.maxChars);
867
+ return;
868
+ }
869
+ const retainedPrefixChars = this.maxChars - chunk.length;
870
+ this.value = `${this.value.slice(-retainedPrefixChars)}${chunk}`;
871
+ }
872
+ toString() {
873
+ return this.value;
874
+ }
875
+ }
876
+ async function resolveProviderProcessLaunch(command, args) {
877
+ if (process.platform !== "win32") {
878
+ return { command, args };
879
+ }
880
+ const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
881
+ if (cursorDirect) {
882
+ return cursorDirect;
883
+ }
884
+ const resolved = await resolveWindowsCommand(command);
885
+ if (!resolved) {
886
+ return { command, args };
887
+ }
888
+ return resolveCodexNpmDirectLaunch(resolved, args)
889
+ ?? resolveClaudeNpmDirectLaunch(resolved, args)
890
+ ?? resolvePackageManagerDirectLaunch(resolved, args)
891
+ ?? buildWindowsLaunchCommand(resolved, args);
892
+ }
893
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
894
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
895
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
896
+ /**
897
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
898
+ * itself with the provider (`exec`), so the supervised root PID, process group
899
+ * and birth identity stay the provider's. The provider command and arguments
900
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
901
+ * into the script. EOF, a read error, or any other content on fd 3 exits
902
+ * without running the provider. fd 3 is closed before exec so the provider and
903
+ * its descendants never inherit the grant channel. stdin is not touched, so
904
+ * the prompt stays buffered in its pipe for the provider.
905
+ */
906
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
907
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
908
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
909
+ "exec \"$@\" 3<&-",
910
+ ].join("\n");
911
+ export function buildUnixProviderStartGateLaunch(command, args) {
912
+ return {
913
+ command: UNIX_PROVIDER_START_GATE_SHELL,
914
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
915
+ };
916
+ }
917
+ /**
918
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
919
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
920
+ * ENOENT before any start is recorded; nothing can run in that case. The check
921
+ * is advisory: if the executable disappears between this lookup and the gated
922
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
923
+ * start was recorded, which surfaces as an ordinary provider failure.
924
+ */
925
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
926
+ if (!command || command.startsWith("-"))
927
+ return false;
928
+ const candidates = command.includes("/")
929
+ ? [path.resolve(cwd, command)]
930
+ : pathValue === undefined
931
+ ? null
932
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
933
+ if (candidates === null)
934
+ return true;
935
+ return candidates.some(candidate => {
936
+ try {
937
+ if (!fs.statSync(candidate).isFile())
938
+ return false;
939
+ fs.accessSync(candidate, fs.constants.X_OK);
940
+ return true;
941
+ }
942
+ catch {
943
+ return false;
944
+ }
945
+ });
946
+ }
947
+ function isBrokenPipeError(error) {
948
+ const code = error?.code;
949
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
950
+ }
951
+ function grantWindowsProviderStart(launch) {
952
+ if (!launch.startGrantPath) {
953
+ throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
954
+ }
955
+ fs.writeFileSync(launch.startGrantPath, "granted\n", {
956
+ encoding: "utf8",
957
+ flag: "wx",
958
+ mode: 0o600,
959
+ });
960
+ }
961
+ async function waitForWindowsProviderReady(launch, signal, isClosed) {
962
+ const readyPath = launch.readyPath;
963
+ if (!readyPath) {
964
+ throw new Error("host_process_supervisor_invalid: Windows provider-ready path was not assigned.");
965
+ }
966
+ while (true) {
967
+ try {
968
+ const parsed = JSON.parse(await fs.promises.readFile(readyPath, "utf8"));
969
+ if (parsed.schemaVersion !== 1
970
+ || parsed.supervisorId !== launch.supervisorId
971
+ || !Number.isSafeInteger(parsed.rootPid)
972
+ || (parsed.rootPid ?? 0) <= 0
973
+ || typeof parsed.rootIdentity !== "string"
974
+ || !/^win32:\d+$/u.test(parsed.rootIdentity)
975
+ || !Number.isSafeInteger(parsed.providerPid)
976
+ || (parsed.providerPid ?? 0) <= 0
977
+ || typeof parsed.providerCreatedAt !== "string"
978
+ || Number.isNaN(Date.parse(parsed.providerCreatedAt))
979
+ || (parsed.providerIdentity !== undefined
980
+ && (typeof parsed.providerIdentity !== "string" || !/^win32:\d+$/u.test(parsed.providerIdentity)))
981
+ || !Number.isSafeInteger(parsed.startAttempt)
982
+ || (parsed.startAttempt ?? 0) < 1) {
983
+ throw new Error("host_process_supervisor_invalid: provider-ready receipt was invalid.");
984
+ }
985
+ return parsed;
986
+ }
987
+ catch (error) {
988
+ if (error.code !== "ENOENT")
989
+ throw error;
990
+ }
991
+ if (isClosed()) {
992
+ throw new ForgeFailureError("attempt_process_supervisor_start_failed", "host_process_supervisor_start_failed: supervisor exited before the provider became ready.", "bridge");
993
+ }
994
+ if (signal?.aborted) {
995
+ throw signal.reason instanceof Error ? signal.reason : new Error("Provider process launch was aborted.");
996
+ }
997
+ await new Promise(resolve => setTimeout(resolve, 25));
998
+ }
999
+ }
1000
+ export function resolveCodexNpmDirectLaunch(commandPath, args) {
1001
+ const extension = path.extname(commandPath).toLowerCase();
1002
+ if ((extension !== ".cmd" && extension !== ".ps1")
1003
+ || path.basename(commandPath, extension).toLowerCase() !== "codex") {
1004
+ return null;
1005
+ }
1006
+ const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@openai", "codex", "bin", "codex.js");
1007
+ return fs.existsSync(entryPoint)
1008
+ ? { command: process.execPath, args: [entryPoint, ...args] }
1009
+ : null;
1010
+ }
1011
+ /**
1012
+ * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
1013
+ * PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
1014
+ * ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
1015
+ */
1016
+ export function resolveClaudeNpmDirectLaunch(commandPath, args) {
1017
+ const extension = path.extname(commandPath).toLowerCase();
1018
+ if ((extension !== ".cmd" && extension !== ".ps1")
1019
+ || path.basename(commandPath, extension).toLowerCase() !== "claude") {
1020
+ return null;
1021
+ }
1022
+ const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@anthropic-ai", "claude-code", "cli.js");
1023
+ return fs.existsSync(entryPoint)
1024
+ ? { command: process.execPath, args: [entryPoint, ...args] }
1025
+ : null;
1026
+ }
1027
+ /**
1028
+ * Avoids cmd.exe's nested-quote handling for package-manager shims. That
1029
+ * quoting loses executable paths containing spaces after the command is
1030
+ * wrapped by the Windows Job Object supervisor.
1031
+ */
1032
+ export function resolvePackageManagerDirectLaunch(commandPath, args) {
1033
+ const extension = path.extname(commandPath).toLowerCase();
1034
+ if (extension !== ".cmd" && extension !== ".ps1")
1035
+ return null;
1036
+ const packageManager = path.basename(commandPath, extension).toLowerCase();
1037
+ if (!["corepack", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
1038
+ return null;
1039
+ const root = path.dirname(commandPath);
1040
+ const candidates = [
1041
+ path.join(root, "node_modules", "corepack", "dist", packageManager === "corepack" ? "corepack.js" : `${packageManager}.js`),
1042
+ ...(packageManager === "npm" || packageManager === "npx"
1043
+ ? [path.join(root, "node_modules", "npm", "bin", `${packageManager}-cli.js`)]
1044
+ : []),
1045
+ ...(packageManager === "pnpm" || packageManager === "pnpx"
1046
+ ? [path.join(root, "node_modules", "pnpm", "bin", `${packageManager}.cjs`)]
1047
+ : []),
1048
+ ...(packageManager === "yarn" || packageManager === "yarnpkg"
1049
+ ? [path.join(root, "node_modules", "yarn", "bin", "yarn.js")]
1050
+ : []),
1051
+ ];
1052
+ const entryPoint = candidates.find(candidate => fs.existsSync(candidate));
1053
+ if (!entryPoint)
1054
+ return null;
1055
+ const adjacentNode = path.join(root, "node.exe");
1056
+ return {
1057
+ command: fs.existsSync(adjacentNode) ? adjacentNode : process.execPath,
1058
+ args: [entryPoint, ...args],
1059
+ };
1060
+ }
1061
+ async function resolveWindowsCommand(command) {
1062
+ if (path.isAbsolute(command)) {
1063
+ return command;
1064
+ }
1065
+ const resolvedFromPath = resolveWindowsCommandFromPath(command);
1066
+ if (resolvedFromPath) {
1067
+ return resolvedFromPath;
1068
+ }
1069
+ try {
1070
+ const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
1071
+ return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
1072
+ }
1073
+ catch {
1074
+ return null;
1075
+ }
1076
+ }
1077
+ /**
1078
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
1079
+ * happen while the machine is under enough process pressure for where.exe to
1080
+ * miss its timeout; returning the unresolved package-manager name in that case
1081
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
1082
+ */
1083
+ export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
1084
+ if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
1085
+ return null;
1086
+ }
1087
+ const hasExtension = path.extname(command).length > 0;
1088
+ const extensions = hasExtension
1089
+ ? [""]
1090
+ : [...new Set([
1091
+ "",
1092
+ ".exe",
1093
+ ".ps1",
1094
+ ".cmd",
1095
+ ".bat",
1096
+ ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
1097
+ ])];
1098
+ for (const rawDirectory of pathValue.split(path.delimiter)) {
1099
+ const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
1100
+ if (!directory)
1101
+ continue;
1102
+ const candidates = [];
1103
+ for (const extension of extensions) {
1104
+ const candidate = path.join(directory, `${command}${extension}`);
1105
+ if (fs.existsSync(candidate))
1106
+ candidates.push(candidate);
1107
+ }
1108
+ const resolved = chooseWindowsCommandCandidate(candidates);
1109
+ if (resolved)
1110
+ return resolved;
1111
+ }
1112
+ return null;
1113
+ }
1114
+ export function chooseWindowsCommandCandidate(candidates) {
1115
+ const normalized = candidates
1116
+ .map((candidate) => candidate.trim())
1117
+ .filter((candidate) => candidate.length > 0);
1118
+ if (normalized.length === 0) {
1119
+ return null;
1120
+ }
1121
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1122
+ for (const extension of preferredExtensions) {
1123
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1124
+ if (candidate) {
1125
+ return candidate;
1126
+ }
1127
+ }
1128
+ return normalized[0];
1129
+ }
1130
+ async function readProcessLines(stream, onLine) {
1131
+ const reader = readline.createInterface({ input: stream });
1132
+ try {
1133
+ for await (const line of reader) {
1134
+ await onLine(line);
1135
+ }
1136
+ }
1137
+ finally {
1138
+ reader.close();
1139
+ }
1140
+ }