@loucompanion/forge-bridge 0.1.4-dev.b1c678efffd2 → 0.1.4-dev.bb5355d0d83f

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 (73) hide show
  1. package/README.md +13 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +1 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +16 -4
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  7. package/dist/bridge/runner-host-capabilities.js +13 -0
  8. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  9. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  10. package/dist/runtime/docker-engine-probe.js +7 -0
  11. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  12. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  13. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  14. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  15. package/dist/runtime/host-facts.d.ts +2 -1
  16. package/dist/runtime/host-load-admission.d.ts +9 -2
  17. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  18. package/dist/runtime/host-load-child-environment.js +19 -10
  19. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  20. package/dist/runtime/host-load-governor-config.js +7 -0
  21. package/dist/runtime/host-load-governor.d.ts +10 -0
  22. package/dist/runtime/host-load-governor.js +125 -34
  23. package/dist/runtime/host-load-sampler.d.ts +34 -4
  24. package/dist/runtime/host-load-sampler.js +73 -7
  25. package/dist/runtime/host-load-step-class.d.ts +3 -1
  26. package/dist/runtime/host-load-step-class.js +60 -5
  27. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  28. package/dist/runtime/host-load-test-slot.js +81 -0
  29. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  30. package/dist/runtime/host-load-token-ledger.js +93 -61
  31. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  32. package/dist/runtime/host-load-windows-cpu.js +85 -0
  33. package/dist/runtime/host-runtime-lease.d.ts +1 -1
  34. package/dist/runtime/host-runtime-lease.js +1 -1
  35. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  36. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  37. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  38. package/dist/sandbox/host-capacity-broker.js +23 -4
  39. package/dist/session/architect-waits.d.ts +2 -0
  40. package/dist/session/architect-waits.js +138 -0
  41. package/dist/session/managed-attempt-tools.d.ts +0 -7
  42. package/dist/session/managed-attempt-tools.js +51 -62
  43. package/dist/session/managed-command-host-load.d.ts +2 -0
  44. package/dist/session/managed-command-host-load.js +2 -1
  45. package/dist/session/phase-completion.runtime.js +1 -1
  46. package/dist/session/phase-completion.schemas.js +3 -11
  47. package/dist/session/phase-completion.validation.js +3 -1
  48. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  49. package/dist/session/pre-publication-native-postgres.js +111 -0
  50. package/dist/session/pre-publication-pass.d.ts +2 -1
  51. package/dist/session/pre-publication-pass.js +8 -5
  52. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  53. package/dist/session/pre-publication-step-execution.js +6 -5
  54. package/dist/session/pre-publication-validation.d.ts +9 -3
  55. package/dist/session/pre-publication-validation.js +62 -34
  56. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  57. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  58. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  59. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  60. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -16
  61. package/dist/session/provider-cli/provider-cli.process.js +22 -283
  62. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  63. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  64. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  65. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  66. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  67. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  68. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  69. package/dist/shared/process/windows-launch.d.ts +18 -0
  70. package/dist/shared/process/windows-launch.js +68 -0
  71. package/dist/version.d.ts +1 -1
  72. package/dist/version.js +1 -1
  73. package/package.json +1 -1
@@ -1,5 +1,7 @@
1
1
  import { type LaunchCommand } from "../../shared/process/windows-launch.js";
2
2
  import { ForgeFailureError } from "../session.types.js";
3
+ export { chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
4
+ export { buildProviderChildEnvironment, type ProviderChildEnvironmentOptions } from "./provider-cli.child-environment.js";
3
5
  export declare const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS: number;
4
6
  export type ProviderCliCommand = LaunchCommand;
5
7
  export interface ProviderProcessRunRequest {
@@ -36,6 +38,8 @@ export interface ProviderProcessRunResult {
36
38
  readonly cancelled?: true;
37
39
  /** Present when Forge stopped a provider that stayed resident after its turn ended. */
38
40
  readonly terminalStopReason?: ProviderTerminalStopReason;
41
+ /** Present when Forge closed output pipes a descendant still held after the provider exited. */
42
+ readonly outputPipesReleasedAfterExit?: true;
39
43
  }
40
44
  export interface ProviderProcessRunner {
41
45
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
@@ -89,17 +93,12 @@ export declare class CodexResumeRecoveringProcessRunner implements ProviderProce
89
93
  * arbitrary tool/command output and therefore cannot mint retry authority.
90
94
  */
91
95
  export declare function isTransientCodexProviderNotFoundFailure(command: string, result: ProviderProcessRunResult): boolean;
92
- interface ProviderChildEnvironmentOptions {
93
- readonly parentEnv?: NodeJS.ProcessEnv;
94
- readonly platform?: NodeJS.Platform;
95
- readonly homeDir?: string;
96
- }
97
- export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
98
96
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
99
97
  private readonly terminalExitGraceMs;
100
98
  private readonly terminalSuccessCeilingMs;
101
99
  private readonly terminalWorkPollMs;
102
- constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
100
+ private readonly outputPipeReleaseGraceMs;
101
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number, outputPipeReleaseGraceMs?: number);
103
102
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
104
103
  }
105
104
  /**
@@ -125,12 +124,3 @@ export declare function resolveClaudeNpmDirectLaunch(commandPath: string, args:
125
124
  * wrapped by the Windows Job Object supervisor.
126
125
  */
127
126
  export declare function resolvePackageManagerDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
128
- /**
129
- * Resolves Windows commands without spawning where.exe. Runtime launches can
130
- * happen while the machine is under enough process pressure for where.exe to
131
- * miss its timeout; returning the unresolved package-manager name in that case
132
- * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
133
- */
134
- export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string): string | null;
135
- export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
136
- export {};
@@ -1,17 +1,19 @@
1
1
  import { execFile, execFileSync, spawn } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
2
  import fs from "node:fs";
4
- import os from "node:os";
5
3
  import path from "node:path";
6
- import readline from "node:readline";
7
4
  import { promisify } from "node:util";
8
5
  import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
6
  import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunch, terminateHostProcessTree, } from "../../shared/process/host-process-supervisor.js";
10
- import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
7
+ import { buildWindowsLaunchCommand, chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
8
+ import { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
9
+ import { isCodexModelsCacheSchemaFailure, quarantineIncompatibleCodexModelsCache } from "./provider-cli.codex-models-cache.js";
11
10
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
11
  import { ForgeFailureError } from "../session.types.js";
13
12
  import { BackgroundWorkStopFailingRunner, ClaudeBackgroundTurnEndWatch, providerTurnEndedWithBackgroundWorkFailure } from "./claude-background-work.js";
14
13
  import { hasNonterminalManagedCommand, isProviderTerminalFailure, isProviderTerminalSuccess, isProviderTurnActivity } from "./provider-in-flight-work.js";
14
+ import { OutputPipeRelease, readProcessLines, PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS } from "./provider-output-pipes.js";
15
+ export { chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
16
+ export { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
15
17
  const execFileAsync = promisify(execFile);
16
18
  // Provider processes can emit many gigabytes over a long-running session. The
17
19
  // line handlers stream that output to Forge as it arrives; the completed result
@@ -24,7 +26,6 @@ const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
24
26
  const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
25
27
  // How often the end-of-turn timers re-check whether supervised work is still in flight.
26
28
  const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
27
- const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
28
29
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
29
30
  * relaunch needs a new fenced child generation and exclusive launch files. The outer
30
31
  * layer fails any run Forge stopped because its turn ended with background work live. */
@@ -123,216 +124,16 @@ function codexFreshTurnRequest(request) {
123
124
  function isCodexCommand(command) {
124
125
  return path.parse(command).name.toLowerCase() === "codex";
125
126
  }
126
- function isCodexModelsCacheSchemaFailure(result) {
127
- const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
128
- return output.includes("base_instructions")
129
- && output.includes("missing field")
130
- && (output.includes("models_cache") || output.includes("models cache") || output.includes("model cache"));
131
- }
132
- async function quarantineIncompatibleCodexModelsCache(requestEnv) {
133
- const configuredHome = readEnvironmentValue(requestEnv ?? {}, "CODEX_HOME")
134
- ?? readEnvironmentValue(process.env, "CODEX_HOME")
135
- ?? readEnvironmentValue(process.env, "FORGE_CODEX_HOME");
136
- const codexHome = path.resolve(configuredHome ?? path.join(os.homedir(), ".codex"));
137
- if (!path.isAbsolute(codexHome) || codexHome === path.parse(codexHome).root)
138
- return false;
139
- const cachePath = path.join(codexHome, "models_cache.json");
140
- const cacheStat = await fs.promises.lstat(cachePath).catch(error => {
141
- if (error.code === "ENOENT")
142
- return null;
143
- throw error;
144
- });
145
- if (!cacheStat
146
- || !cacheStat.isFile()
147
- || cacheStat.isSymbolicLink()
148
- || cacheStat.nlink !== 1
149
- || cacheStat.size <= 0
150
- || cacheStat.size > maximumRecoverableCodexModelsCacheBytes) {
151
- return false;
152
- }
153
- const quarantinePath = path.join(codexHome, `models_cache.forge-incompatible-${Date.now()}-${randomUUID()}.json`);
154
- await fs.promises.rename(cachePath, quarantinePath);
155
- return true;
156
- }
157
- const allowedProviderParentEnvNames = [
158
- "PATH",
159
- "HOME",
160
- "USERPROFILE",
161
- "TMPDIR",
162
- "TEMP",
163
- "TMP",
164
- "LANG",
165
- "CLAUDE_CONFIG_DIR"
166
- ];
167
- const windowsAllowedProviderParentEnvNames = [
168
- "SystemRoot",
169
- "SystemDrive",
170
- "ComSpec",
171
- "PATHEXT",
172
- "APPDATA",
173
- "LOCALAPPDATA",
174
- "USERNAME",
175
- "USERDOMAIN",
176
- "HOMEDRIVE",
177
- "HOMEPATH",
178
- "ProgramData",
179
- "ProgramFiles",
180
- "ProgramFiles(x86)",
181
- "ProgramW6432",
182
- "DOTNET_ROOT",
183
- "DOTNET_ROOT(x86)",
184
- "DOTNET_CLI_HOME",
185
- "NUGET_PACKAGES",
186
- "NUGET_HTTP_CACHE_PATH",
187
- "CLAUDE_CODE_GIT_BASH_PATH"
188
- ];
189
- export function buildProviderChildEnvironment(requestEnv, options = {}) {
190
- const parentEnv = options.parentEnv ?? process.env;
191
- const platform = options.platform ?? process.platform;
192
- const env = {};
193
- for (const [key, value] of Object.entries(parentEnv)) {
194
- if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
195
- env[key] = value;
196
- }
197
- }
198
- if (requestEnv) {
199
- for (const [key, value] of Object.entries(requestEnv)) {
200
- const trimmedKey = key.trim();
201
- if (trimmedKey.length > 0) {
202
- env[trimmedKey] = value;
203
- }
204
- }
205
- }
206
- if (platform === "win32") {
207
- normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
208
- }
209
- normalizeProviderBuildEnvironment(env);
210
- return env;
211
- }
212
- function normalizeProviderBuildEnvironment(env) {
213
- // Provider sessions are long lived and commonly run many dotnet builds. Persistent
214
- // MSBuild and Roslyn compiler servers otherwise survive individual commands and can
215
- // retain more memory than the active Forge lane. Keep those caches process-scoped by
216
- // default on every runner OS; an explicitly supplied request value still wins.
217
- setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
218
- setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
219
- setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
220
- }
221
- function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
222
- // The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
223
- // property names are case-insensitive on every OS. Collapse request aliases to
224
- // one canonical key so the explicit value wins without producing ambiguity.
225
- const exact = env[name];
226
- const alias = Object.entries(env).find(([key, candidate]) => key !== name
227
- && key.toLowerCase() === name.toLowerCase()
228
- && typeof candidate === "string"
229
- && candidate.trim().length > 0)?.[1];
230
- const resolved = typeof exact === "string" && exact.trim().length > 0
231
- ? exact
232
- : alias ?? value;
233
- for (const key of Object.keys(env)) {
234
- if (key !== name && key.toLowerCase() === name.toLowerCase()) {
235
- delete env[key];
236
- }
237
- }
238
- env[name] = resolved;
239
- }
240
- function isAllowedProviderParentEnv(key, platform = process.platform) {
241
- return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
242
- || key.toUpperCase().startsWith("LC_")
243
- || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
244
- }
245
- function isAllowedProviderParentEnvName(key, allowedNames) {
246
- return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
247
- }
248
- function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
249
- const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
250
- const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
251
- setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
252
- setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
253
- setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
254
- setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
255
- const resolvedSystemDrive = readEnvironmentValue(env, "SystemDrive") ?? systemDrive;
256
- const defaultProgramFiles = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files");
257
- const defaultProgramFilesX86 = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files (x86)");
258
- const defaultProgramData = path.win32.join(`${resolvedSystemDrive}\\`, "ProgramData");
259
- const programFiles = readEnvironmentValue(env, "ProgramFiles")
260
- ?? readEnvironmentValue(parentEnv, "ProgramFiles")
261
- ?? defaultProgramFiles;
262
- setEnvironmentValueIfMissing(env, "ProgramFiles", programFiles);
263
- setEnvironmentValueIfMissing(env, "ProgramW6432", readEnvironmentValue(parentEnv, "ProgramW6432") ?? defaultProgramFiles);
264
- setEnvironmentValueIfMissing(env, "ProgramFiles(x86)", readEnvironmentValue(parentEnv, "ProgramFiles(x86)") ?? defaultProgramFilesX86);
265
- setEnvironmentValueIfMissing(env, "ProgramData", readEnvironmentValue(parentEnv, "ProgramData") ?? defaultProgramData);
266
- const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
267
- if (userProfile) {
268
- setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
269
- setEnvironmentValueIfMissing(env, "HOME", userProfile);
270
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
271
- setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
272
- const parsed = path.win32.parse(userProfile);
273
- if (parsed.root) {
274
- setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
275
- setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
276
- }
277
- }
278
- const appData = readEnvironmentValue(env, "APPDATA")
279
- ?? readEnvironmentValue(parentEnv, "APPDATA")
280
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
281
- const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
282
- ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
283
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
284
- if (appData) {
285
- setEnvironmentValueIfMissing(env, "APPDATA", appData);
286
- }
287
- if (localAppData) {
288
- setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
289
- setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
290
- }
291
- setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
292
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
293
- setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
294
- setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
295
- }
296
- function resolveWindowsUserProfile(env, parentEnv, homeDir) {
297
- const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
298
- if (existing) {
299
- return existing;
300
- }
301
- const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
302
- if (home && path.win32.isAbsolute(home)) {
303
- return home;
304
- }
305
- const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
306
- const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
307
- if (homeDrive && homePath) {
308
- return `${homeDrive}${homePath}`;
309
- }
310
- if (homeDir && path.win32.isAbsolute(homeDir)) {
311
- return homeDir;
312
- }
313
- const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
314
- const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
315
- return username ? path.win32.join(systemDrive, "Users", username) : undefined;
316
- }
317
- function readEnvironmentValue(env, name) {
318
- const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
319
- const value = entry?.[1];
320
- return typeof value === "string" && value.trim().length > 0 ? value : undefined;
321
- }
322
- function setEnvironmentValueIfMissing(env, name, value) {
323
- if (readEnvironmentValue(env, name)) {
324
- return;
325
- }
326
- env[name] = value;
327
- }
328
127
  export class StreamingProviderProcessRunner {
329
128
  terminalExitGraceMs;
330
129
  terminalSuccessCeilingMs;
331
130
  terminalWorkPollMs;
332
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
131
+ outputPipeReleaseGraceMs;
132
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS, outputPipeReleaseGraceMs = PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS) {
333
133
  this.terminalExitGraceMs = terminalExitGraceMs;
334
134
  this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
335
135
  this.terminalWorkPollMs = terminalWorkPollMs;
136
+ this.outputPipeReleaseGraceMs = outputPipeReleaseGraceMs;
336
137
  }
337
138
  async run(request, handlers = {}, signal) {
338
139
  assertHostDatabaseCapabilityBoundary();
@@ -386,6 +187,7 @@ export class StreamingProviderProcessRunner {
386
187
  }
387
188
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
388
189
  const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
190
+ const outputPipes = new OutputPipeRelease(child, this.outputPipeReleaseGraceMs, message => stderr.appendLine(message));
389
191
  let settled = false;
390
192
  let closed = false;
391
193
  let cancellationRequested = false;
@@ -516,16 +318,6 @@ export class StreamingProviderProcessRunner {
516
318
  stopTerminalWorkTimer();
517
319
  void terminate().catch(fail);
518
320
  };
519
- const workInFlight = async () => {
520
- try {
521
- if (handlers.isToolCallInFlight?.())
522
- return true;
523
- }
524
- catch {
525
- // A failing probe must not keep the provider open or stop it early on its own.
526
- }
527
- return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
528
- };
529
321
  // The grace and the ceiling only count time in which no supervised work is in flight:
530
322
  // a provider waiting on an MCP tool call or on a managed command it started is not
531
323
  // finished, even when its turn has ended. The grace restarts once that work is done.
@@ -534,7 +326,7 @@ export class StreamingProviderProcessRunner {
534
326
  return;
535
327
  terminalWorkTickRunning = true;
536
328
  try {
537
- const inFlight = await workInFlight();
329
+ const inFlight = await providerWorkInFlight(handlers, request.env?.FORGE_LOG_DIR);
538
330
  const now = performance.now();
539
331
  const elapsed = Math.max(0, now - terminalWorkTickAt);
540
332
  terminalWorkTickAt = now;
@@ -669,12 +461,23 @@ export class StreamingProviderProcessRunner {
669
461
  ...(memory ?? {}),
670
462
  ...(cancelledBeforeClose ? { cancelled: true } : {}),
671
463
  ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
464
+ ...outputPipes.resultFields(),
672
465
  });
673
466
  }).catch(fail);
674
467
  });
675
468
  });
676
469
  }
677
470
  }
471
+ async function providerWorkInFlight(handlers, logDirectory) {
472
+ try {
473
+ if (handlers.isToolCallInFlight?.())
474
+ return true;
475
+ }
476
+ catch {
477
+ // A failing probe must not keep the provider open or stop it early on its own.
478
+ }
479
+ return await hasNonterminalManagedCommand(logDirectory).catch(() => false);
480
+ }
678
481
  /**
679
482
  * The typed failure for a provider run that ended without calling its required Forge
680
483
  * completion tool. A run Forge stopped at the success ceiling or for background work is
@@ -1042,67 +845,3 @@ async function resolveWindowsCommand(command) {
1042
845
  return null;
1043
846
  }
1044
847
  }
1045
- /**
1046
- * Resolves Windows commands without spawning where.exe. Runtime launches can
1047
- * happen while the machine is under enough process pressure for where.exe to
1048
- * miss its timeout; returning the unresolved package-manager name in that case
1049
- * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
1050
- */
1051
- export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
1052
- if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
1053
- return null;
1054
- }
1055
- const hasExtension = path.extname(command).length > 0;
1056
- const extensions = hasExtension
1057
- ? [""]
1058
- : [...new Set([
1059
- "",
1060
- ".exe",
1061
- ".ps1",
1062
- ".cmd",
1063
- ".bat",
1064
- ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
1065
- ])];
1066
- for (const rawDirectory of pathValue.split(path.delimiter)) {
1067
- const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
1068
- if (!directory)
1069
- continue;
1070
- const candidates = [];
1071
- for (const extension of extensions) {
1072
- const candidate = path.join(directory, `${command}${extension}`);
1073
- if (fs.existsSync(candidate))
1074
- candidates.push(candidate);
1075
- }
1076
- const resolved = chooseWindowsCommandCandidate(candidates);
1077
- if (resolved)
1078
- return resolved;
1079
- }
1080
- return null;
1081
- }
1082
- export function chooseWindowsCommandCandidate(candidates) {
1083
- const normalized = candidates
1084
- .map((candidate) => candidate.trim())
1085
- .filter((candidate) => candidate.length > 0);
1086
- if (normalized.length === 0) {
1087
- return null;
1088
- }
1089
- const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1090
- for (const extension of preferredExtensions) {
1091
- const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1092
- if (candidate) {
1093
- return candidate;
1094
- }
1095
- }
1096
- return normalized[0];
1097
- }
1098
- async function readProcessLines(stream, onLine) {
1099
- const reader = readline.createInterface({ input: stream });
1100
- try {
1101
- for await (const line of reader) {
1102
- await onLine(line);
1103
- }
1104
- }
1105
- finally {
1106
- reader.close();
1107
- }
1108
- }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The Windows environment a provider child (and every tool it runs, such as dotnet and pwsh)
3
+ * gets from the Bridge. Provider children start from an allowlist, not the Bridge's whole
4
+ * environment, so each variable Windows tools expect must be listed here or defaulted below.
5
+ */
6
+ export declare const windowsAllowedProviderParentEnvNames: readonly ["SystemRoot", "SystemDrive", "ComSpec", "PATHEXT", "APPDATA", "LOCALAPPDATA", "USERNAME", "USERDOMAIN", "HOMEDRIVE", "HOMEPATH", "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER", "NUMBER_OF_PROCESSORS", "ALLUSERSPROFILE", "PUBLIC", "CommonProgramFiles", "CommonProgramFiles(x86)", "CommonProgramW6432", "OS", "windir", "DOTNET_ROOT", "DOTNET_ROOT(x86)", "DOTNET_CLI_HOME", "NUGET_PACKAGES", "NUGET_HTTP_CACHE_PATH", "CLAUDE_CODE_GIT_BASH_PATH"];
7
+ /** Fills in the Windows system, machine, profile and .NET variables a provider child needs. */
8
+ export declare function normalizeWindowsProviderEnvironment(env: NodeJS.ProcessEnv, parentEnv: NodeJS.ProcessEnv, homeDir: string, arch: string): void;
9
+ /** A case-insensitive, non-blank environment lookup (Windows variable names ignore case). */
10
+ export declare function readEnvironmentValue(env: NodeJS.ProcessEnv, name: string): string | undefined;
@@ -0,0 +1,151 @@
1
+ import path from "node:path";
2
+ /**
3
+ * The Windows environment a provider child (and every tool it runs, such as dotnet and pwsh)
4
+ * gets from the Bridge. Provider children start from an allowlist, not the Bridge's whole
5
+ * environment, so each variable Windows tools expect must be listed here or defaulted below.
6
+ */
7
+ export const windowsAllowedProviderParentEnvNames = [
8
+ "SystemRoot",
9
+ "SystemDrive",
10
+ "ComSpec",
11
+ "PATHEXT",
12
+ "APPDATA",
13
+ "LOCALAPPDATA",
14
+ "USERNAME",
15
+ "USERDOMAIN",
16
+ "HOMEDRIVE",
17
+ "HOMEPATH",
18
+ "ProgramData",
19
+ "ProgramFiles",
20
+ "ProgramFiles(x86)",
21
+ "ProgramW6432",
22
+ // The .NET SDK reads these during startup (the MSI workload installer behind
23
+ // `dotnet --info` and `dotnet workload` throws on a missing PROCESSOR_ARCHITECTURE),
24
+ // and other Windows tools expect the standard machine variables too.
25
+ "PROCESSOR_ARCHITECTURE",
26
+ "PROCESSOR_IDENTIFIER",
27
+ "NUMBER_OF_PROCESSORS",
28
+ "ALLUSERSPROFILE",
29
+ "PUBLIC",
30
+ "CommonProgramFiles",
31
+ "CommonProgramFiles(x86)",
32
+ "CommonProgramW6432",
33
+ "OS",
34
+ "windir",
35
+ "DOTNET_ROOT",
36
+ "DOTNET_ROOT(x86)",
37
+ "DOTNET_CLI_HOME",
38
+ "NUGET_PACKAGES",
39
+ "NUGET_HTTP_CACHE_PATH",
40
+ "CLAUDE_CODE_GIT_BASH_PATH"
41
+ ];
42
+ /** Fills in the Windows system, machine, profile and .NET variables a provider child needs. */
43
+ export function normalizeWindowsProviderEnvironment(env, parentEnv, homeDir, arch) {
44
+ const systemRoot = normalizeWindowsSystemEnvironment(env, parentEnv);
45
+ normalizeWindowsProgramFolders(env, parentEnv);
46
+ normalizeWindowsMachineEnvironment(env, parentEnv, systemRoot, arch);
47
+ normalizeWindowsProfileEnvironment(env, parentEnv, homeDir);
48
+ setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
49
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
50
+ setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
51
+ setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
52
+ }
53
+ function normalizeWindowsSystemEnvironment(env, parentEnv) {
54
+ const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
55
+ const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
56
+ setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
57
+ setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
58
+ setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
59
+ setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
60
+ return systemRoot;
61
+ }
62
+ function normalizeWindowsProgramFolders(env, parentEnv) {
63
+ const systemDriveRoot = `${readEnvironmentValue(env, "SystemDrive") ?? "C:"}\\`;
64
+ const defaultProgramFiles = path.win32.join(systemDriveRoot, "Program Files");
65
+ const defaultProgramData = path.win32.join(systemDriveRoot, "ProgramData");
66
+ const programFiles = readEnvironmentValue(env, "ProgramFiles")
67
+ ?? readEnvironmentValue(parentEnv, "ProgramFiles")
68
+ ?? defaultProgramFiles;
69
+ setEnvironmentValueIfMissing(env, "ProgramFiles", programFiles);
70
+ setEnvironmentValueIfMissing(env, "ProgramW6432", readEnvironmentValue(parentEnv, "ProgramW6432") ?? defaultProgramFiles);
71
+ setEnvironmentValueIfMissing(env, "ProgramFiles(x86)", readEnvironmentValue(parentEnv, "ProgramFiles(x86)") ?? path.win32.join(systemDriveRoot, "Program Files (x86)"));
72
+ setEnvironmentValueIfMissing(env, "ProgramData", readEnvironmentValue(parentEnv, "ProgramData") ?? defaultProgramData);
73
+ setEnvironmentValueIfMissing(env, "ALLUSERSPROFILE", readEnvironmentValue(parentEnv, "ALLUSERSPROFILE") ?? readEnvironmentValue(env, "ProgramData") ?? defaultProgramData);
74
+ }
75
+ function normalizeWindowsMachineEnvironment(env, parentEnv, systemRoot, arch) {
76
+ setEnvironmentValueIfMissing(env, "windir", readEnvironmentValue(parentEnv, "windir") ?? systemRoot);
77
+ setEnvironmentValueIfMissing(env, "OS", readEnvironmentValue(parentEnv, "OS") ?? "Windows_NT");
78
+ const processorArchitecture = readEnvironmentValue(parentEnv, "PROCESSOR_ARCHITECTURE") ?? windowsProcessorArchitecture(arch);
79
+ if (processorArchitecture) {
80
+ setEnvironmentValueIfMissing(env, "PROCESSOR_ARCHITECTURE", processorArchitecture);
81
+ }
82
+ }
83
+ /** The PROCESSOR_ARCHITECTURE value Windows sets for a native process of this architecture. */
84
+ function windowsProcessorArchitecture(arch) {
85
+ switch (arch) {
86
+ case "x64": return "AMD64";
87
+ case "arm64": return "ARM64";
88
+ case "ia32": return "x86";
89
+ default: return undefined;
90
+ }
91
+ }
92
+ function normalizeWindowsProfileEnvironment(env, parentEnv, homeDir) {
93
+ const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
94
+ if (userProfile) {
95
+ setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
96
+ setEnvironmentValueIfMissing(env, "HOME", userProfile);
97
+ setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
98
+ setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
99
+ const parsed = path.win32.parse(userProfile);
100
+ if (parsed.root) {
101
+ setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
102
+ setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
103
+ }
104
+ }
105
+ const appData = readEnvironmentValue(env, "APPDATA")
106
+ ?? readEnvironmentValue(parentEnv, "APPDATA")
107
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
108
+ const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
109
+ ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
110
+ ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
111
+ if (appData) {
112
+ setEnvironmentValueIfMissing(env, "APPDATA", appData);
113
+ }
114
+ if (localAppData) {
115
+ setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
116
+ setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
117
+ }
118
+ }
119
+ function resolveWindowsUserProfile(env, parentEnv, homeDir) {
120
+ const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
121
+ if (existing) {
122
+ return existing;
123
+ }
124
+ const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
125
+ if (home && path.win32.isAbsolute(home)) {
126
+ return home;
127
+ }
128
+ const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
129
+ const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
130
+ if (homeDrive && homePath) {
131
+ return `${homeDrive}${homePath}`;
132
+ }
133
+ if (homeDir && path.win32.isAbsolute(homeDir)) {
134
+ return homeDir;
135
+ }
136
+ const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
137
+ const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
138
+ return username ? path.win32.join(systemDrive, "Users", username) : undefined;
139
+ }
140
+ /** A case-insensitive, non-blank environment lookup (Windows variable names ignore case). */
141
+ export function readEnvironmentValue(env, name) {
142
+ const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
143
+ const value = entry?.[1];
144
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
145
+ }
146
+ function setEnvironmentValueIfMissing(env, name, value) {
147
+ if (readEnvironmentValue(env, name)) {
148
+ return;
149
+ }
150
+ env[name] = value;
151
+ }
@@ -0,0 +1,30 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ /**
3
+ * How long Forge keeps waiting, once the provider's root process has exited, for its output
4
+ * pipes to reach end-of-file. Node reports a child's "close" only after every copy of its
5
+ * stdout and stderr write ends is closed, and a descendant that escaped the provider's
6
+ * supervision can hold an inherited copy for as long as it runs: on Windows, a process that a
7
+ * Microsoft Store app-execution alias (`...\WindowsApps\pwsh.exe`) created outside the provider's
8
+ * Job Object; elsewhere, one that left the provider's process group. Output the root wrote
9
+ * before it exited drains within this grace. After it, Forge closes its read ends, so the run
10
+ * settles on the root's exit instead of on that descendant's.
11
+ */
12
+ export declare const PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS = 5000;
13
+ export interface OutputPipeReleaseFields {
14
+ /** Present when Forge closed the provider's output pipes because they outlived its root process. */
15
+ readonly outputPipesReleasedAfterExit?: true;
16
+ }
17
+ /** Closes a child's output pipes a bounded grace after the child exits, unless they close first. */
18
+ export declare class OutputPipeRelease {
19
+ private readonly child;
20
+ private readonly graceMs;
21
+ private readonly onRelease;
22
+ private timer;
23
+ private released;
24
+ constructor(child: ChildProcess, graceMs: number, onRelease: (message: string) => void);
25
+ resultFields(): OutputPipeReleaseFields;
26
+ stop(): void;
27
+ private arm;
28
+ private release;
29
+ }
30
+ export declare function readProcessLines(stream: NodeJS.ReadableStream, onLine: (line: string) => Promise<void> | void): Promise<void>;