@loucompanion/forge-bridge 0.1.4-dev.81e48ecc185d → 0.1.4-dev.866b33be3065

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 (61) hide show
  1. package/README.md +3 -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 +4 -1
  17. package/dist/runtime/host-load-sampler.d.ts +34 -4
  18. package/dist/runtime/host-load-sampler.js +73 -7
  19. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  20. package/dist/runtime/host-load-windows-cpu.js +85 -0
  21. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  22. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  23. package/dist/session/architect-waits.d.ts +2 -0
  24. package/dist/session/architect-waits.js +138 -0
  25. package/dist/session/managed-attempt-tools.d.ts +0 -7
  26. package/dist/session/managed-attempt-tools.js +44 -54
  27. package/dist/session/phase-completion.artifacts.js +2 -1
  28. package/dist/session/phase-completion.runtime.js +1 -1
  29. package/dist/session/phase-completion.schemas.js +3 -11
  30. package/dist/session/phase-completion.validation.js +3 -1
  31. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  32. package/dist/session/pre-publication-native-postgres.js +111 -0
  33. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  34. package/dist/session/pre-publication-step-execution.js +6 -5
  35. package/dist/session/pre-publication-validation.d.ts +7 -3
  36. package/dist/session/pre-publication-validation.js +32 -30
  37. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  38. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  39. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  40. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  41. package/dist/session/provider-cli/provider-cli.process.d.ts +8 -30
  42. package/dist/session/provider-cli/provider-cli.process.js +25 -376
  43. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  44. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  45. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  46. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  47. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  48. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  49. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  50. package/dist/session/qa-sidecar-validation.js +28 -0
  51. package/dist/session/session-redaction.js +31 -181
  52. package/dist/session/session.types.js +1 -1
  53. package/dist/session/sidecar-json-shape.d.ts +31 -0
  54. package/dist/session/sidecar-json-shape.js +217 -0
  55. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  56. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  57. package/dist/shared/process/windows-launch.d.ts +18 -0
  58. package/dist/shared/process/windows-launch.js +68 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +1 -1
@@ -1,18 +1,17 @@
1
- import { execFile, execFileSync, spawn } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
1
+ import { execFileSync, spawn } from "node:child_process";
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
- import { promisify } from "node:util";
8
- import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
9
4
  import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunch, terminateHostProcessTree, } from "../../shared/process/host-process-supervisor.js";
10
- import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
5
+ import { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
6
+ import { resolveWindowsProviderLaunch } from "./provider-cli.windows-launch.js";
7
+ import { isCodexModelsCacheSchemaFailure, quarantineIncompatibleCodexModelsCache } from "./provider-cli.codex-models-cache.js";
11
8
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
9
  import { ForgeFailureError } from "../session.types.js";
13
10
  import { BackgroundWorkStopFailingRunner, ClaudeBackgroundTurnEndWatch, providerTurnEndedWithBackgroundWorkFailure } from "./claude-background-work.js";
14
11
  import { hasNonterminalManagedCommand, isProviderTerminalFailure, isProviderTerminalSuccess, isProviderTurnActivity } from "./provider-in-flight-work.js";
15
- const execFileAsync = promisify(execFile);
12
+ import { OutputPipeRelease, readProcessLines, PROVIDER_OUTPUT_PIPE_RELEASE_GRACE_MS } from "./provider-output-pipes.js";
13
+ export { chooseWindowsCommandCandidate, resolveWindowsCommandFromPath } from "../../shared/process/windows-launch.js";
14
+ export { buildProviderChildEnvironment } from "./provider-cli.child-environment.js";
16
15
  // Provider processes can emit many gigabytes over a long-running session. The
17
16
  // line handlers stream that output to Forge as it arrives; the completed result
18
17
  // only needs a bounded diagnostic tail for failure classification.
@@ -24,7 +23,7 @@ const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
24
23
  const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
25
24
  // How often the end-of-turn timers re-check whether supervised work is still in flight.
26
25
  const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
27
- const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
26
+ export { resolveClaudeNpmDirectLaunch, resolveCodexNpmDirectLaunch, resolvePackageManagerDirectLaunch } from "./provider-cli.windows-launch.js";
28
27
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
29
28
  * relaunch needs a new fenced child generation and exclusive launch files. The outer
30
29
  * layer fails any run Forge stopped because its turn ended with background work live. */
@@ -123,216 +122,16 @@ function codexFreshTurnRequest(request) {
123
122
  function isCodexCommand(command) {
124
123
  return path.parse(command).name.toLowerCase() === "codex";
125
124
  }
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
125
  export class StreamingProviderProcessRunner {
329
126
  terminalExitGraceMs;
330
127
  terminalSuccessCeilingMs;
331
128
  terminalWorkPollMs;
332
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
129
+ outputPipeReleaseGraceMs;
130
+ 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
131
  this.terminalExitGraceMs = terminalExitGraceMs;
334
132
  this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
335
133
  this.terminalWorkPollMs = terminalWorkPollMs;
134
+ this.outputPipeReleaseGraceMs = outputPipeReleaseGraceMs;
336
135
  }
337
136
  async run(request, handlers = {}, signal) {
338
137
  assertHostDatabaseCapabilityBoundary();
@@ -386,6 +185,7 @@ export class StreamingProviderProcessRunner {
386
185
  }
387
186
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
388
187
  const stderr = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
188
+ const outputPipes = new OutputPipeRelease(child, this.outputPipeReleaseGraceMs, message => stderr.appendLine(message));
389
189
  let settled = false;
390
190
  let closed = false;
391
191
  let cancellationRequested = false;
@@ -516,16 +316,6 @@ export class StreamingProviderProcessRunner {
516
316
  stopTerminalWorkTimer();
517
317
  void terminate().catch(fail);
518
318
  };
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
319
  // The grace and the ceiling only count time in which no supervised work is in flight:
530
320
  // a provider waiting on an MCP tool call or on a managed command it started is not
531
321
  // finished, even when its turn has ended. The grace restarts once that work is done.
@@ -534,7 +324,7 @@ export class StreamingProviderProcessRunner {
534
324
  return;
535
325
  terminalWorkTickRunning = true;
536
326
  try {
537
- const inFlight = await workInFlight();
327
+ const inFlight = await providerWorkInFlight(handlers, request.env?.FORGE_LOG_DIR);
538
328
  const now = performance.now();
539
329
  const elapsed = Math.max(0, now - terminalWorkTickAt);
540
330
  terminalWorkTickAt = now;
@@ -669,12 +459,23 @@ export class StreamingProviderProcessRunner {
669
459
  ...(memory ?? {}),
670
460
  ...(cancelledBeforeClose ? { cancelled: true } : {}),
671
461
  ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
462
+ ...outputPipes.resultFields(),
672
463
  });
673
464
  }).catch(fail);
674
465
  });
675
466
  });
676
467
  }
677
468
  }
469
+ async function providerWorkInFlight(handlers, logDirectory) {
470
+ try {
471
+ if (handlers.isToolCallInFlight?.())
472
+ return true;
473
+ }
474
+ catch {
475
+ // A failing probe must not keep the provider open or stop it early on its own.
476
+ }
477
+ return await hasNonterminalManagedCommand(logDirectory).catch(() => false);
478
+ }
678
479
  /**
679
480
  * The typed failure for a provider run that ended without calling its required Forge
680
481
  * completion tool. A run Forge stopped at the success ceiling or for background work is
@@ -845,18 +646,7 @@ async function resolveProviderProcessLaunch(command, args) {
845
646
  if (process.platform !== "win32") {
846
647
  return { command, args };
847
648
  }
848
- const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
849
- if (cursorDirect) {
850
- return cursorDirect;
851
- }
852
- const resolved = await resolveWindowsCommand(command);
853
- if (!resolved) {
854
- return { command, args };
855
- }
856
- return resolveCodexNpmDirectLaunch(resolved, args)
857
- ?? resolveClaudeNpmDirectLaunch(resolved, args)
858
- ?? resolvePackageManagerDirectLaunch(resolved, args)
859
- ?? buildWindowsLaunchCommand(resolved, args);
649
+ return await resolveWindowsProviderLaunch(command, args);
860
650
  }
861
651
  const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
862
652
  const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
@@ -965,144 +755,3 @@ async function waitForWindowsProviderReady(launch, signal, isClosed) {
965
755
  await new Promise(resolve => setTimeout(resolve, 25));
966
756
  }
967
757
  }
968
- export function resolveCodexNpmDirectLaunch(commandPath, args) {
969
- const extension = path.extname(commandPath).toLowerCase();
970
- if ((extension !== ".cmd" && extension !== ".ps1")
971
- || path.basename(commandPath, extension).toLowerCase() !== "codex") {
972
- return null;
973
- }
974
- const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@openai", "codex", "bin", "codex.js");
975
- return fs.existsSync(entryPoint)
976
- ? { command: process.execPath, args: [entryPoint, ...args] }
977
- : null;
978
- }
979
- /**
980
- * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
981
- * PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
982
- * ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
983
- */
984
- export function resolveClaudeNpmDirectLaunch(commandPath, args) {
985
- const extension = path.extname(commandPath).toLowerCase();
986
- if ((extension !== ".cmd" && extension !== ".ps1")
987
- || path.basename(commandPath, extension).toLowerCase() !== "claude") {
988
- return null;
989
- }
990
- const entryPoint = path.join(path.dirname(commandPath), "node_modules", "@anthropic-ai", "claude-code", "cli.js");
991
- return fs.existsSync(entryPoint)
992
- ? { command: process.execPath, args: [entryPoint, ...args] }
993
- : null;
994
- }
995
- /**
996
- * Avoids cmd.exe's nested-quote handling for package-manager shims. That
997
- * quoting loses executable paths containing spaces after the command is
998
- * wrapped by the Windows Job Object supervisor.
999
- */
1000
- export function resolvePackageManagerDirectLaunch(commandPath, args) {
1001
- const extension = path.extname(commandPath).toLowerCase();
1002
- if (extension !== ".cmd" && extension !== ".ps1")
1003
- return null;
1004
- const packageManager = path.basename(commandPath, extension).toLowerCase();
1005
- if (!["corepack", "npm", "npx", "pnpm", "pnpx", "yarn", "yarnpkg"].includes(packageManager))
1006
- return null;
1007
- const root = path.dirname(commandPath);
1008
- const candidates = [
1009
- path.join(root, "node_modules", "corepack", "dist", packageManager === "corepack" ? "corepack.js" : `${packageManager}.js`),
1010
- ...(packageManager === "npm" || packageManager === "npx"
1011
- ? [path.join(root, "node_modules", "npm", "bin", `${packageManager}-cli.js`)]
1012
- : []),
1013
- ...(packageManager === "pnpm" || packageManager === "pnpx"
1014
- ? [path.join(root, "node_modules", "pnpm", "bin", `${packageManager}.cjs`)]
1015
- : []),
1016
- ...(packageManager === "yarn" || packageManager === "yarnpkg"
1017
- ? [path.join(root, "node_modules", "yarn", "bin", "yarn.js")]
1018
- : []),
1019
- ];
1020
- const entryPoint = candidates.find(candidate => fs.existsSync(candidate));
1021
- if (!entryPoint)
1022
- return null;
1023
- const adjacentNode = path.join(root, "node.exe");
1024
- return {
1025
- command: fs.existsSync(adjacentNode) ? adjacentNode : process.execPath,
1026
- args: [entryPoint, ...args],
1027
- };
1028
- }
1029
- async function resolveWindowsCommand(command) {
1030
- if (path.isAbsolute(command)) {
1031
- return command;
1032
- }
1033
- const resolvedFromPath = resolveWindowsCommandFromPath(command);
1034
- if (resolvedFromPath) {
1035
- return resolvedFromPath;
1036
- }
1037
- try {
1038
- const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
1039
- return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
1040
- }
1041
- catch {
1042
- return null;
1043
- }
1044
- }
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,23 @@
1
+ import { type LaunchCommand } from "../../shared/process/windows-launch.js";
2
+ export declare function resolveWindowsProviderLaunch(command: string, args: readonly string[]): Promise<LaunchCommand>;
3
+ export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
4
+ /**
5
+ * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
6
+ * PATH; launch its cli.js directly for the same Job Object reasons as Codex. The native installer
7
+ * ships `claude.exe`, which is preferred by PATH resolution and needs no rewrite.
8
+ */
9
+ export declare function resolveClaudeNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
10
+ /**
11
+ * Avoids cmd.exe's nested-quote handling for package-manager shims. That
12
+ * quoting loses executable paths containing spaces after the command is
13
+ * wrapped by the Windows Job Object supervisor.
14
+ *
15
+ * Launches the entry point the shim itself runs. A Windows Node install ships
16
+ * both npm's own CLI and Corepack's npm shim next to `npm.cmd`, and `npm.cmd`
17
+ * runs npm's CLI. Launching Corepack's shim instead would apply Corepack's
18
+ * strict `packageManager` check: in a repository whose root pins pnpm, an npm
19
+ * package below it (with its own package-lock) is refused although its scripts
20
+ * pass when npm runs them. A shim that names none of the candidates prefers
21
+ * the tool's own CLI over Corepack's.
22
+ */
23
+ export declare function resolvePackageManagerDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;