@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 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 (185) hide show
  1. package/README.md +89 -3
  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 +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  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 +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,4 +1,5 @@
1
- import { execFile, spawn } from "node:child_process";
1
+ import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
@@ -7,7 +8,145 @@ import { promisify } from "node:util";
7
8
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
8
9
  import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunch, terminateHostProcessTree, } from "../../shared/process/host-process-supervisor.js";
9
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";
10
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
+ }
11
150
  const allowedProviderParentEnvNames = [
12
151
  "PATH",
13
152
  "HOME",
@@ -15,7 +154,8 @@ const allowedProviderParentEnvNames = [
15
154
  "TMPDIR",
16
155
  "TEMP",
17
156
  "TMP",
18
- "LANG"
157
+ "LANG",
158
+ "CLAUDE_CONFIG_DIR"
19
159
  ];
20
160
  const windowsAllowedProviderParentEnvNames = [
21
161
  "SystemRoot",
@@ -36,7 +176,8 @@ const windowsAllowedProviderParentEnvNames = [
36
176
  "DOTNET_ROOT(x86)",
37
177
  "DOTNET_CLI_HOME",
38
178
  "NUGET_PACKAGES",
39
- "NUGET_HTTP_CACHE_PATH"
179
+ "NUGET_HTTP_CACHE_PATH",
180
+ "CLAUDE_CODE_GIT_BASH_PATH"
40
181
  ];
41
182
  export function buildProviderChildEnvironment(requestEnv, options = {}) {
42
183
  const parentEnv = options.parentEnv ?? process.env;
@@ -58,8 +199,37 @@ export function buildProviderChildEnvironment(requestEnv, options = {}) {
58
199
  if (platform === "win32") {
59
200
  normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
60
201
  }
202
+ normalizeProviderBuildEnvironment(env);
61
203
  return env;
62
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
+ }
63
233
  function isAllowedProviderParentEnv(key, platform = process.platform) {
64
234
  return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
65
235
  || key.toUpperCase().startsWith("LC_")
@@ -75,6 +245,17 @@ function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
75
245
  setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
76
246
  setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
77
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);
78
259
  const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
79
260
  if (userProfile) {
80
261
  setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
@@ -138,19 +319,50 @@ function setEnvironmentValueIfMissing(env, name, value) {
138
319
  env[name] = value;
139
320
  }
140
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
+ }
141
330
  async run(request, handlers = {}, signal) {
331
+ assertHostDatabaseCapabilityBoundary();
142
332
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
143
333
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
144
- const launch = supervisedLaunch ?? { ...providerLaunch, detached: false };
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;
145
351
  return await new Promise((resolve, reject) => {
146
352
  const rootCreatedAt = new Date().toISOString();
147
- const child = spawn(launch.command, launch.args, {
353
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
354
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
148
355
  cwd: request.cwd,
149
- env: buildProviderChildEnvironment(request.env),
150
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
356
+ env: childEnvironment,
357
+ stdio: startGated
358
+ ? [stdinMode, "pipe", "pipe", "pipe"]
359
+ : [stdinMode, "pipe", "pipe"],
151
360
  windowsHide: true,
152
361
  detached: launch.detached,
153
362
  });
363
+ const memoryObserver = supervisedLaunch
364
+ ? new HostProcessTreeMemoryObserver(supervisedLaunch, child.pid ?? 0)
365
+ : null;
154
366
  let termination = null;
155
367
  const terminate = () => {
156
368
  termination ??= terminateHostProcessTree(child, supervisedLaunch);
@@ -159,16 +371,33 @@ export class StreamingProviderProcessRunner {
159
371
  const childStdout = child.stdout;
160
372
  const childStderr = child.stderr;
161
373
  if (!childStdout || !childStderr) {
162
- void terminate();
163
- reject(new Error("Provider process stdout/stderr streams were not piped."));
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.")));
164
376
  return;
165
377
  }
166
- let stdout = "";
167
- let stderr = "";
378
+ const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
379
+ const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
168
380
  let settled = false;
169
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;
170
396
  let readiness = null;
171
397
  const cleanup = () => {
398
+ stopTerminalWorkTimer();
399
+ graceIdleMs = null;
400
+ ceilingIdleMs = null;
172
401
  signal?.removeEventListener("abort", abort);
173
402
  };
174
403
  const fail = (error) => {
@@ -177,10 +406,14 @@ export class StreamingProviderProcessRunner {
177
406
  }
178
407
  settled = true;
179
408
  cleanup();
180
- void terminate().catch(() => undefined);
181
- reject(error);
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.")));
182
412
  };
183
413
  const abort = () => {
414
+ if (!closed)
415
+ cancelledBeforeClose = true;
416
+ cancellationRequested = true;
184
417
  // Cancellation is not a launch failure when the supervised tree can be
185
418
  // proven stopped. Let the close handler settle the command after exact
186
419
  // termination; only a failed termination proof rejects the run.
@@ -193,6 +426,27 @@ export class StreamingProviderProcessRunner {
193
426
  signal?.addEventListener("abort", abort, { once: true });
194
427
  }
195
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
+ };
196
450
  child.once("spawn", () => {
197
451
  readiness = (async () => {
198
452
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -205,6 +459,9 @@ export class StreamingProviderProcessRunner {
205
459
  if (supervisedLaunch?.strategy === "windows_job_object") {
206
460
  grantWindowsProviderStart(supervisedLaunch);
207
461
  }
462
+ else if (startGated) {
463
+ grantUnixProviderStart();
464
+ }
208
465
  })();
209
466
  void readiness.catch(error => {
210
467
  if (!closed && !signal?.aborted)
@@ -220,15 +477,20 @@ export class StreamingProviderProcessRunner {
220
477
  return;
221
478
  }
222
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;
223
485
  void terminate();
224
486
  fail(error);
225
487
  });
226
488
  child.stdin.end(request.stdin, "utf8");
227
489
  };
228
490
  if (request.stdin !== undefined) {
229
- if (supervisedLaunch?.strategy === "windows_job_object") {
230
- // The outer supervisor must receive stdin before it can launch the
231
- // inner provider. Its start-grant file prevents prompt delivery.
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.
232
494
  writeProviderInput();
233
495
  }
234
496
  else {
@@ -237,18 +499,121 @@ export class StreamingProviderProcessRunner {
237
499
  });
238
500
  }
239
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
+ };
240
577
  const readers = [
241
578
  readProcessLines(childStdout, (line) => {
242
579
  if (request.captureOutput !== false)
243
- stdout += `${line}\n`;
244
- return handlers.onStdoutLine?.(line);
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;
245
607
  }),
246
608
  readProcessLines(childStderr, (line) => {
247
609
  if (request.captureOutput !== false)
248
- stderr += `${line}\n`;
610
+ stderr.appendLine(line);
249
611
  return handlers.onStderrLine?.(line);
250
612
  })
251
613
  ];
614
+ for (const reader of readers) {
615
+ void reader.catch(fail);
616
+ }
252
617
  child.on("close", (code) => {
253
618
  closed = true;
254
619
  Promise.allSettled(readers).then(async (readerResults) => {
@@ -262,7 +627,8 @@ export class StreamingProviderProcessRunner {
262
627
  return;
263
628
  }
264
629
  try {
265
- if (supervisedLaunch?.strategy === "unix_process_group") {
630
+ memoryObserver?.sample();
631
+ if (supervisedLaunch?.strategy === "unix_process_group" || !supervisedLaunch) {
266
632
  await terminate();
267
633
  }
268
634
  else if (termination) {
@@ -275,16 +641,238 @@ export class StreamingProviderProcessRunner {
275
641
  }
276
642
  settled = true;
277
643
  cleanup();
644
+ const memory = memoryObserver?.complete();
278
645
  resolve({
279
- exitCode: code ?? 1,
280
- stdout,
281
- stderr
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 } : {}),
282
661
  });
283
662
  }).catch(fail);
284
663
  });
285
664
  });
286
665
  }
287
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
+ }
288
876
  async function resolveProviderProcessLaunch(command, args) {
289
877
  if (process.platform !== "win32") {
290
878
  return { command, args };
@@ -298,9 +886,68 @@ async function resolveProviderProcessLaunch(command, args) {
298
886
  return { command, args };
299
887
  }
300
888
  return resolveCodexNpmDirectLaunch(resolved, args)
889
+ ?? resolveClaudeNpmDirectLaunch(resolved, args)
301
890
  ?? resolvePackageManagerDirectLaunch(resolved, args)
302
891
  ?? buildWindowsLaunchCommand(resolved, args);
303
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
+ }
304
951
  function grantWindowsProviderStart(launch) {
305
952
  if (!launch.startGrantPath) {
306
953
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
@@ -342,7 +989,7 @@ async function waitForWindowsProviderReady(launch, signal, isClosed) {
342
989
  throw error;
343
990
  }
344
991
  if (isClosed()) {
345
- throw new Error("host_process_supervisor_start_failed: supervisor exited before the provider became ready.");
992
+ throw new ForgeFailureError("attempt_process_supervisor_start_failed", "host_process_supervisor_start_failed: supervisor exited before the provider became ready.", "bridge");
346
993
  }
347
994
  if (signal?.aborted) {
348
995
  throw signal.reason instanceof Error ? signal.reason : new Error("Provider process launch was aborted.");
@@ -361,6 +1008,22 @@ export function resolveCodexNpmDirectLaunch(commandPath, args) {
361
1008
  ? { command: process.execPath, args: [entryPoint, ...args] }
362
1009
  : null;
363
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
+ }
364
1027
  /**
365
1028
  * Avoids cmd.exe's nested-quote handling for package-manager shims. That
366
1029
  * quoting loses executable paths containing spaces after the command is
@@ -371,11 +1034,11 @@ export function resolvePackageManagerDirectLaunch(commandPath, args) {
371
1034
  if (extension !== ".cmd" && extension !== ".ps1")
372
1035
  return null;
373
1036
  const packageManager = path.basename(commandPath, extension).toLowerCase();
374
- if (!["npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
1037
+ if (!["corepack", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
375
1038
  return null;
376
1039
  const root = path.dirname(commandPath);
377
1040
  const candidates = [
378
- path.join(root, "node_modules", "corepack", "dist", `${packageManager}.js`),
1041
+ path.join(root, "node_modules", "corepack", "dist", packageManager === "corepack" ? "corepack.js" : `${packageManager}.js`),
379
1042
  ...(packageManager === "npm" || packageManager === "npx"
380
1043
  ? [path.join(root, "node_modules", "npm", "bin", `${packageManager}-cli.js`)]
381
1044
  : []),
@@ -432,18 +1095,21 @@ export function resolveWindowsCommandFromPath(command, pathValue = process.env.P
432
1095
  ".bat",
433
1096
  ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
434
1097
  ])];
435
- const candidates = [];
436
1098
  for (const rawDirectory of pathValue.split(path.delimiter)) {
437
1099
  const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
438
1100
  if (!directory)
439
1101
  continue;
1102
+ const candidates = [];
440
1103
  for (const extension of extensions) {
441
1104
  const candidate = path.join(directory, `${command}${extension}`);
442
1105
  if (fs.existsSync(candidate))
443
1106
  candidates.push(candidate);
444
1107
  }
1108
+ const resolved = chooseWindowsCommandCandidate(candidates);
1109
+ if (resolved)
1110
+ return resolved;
445
1111
  }
446
- return chooseWindowsCommandCandidate(candidates);
1112
+ return null;
447
1113
  }
448
1114
  export function chooseWindowsCommandCandidate(candidates) {
449
1115
  const normalized = candidates