@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.573a8a5fa582

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 (57) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.service.js +1 -9
  3. package/dist/bridge/bridge.types.d.ts +10 -0
  4. package/dist/bridge/bridge.types.js +2 -1
  5. package/dist/bridge/runner-host-capabilities.js +14 -1
  6. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  7. package/dist/bridge/windows-bash-resolution.js +153 -0
  8. package/dist/cli/cli.service.js +8 -40
  9. package/dist/cli/local-config.d.ts +10 -1
  10. package/dist/cli/local-config.js +32 -1
  11. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  12. package/dist/cli/provider-cli-advertising.js +88 -0
  13. package/dist/runtime/host-load-admission.d.ts +5 -0
  14. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  15. package/dist/runtime/host-load-governor-config.js +4 -1
  16. package/dist/runtime/host-load-governor.d.ts +8 -1
  17. package/dist/runtime/host-load-governor.js +33 -3
  18. package/dist/runtime/host-load-test-slot.js +7 -0
  19. package/dist/runtime/host-runtime-contract.js +6 -4
  20. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  21. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  22. package/dist/sandbox/runtime.js +1 -1
  23. package/dist/session/provider-cli/pre-publication-repair.js +1 -0
  24. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  25. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  26. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  27. package/dist/session/provider-cli/provider-cli.prompts.js +37 -0
  28. package/dist/session/provider-cli/provider-cli.service.js +9 -9
  29. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  30. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  31. package/dist/session/session-host-project.d.ts +22 -0
  32. package/dist/session/session-host-project.js +98 -0
  33. package/dist/session/session.service.js +24 -70
  34. package/dist/session/session.types.d.ts +1 -0
  35. package/dist/session/session.types.js +2 -2
  36. package/dist/shared/provider-capabilities.d.ts +2 -0
  37. package/dist/shared/provider-capabilities.js +9 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/dist/worktree/wip-git.d.ts +25 -0
  41. package/dist/worktree/wip-git.js +64 -4
  42. package/dist/worktree/wip-refs.d.ts +23 -0
  43. package/dist/worktree/wip-refs.js +52 -2
  44. package/dist/worktree/wip-restore.d.ts +13 -0
  45. package/dist/worktree/wip-restore.js +159 -25
  46. package/dist/worktree/wip-snapshot.d.ts +5 -2
  47. package/dist/worktree/wip-snapshot.js +15 -13
  48. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  49. package/dist/worktree/worktree-origin-sync.js +1 -0
  50. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  51. package/dist/worktree/worktree-wip-events.js +53 -3
  52. package/dist/worktree/worktree-wip.d.ts +7 -0
  53. package/dist/worktree/worktree-wip.js +17 -2
  54. package/dist/worktree/worktree.service.d.ts +1 -1
  55. package/dist/worktree/worktree.service.js +6 -3
  56. package/dist/worktree/worktree.types.d.ts +9 -0
  57. package/package.json +1 -1
package/README.md CHANGED
@@ -55,7 +55,7 @@ a parent containing unrelated maintenance checkouts and generated projects.
55
55
 
56
56
  ## Provider CLIs
57
57
 
58
- The bridge auto-detects these provider CLIs on `PATH` and advertises the ones it finds:
58
+ The bridge auto-detects these provider CLIs on `PATH` and advertises the ones it finds. `pair` and every `connect` probe all of them, not only the providers saved in `bridge.json`, so a CLI installed after pairing is advertised on the next `connect`. A saved provider whose CLI is no longer found stays advertised; detection only adds providers. Advertising cursor doesn't make it runnable: the bridge still refuses to launch it, because Forge can't keep `cursor-agent`'s own configuration out of the session.
59
59
 
60
60
  | Provider | CLI | Sign-in | Headless invocation |
61
61
  | --- | --- | --- | --- |
@@ -70,6 +70,8 @@ Claude Code notes:
70
70
  - Claude Code has no model-listing command, so the bridge advertises the `sonnet`, `opus`, and `haiku` aliases. Set `FORGE_CLAUDE_MODELS` to advertise specific model ids instead.
71
71
  - Claude runs in host mode only. Docker sandbox placement currently supports Codex only.
72
72
 
73
+ On Windows the bridge's `bash` capability is Git for Windows' `bash.exe`, resolved to an absolute path: `FORGE_BRIDGE_BASH_PATH` (then `CLAUDE_CODE_GIT_BASH_PATH`) if set, otherwise the Git install found from `git --exec-path` or `git.exe` on `PATH`, then `bash.exe` on `PATH`, then the standard Program Files locations. WSL's `System32\bash.exe` and Store aliases are never accepted. A bare `bash` is not used because Windows' executable search checks the current directory before `PATH`, and a scheduled task with no working directory starts in `System32`.
74
+
73
75
  Show or change the saved server without editing `bridge.json`:
74
76
 
75
77
  ```bash
@@ -5,7 +5,7 @@ import path from "node:path";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import os from "node:os";
7
7
  import { defaultForgeBridgeConfig } from "../config.js";
8
- import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
8
+ import { bridgeChatCapabilityFor, defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { BridgeSessionService } from "../session/session.service.js";
11
11
  import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
@@ -2532,14 +2532,6 @@ function providerStatus(config, provider) {
2532
2532
  return Object.entries(config.providerStatuses)
2533
2533
  .find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
2534
2534
  }
2535
- function defaultSandboxProfiles(providers, platform = process.platform) {
2536
- if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
2537
- return ["none"];
2538
- }
2539
- return platform === "win32"
2540
- ? ["danger-full-access"]
2541
- : ["provider-workspace-write"];
2542
- }
2543
2535
  function configuredModelsFor(provider) {
2544
2536
  const envName = `FORGE_${provider.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase()}_MODELS`;
2545
2537
  return splitCsv(process.env[envName] ?? "");
@@ -9,6 +9,10 @@ import type { HostFacts } from "../runtime/host-facts.js";
9
9
  import type { HostLoadSnapshot } from "../runtime/host-load-sampler.js";
10
10
  import type { RunnerSettingsReport } from "../runtime/runner-settings.js";
11
11
  import type { BridgeChatCapability, ChatTurnCancelPacket } from "./bridge-chat.types.js";
12
+ /** Capability fields the bridge derives from its provider list (see provider-capabilities.ts). */
13
+ export declare const derivedCapabilityFields: readonly ["supportsDraftImageAttachments", "sandboxProfiles"];
14
+ export type DerivedCapabilityField = (typeof derivedCapabilityFields)[number];
15
+ export type CapabilitySource = "derived" | "explicit";
12
16
  export interface BridgeServiceConfig {
13
17
  readonly serverUrl: string;
14
18
  readonly runnerId: string;
@@ -58,6 +62,12 @@ export interface BridgeServiceConfig {
58
62
  readonly supportsDraftRunOnce: boolean;
59
63
  readonly supportsDraftAttachments: boolean;
60
64
  readonly supportsDraftImageAttachments: boolean;
65
+ /**
66
+ * Where each provider-derived capability's value came from: "derived" from the provider list
67
+ * (pair or the defaults) or "explicit" (set by the user in bridge.json). A field with no entry
68
+ * comes from a bridge.json written before the marker existed, so its source is unknown.
69
+ */
70
+ readonly capabilitySources?: Readonly<Partial<Record<DerivedCapabilityField, CapabilitySource>>>;
61
71
  readonly bridgeChat: BridgeChatCapability;
62
72
  readonly version: string;
63
73
  readonly protocolVersion: number;
@@ -1 +1,2 @@
1
- export {};
1
+ /** Capability fields the bridge derives from its provider list (see provider-capabilities.ts). */
2
+ export const derivedCapabilityFields = ["supportsDraftImageAttachments", "sandboxProfiles"];
@@ -5,6 +5,7 @@ import { promisify } from "node:util";
5
5
  import { probeTestPostgresCapability } from "./test-postgres-capability.js";
6
6
  import { appExecutionAliasWarning } from "../shared/process/windows-app-execution-alias.js";
7
7
  import { buildProviderChildEnvironment } from "../session/provider-cli/provider-cli.process.js";
8
+ import { resolveBashExecutable } from "./windows-bash-resolution.js";
8
9
  const execFileAsync = promisify(execFile);
9
10
  export class ProcessRunnerHostCapabilityProbe {
10
11
  warn;
@@ -23,7 +24,7 @@ export class ProcessRunnerHostCapabilityProbe {
23
24
  probe("pnpm", ["--version"]),
24
25
  probe("dotnet", ["--version"]),
25
26
  probe("git", ["--version"]),
26
- probe("bash", ["--version"]),
27
+ probeBash(this.warn),
27
28
  probe("pwsh", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"]),
28
29
  process.platform === "win32"
29
30
  ? probe("powershell.exe", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"])
@@ -62,6 +63,18 @@ async function probe(executable, args) {
62
63
  return unavailable(executable);
63
64
  }
64
65
  }
66
+ // On Windows a bare "bash" can resolve to WSL's System32\bash.exe (see resolveBashExecutable), so
67
+ // the probe runs, and reports, the resolved absolute Git Bash path instead.
68
+ async function probeBash(warn) {
69
+ const resolution = await resolveBashExecutable({
70
+ platform: process.platform,
71
+ env: process.env,
72
+ gitExecPath: async () => (await execFileAsync("git", ["--exec-path"], { encoding: "utf8", timeout: 5_000 })).stdout,
73
+ });
74
+ if (resolution.warning)
75
+ warn(resolution.warning);
76
+ return resolution.executable ? probe(resolution.executable, ["--version"]) : unavailable("bash");
77
+ }
65
78
  function unavailable(executable) {
66
79
  return { available: false, executable, version: null };
67
80
  }
@@ -0,0 +1,31 @@
1
+ /** Environment variables that name the bash the bridge should use on Windows, in priority order. */
2
+ export declare const WINDOWS_BASH_OVERRIDE_VARIABLES: readonly ["FORGE_BRIDGE_BASH_PATH", "CLAUDE_CODE_GIT_BASH_PATH"];
3
+ export interface BashResolutionInput {
4
+ readonly platform: NodeJS.Platform;
5
+ readonly env: NodeJS.ProcessEnv;
6
+ /** Output of `git --exec-path`, or null when git is unavailable. Called only on Windows. */
7
+ readonly gitExecPath: () => Promise<string | null>;
8
+ readonly fileExists?: (candidate: string) => boolean;
9
+ }
10
+ export interface BashResolution {
11
+ /** What to run: "bash" off Windows, an absolute bash.exe path on Windows, or null when none was found. */
12
+ readonly executable: string | null;
13
+ /** Why the result is not what the host may expect (an override was rejected, nothing was found). */
14
+ readonly warning?: string;
15
+ }
16
+ /**
17
+ * Picks the bash the bridge runs. Off Windows this is plain `bash` from PATH, unchanged.
18
+ *
19
+ * On Windows a bare `bash` is not safe: libuv's executable search looks in the current directory
20
+ * before PATH (unless `NoDefaultCurrentDirectoryInExePath` is set), and a scheduled task with no
21
+ * working directory starts in `C:\Windows\System32`, so `bash` becomes WSL's `System32\bash.exe`
22
+ * even with Git Bash first on PATH. The bridge therefore resolves Git for Windows' bash.exe to an
23
+ * absolute path and never accepts the WSL launcher or a Store app-execution alias.
24
+ */
25
+ export declare function resolveBashExecutable(input: BashResolutionInput): Promise<BashResolution>;
26
+ /** True for WSL's bash.exe launcher (System32, SysWOW64, Sysnative) and for Store app-execution aliases. */
27
+ export declare function isRejectedWindowsBash(candidate: string, env: NodeJS.ProcessEnv): boolean;
28
+ /** `git --exec-path` is `<root>/mingw64/libexec/git-core` (or clangarm64, mingw32) on Git for Windows. */
29
+ export declare function gitRootFromExecPath(execPath: string | null): string | null;
30
+ /** git.exe lives in `<root>\cmd`, `<root>\bin` or `<root>\mingw64\bin` on Git for Windows. */
31
+ export declare function gitRootFromGitExecutable(gitExecutable: string | null): string | null;
@@ -0,0 +1,153 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isWindowsAppExecutionAliasPath } from "../shared/process/windows-launch.js";
4
+ /** Environment variables that name the bash the bridge should use on Windows, in priority order. */
5
+ export const WINDOWS_BASH_OVERRIDE_VARIABLES = ["FORGE_BRIDGE_BASH_PATH", "CLAUDE_CODE_GIT_BASH_PATH"];
6
+ /**
7
+ * Picks the bash the bridge runs. Off Windows this is plain `bash` from PATH, unchanged.
8
+ *
9
+ * On Windows a bare `bash` is not safe: libuv's executable search looks in the current directory
10
+ * before PATH (unless `NoDefaultCurrentDirectoryInExePath` is set), and a scheduled task with no
11
+ * working directory starts in `C:\Windows\System32`, so `bash` becomes WSL's `System32\bash.exe`
12
+ * even with Git Bash first on PATH. The bridge therefore resolves Git for Windows' bash.exe to an
13
+ * absolute path and never accepts the WSL launcher or a Store app-execution alias.
14
+ */
15
+ export async function resolveBashExecutable(input) {
16
+ if (input.platform !== "win32")
17
+ return { executable: "bash" };
18
+ const fileExists = input.fileExists ?? defaultFileExists;
19
+ const env = input.env;
20
+ // Relative candidates (a "." PATH entry, a relative override) would put the cwd lookup back.
21
+ const accept = (candidate) => Boolean(candidate)
22
+ && isAbsoluteWindowsPath(candidate)
23
+ && !isRejectedWindowsBash(candidate, env)
24
+ && fileExists(candidate);
25
+ for (const name of WINDOWS_BASH_OVERRIDE_VARIABLES) {
26
+ const raw = environmentValue(env, name)?.trim().replace(/^"|"$/gu, "");
27
+ if (!raw)
28
+ continue;
29
+ if (accept(raw))
30
+ return { executable: path.win32.normalize(raw) };
31
+ const reason = !isAbsoluteWindowsPath(raw)
32
+ ? "is not an absolute path"
33
+ : isRejectedWindowsBash(raw, env)
34
+ ? "points at the WSL launcher or a Store alias, not Git Bash"
35
+ : "does not exist";
36
+ return { executable: null, warning: `${name}=${raw} ${reason}; bash is reported unavailable.` };
37
+ }
38
+ const pathValue = environmentValue(env, "PATH") ?? "";
39
+ const gitRoots = [
40
+ gitRootFromExecPath(await input.gitExecPath().catch(() => null)),
41
+ gitRootFromGitExecutable(findOnWindowsPath(pathValue, "git.exe", fileExists)),
42
+ ];
43
+ for (const root of gitRoots) {
44
+ if (!root)
45
+ continue;
46
+ for (const candidate of gitBashCandidates(root)) {
47
+ if (accept(candidate))
48
+ return { executable: candidate };
49
+ }
50
+ }
51
+ for (const directory of windowsPathDirectories(pathValue)) {
52
+ const candidate = path.win32.join(directory, "bash.exe");
53
+ if (accept(candidate))
54
+ return { executable: candidate };
55
+ }
56
+ for (const root of standardGitRoots(env)) {
57
+ for (const candidate of gitBashCandidates(root)) {
58
+ if (accept(candidate))
59
+ return { executable: candidate };
60
+ }
61
+ }
62
+ return {
63
+ executable: null,
64
+ warning: "Git Bash (bash.exe from Git for Windows) was not found; bash is reported unavailable. "
65
+ + "Install Git for Windows or set FORGE_BRIDGE_BASH_PATH to its bin\\bash.exe.",
66
+ };
67
+ }
68
+ /** True for WSL's bash.exe launcher (System32, SysWOW64, Sysnative) and for Store app-execution aliases. */
69
+ export function isRejectedWindowsBash(candidate, env) {
70
+ if (isWindowsAppExecutionAliasPath(candidate))
71
+ return true;
72
+ const normalized = path.win32.normalize(candidate).toLowerCase();
73
+ if (path.win32.basename(normalized) !== "bash.exe" && path.win32.basename(normalized) !== "bash")
74
+ return false;
75
+ const directory = path.win32.dirname(normalized);
76
+ const systemRoot = (environmentValue(env, "SystemRoot") ?? environmentValue(env, "windir") ?? "C:\\Windows").toLowerCase();
77
+ const systemDirectories = ["system32", "syswow64", "sysnative"].map(name => path.win32.join(systemRoot, name));
78
+ return systemDirectories.includes(directory) || /\\windows\\(system32|syswow64|sysnative)$/u.test(directory);
79
+ }
80
+ /** `git --exec-path` is `<root>/mingw64/libexec/git-core` (or clangarm64, mingw32) on Git for Windows. */
81
+ export function gitRootFromExecPath(execPath) {
82
+ const trimmed = execPath?.trim();
83
+ if (!trimmed)
84
+ return null;
85
+ const normalized = path.win32.normalize(trimmed);
86
+ const libexec = normalized.toLowerCase().lastIndexOf("\\libexec");
87
+ if (libexec <= 0)
88
+ return null;
89
+ return path.win32.dirname(normalized.slice(0, libexec));
90
+ }
91
+ /** git.exe lives in `<root>\cmd`, `<root>\bin` or `<root>\mingw64\bin` on Git for Windows. */
92
+ export function gitRootFromGitExecutable(gitExecutable) {
93
+ if (!gitExecutable)
94
+ return null;
95
+ const directory = path.win32.dirname(path.win32.normalize(gitExecutable));
96
+ const leaf = path.win32.basename(directory).toLowerCase();
97
+ if (leaf === "cmd")
98
+ return path.win32.dirname(directory);
99
+ if (leaf === "bin") {
100
+ const parent = path.win32.dirname(directory);
101
+ return /^(mingw64|mingw32|clangarm64|usr)$/u.test(path.win32.basename(parent).toLowerCase())
102
+ ? path.win32.dirname(parent)
103
+ : parent;
104
+ }
105
+ return null;
106
+ }
107
+ /** A drive-letter (`C:\...`) or UNC path; rooted-but-driveless (`\bin`) and relative paths are not. */
108
+ function isAbsoluteWindowsPath(candidate) {
109
+ return /^[a-z]:[\\/]/iu.test(candidate) || /^[\\/]{2}[^\\/]/u.test(candidate);
110
+ }
111
+ // path.win32 and ";" rather than the host's path module, so the Windows rules are testable anywhere.
112
+ function windowsPathDirectories(pathValue) {
113
+ return pathValue.split(";").map(entry => entry.trim().replace(/^"|"$/gu, "")).filter(Boolean);
114
+ }
115
+ function findOnWindowsPath(pathValue, fileName, fileExists) {
116
+ for (const directory of windowsPathDirectories(pathValue)) {
117
+ const candidate = path.win32.join(directory, fileName);
118
+ if (!isWindowsAppExecutionAliasPath(candidate) && fileExists(candidate))
119
+ return candidate;
120
+ }
121
+ return null;
122
+ }
123
+ function gitBashCandidates(root) {
124
+ return [path.win32.join(root, "bin", "bash.exe"), path.win32.join(root, "usr", "bin", "bash.exe")];
125
+ }
126
+ function standardGitRoots(env) {
127
+ const roots = [
128
+ environmentValue(env, "ProgramFiles"),
129
+ environmentValue(env, "ProgramW6432"),
130
+ environmentValue(env, "ProgramFiles(x86)"),
131
+ ].filter((value) => Boolean(value)).map(value => path.win32.join(value, "Git"));
132
+ const localAppData = environmentValue(env, "LOCALAPPDATA");
133
+ if (localAppData)
134
+ roots.push(path.win32.join(localAppData, "Programs", "Git"));
135
+ roots.push("C:\\Program Files\\Git");
136
+ const seen = new Set();
137
+ return roots.filter(root => !seen.has(root.toLowerCase()) && Boolean(seen.add(root.toLowerCase())));
138
+ }
139
+ /** Windows environment keys are case-insensitive ("Path"), but a copied env object is not. */
140
+ function environmentValue(env, name) {
141
+ if (env[name] !== undefined)
142
+ return env[name];
143
+ const key = Object.keys(env).find(candidate => candidate.toLowerCase() === name.toLowerCase());
144
+ return key === undefined ? undefined : env[key];
145
+ }
146
+ function defaultFileExists(candidate) {
147
+ try {
148
+ return fs.statSync(candidate).isFile();
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
@@ -3,12 +3,11 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { configureDotNetToolchain } from "../shared/process/dotnet-toolchain.js";
6
- import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
7
6
  import { redactText } from "../shared/redaction/redaction.js";
8
7
  import { BridgeRevokedError, bridgeRevokedExitCode, defaultBridgeServiceConfig, ForgeBridgeService, } from "../bridge/bridge.service.js";
9
8
  import { forgeBridgeVersion } from "../version.js";
10
9
  import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
11
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
10
+ import { addRepoMapping, applyLocalConfigDefaults, pairDerivedCapabilities, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
12
11
  import { BridgeSessionService } from "../session/session.service.js";
13
12
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
14
13
  import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
@@ -19,7 +18,7 @@ import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase
19
18
  import { failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
20
19
  import { commandHelpText, helpText } from "./cli.help.js";
21
20
  import { readLocalYieldFlag, writeLocalYieldFlag } from "../bridge/local-yield-flag.js";
22
- import { detectCliProviders } from "./provider-cli-detection.js";
21
+ import { detectKnownCliProviders, knownProviderCandidates, withDetectedCliProviders } from "./provider-cli-advertising.js";
23
22
  import { idleSummaryLine, parseStatusArgs, runIdleStatusCommand } from "./idle-status.js";
24
23
  export { claudeDefaultModels, parseCodexModelCatalog, parseCursorModelList } from "./provider-cli-detection.js";
25
24
  const apiKeySecretGrantEnv = "FORGE_API_KEY_SECRET_GRANT";
@@ -61,7 +60,9 @@ export class ForgeBridgeCliService {
61
60
  return 2;
62
61
  }
63
62
  if (args.command === "connect") {
64
- const config = await withDetectedCliProviders(args.config);
63
+ // Probe every known provider CLI, not only the configured ones, so a CLI installed after
64
+ // pairing gets advertised.
65
+ const config = await withDetectedCliProviders(args.config, knownProviderCandidates(args.config.cliProviders));
65
66
  const missing = [
66
67
  ["server", config.serverUrl],
67
68
  ["runner id", config.runnerId],
@@ -956,7 +957,7 @@ function pairedConfig(current, args, claim) {
956
957
  supportsRunnerAuthoredPhaseArtifacts: current.supportsRunnerAuthoredPhaseArtifacts ?? true,
957
958
  supportsDraftRunOnce: current.supportsDraftRunOnce ?? true,
958
959
  supportsDraftAttachments: current.supportsDraftAttachments ?? true,
959
- supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(args.cliProviders),
960
+ ...pairDerivedCapabilities(current, args.cliProviders),
960
961
  repoMappings: current.repoMappings ?? []
961
962
  };
962
963
  }
@@ -1056,7 +1057,7 @@ async function runStatus(args, io) {
1056
1057
  return args.idle ? await runIdleStatusCommand(args.idle, io) : await writeStatus(args.config, args.checkUpdates, io);
1057
1058
  }
1058
1059
  async function writeStatus(config, checkUpdates, io) {
1059
- const detected = await detectCliProviders([...new Set([...config.cliProviders, "codex", "cursor", "claude"])]);
1060
+ const detected = await detectKnownCliProviders(config.cliProviders);
1060
1061
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
1061
1062
  io.stdout.write(`Forge bridge ${config.version}\n`);
1062
1063
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
@@ -1128,32 +1129,8 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
1128
1129
  }
1129
1130
  return failures === 0 ? 0 : 1;
1130
1131
  }
1131
- async function withDetectedCliProviders(config, candidates = config.cliProviders) {
1132
- const detected = await detectCliProviders(uniqueProviders(candidates));
1133
- const found = detected.filter((result) => result.found);
1134
- if (found.length === 0) {
1135
- return config;
1136
- }
1137
- const cliProviders = uniqueProviders([...config.cliProviders, ...found.map((result) => result.provider)]);
1138
- const providerStatuses = { ...config.providerStatuses };
1139
- for (const result of found) {
1140
- const existing = providerStatuses[result.provider];
1141
- providerStatuses[result.provider] = {
1142
- signedIn: existing?.signedIn ?? true,
1143
- version: result.version || existing?.version || "",
1144
- models: result.models.length > 0
1145
- ? result.models
1146
- : existing?.models ?? providerStatusesFor([result.provider])[result.provider]?.models ?? []
1147
- };
1148
- }
1149
- return {
1150
- ...config,
1151
- cliProviders,
1152
- providerStatuses
1153
- };
1154
- }
1155
1132
  async function withDetectedPairCliProviders(args) {
1156
- const configured = configuredProviderCandidates(args.cliProviders);
1133
+ const configured = knownProviderCandidates(args.cliProviders);
1157
1134
  const detectedConfig = await withDetectedCliProviders({
1158
1135
  ...defaultBridgeServiceConfig({
1159
1136
  serverUrl: args.serverUrl,
@@ -1169,12 +1146,3 @@ async function withDetectedPairCliProviders(args) {
1169
1146
  cliProviders: detectedConfig.cliProviders
1170
1147
  };
1171
1148
  }
1172
- function configuredProviderCandidates(providers) {
1173
- return uniqueProviders([...providers, "codex", "cursor", "claude"]);
1174
- }
1175
- function uniqueProviders(providers) {
1176
- return providers
1177
- .map((provider) => provider.trim())
1178
- .filter((provider) => provider.length > 0)
1179
- .filter((provider, index, all) => all.findIndex((candidate) => candidate.toLowerCase() === provider.toLowerCase()) === index);
1180
- }
@@ -1,4 +1,4 @@
1
- import type { BridgeProviderStatus, BridgeRepoMapping, BridgeServiceConfig } from "../bridge/bridge.types.js";
1
+ import { type BridgeProviderStatus, type BridgeRepoMapping, type BridgeServiceConfig, type DerivedCapabilityField } from "../bridge/bridge.types.js";
2
2
  export interface BridgeLocalConfig {
3
3
  readonly schemaVersion: 1 | 2;
4
4
  readonly serverUrl?: string;
@@ -22,6 +22,13 @@ export interface BridgeLocalConfig {
22
22
  readonly supportsDraftRunOnce?: boolean;
23
23
  readonly supportsDraftAttachments?: boolean;
24
24
  readonly supportsDraftImageAttachments?: boolean;
25
+ /**
26
+ * The capability fields in this file that `pair` derived from cliProviders rather than the user
27
+ * setting them. `connect` may re-derive these when it detects a new provider CLI; any other
28
+ * field present here is the user's choice and is kept. Files written before this marker
29
+ * existed don't have it (see `capabilitySourcesFor`).
30
+ */
31
+ readonly derivedCapabilities?: readonly DerivedCapabilityField[];
25
32
  }
26
33
  export interface LocalRepoMapping extends BridgeRepoMapping {
27
34
  readonly label: string;
@@ -46,3 +53,5 @@ export declare function removeRepoMapping(label: string): Promise<{
46
53
  export declare function setServerUrl(serverUrl: string): Promise<BridgeLocalConfig>;
47
54
  export declare function setSandboxPolicy(dockerEnabled: boolean, allowOpenPublicSandbox: boolean): Promise<BridgeLocalConfig>;
48
55
  export declare function providerStatusesFor(providers: readonly string[]): Readonly<Record<string, BridgeProviderStatus>>;
56
+ /** The capability fields `pair` derives, and marks as derived, when it writes bridge.json. */
57
+ export declare function pairDerivedCapabilities(current: BridgeLocalConfig, cliProviders: readonly string[]): Pick<BridgeLocalConfig, "supportsDraftImageAttachments" | "derivedCapabilities">;
@@ -2,6 +2,8 @@ import fs from "node:fs/promises";
2
2
  import fsSync from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { derivedCapabilityFields, } from "../bridge/bridge.types.js";
6
+ import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
5
7
  import { localYieldFlagPathFor } from "../bridge/local-yield-flag.js";
6
8
  import { bridgeStatePathFor } from "../bridge/bridge-state-file.js";
7
9
  export function resolveLocalConfigPath() {
@@ -84,6 +86,7 @@ export function applyLocalConfigDefaults(config, local) {
84
86
  supportsDraftRunOnce: local.supportsDraftRunOnce ?? config.supportsDraftRunOnce,
85
87
  supportsDraftAttachments: local.supportsDraftAttachments ?? config.supportsDraftAttachments,
86
88
  supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments,
89
+ capabilitySources: capabilitySourcesFor(local),
87
90
  localYieldFlagPath: resolveLocalYieldFlagPath(),
88
91
  bridgeStatePath: resolveBridgeStatePath()
89
92
  };
@@ -170,9 +173,37 @@ function normalizeLocalConfig(config) {
170
173
  supportsRunnerAuthoredPhaseArtifacts: config.supportsRunnerAuthoredPhaseArtifacts,
171
174
  supportsDraftRunOnce: config.supportsDraftRunOnce,
172
175
  supportsDraftAttachments: config.supportsDraftAttachments,
173
- supportsDraftImageAttachments: config.supportsDraftImageAttachments
176
+ supportsDraftImageAttachments: config.supportsDraftImageAttachments,
177
+ derivedCapabilities: Array.isArray(config.derivedCapabilities)
178
+ ? derivedCapabilityFields.filter((field) => config.derivedCapabilities.includes(field))
179
+ : undefined
174
180
  };
175
181
  }
182
+ /** The capability fields `pair` derives, and marks as derived, when it writes bridge.json. */
183
+ export function pairDerivedCapabilities(current, cliProviders) {
184
+ return {
185
+ supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
186
+ derivedCapabilities: derivedCapabilityFields.filter((field) => field === "supportsDraftImageAttachments" || current.derivedCapabilities?.includes(field)),
187
+ };
188
+ }
189
+ /**
190
+ * Where each derived capability's value comes from. A field bridge.json doesn't set comes from the
191
+ * defaults, so it is derived. A field it sets is derived when the file's marker lists it, and the
192
+ * user's choice when the marker doesn't. Without a marker (a file written before it existed) the
193
+ * source is unknown and gets no entry.
194
+ */
195
+ function capabilitySourcesFor(local) {
196
+ const sources = {};
197
+ for (const field of derivedCapabilityFields) {
198
+ if (local[field] === undefined || local.derivedCapabilities?.includes(field)) {
199
+ sources[field] = "derived";
200
+ }
201
+ else if (local.derivedCapabilities !== undefined) {
202
+ sources[field] = "explicit";
203
+ }
204
+ }
205
+ return sources;
206
+ }
176
207
  function emptyConfig() {
177
208
  return {
178
209
  schemaVersion: 2,
@@ -0,0 +1,24 @@
1
+ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
2
+ import { type CliProviderDetection } from "./provider-cli-detection.js";
3
+ /** Every provider CLI the bridge knows how to detect. */
4
+ export declare const knownCliProviders: readonly string[];
5
+ /** The configured providers followed by every known provider, without duplicates. */
6
+ export declare function knownProviderCandidates(providers: readonly string[]): string[];
7
+ /** Probes the configured providers and every known provider, for `forge-bridge status`. */
8
+ export declare function detectKnownCliProviders(configured: readonly string[]): Promise<CliProviderDetection[]>;
9
+ /**
10
+ * Probes `candidates` and adds the ones found to the advertised providers, with their detected
11
+ * version and models.
12
+ *
13
+ * A configured provider that is no longer found stays advertised with its saved status: the probe
14
+ * can miss a CLI that still works (a PATH the bridge's shell doesn't see, a cold-start timeout),
15
+ * and dropping it would take a working runner away. Detection only ever adds providers.
16
+ *
17
+ * Capabilities derived from the provider list (image attachments, default sandbox profiles) are
18
+ * re-derived for the added providers; see `withRederivedCapabilities`.
19
+ *
20
+ * Advertising a provider doesn't mean the bridge will launch it: a provider whose user
21
+ * configuration Forge can't shut out (cursor) is still refused at launch
22
+ * (`provider-user-config-isolation.ts`).
23
+ */
24
+ export declare function withDetectedCliProviders(config: BridgeServiceConfig, candidates?: readonly string[]): Promise<BridgeServiceConfig>;
@@ -0,0 +1,88 @@
1
+ import { defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
2
+ import { providerStatusesFor } from "./local-config.js";
3
+ import { detectCliProviders } from "./provider-cli-detection.js";
4
+ // Which provider CLIs `forge-bridge connect` and `pair` advertise to Forge. Split out of
5
+ // cli.service.ts (file-size inventory plan).
6
+ /** Every provider CLI the bridge knows how to detect. */
7
+ export const knownCliProviders = Object.freeze(["codex", "cursor", "claude"]);
8
+ /** The configured providers followed by every known provider, without duplicates. */
9
+ export function knownProviderCandidates(providers) {
10
+ return uniqueProviders([...providers, ...knownCliProviders]);
11
+ }
12
+ /** Probes the configured providers and every known provider, for `forge-bridge status`. */
13
+ export async function detectKnownCliProviders(configured) {
14
+ return await detectCliProviders(knownProviderCandidates(configured));
15
+ }
16
+ /**
17
+ * Probes `candidates` and adds the ones found to the advertised providers, with their detected
18
+ * version and models.
19
+ *
20
+ * A configured provider that is no longer found stays advertised with its saved status: the probe
21
+ * can miss a CLI that still works (a PATH the bridge's shell doesn't see, a cold-start timeout),
22
+ * and dropping it would take a working runner away. Detection only ever adds providers.
23
+ *
24
+ * Capabilities derived from the provider list (image attachments, default sandbox profiles) are
25
+ * re-derived for the added providers; see `withRederivedCapabilities`.
26
+ *
27
+ * Advertising a provider doesn't mean the bridge will launch it: a provider whose user
28
+ * configuration Forge can't shut out (cursor) is still refused at launch
29
+ * (`provider-user-config-isolation.ts`).
30
+ */
31
+ export async function withDetectedCliProviders(config, candidates = config.cliProviders) {
32
+ const detected = await detectCliProviders(uniqueProviders(candidates));
33
+ const found = detected.filter((result) => result.found);
34
+ if (found.length === 0) {
35
+ return config;
36
+ }
37
+ const cliProviders = uniqueProviders([...config.cliProviders, ...found.map((result) => result.provider)]);
38
+ const providerStatuses = { ...config.providerStatuses };
39
+ for (const result of found) {
40
+ const existing = providerStatuses[result.provider];
41
+ providerStatuses[result.provider] = {
42
+ signedIn: existing?.signedIn ?? true,
43
+ version: result.version || existing?.version || "",
44
+ models: result.models.length > 0
45
+ ? result.models
46
+ : existing?.models ?? providerStatusesFor([result.provider])[result.provider]?.models ?? []
47
+ };
48
+ }
49
+ return withRederivedCapabilities(config, {
50
+ ...config,
51
+ cliProviders,
52
+ providerStatuses
53
+ });
54
+ }
55
+ /**
56
+ * Re-derives the capabilities that `pair` and the config defaults compute from the provider
57
+ * list, so a provider detected at connect gets them (codex's image attachments and sandbox).
58
+ * A field changes only when the added providers change what the list derives, so detection
59
+ * never turns a capability off. Then, by the field's source (`capabilitySources`):
60
+ * - derived: re-derived from the merged list;
61
+ * - explicit (the user set it in bridge.json): kept;
62
+ * - unknown (a bridge.json written before the marker): re-derived only while it still equals
63
+ * what the configured providers derive, since a value that differs must be the user's.
64
+ */
65
+ function withRederivedCapabilities(before, after) {
66
+ const sources = before.capabilitySources ?? {};
67
+ return {
68
+ ...after,
69
+ supportsDraftImageAttachments: rederive(sources.supportsDraftImageAttachments, before.supportsDraftImageAttachments, supportsDraftImageAttachmentsFor(before.cliProviders), supportsDraftImageAttachmentsFor(after.cliProviders), (left, right) => left === right),
70
+ sandboxProfiles: rederive(sources.sandboxProfiles, before.sandboxProfiles, defaultSandboxProfiles(before.cliProviders), defaultSandboxProfiles(after.cliProviders), sameList),
71
+ };
72
+ }
73
+ function rederive(source, current, fromConfigured, fromMerged, same) {
74
+ if (same(fromConfigured, fromMerged) || source === "explicit")
75
+ return current;
76
+ if (source === undefined && !same(current, fromConfigured))
77
+ return current;
78
+ return fromMerged;
79
+ }
80
+ function sameList(left, right) {
81
+ return left.length === right.length && left.every((value, index) => value.toLowerCase() === right[index]?.toLowerCase());
82
+ }
83
+ function uniqueProviders(providers) {
84
+ return providers
85
+ .map((provider) => provider.trim())
86
+ .filter((provider) => provider.length > 0)
87
+ .filter((provider, index, all) => all.findIndex((candidate) => candidate.toLowerCase() === provider.toLowerCase()) === index);
88
+ }
@@ -55,6 +55,11 @@ export interface HostLoadAdmissionDecision {
55
55
  readonly reservedCpuCores: number;
56
56
  readonly reservedMemoryBytes: number;
57
57
  readonly detail: string;
58
+ /**
59
+ * Set on a host test slot wait whose holders are all healthy (owner alive, lease renewed, not retained):
60
+ * the queue is moving, so the wait does not count toward the stalled-wait limit.
61
+ */
62
+ readonly progressing?: boolean;
58
63
  }
59
64
  /**
60
65
  * Decision 0013 admission rule. A step is admitted when the reserved cost of
@@ -18,8 +18,17 @@ export interface HostLoadGovernorConfig {
18
18
  readonly backpressureSamples: number;
19
19
  /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
20
20
  readonly memoryFullThreshold: number;
21
- /** Maximum queue wait before a retryable host_capacity_timeout. */
21
+ /**
22
+ * FORGE_HOST_LOAD_MAX_WAIT_MS: the longest a step waits while its queue is stalled before a retryable
23
+ * host_capacity_timeout. Time spent behind holders of the host test slot that are all healthy (owner
24
+ * alive, lease renewed, not retained) does not count: their steps are making progress.
25
+ */
22
26
  readonly maxWaitMs: number;
27
+ /**
28
+ * FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS: the longest a step may queue in all, healthy holders or not; the
29
+ * backstop for a holder that is alive but never finishes. Never below maxWaitMs.
30
+ */
31
+ readonly maxTotalWaitMs: number;
23
32
  /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
24
33
  readonly fallbackSlots: number;
25
34
  /** After this long at the head of the queue, later waiters may no longer overtake it. */
@@ -9,6 +9,7 @@ export const defaultHostLoadGovernorConfig = {
9
9
  backpressureSamples: 2,
10
10
  memoryFullThreshold: 5,
11
11
  maxWaitMs: 30 * 60_000,
12
+ maxTotalWaitMs: 4 * 60 * 60_000,
12
13
  fallbackSlots: 1,
13
14
  antiStarvationMs: 2 * 60_000,
14
15
  leaseMs: 2 * 60_000,
@@ -27,6 +28,7 @@ export function hostLoadGovernorEnabled(config) {
27
28
  }
28
29
  export function loadHostLoadGovernorConfig(environment = process.env) {
29
30
  const defaults = defaultHostLoadGovernorConfig;
31
+ const maxWaitMs = bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000);
30
32
  return {
31
33
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
34
  testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
@@ -35,7 +37,8 @@ export function loadHostLoadGovernorConfig(environment = process.env) {
35
37
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
36
38
  backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
37
39
  memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
38
- maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
40
+ maxWaitMs,
41
+ maxTotalWaitMs: Math.max(maxWaitMs, bounded(environment.FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS, defaults.maxTotalWaitMs, 1_000, 24 * 60 * 60_000)),
39
42
  fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
40
43
  antiStarvationMs: defaults.antiStarvationMs,
41
44
  leaseMs: defaults.leaseMs,