@loucompanion/forge-bridge 0.1.4-dev.e3697e9f5c98 → 0.1.4-dev.f22f5e3d01fe

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 (69) hide show
  1. package/README.md +13 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.service.d.ts +1 -1
  5. package/dist/bridge/bridge.service.js +4 -110
  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/host-facts.d.ts +2 -1
  9. package/dist/runtime/host-load-admission.d.ts +9 -2
  10. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  11. package/dist/runtime/host-load-child-environment.js +19 -10
  12. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  13. package/dist/runtime/host-load-governor-config.js +7 -0
  14. package/dist/runtime/host-load-governor.d.ts +10 -0
  15. package/dist/runtime/host-load-governor.js +125 -34
  16. package/dist/runtime/host-load-sampler.d.ts +26 -3
  17. package/dist/runtime/host-load-sampler.js +61 -2
  18. package/dist/runtime/host-load-step-class.d.ts +3 -1
  19. package/dist/runtime/host-load-step-class.js +60 -5
  20. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  21. package/dist/runtime/host-load-test-slot.js +81 -0
  22. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  23. package/dist/runtime/host-load-token-ledger.js +93 -61
  24. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  25. package/dist/runtime/host-load-windows-cpu.js +85 -0
  26. package/dist/runtime/host-runtime-lease.d.ts +1 -1
  27. package/dist/runtime/host-runtime-lease.js +1 -1
  28. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  29. package/dist/sandbox/host-capacity-broker.js +23 -4
  30. package/dist/session/architect-waits.d.ts +2 -0
  31. package/dist/session/architect-waits.js +138 -0
  32. package/dist/session/managed-attempt-tools.js +8 -9
  33. package/dist/session/managed-command-host-load.d.ts +2 -0
  34. package/dist/session/managed-command-host-load.js +2 -1
  35. package/dist/session/phase-completion.schemas.js +25 -23
  36. package/dist/session/phase-completion.validation.js +3 -1
  37. package/dist/session/pre-publication-pass.d.ts +2 -1
  38. package/dist/session/pre-publication-pass.js +8 -5
  39. package/dist/session/pre-publication-validation.d.ts +2 -0
  40. package/dist/session/pre-publication-validation.js +30 -4
  41. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  42. package/dist/session/provider-cli/claude-background-work.js +180 -0
  43. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  44. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  45. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  46. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  47. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  48. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  49. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  50. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  51. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  52. package/dist/session/provider-cli/provider-cli.service.js +2 -8
  53. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  54. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  55. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  56. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  57. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  58. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  59. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  60. package/dist/session/provider-cli/provider-output-state.js +6 -0
  61. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  62. package/dist/session/session.types.js +1 -1
  63. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  64. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  65. package/dist/shared/process/windows-launch.d.ts +18 -0
  66. package/dist/shared/process/windows-launch.js +68 -0
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +1 -1
  69. package/package.json +1 -1
@@ -0,0 +1,3 @@
1
+ import type { ProviderProcessRunResult } from "./provider-cli.process.js";
2
+ export declare function isCodexModelsCacheSchemaFailure(result: ProviderProcessRunResult): boolean;
3
+ export declare function quarantineIncompatibleCodexModelsCache(requestEnv?: Readonly<Record<string, string>>): Promise<boolean>;
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { readEnvironmentValue } from "./provider-cli.windows-environment.js";
6
+ const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
7
+ export function isCodexModelsCacheSchemaFailure(result) {
8
+ const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
9
+ return output.includes("base_instructions")
10
+ && output.includes("missing field")
11
+ && (output.includes("models_cache") || output.includes("models cache") || output.includes("model cache"));
12
+ }
13
+ export async function quarantineIncompatibleCodexModelsCache(requestEnv) {
14
+ const configuredHome = readEnvironmentValue(requestEnv ?? {}, "CODEX_HOME")
15
+ ?? readEnvironmentValue(process.env, "CODEX_HOME")
16
+ ?? readEnvironmentValue(process.env, "FORGE_CODEX_HOME");
17
+ const codexHome = path.resolve(configuredHome ?? path.join(os.homedir(), ".codex"));
18
+ if (!path.isAbsolute(codexHome) || codexHome === path.parse(codexHome).root)
19
+ return false;
20
+ const cachePath = path.join(codexHome, "models_cache.json");
21
+ const cacheStat = await fs.promises.lstat(cachePath).catch(error => {
22
+ if (error.code === "ENOENT")
23
+ return null;
24
+ throw error;
25
+ });
26
+ if (!cacheStat
27
+ || !cacheStat.isFile()
28
+ || cacheStat.isSymbolicLink()
29
+ || cacheStat.nlink !== 1
30
+ || cacheStat.size <= 0
31
+ || cacheStat.size > maximumRecoverableCodexModelsCacheBytes) {
32
+ return false;
33
+ }
34
+ const quarantinePath = path.join(codexHome, `models_cache.forge-incompatible-${Date.now()}-${randomUUID()}.json`);
35
+ await fs.promises.rename(cachePath, quarantinePath);
36
+ return true;
37
+ }
@@ -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 {
@@ -22,8 +24,8 @@ export interface ProviderProcessRunRequest {
22
24
  */
23
25
  readonly resumesProviderThread?: boolean;
24
26
  }
25
- /** Why Forge stopped a provider that was still resident after a successful turn. */
26
- export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
27
+ /** Why Forge stopped a provider still resident after its turn (or its background work, for Claude). */
28
+ export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling" | "turn_ended_with_background_work";
27
29
  export interface ProviderProcessRunResult {
28
30
  readonly exitCode: number;
29
31
  readonly stdout: string;
@@ -34,8 +36,10 @@ export interface ProviderProcessRunResult {
34
36
  readonly memoryObservedAt?: string;
35
37
  /** Present when the caller's cancellation stopped the process before it exited on its own. */
36
38
  readonly cancelled?: true;
37
- /** Present when Forge stopped a provider that stayed resident after a successful turn. */
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>;
@@ -59,7 +63,8 @@ export interface ProviderProcessHandlers {
59
63
  onGenerationStart?(): void;
60
64
  }
61
65
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
62
- * relaunch needs a new fenced child generation and exclusive launch files. */
66
+ * relaunch needs a new fenced child generation and exclusive launch files. The outer
67
+ * layer fails any run Forge stopped because its turn ended with background work live. */
63
68
  export declare function recoveringProviderProcessRunner(inner: ProviderProcessRunner): ProviderProcessRunner;
64
69
  /**
65
70
  * Codex Desktop and an independently installed Codex CLI can briefly disagree
@@ -88,23 +93,18 @@ export declare class CodexResumeRecoveringProcessRunner implements ProviderProce
88
93
  * arbitrary tool/command output and therefore cannot mint retry authority.
89
94
  */
90
95
  export declare function isTransientCodexProviderNotFoundFailure(command: string, result: ProviderProcessRunResult): boolean;
91
- interface ProviderChildEnvironmentOptions {
92
- readonly parentEnv?: NodeJS.ProcessEnv;
93
- readonly platform?: NodeJS.Platform;
94
- readonly homeDir?: string;
95
- }
96
- export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
97
96
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
98
97
  private readonly terminalExitGraceMs;
99
98
  private readonly terminalSuccessCeilingMs;
100
99
  private readonly terminalWorkPollMs;
101
- constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
100
+ private readonly outputPipeReleaseGraceMs;
101
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number, outputPipeReleaseGraceMs?: number);
102
102
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
103
103
  }
104
104
  /**
105
105
  * The typed failure for a provider run that ended without calling its required Forge
106
- * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
107
- * is not mistaken for an agent that simply ended its turn.
106
+ * completion tool. A run Forge stopped at the success ceiling or for background work is
107
+ * reported as such, so it is not mistaken for an agent that simply ended its turn.
108
108
  */
109
109
  export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
110
110
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
@@ -124,12 +124,3 @@ export declare function resolveClaudeNpmDirectLaunch(commandPath: string, args:
124
124
  * wrapped by the Windows Job Object supervisor.
125
125
  */
126
126
  export declare function resolvePackageManagerDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
127
- /**
128
- * Resolves Windows commands without spawning where.exe. Runtime launches can
129
- * happen while the machine is under enough process pressure for where.exe to
130
- * miss its timeout; returning the unresolved package-manager name in that case
131
- * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
132
- */
133
- export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string): string | null;
134
- export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
135
- export {};
@@ -1,16 +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
- import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
12
+ import { BackgroundWorkStopFailingRunner, ClaudeBackgroundTurnEndWatch, providerTurnEndedWithBackgroundWorkFailure } from "./claude-background-work.js";
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";
14
17
  const execFileAsync = promisify(execFile);
15
18
  // Provider processes can emit many gigabytes over a long-running session. The
16
19
  // line handlers stream that output to Forge as it arrives; the completed result
@@ -23,11 +26,11 @@ const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
23
26
  const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
24
27
  // How often the end-of-turn timers re-check whether supervised work is still in flight.
25
28
  const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
26
- const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
27
29
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
28
- * relaunch needs a new fenced child generation and exclusive launch files. */
30
+ * relaunch needs a new fenced child generation and exclusive launch files. The outer
31
+ * layer fails any run Forge stopped because its turn ended with background work live. */
29
32
  export function recoveringProviderProcessRunner(inner) {
30
- return new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner));
33
+ return new BackgroundWorkStopFailingRunner(new CodexResumeRecoveringProcessRunner(new CodexModelsCacheRecoveringProcessRunner(inner)));
31
34
  }
32
35
  /**
33
36
  * Codex Desktop and an independently installed Codex CLI can briefly disagree
@@ -121,216 +124,16 @@ function codexFreshTurnRequest(request) {
121
124
  function isCodexCommand(command) {
122
125
  return path.parse(command).name.toLowerCase() === "codex";
123
126
  }
124
- function isCodexModelsCacheSchemaFailure(result) {
125
- const output = `${result.stderr}\n${result.stdout}`.toLowerCase();
126
- return output.includes("base_instructions")
127
- && output.includes("missing field")
128
- && (output.includes("models_cache") || output.includes("models cache") || output.includes("model cache"));
129
- }
130
- async function quarantineIncompatibleCodexModelsCache(requestEnv) {
131
- const configuredHome = readEnvironmentValue(requestEnv ?? {}, "CODEX_HOME")
132
- ?? readEnvironmentValue(process.env, "CODEX_HOME")
133
- ?? readEnvironmentValue(process.env, "FORGE_CODEX_HOME");
134
- const codexHome = path.resolve(configuredHome ?? path.join(os.homedir(), ".codex"));
135
- if (!path.isAbsolute(codexHome) || codexHome === path.parse(codexHome).root)
136
- return false;
137
- const cachePath = path.join(codexHome, "models_cache.json");
138
- const cacheStat = await fs.promises.lstat(cachePath).catch(error => {
139
- if (error.code === "ENOENT")
140
- return null;
141
- throw error;
142
- });
143
- if (!cacheStat
144
- || !cacheStat.isFile()
145
- || cacheStat.isSymbolicLink()
146
- || cacheStat.nlink !== 1
147
- || cacheStat.size <= 0
148
- || cacheStat.size > maximumRecoverableCodexModelsCacheBytes) {
149
- return false;
150
- }
151
- const quarantinePath = path.join(codexHome, `models_cache.forge-incompatible-${Date.now()}-${randomUUID()}.json`);
152
- await fs.promises.rename(cachePath, quarantinePath);
153
- return true;
154
- }
155
- const allowedProviderParentEnvNames = [
156
- "PATH",
157
- "HOME",
158
- "USERPROFILE",
159
- "TMPDIR",
160
- "TEMP",
161
- "TMP",
162
- "LANG",
163
- "CLAUDE_CONFIG_DIR"
164
- ];
165
- const windowsAllowedProviderParentEnvNames = [
166
- "SystemRoot",
167
- "SystemDrive",
168
- "ComSpec",
169
- "PATHEXT",
170
- "APPDATA",
171
- "LOCALAPPDATA",
172
- "USERNAME",
173
- "USERDOMAIN",
174
- "HOMEDRIVE",
175
- "HOMEPATH",
176
- "ProgramData",
177
- "ProgramFiles",
178
- "ProgramFiles(x86)",
179
- "ProgramW6432",
180
- "DOTNET_ROOT",
181
- "DOTNET_ROOT(x86)",
182
- "DOTNET_CLI_HOME",
183
- "NUGET_PACKAGES",
184
- "NUGET_HTTP_CACHE_PATH",
185
- "CLAUDE_CODE_GIT_BASH_PATH"
186
- ];
187
- export function buildProviderChildEnvironment(requestEnv, options = {}) {
188
- const parentEnv = options.parentEnv ?? process.env;
189
- const platform = options.platform ?? process.platform;
190
- const env = {};
191
- for (const [key, value] of Object.entries(parentEnv)) {
192
- if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
193
- env[key] = value;
194
- }
195
- }
196
- if (requestEnv) {
197
- for (const [key, value] of Object.entries(requestEnv)) {
198
- const trimmedKey = key.trim();
199
- if (trimmedKey.length > 0) {
200
- env[trimmedKey] = value;
201
- }
202
- }
203
- }
204
- if (platform === "win32") {
205
- normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
206
- }
207
- normalizeProviderBuildEnvironment(env);
208
- return env;
209
- }
210
- function normalizeProviderBuildEnvironment(env) {
211
- // Provider sessions are long lived and commonly run many dotnet builds. Persistent
212
- // MSBuild and Roslyn compiler servers otherwise survive individual commands and can
213
- // retain more memory than the active Forge lane. Keep those caches process-scoped by
214
- // default on every runner OS; an explicitly supplied request value still wins.
215
- setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
216
- setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
217
- setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
218
- }
219
- function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
220
- // The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
221
- // property names are case-insensitive on every OS. Collapse request aliases to
222
- // one canonical key so the explicit value wins without producing ambiguity.
223
- const exact = env[name];
224
- const alias = Object.entries(env).find(([key, candidate]) => key !== name
225
- && key.toLowerCase() === name.toLowerCase()
226
- && typeof candidate === "string"
227
- && candidate.trim().length > 0)?.[1];
228
- const resolved = typeof exact === "string" && exact.trim().length > 0
229
- ? exact
230
- : alias ?? value;
231
- for (const key of Object.keys(env)) {
232
- if (key !== name && key.toLowerCase() === name.toLowerCase()) {
233
- delete env[key];
234
- }
235
- }
236
- env[name] = resolved;
237
- }
238
- function isAllowedProviderParentEnv(key, platform = process.platform) {
239
- return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
240
- || key.toUpperCase().startsWith("LC_")
241
- || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
242
- }
243
- function isAllowedProviderParentEnvName(key, allowedNames) {
244
- return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
245
- }
246
- function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
247
- const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
248
- const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
249
- setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
250
- setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
251
- setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
252
- setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
253
- const resolvedSystemDrive = readEnvironmentValue(env, "SystemDrive") ?? systemDrive;
254
- const defaultProgramFiles = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files");
255
- const defaultProgramFilesX86 = path.win32.join(`${resolvedSystemDrive}\\`, "Program Files (x86)");
256
- const defaultProgramData = path.win32.join(`${resolvedSystemDrive}\\`, "ProgramData");
257
- const programFiles = readEnvironmentValue(env, "ProgramFiles")
258
- ?? readEnvironmentValue(parentEnv, "ProgramFiles")
259
- ?? defaultProgramFiles;
260
- setEnvironmentValueIfMissing(env, "ProgramFiles", programFiles);
261
- setEnvironmentValueIfMissing(env, "ProgramW6432", readEnvironmentValue(parentEnv, "ProgramW6432") ?? defaultProgramFiles);
262
- setEnvironmentValueIfMissing(env, "ProgramFiles(x86)", readEnvironmentValue(parentEnv, "ProgramFiles(x86)") ?? defaultProgramFilesX86);
263
- setEnvironmentValueIfMissing(env, "ProgramData", readEnvironmentValue(parentEnv, "ProgramData") ?? defaultProgramData);
264
- const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
265
- if (userProfile) {
266
- setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
267
- setEnvironmentValueIfMissing(env, "HOME", userProfile);
268
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
269
- setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
270
- const parsed = path.win32.parse(userProfile);
271
- if (parsed.root) {
272
- setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
273
- setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
274
- }
275
- }
276
- const appData = readEnvironmentValue(env, "APPDATA")
277
- ?? readEnvironmentValue(parentEnv, "APPDATA")
278
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
279
- const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
280
- ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
281
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
282
- if (appData) {
283
- setEnvironmentValueIfMissing(env, "APPDATA", appData);
284
- }
285
- if (localAppData) {
286
- setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
287
- setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
288
- }
289
- setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
290
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
291
- setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
292
- setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
293
- }
294
- function resolveWindowsUserProfile(env, parentEnv, homeDir) {
295
- const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
296
- if (existing) {
297
- return existing;
298
- }
299
- const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
300
- if (home && path.win32.isAbsolute(home)) {
301
- return home;
302
- }
303
- const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
304
- const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
305
- if (homeDrive && homePath) {
306
- return `${homeDrive}${homePath}`;
307
- }
308
- if (homeDir && path.win32.isAbsolute(homeDir)) {
309
- return homeDir;
310
- }
311
- const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
312
- const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
313
- return username ? path.win32.join(systemDrive, "Users", username) : undefined;
314
- }
315
- function readEnvironmentValue(env, name) {
316
- const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
317
- const value = entry?.[1];
318
- return typeof value === "string" && value.trim().length > 0 ? value : undefined;
319
- }
320
- function setEnvironmentValueIfMissing(env, name, value) {
321
- if (readEnvironmentValue(env, name)) {
322
- return;
323
- }
324
- env[name] = value;
325
- }
326
127
  export class StreamingProviderProcessRunner {
327
128
  terminalExitGraceMs;
328
129
  terminalSuccessCeilingMs;
329
130
  terminalWorkPollMs;
330
- 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) {
331
133
  this.terminalExitGraceMs = terminalExitGraceMs;
332
134
  this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
333
135
  this.terminalWorkPollMs = terminalWorkPollMs;
136
+ this.outputPipeReleaseGraceMs = outputPipeReleaseGraceMs;
334
137
  }
335
138
  async run(request, handlers = {}, signal) {
336
139
  assertHostDatabaseCapabilityBoundary();
@@ -384,6 +187,7 @@ export class StreamingProviderProcessRunner {
384
187
  }
385
188
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
386
189
  const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
190
+ const outputPipes = new OutputPipeRelease(child, this.outputPipeReleaseGraceMs, message => stderr.appendLine(message));
387
191
  let settled = false;
388
192
  let closed = false;
389
193
  let cancellationRequested = false;
@@ -401,8 +205,10 @@ export class StreamingProviderProcessRunner {
401
205
  let terminalWorkTickRunning = false;
402
206
  let latestTurnFailed = false;
403
207
  let readiness = null;
208
+ const backgroundTurnEnd = new ClaudeBackgroundTurnEndWatch(request.command, this.terminalExitGraceMs, () => finishAfterTerminalSuccess("turn_ended_with_background_work"));
404
209
  const cleanup = () => {
405
210
  stopTerminalWorkTimer();
211
+ backgroundTurnEnd.stop();
406
212
  graceIdleMs = null;
407
213
  ceilingIdleMs = null;
408
214
  signal?.removeEventListener("abort", abort);
@@ -426,12 +232,10 @@ export class StreamingProviderProcessRunner {
426
232
  // termination; only a failed termination proof rejects the run.
427
233
  void terminate().catch(fail);
428
234
  };
429
- if (signal?.aborted) {
235
+ if (signal?.aborted)
430
236
  abort();
431
- }
432
- else {
237
+ else
433
238
  signal?.addEventListener("abort", abort, { once: true });
434
- }
435
239
  child.on("error", fail);
436
240
  const startGrant = startGated ? child.stdio[3] : null;
437
241
  if (startGated && !startGrant) {
@@ -514,16 +318,6 @@ export class StreamingProviderProcessRunner {
514
318
  stopTerminalWorkTimer();
515
319
  void terminate().catch(fail);
516
320
  };
517
- const workInFlight = async () => {
518
- try {
519
- if (handlers.isToolCallInFlight?.())
520
- return true;
521
- }
522
- catch {
523
- // A failing probe must not keep the provider open or stop it early on its own.
524
- }
525
- return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
526
- };
527
321
  // The grace and the ceiling only count time in which no supervised work is in flight:
528
322
  // a provider waiting on an MCP tool call or on a managed command it started is not
529
323
  // finished, even when its turn has ended. The grace restarts once that work is done.
@@ -532,7 +326,7 @@ export class StreamingProviderProcessRunner {
532
326
  return;
533
327
  terminalWorkTickRunning = true;
534
328
  try {
535
- const inFlight = await workInFlight();
329
+ const inFlight = await providerWorkInFlight(handlers, request.env?.FORGE_LOG_DIR);
536
330
  const now = performance.now();
537
331
  const elapsed = Math.max(0, now - terminalWorkTickAt);
538
332
  terminalWorkTickAt = now;
@@ -586,6 +380,7 @@ export class StreamingProviderProcessRunner {
586
380
  if (request.captureOutput !== false)
587
381
  stdout.appendLine(line);
588
382
  const handled = handlers.onStdoutLine?.(line);
383
+ backgroundTurnEnd.consume(line);
589
384
  if (!terminalTerminationStarted) {
590
385
  if (isProviderTerminalSuccess(line)) {
591
386
  latestTurnFailed = false;
@@ -666,68 +461,36 @@ export class StreamingProviderProcessRunner {
666
461
  ...(memory ?? {}),
667
462
  ...(cancelledBeforeClose ? { cancelled: true } : {}),
668
463
  ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
464
+ ...outputPipes.resultFields(),
669
465
  });
670
466
  }).catch(fail);
671
467
  });
672
468
  });
673
469
  }
674
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
+ }
675
481
  /**
676
482
  * The typed failure for a provider run that ended without calling its required Forge
677
- * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
678
- * is not mistaken for an agent that simply ended its turn.
483
+ * completion tool. A run Forge stopped at the success ceiling or for background work is
484
+ * reported as such, so it is not mistaken for an agent that simply ended its turn.
679
485
  */
680
486
  export function providerCompletionToolMissingFailure(message, result) {
487
+ if (result?.terminalStopReason === "turn_ended_with_background_work")
488
+ return providerTurnEndedWithBackgroundWorkFailure(message);
681
489
  if (result?.terminalStopReason === "success_ceiling") {
682
490
  return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
683
491
  }
684
492
  return new ForgeFailureError("provider_completion_tool_missing", message);
685
493
  }
686
- /** A stream event that shows the provider is working on a turn: model output or a tool result. */
687
- function isProviderTurnActivity(line) {
688
- const trimmed = line.trim();
689
- if (!trimmed.startsWith("{"))
690
- return false;
691
- try {
692
- const event = JSON.parse(trimmed);
693
- return event.type === "assistant"
694
- || event.type === "user"
695
- || (event.type === "system" && event.subtype === "init")
696
- || event.type === "turn.started"
697
- || event.type === "item.started";
698
- }
699
- catch {
700
- return false;
701
- }
702
- }
703
- function isProviderTerminalFailure(line) {
704
- const trimmed = line.trim();
705
- if (!trimmed.startsWith("{"))
706
- return false;
707
- try {
708
- const event = JSON.parse(trimmed);
709
- // The same events the output parsers report as provider errors.
710
- return event.type === "turn.failed"
711
- || event.type === "error"
712
- || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
713
- }
714
- catch {
715
- return false;
716
- }
717
- }
718
- function isProviderTerminalSuccess(line) {
719
- const trimmed = line.trim();
720
- if (!trimmed.startsWith("{"))
721
- return false;
722
- try {
723
- const event = JSON.parse(trimmed);
724
- return event.type === "turn.completed"
725
- || (event.type === "result" && event.subtype === "success" && event.is_error !== true);
726
- }
727
- catch {
728
- return false;
729
- }
730
- }
731
494
  class HostProcessTreeMemoryObserver {
732
495
  launch;
733
496
  processGroupId;
@@ -1082,67 +845,3 @@ async function resolveWindowsCommand(command) {
1082
845
  return null;
1083
846
  }
1084
847
  }
1085
- /**
1086
- * Resolves Windows commands without spawning where.exe. Runtime launches can
1087
- * happen while the machine is under enough process pressure for where.exe to
1088
- * miss its timeout; returning the unresolved package-manager name in that case
1089
- * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
1090
- */
1091
- export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
1092
- if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
1093
- return null;
1094
- }
1095
- const hasExtension = path.extname(command).length > 0;
1096
- const extensions = hasExtension
1097
- ? [""]
1098
- : [...new Set([
1099
- "",
1100
- ".exe",
1101
- ".ps1",
1102
- ".cmd",
1103
- ".bat",
1104
- ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
1105
- ])];
1106
- for (const rawDirectory of pathValue.split(path.delimiter)) {
1107
- const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
1108
- if (!directory)
1109
- continue;
1110
- const candidates = [];
1111
- for (const extension of extensions) {
1112
- const candidate = path.join(directory, `${command}${extension}`);
1113
- if (fs.existsSync(candidate))
1114
- candidates.push(candidate);
1115
- }
1116
- const resolved = chooseWindowsCommandCandidate(candidates);
1117
- if (resolved)
1118
- return resolved;
1119
- }
1120
- return null;
1121
- }
1122
- export function chooseWindowsCommandCandidate(candidates) {
1123
- const normalized = candidates
1124
- .map((candidate) => candidate.trim())
1125
- .filter((candidate) => candidate.length > 0);
1126
- if (normalized.length === 0) {
1127
- return null;
1128
- }
1129
- const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1130
- for (const extension of preferredExtensions) {
1131
- const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1132
- if (candidate) {
1133
- return candidate;
1134
- }
1135
- }
1136
- return normalized[0];
1137
- }
1138
- async function readProcessLines(stream, onLine) {
1139
- const reader = readline.createInterface({ input: stream });
1140
- try {
1141
- for await (const line of reader) {
1142
- await onLine(line);
1143
- }
1144
- }
1145
- finally {
1146
- reader.close();
1147
- }
1148
- }
@@ -34,6 +34,8 @@ export declare function codexSandboxModeForPlatform(platform?: NodeJS.Platform,
34
34
  export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): string;
35
35
  export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
36
36
  export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
37
+ export declare function designerRefBuildInstruction(dispatch: RunOnceDispatchPacket): string;
38
+ export declare function designerRefQaInstruction(dispatch: RunOnceDispatchPacket): string;
37
39
  export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
38
40
  /**
39
41
  * Headless providers must not end a turn to wait: Forge stops the provider shortly after