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

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 (112) hide show
  1. package/README.md +14 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  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/bridge.service.d.ts +1 -1
  7. package/dist/bridge/bridge.service.js +4 -110
  8. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  9. package/dist/bridge/runner-host-capabilities.js +13 -0
  10. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  11. package/dist/runtime/aspnet-runtime-prebuild.js +44 -0
  12. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  13. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  14. package/dist/runtime/docker-engine-probe.js +7 -0
  15. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  16. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  17. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  18. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  19. package/dist/runtime/host-facts.d.ts +2 -1
  20. package/dist/runtime/host-load-admission.d.ts +9 -2
  21. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  22. package/dist/runtime/host-load-child-environment.js +19 -10
  23. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  24. package/dist/runtime/host-load-governor-config.js +7 -0
  25. package/dist/runtime/host-load-governor.d.ts +10 -0
  26. package/dist/runtime/host-load-governor.js +125 -34
  27. package/dist/runtime/host-load-sampler.d.ts +34 -4
  28. package/dist/runtime/host-load-sampler.js +73 -7
  29. package/dist/runtime/host-load-step-class.d.ts +3 -1
  30. package/dist/runtime/host-load-step-class.js +60 -5
  31. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  32. package/dist/runtime/host-load-test-slot.js +81 -0
  33. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  34. package/dist/runtime/host-load-token-ledger.js +93 -61
  35. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  36. package/dist/runtime/host-load-windows-cpu.js +85 -0
  37. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  38. package/dist/runtime/host-runtime-contract.js +29 -1
  39. package/dist/runtime/host-runtime-lease.d.ts +1 -1
  40. package/dist/runtime/host-runtime-lease.js +11 -51
  41. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  42. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  43. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  44. package/dist/sandbox/host-capacity-broker.js +23 -4
  45. package/dist/session/architect-waits.d.ts +2 -0
  46. package/dist/session/architect-waits.js +138 -0
  47. package/dist/session/managed-attempt-tools.d.ts +0 -7
  48. package/dist/session/managed-attempt-tools.js +51 -62
  49. package/dist/session/managed-command-host-load.d.ts +2 -0
  50. package/dist/session/managed-command-host-load.js +2 -1
  51. package/dist/session/phase-completion.artifacts.js +2 -1
  52. package/dist/session/phase-completion.d.ts +8 -0
  53. package/dist/session/phase-completion.js +1 -0
  54. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  55. package/dist/session/phase-completion.mcp-args.js +156 -0
  56. package/dist/session/phase-completion.runtime.d.ts +0 -8
  57. package/dist/session/phase-completion.runtime.js +43 -197
  58. package/dist/session/phase-completion.schemas.js +25 -23
  59. package/dist/session/phase-completion.validation.js +3 -1
  60. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  61. package/dist/session/pre-publication-native-postgres.js +111 -0
  62. package/dist/session/pre-publication-pass.d.ts +2 -1
  63. package/dist/session/pre-publication-pass.js +8 -5
  64. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  65. package/dist/session/pre-publication-step-execution.js +6 -5
  66. package/dist/session/pre-publication-validation.d.ts +9 -3
  67. package/dist/session/pre-publication-validation.js +62 -34
  68. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  69. package/dist/session/provider-cli/claude-background-work.js +181 -0
  70. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  71. package/dist/session/provider-cli/host-build-lock.js +30 -0
  72. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  73. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  74. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  75. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  76. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  77. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  78. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  79. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  80. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  81. package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
  82. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  83. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  84. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  85. package/dist/session/provider-cli/provider-cli.service.js +29 -51
  86. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  87. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  88. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  89. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  90. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  91. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  92. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  93. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  94. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  95. package/dist/session/provider-cli/provider-output-state.js +6 -0
  96. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  97. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  98. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  99. package/dist/session/qa-sidecar-validation.js +28 -0
  100. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  101. package/dist/session/session-redaction.js +31 -181
  102. package/dist/session/session.types.js +2 -2
  103. package/dist/session/sidecar-json-shape.d.ts +31 -0
  104. package/dist/session/sidecar-json-shape.js +217 -0
  105. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  106. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  107. package/dist/shared/process/windows-launch.d.ts +18 -0
  108. package/dist/shared/process/windows-launch.js +68 -0
  109. package/dist/shared/provider-capabilities.js +9 -1
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.js +1 -1
  112. package/package.json +1 -1
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Headless Claude Code runs must not start work that outlives the turn.
3
+ *
4
+ * Forge runs `claude -p` and treats the turn's terminal `result` event as the end of the run.
5
+ * When background work is still live at the end of a turn (a background subagent or shell, a
6
+ * Monitor watch, a scheduled wakeup), Claude Code withholds that `result` and keeps the process
7
+ * open for the work, so Forge sees a silent provider instead of a finished one. The launch
8
+ * restrictions below remove the ways to start such work; `ClaudeBackgroundTurnEndWatch` is the
9
+ * backstop for anything that still gets through.
10
+ */
11
+ import path from "node:path";
12
+ import { ForgeFailureError } from "../session.types.js";
13
+ /**
14
+ * Removes the `run_in_background` parameter from Bash, PowerShell and the Agent tool, runs
15
+ * forked subagents and forked skills in the foreground, and stops Claude Code from moving long
16
+ * shell commands, subagents and MCP calls to the background on its own. Cron disables the
17
+ * session-scoped scheduled tasks (`CronCreate`, `/loop`). Applied last, so a project's runtime
18
+ * environment cannot turn them back on.
19
+ */
20
+ export const claudeHeadlessEnvironment = Object.freeze({
21
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
22
+ CLAUDE_CODE_DISABLE_CRON: "1",
23
+ });
24
+ /**
25
+ * Tools whose only purpose is work that reports after the turn. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`
26
+ * leaves Monitor running in the background, so it is removed here, together with self-paced
27
+ * wakeups, workflows (which run their agents in the background), cloud routines, cron
28
+ * (also disabled by environment), SendMessage, which resumes an earlier subagent in the
29
+ * background, and agent teams, whose teammates run alongside the turn. Foreground subagents
30
+ * stay available: they block the turn until they finish.
31
+ */
32
+ export const claudeHeadlessDisallowedTools = Object.freeze([
33
+ "Monitor",
34
+ "ScheduleWakeup",
35
+ "Workflow",
36
+ "RemoteTrigger",
37
+ "CronCreate",
38
+ "SendMessage",
39
+ "TeamCreate",
40
+ ]);
41
+ /**
42
+ * The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
43
+ * again as flag settings, which outrank a user's or repository's settings `env` block. Other flag
44
+ * settings (`provider-user-config-isolation.ts`) share the one `--settings` value.
45
+ */
46
+ export function claudeHeadlessToolArgs(additionalSettings = {}) {
47
+ return [
48
+ "--disallowedTools", claudeHeadlessDisallowedTools.join(","),
49
+ "--settings", JSON.stringify({ ...additionalSettings, env: claudeHeadlessEnvironment }),
50
+ ];
51
+ }
52
+ /**
53
+ * The provider ended its turn while background work it started (a background subagent or
54
+ * shell, a Monitor watch, a wakeup) was still live. Claude Code withholds the turn's terminal
55
+ * result for such work, and nothing started in the background reports to Forge, so Forge stops
56
+ * the provider at once instead of waiting for an idle watchdog. Retryable: the harness, not the
57
+ * task, ended the run.
58
+ */
59
+ export function providerTurnEndedWithBackgroundWorkFailure(message) {
60
+ return new ForgeFailureError("provider_turn_ended_with_background_work", `${message} The provider ended its turn while background work it started was still running, so it never delivered a terminal result; Forge stopped it instead of waiting.`);
61
+ }
62
+ /**
63
+ * Fails every provider run Forge stopped because its turn ended with background work still live,
64
+ * whether or not the turn recorded a completion first: the stop cut that work short, so nothing
65
+ * may validate, commit or publish the worktree it left behind.
66
+ */
67
+ export class BackgroundWorkStopFailingRunner {
68
+ inner;
69
+ constructor(inner) {
70
+ this.inner = inner;
71
+ }
72
+ async run(request, handlers, signal) {
73
+ const result = await this.inner.run(request, handlers, signal);
74
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
75
+ throw providerTurnEndedWithBackgroundWorkFailure("The provider turn did not finish.");
76
+ }
77
+ return result;
78
+ }
79
+ }
80
+ /**
81
+ * Recognizes a main-conversation turn that ended while background tasks it started were still
82
+ * live, the case in which Claude Code withholds the turn's `result`. The turn end is Claude
83
+ * Code's `post_turn_summary` event; the live set is the documented `background_tasks_changed`
84
+ * event (Claude Code's own `ambient` tasks and `awaited` ones do not count). After `graceMs`
85
+ * without the result or new main-conversation activity, it calls `onTurnEndedWithBackgroundWork`
86
+ * once, so the runner can stop the provider instead of waiting on work no one will collect.
87
+ */
88
+ export class ClaudeBackgroundTurnEndWatch {
89
+ graceMs;
90
+ onTurnEndedWithBackgroundWork;
91
+ liveBackgroundTasks = 0;
92
+ terminalSinceMainActivity = false;
93
+ mainTurnEnded = false;
94
+ timer = null;
95
+ stopped = false;
96
+ enabled;
97
+ /** Watches only Claude Code, by its executable `command`; other output is left alone. */
98
+ constructor(command, graceMs, onTurnEndedWithBackgroundWork) {
99
+ this.graceMs = graceMs;
100
+ this.onTurnEndedWithBackgroundWork = onTurnEndedWithBackgroundWork;
101
+ this.enabled = path.parse(command).name.toLowerCase() === "claude";
102
+ }
103
+ consume(line) {
104
+ if (!this.enabled || this.stopped)
105
+ return;
106
+ const event = parseStreamEvent(line);
107
+ if (!event)
108
+ return;
109
+ if (isTerminalEvent(event)) {
110
+ this.terminalSinceMainActivity = true;
111
+ this.cancel();
112
+ }
113
+ else if (event.type === "system" && event.subtype === "background_tasks_changed") {
114
+ this.liveBackgroundTasks = liveBackgroundTaskCount(event.tasks);
115
+ // The work settled: Claude Code now delivers the result or starts a turn for it, and a
116
+ // follow-up turn can think for a while before its first event.
117
+ if (this.liveBackgroundTasks === 0)
118
+ this.cancel();
119
+ // A task can be reported just after the turn summary, as the turn ends.
120
+ else if (this.mainTurnEnded)
121
+ this.armIfTurnEndedWithBackgroundWork();
122
+ }
123
+ else if (event.type === "system" && event.subtype === "post_turn_summary") {
124
+ this.mainTurnEnded = true;
125
+ this.armIfTurnEndedWithBackgroundWork();
126
+ }
127
+ else if ((event.type === "assistant" || event.type === "user") && !event.parent_tool_use_id) {
128
+ // The main conversation is working again (a new turn, or a turn that is still going).
129
+ this.terminalSinceMainActivity = false;
130
+ this.mainTurnEnded = false;
131
+ this.cancel();
132
+ }
133
+ }
134
+ stop() {
135
+ this.stopped = true;
136
+ this.cancel();
137
+ }
138
+ armIfTurnEndedWithBackgroundWork() {
139
+ if (this.timer || this.terminalSinceMainActivity || this.liveBackgroundTasks === 0)
140
+ return;
141
+ this.timer = setTimeout(() => {
142
+ this.timer = null;
143
+ this.stopped = true;
144
+ this.onTurnEndedWithBackgroundWork();
145
+ }, this.graceMs);
146
+ this.timer.unref?.();
147
+ }
148
+ cancel() {
149
+ if (!this.timer)
150
+ return;
151
+ clearTimeout(this.timer);
152
+ this.timer = null;
153
+ }
154
+ }
155
+ function parseStreamEvent(line) {
156
+ const trimmed = line.trim();
157
+ if (!trimmed.startsWith("{"))
158
+ return null;
159
+ try {
160
+ const parsed = JSON.parse(trimmed);
161
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
162
+ }
163
+ catch {
164
+ return null;
165
+ }
166
+ }
167
+ function isTerminalEvent(event) {
168
+ return event.type === "result" || event.type === "error";
169
+ }
170
+ /**
171
+ * Tasks that keep the turn's result back: not Claude Code's own `ambient` tasks, and not
172
+ * `awaited` ones, which a still-running tool call of the turn waits for.
173
+ */
174
+ function liveBackgroundTaskCount(tasks) {
175
+ if (!Array.isArray(tasks))
176
+ return 0;
177
+ return tasks.filter(task => {
178
+ const entry = task && typeof task === "object" ? task : {};
179
+ return entry.ambient !== true && entry.awaited !== true;
180
+ }).length;
181
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * A runner host can allow only one local .NET build or test at a time across everything that runs
3
+ * on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
4
+ * memory and break each other's shared test output. The host's owner names the lock wrapper in the
5
+ * bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
6
+ * tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
7
+ * user-level instruction file (provider-user-config-isolation.ts).
8
+ */
9
+ export declare const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
10
+ /** The host's .NET build lock wrapper, when the bridge's environment names one. */
11
+ export declare function hostDotnetBuildLock(environment?: NodeJS.ProcessEnv): string | null;
12
+ export declare function hostDotnetBuildLockEnvironment(environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
13
+ /**
14
+ * The runtime-context instruction for a host that names a .NET build lock, or an empty string.
15
+ * Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
16
+ * Chat turns have no Forge tools.
17
+ */
18
+ export declare function hostDotnetBuildLockInstruction(environment?: NodeJS.ProcessEnv, turn?: "session" | "chat"): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A runner host can allow only one local .NET build or test at a time across everything that runs
3
+ * on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
4
+ * memory and break each other's shared test output. The host's owner names the lock wrapper in the
5
+ * bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
6
+ * tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
7
+ * user-level instruction file (provider-user-config-isolation.ts).
8
+ */
9
+ export const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
10
+ /** The host's .NET build lock wrapper, when the bridge's environment names one. */
11
+ export function hostDotnetBuildLock(environment = process.env) {
12
+ return environment[hostDotnetBuildLockVariable]?.trim() || null;
13
+ }
14
+ export function hostDotnetBuildLockEnvironment(environment = process.env) {
15
+ const lock = hostDotnetBuildLock(environment);
16
+ return lock ? { [hostDotnetBuildLockVariable]: lock } : {};
17
+ }
18
+ /**
19
+ * The runtime-context instruction for a host that names a .NET build lock, or an empty string.
20
+ * Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
21
+ * Chat turns have no Forge tools.
22
+ */
23
+ export function hostDotnetBuildLockInstruction(environment = process.env, turn = "session") {
24
+ if (!hostDotnetBuildLock(environment))
25
+ return "";
26
+ const forgeScheduled = turn === "session"
27
+ ? " Commands Forge runs for you (`forge.start_managed_verification`, pre-publication checks) are scheduled by Forge."
28
+ : "";
29
+ return `\n- This host runs one local .NET build or test at a time. Run every \`dotnet build\` and \`dotnet test\` you start yourself through the host lock in \`${hostDotnetBuildLockVariable}\`, for example \`"$${hostDotnetBuildLockVariable}" dotnet test <project> --filter <tests>\`. It waits while another build or test holds the lock and exits 75 if the wait times out; wait and retry rather than running without it.${forgeScheduled}`;
30
+ }
@@ -1,5 +1,8 @@
1
1
  import { PrePublicationValidationError, type PrePublicationProfile, type PrePublicationValidator } from "../pre-publication-validation.js";
2
+ import { prepareCompletionToolRuntime } from "../phase-completion.js";
3
+ import { type RunOnceDispatchPacket } from "../session.types.js";
2
4
  import type { ProviderProcessRunner } from "./provider-cli.process.js";
5
+ import { buildProviderCliCommand } from "./provider-cli.prompts.js";
3
6
  import type { ProviderCliRunContext } from "./provider-cli.types.js";
4
7
  import { type ProviderOutputState } from "./provider-output-state.js";
5
8
  /**
@@ -37,4 +40,17 @@ export interface PrePublicationRepairDependencies {
37
40
  readonly runRepairTurn: (turn: PrePublicationRepairTurn) => Promise<void>;
38
41
  }
39
42
  export declare function validatePrePublicationWithRepair(options: PrePublicationRepairOptions, dependencies: PrePublicationRepairDependencies): Promise<void>;
43
+ /**
44
+ * The resumed command for one pre-publication repair turn. The main turn's Forge MCP server was
45
+ * cleaned up when that turn exited, so the repair turn gets its own: the managed-attempt tools its
46
+ * prompt directs long checks to, without the completion tools whose artifacts are already recorded.
47
+ * The caller owns the returned runtime and cleans it up when the turn exits.
48
+ */
49
+ export declare function prepareRepairTurnLaunch(context: ProviderCliRunContext, turn: PrePublicationRepairTurn): Promise<{
50
+ readonly repairDispatch: RunOnceDispatchPacket;
51
+ readonly providerPrompt: string;
52
+ readonly pipePromptToStdin: boolean;
53
+ readonly completionTools: Awaited<ReturnType<typeof prepareCompletionToolRuntime>>;
54
+ readonly command: ReturnType<typeof buildProviderCliCommand>;
55
+ }>;
40
56
  export declare function buildPrePublicationRepairPrompt(error: PrePublicationValidationError, repairTurn: number, maxRepairTurns: number, repairScope: "implementation" | "pull_request"): string;
@@ -2,7 +2,9 @@ import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
2
2
  import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
3
3
  import { runtimeRestartCheckId } from "../pre-publication-pass.js";
4
4
  import { PrePublicationValidationError, } from "../pre-publication-validation.js";
5
+ import { prepareCompletionToolRuntime } from "../phase-completion.js";
5
6
  import { ForgeFailureError } from "../session.types.js";
7
+ import { buildProviderCliCommand, buildProviderCliPrompt, shouldPipePromptToStdin, usesManagedWindowsHost, } from "./provider-cli.prompts.js";
6
8
  import { prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
7
9
  import { clip } from "./provider-output-state.js";
8
10
  // Pre-publication validation with bounded in-place repair: each pass restarts the attempt's runtime
@@ -88,6 +90,37 @@ export async function validatePrePublicationWithRepair(options, dependencies) {
88
90
  });
89
91
  }
90
92
  }
93
+ /**
94
+ * The resumed command for one pre-publication repair turn. The main turn's Forge MCP server was
95
+ * cleaned up when that turn exited, so the repair turn gets its own: the managed-attempt tools its
96
+ * prompt directs long checks to, without the completion tools whose artifacts are already recorded.
97
+ * The caller owns the returned runtime and cleans it up when the turn exits.
98
+ */
99
+ export async function prepareRepairTurnLaunch(context, turn) {
100
+ const { dispatch, worktree } = context;
101
+ const { prompt: focusedPrompt, repairEnvironment } = turn;
102
+ const repairDispatch = {
103
+ ...dispatch,
104
+ session: { ...dispatch.session, resumeProviderThreadId: turn.providerThreadId },
105
+ };
106
+ const providerPrompt = buildProviderCliPrompt(repairDispatch, focusedPrompt, repairEnvironment);
107
+ const pipePromptToStdin = shouldPipePromptToStdin(repairDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(repairDispatch));
108
+ const completionTools = await prepareCompletionToolRuntime({
109
+ dispatch: repairDispatch,
110
+ worktree,
111
+ runtimeEnvironment: repairEnvironment,
112
+ hostLoadEnvironment: context.hostLoadEnvironment,
113
+ managedToolsOnly: true,
114
+ });
115
+ const command = buildProviderCliCommand(repairDispatch, {
116
+ worktreePath: worktree.worktreePath,
117
+ prompt: focusedPrompt,
118
+ promptFromStdin: pipePromptToStdin,
119
+ completionTools,
120
+ runtimeEnvironment: repairEnvironment,
121
+ });
122
+ return { repairDispatch, providerPrompt, pipePromptToStdin, completionTools, command };
123
+ }
91
124
  /** Restarts the runtime stack if needed, then validates; returns every failure of the pass, or null. */
92
125
  async function runValidationPass(options, dependencies, environments, repairTurn) {
93
126
  const { context, validationProfile, preparedHeadSha } = options;
@@ -0,0 +1,7 @@
1
+ export interface ProviderChildEnvironmentOptions {
2
+ readonly parentEnv?: NodeJS.ProcessEnv;
3
+ readonly platform?: NodeJS.Platform;
4
+ readonly homeDir?: string;
5
+ readonly arch?: string;
6
+ }
7
+ export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
@@ -0,0 +1,75 @@
1
+ import os from "node:os";
2
+ import { normalizeWindowsProviderEnvironment, windowsAllowedProviderParentEnvNames } from "./provider-cli.windows-environment.js";
3
+ // The environment a provider child process starts with: an allowlist of the Bridge's own
4
+ // variables, the request's values, the Windows defaults, then the .NET build-server settings.
5
+ // CLAUDE_CONFIG_DIR is not passed: it would point Claude Code at a user configuration directory
6
+ // of the host's choosing (provider-user-config-isolation.ts). Claude signs in from the provider
7
+ // home's default `.claude` directory under HOME or USERPROFILE, or with a Forge-granted API key.
8
+ const allowedProviderParentEnvNames = [
9
+ "PATH",
10
+ "HOME",
11
+ "USERPROFILE",
12
+ "TMPDIR",
13
+ "TEMP",
14
+ "TMP",
15
+ "LANG"
16
+ ];
17
+ export function buildProviderChildEnvironment(requestEnv, options = {}) {
18
+ const parentEnv = options.parentEnv ?? process.env;
19
+ const platform = options.platform ?? process.platform;
20
+ const env = {};
21
+ for (const [key, value] of Object.entries(parentEnv)) {
22
+ if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
23
+ env[key] = value;
24
+ }
25
+ }
26
+ if (requestEnv) {
27
+ for (const [key, value] of Object.entries(requestEnv)) {
28
+ const trimmedKey = key.trim();
29
+ if (trimmedKey.length > 0) {
30
+ env[trimmedKey] = value;
31
+ }
32
+ }
33
+ }
34
+ if (platform === "win32") {
35
+ normalizeWindowsProviderEnvironment(env, parentEnv, options.homeDir ?? os.homedir(), options.arch ?? os.arch());
36
+ }
37
+ normalizeProviderBuildEnvironment(env);
38
+ return env;
39
+ }
40
+ function normalizeProviderBuildEnvironment(env) {
41
+ // Provider sessions are long lived and commonly run many dotnet builds. Persistent
42
+ // MSBuild and Roslyn compiler servers otherwise survive individual commands and can
43
+ // retain more memory than the active Forge lane. Keep those caches process-scoped by
44
+ // default on every runner OS; an explicitly supplied request value still wins.
45
+ setCanonicalProviderBuildEnvironmentValue(env, "DOTNET_CLI_USE_MSBUILD_SERVER", "0");
46
+ setCanonicalProviderBuildEnvironmentValue(env, "MSBUILDDISABLENODEREUSE", "1");
47
+ setCanonicalProviderBuildEnvironmentValue(env, "UseSharedCompilation", "false");
48
+ }
49
+ function setCanonicalProviderBuildEnvironmentValue(env, name, value) {
50
+ // The dotnet CLI uses case-sensitive environment lookup on POSIX, while MSBuild
51
+ // property names are case-insensitive on every OS. Collapse request aliases to
52
+ // one canonical key so the explicit value wins without producing ambiguity.
53
+ const exact = env[name];
54
+ const alias = Object.entries(env).find(([key, candidate]) => key !== name
55
+ && key.toLowerCase() === name.toLowerCase()
56
+ && typeof candidate === "string"
57
+ && candidate.trim().length > 0)?.[1];
58
+ const resolved = typeof exact === "string" && exact.trim().length > 0
59
+ ? exact
60
+ : alias ?? value;
61
+ for (const key of Object.keys(env)) {
62
+ if (key !== name && key.toLowerCase() === name.toLowerCase()) {
63
+ delete env[key];
64
+ }
65
+ }
66
+ env[name] = resolved;
67
+ }
68
+ function isAllowedProviderParentEnv(key, platform = process.platform) {
69
+ return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
70
+ || key.toUpperCase().startsWith("LC_")
71
+ || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
72
+ }
73
+ function isAllowedProviderParentEnvName(key, allowedNames) {
74
+ return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
75
+ }
@@ -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,7 +1,10 @@
1
- import { type LaunchCommand } from "../../shared/process/windows-launch.js";
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;
7
+ export { resolveClaudeNpmDirectLaunch, resolveCodexNpmDirectLaunch, resolvePackageManagerDirectLaunch } from "./provider-cli.windows-launch.js";
5
8
  export interface ProviderProcessRunRequest {
6
9
  readonly command: string;
7
10
  readonly args: readonly string[];
@@ -22,8 +25,8 @@ export interface ProviderProcessRunRequest {
22
25
  */
23
26
  readonly resumesProviderThread?: boolean;
24
27
  }
25
- /** Why Forge stopped a provider that was still resident after a successful turn. */
26
- export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
28
+ /** Why Forge stopped a provider still resident after its turn (or its background work, for Claude). */
29
+ export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling" | "turn_ended_with_background_work";
27
30
  export interface ProviderProcessRunResult {
28
31
  readonly exitCode: number;
29
32
  readonly stdout: string;
@@ -34,8 +37,10 @@ export interface ProviderProcessRunResult {
34
37
  readonly memoryObservedAt?: string;
35
38
  /** Present when the caller's cancellation stopped the process before it exited on its own. */
36
39
  readonly cancelled?: true;
37
- /** Present when Forge stopped a provider that stayed resident after a successful turn. */
40
+ /** Present when Forge stopped a provider that stayed resident after its turn ended. */
38
41
  readonly terminalStopReason?: ProviderTerminalStopReason;
42
+ /** Present when Forge closed output pipes a descendant still held after the provider exited. */
43
+ readonly outputPipesReleasedAfterExit?: true;
39
44
  }
40
45
  export interface ProviderProcessRunner {
41
46
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
@@ -59,7 +64,8 @@ export interface ProviderProcessHandlers {
59
64
  onGenerationStart?(): void;
60
65
  }
61
66
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
62
- * relaunch needs a new fenced child generation and exclusive launch files. */
67
+ * relaunch needs a new fenced child generation and exclusive launch files. The outer
68
+ * layer fails any run Forge stopped because its turn ended with background work live. */
63
69
  export declare function recoveringProviderProcessRunner(inner: ProviderProcessRunner): ProviderProcessRunner;
64
70
  /**
65
71
  * Codex Desktop and an independently installed Codex CLI can briefly disagree
@@ -88,48 +94,21 @@ export declare class CodexResumeRecoveringProcessRunner implements ProviderProce
88
94
  * arbitrary tool/command output and therefore cannot mint retry authority.
89
95
  */
90
96
  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
97
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
98
98
  private readonly terminalExitGraceMs;
99
99
  private readonly terminalSuccessCeilingMs;
100
100
  private readonly terminalWorkPollMs;
101
- constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
101
+ private readonly outputPipeReleaseGraceMs;
102
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number, outputPipeReleaseGraceMs?: number);
102
103
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
103
104
  }
104
105
  /**
105
106
  * 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.
107
+ * completion tool. A run Forge stopped at the success ceiling or for background work is
108
+ * reported as such, so it is not mistaken for an agent that simply ended its turn.
108
109
  */
109
110
  export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
110
111
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
111
112
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
112
113
  export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
113
114
  export declare function buildUnixProviderStartGateLaunch(command: string, args: readonly string[]): LaunchCommand;
114
- export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
115
- /**
116
- * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
117
- * PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
118
- * ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
119
- */
120
- export declare function resolveClaudeNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
121
- /**
122
- * Avoids cmd.exe's nested-quote handling for package-manager shims. That
123
- * quoting loses executable paths containing spaces after the command is
124
- * wrapped by the Windows Job Object supervisor.
125
- */
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 {};