@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.7171bf414613

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 (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. 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
@@ -160,8 +162,28 @@ managed commands and dependency installs never wait for it. A waiting step repor
160
162
  (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
161
163
  `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
162
164
  A holder that crashes or stalls keeps the slot only until the host load ledger takes its token back (its
163
- process tree stopped, its lease fenced, or attempt teardown). `FORGE_HOST_LOAD_TEST_SLOTS` sets how many
164
- run at once (default 1; `0` turns the slot off).
165
+ process tree stopped, its lease fenced, or attempt teardown).
166
+
167
+ How many run at once is sized from the host, with nothing to set: `min(floor((CPUs - reserve) / 6),
168
+ floor((memory - reserve) / 4 GiB))`, from 1 to 4, where the reserve kept for the system and the person using
169
+ the machine is a quarter of the CPUs (at least 2) and a quarter of the memory (at least 4 GiB). One heavy step
170
+ is planned at 6 cores and 4 GiB: a Forge .NET suite averages about 1.6 cores with peaks well above, and about
171
+ 2.2 GB for the test host and its PostgreSQL. A 24-CPU, 64 GB host runs 3; an 8-CPU, 16 GB or a 4-CPU, 8 GB host
172
+ runs 1. A bridge under a CPU quota or memory limit (a systemd unit, a container, a pod) is sized within it.
173
+ While the bridge runs, the count drops when other work on the machine needs it (two readings in a
174
+ row, about 10 seconds) and comes back one slot at a time after the host has stayed clear for 2 minutes;
175
+ running steps are never stopped. Each reading is judged with the heavy steps running when it was taken, so
176
+ suites that have since finished are not other work. Without a measured Forge share (Windows, or no
177
+ dedicated cgroup), CPU never lowers the count while a heavy step runs (one build can use every core), and
178
+ each running step is taken to use at least its planned memory. On macOS, whose free-memory figure leaves
179
+ out inactive and purgeable memory, memory readings are not used. The bridge and every completion MCP
180
+ server admit against the lowest count any of them has in force; a lowered count lapses 90 seconds after
181
+ its governor stops reading the host, and is ignored once its process exits. With more than one slot, each step gets
182
+ `FORGE_TEST_MAX_PARALLEL_CLASSES` for its share of the
183
+ machine unless it is already set. The bridge logs the count and how it was chosen at startup (`Host test
184
+ slots: …`), and a waiting step says when the count is lowered and why. `FORGE_HOST_LOAD_TEST_SLOTS` is the
185
+ operator's override (`0` turns the slot off; live adjustment only lowers it), and
186
+ `FORGE_HOST_LOAD_LIVE_SLOTS=off` turns live adjustment off.
165
187
 
166
188
  Yield this machine to foreground work (for example while gaming) from the host itself:
167
189
 
@@ -333,6 +355,22 @@ Before selecting `sandbox_required`, save the full approved 40- or 64-character
333
355
 
334
356
  Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
335
357
 
358
+ ### Forge PR reviews run only in the Docker sandbox
359
+
360
+ A Forge PR review reads code its author controls, so it runs only where the bridge isolates it, and today that means the Docker sandbox. Forge decides where a review runs before it offers it to any runner. It places the review in a runner's Docker sandbox when that sandbox can take it, and gives it no publication grant. The sandbox can take it when the project runs in a sandbox (`sandbox_preferred` or `sandbox_required`, so it has the `.forge/forge.sandbox.yml` contract the container is built from; a `host_allowed` project never ran in one, and most have no contract) and the provider can reach its API from it. Either the project's network policy allows the provider's hosts (`public_allowlist`), or the runner approves open public networking (`forge-bridge sandbox on --allow-open-public`), which a review outside `sandbox_required` then uses. The container gets the dispatched head as a bundle with no remote, no git credential and no GitHub token. The review diffs against the merge base of the pull request's base and head, which is always in that bundle; the bridge resolves it with its own git, fetching the base by SHA when needed. Codex runs a review with `danger-full-access` in the container, as every other Docker lane does, because its own Linux sandbox cannot be relied on inside the hardened container; the container is the boundary. On a host, Codex runs a review `read-only`. The bridge does not set up Claude Code's own OS sandbox. If a bridge cannot build the sandbox for a review it was offered anyway, it refuses with the non-retryable `pr_review.sandbox_unavailable`, and Forge does not offer that head to the same runner again.
361
+
362
+ On a plain host the provider runs as your user, next to your git credential store, your GitHub CLI login and every file in your home directory. The review guardrails still apply: the git and `gh` environment, the tool deny list, and the checks that the worktree, the local refs and the pull request branch on `origin` haven't changed. They are defence in depth, though, not a boundary. A push to another remote, or anything read and sent elsewhere, would go unnoticed. So a bridge refuses a review placed on its host with the non-retryable `pr_review.unsandboxed_host` before any provider starts. Forge does not offer that head to the same runner again.
363
+
364
+ If no runner can take the review in its sandbox and none has opted in (below), Forge doesn't run it. The pull request's Forge review status becomes `unavailable`, the timeline records `pr_review.no_isolated_runner`, and the bounded review wait releases the head the same way it releases any review that can't run.
365
+
366
+ To accept unsandboxed reviews on a machine anyway, set this in its `bridge.json` and restart the bridge:
367
+
368
+ ```json
369
+ { "allowUnsandboxedPrReview": true }
370
+ ```
371
+
372
+ The setting defaults to `false` and has no environment override. With it set, the bridge advertises the `pr_review_unsandboxed_host` facility, and Forge places a review on that host when its Docker sandbox can't take it and the project's policy lets work run on the host. The server's Local Runner has no Docker sandbox: it runs a review only in its container sandbox or when it advertises the same facility, and refuses any other review with `pr_review.unsandboxed_host`, as `forge-bridge run-once` does. Each such review logs a warning, emits a `pr_review_unsandboxed_host_warning` event and notes the warning in its session result. Turn it on only on a machine whose credentials and files you are willing to expose to the code under review, such as a disposable VM or a host with no credentials worth stealing.
373
+
336
374
  The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
337
375
 
338
376
  Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
@@ -6,6 +6,10 @@
6
6
  export declare function writeJsonFileAtomically(target: string, value: unknown): Promise<void>;
7
7
  /** True when a process with this id exists. EPERM means it exists but belongs to someone else. */
8
8
  export declare function isProcessAlive(pid: number): boolean;
9
- /** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
10
- export declare function withFsRetry<T>(operation: () => Promise<T>, attempts?: number): Promise<T>;
9
+ /**
10
+ * Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is
11
+ * open. The backoff is jittered so a writer does not keep landing in lockstep with polling
12
+ * readers, and the budget runs on the monotonic clock so a faked `Date` cannot stretch it.
13
+ */
14
+ export declare function withFsRetry<T>(operation: () => Promise<T>, budgetMs?: number): Promise<T>;
11
15
  export declare function errorCode(error: unknown): string;
@@ -32,16 +32,34 @@ export function isProcessAlive(pid) {
32
32
  return errorCode(error) === "EPERM";
33
33
  }
34
34
  }
35
- /** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
36
- export async function withFsRetry(operation, attempts = 8) {
35
+ /**
36
+ * How long an fs call keeps retrying while Windows refuses it. Windows cannot rename over
37
+ * or delete a file that any handle has open, and a reader of a large file holds it open
38
+ * across several chunked reads: on a Windows 11 host, three readers polling a 2 MB state
39
+ * file every few milliseconds kept a rename refused for up to ~0.6 s, past the old ~0.4 s
40
+ * budget. Two seconds rides that out and stays well inside the state file's staleness window.
41
+ */
42
+ const fsRetryBudgetMs = 2_000;
43
+ /** A backstop on top of the time budget. */
44
+ const fsRetryMaxAttempts = 100;
45
+ /**
46
+ * Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is
47
+ * open. The backoff is jittered so a writer does not keep landing in lockstep with polling
48
+ * readers, and the budget runs on the monotonic clock so a faked `Date` cannot stretch it.
49
+ */
50
+ export async function withFsRetry(operation, budgetMs = fsRetryBudgetMs) {
51
+ const deadline = performance.now() + budgetMs;
37
52
  for (let attempt = 1;; attempt += 1) {
38
53
  try {
39
54
  return await operation();
40
55
  }
41
56
  catch (error) {
42
- if (attempt >= attempts || !retryableFsCodes.has(errorCode(error)))
57
+ if (attempt >= fsRetryMaxAttempts || !retryableFsCodes.has(errorCode(error)))
58
+ throw error;
59
+ const delayMs = Math.min(100, 10 * attempt) * (0.5 + Math.random());
60
+ if (performance.now() + delayMs > deadline)
43
61
  throw error;
44
- await new Promise(resolve => setTimeout(resolve, 15 * attempt));
62
+ await new Promise(resolve => setTimeout(resolve, delayMs));
45
63
  }
46
64
  }
47
65
  }
@@ -79,7 +79,11 @@ export declare class ForgeBridgeService implements BridgeService {
79
79
  private hostRequirementFacts;
80
80
  private readonly recoveredHostAttempts;
81
81
  private hostCapabilitiesDetected;
82
+ /** The default session service's host load governor, for the startup capacity log line. */
83
+ private readonly hostLoadGovernor;
82
84
  constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
85
+ /** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
86
+ private detectHostCapabilities;
83
87
  connectOnce(): Promise<void>;
84
88
  private rememberRecoveredHostAttempts;
85
89
  private recoveredHostAttemptsForHello;
@@ -165,6 +169,12 @@ export declare class ForgeBridgeService implements BridgeService {
165
169
  private redeemPublishGrant;
166
170
  private handleLeaseUpdate;
167
171
  private sendOfferDecision;
172
+ /**
173
+ * The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
174
+ * database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
175
+ * without the owner's opt-in. Null when it may run.
176
+ */
177
+ private refusalBeforeRun;
168
178
  private parseDispatchOrReport;
169
179
  private parseChatTurnOrReport;
170
180
  private handleCancel;
@@ -1,20 +1,19 @@
1
- import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
2
1
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
3
2
  import fs from "node:fs";
4
3
  import path from "node:path";
5
4
  import { randomUUID } from "node:crypto";
6
5
  import os from "node:os";
7
6
  import { defaultForgeBridgeConfig } from "../config.js";
8
- import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
7
+ import { bridgeChatCapabilityFor, defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
8
  import { redactText } from "../shared/redaction/redaction.js";
10
- import { BridgeSessionService } from "../session/session.service.js";
11
- import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
9
+ import { formatProviderCliCommandForCheckpoint, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
10
  import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } from "./bridge-chat-provider-command.js";
13
11
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
12
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
- import { PrePublicationValidator } from "../session/pre-publication-validation.js";
13
+ import { describeHostTestSlotCapacity } from "../runtime/host-load-governor.js";
16
14
  import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
- import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
15
+ import { createDefaultSessionService } from "./default-session-service.js";
16
+ import { hostCapacityLimitDefaults, } from "../runtime/host-runtime-lease.js";
18
17
  import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
18
  import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
19
  import { readLocalYieldFlag } from "./local-yield-flag.js";
@@ -22,12 +21,7 @@ import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBo
22
21
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
23
22
  import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
24
23
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
25
- import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
26
- import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
27
24
  import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
28
- import { GitWorktreeService } from "../worktree/worktree.service.js";
29
- import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
30
- import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
31
25
  import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
32
26
  import { forgeBridgeVersion } from "../version.js";
33
27
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
@@ -39,6 +33,7 @@ import { HostLoadSampler } from "../runtime/host-load-sampler.js";
39
33
  import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
40
34
  import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
41
35
  import { BridgeStatePublisher } from "./bridge-state-file.js";
36
+ import { offerPolicyRefusal, prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning, sandboxProfileRefusalCode, unmetHostRuntimeRequirements, } from "./dispatch-offer-policy.js";
42
37
  import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
43
38
  import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
44
39
  export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
@@ -129,6 +124,8 @@ export class ForgeBridgeService {
129
124
  // leaves those attempts on Forge's conservative unknown-outcome path.
130
125
  recoveredHostAttempts = new Map();
131
126
  hostCapabilitiesDetected = false;
127
+ /** The default session service's host load governor, for the startup capacity log line. */
128
+ hostLoadGovernor;
132
129
  constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
133
130
  // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
134
131
  hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
@@ -170,6 +167,7 @@ export class ForgeBridgeService {
170
167
  });
171
168
  const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
172
169
  this.sessions = sessions ?? defaultSessions.sessions;
170
+ this.hostLoadGovernor = defaultSessions?.hostLoadGovernor ?? null;
173
171
  // Docker sandboxes ask the same host load governor for their validation tokens.
174
172
  this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
175
173
  this.sandboxResourceResolver = sandboxResourceResolver
@@ -185,6 +183,13 @@ export class ForgeBridgeService {
185
183
  ...readinessInFlightEntries(this.activeReadinessProbes),
186
184
  ]);
187
185
  }
186
+ /** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
187
+ async detectHostCapabilities() {
188
+ this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
189
+ this.hostCapabilitiesDetected = true;
190
+ if (this.hostLoadGovernor?.enabled)
191
+ logBridgeStatus(describeHostTestSlotCapacity(this.hostLoadGovernor.testSlotCapacity()));
192
+ }
188
193
  async connectOnce() {
189
194
  if (this.revokedReason !== null) {
190
195
  throw new BridgeRevokedError(this.revokedReason);
@@ -210,10 +215,8 @@ export class ForgeBridgeService {
210
215
  }
211
216
  }
212
217
  await this.dockerEngineProbe.refresh(true);
213
- if (!this.hostCapabilitiesDetected) {
214
- this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
215
- this.hostCapabilitiesDetected = true;
216
- }
218
+ if (!this.hostCapabilitiesDetected)
219
+ await this.detectHostCapabilities();
217
220
  // Static host facts and the first load sample ride on Hello; the sampler
218
221
  // keeps refreshing its cached snapshot for later heartbeats.
219
222
  await this.hostLoad.start().catch(() => undefined);
@@ -886,37 +889,16 @@ export class ForgeBridgeService {
886
889
  this.releaseReservedDispatchHandoff(reservationHandoff);
887
890
  return;
888
891
  }
889
- if (this.enforceHostDatabaseCapabilityBoundary) {
890
- try {
891
- assertHostDatabaseCapabilityBoundary();
892
- }
893
- catch (error) {
894
- const message = errorMessage(error);
895
- await this.sendResult(dispatch, failureResult(message, [{
896
- role: "runner",
897
- kind: "error",
898
- content: message,
899
- eventType: "host_database_capability_forbidden",
900
- }], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
901
- this.releaseReservedDispatchHandoff(reservationHandoff);
902
- return;
903
- }
904
- }
905
- let capabilityFailure;
892
+ let refusal;
906
893
  try {
907
- capabilityFailure = await this.requiredCapabilityFailure(dispatch);
894
+ refusal = await this.refusalBeforeRun(dispatch);
908
895
  }
909
896
  catch (error) {
910
897
  this.releaseReservedDispatchHandoff(reservationHandoff);
911
898
  throw error;
912
899
  }
913
- if (capabilityFailure) {
914
- await this.sendResult(dispatch, failureResult(capabilityFailure, [{
915
- role: "runner",
916
- kind: "error",
917
- content: capabilityFailure,
918
- eventType: "docker_engine_unavailable",
919
- }], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
900
+ if (refusal) {
901
+ await this.sendResult(dispatch, refusal).catch(() => undefined);
920
902
  this.releaseReservedDispatchHandoff(reservationHandoff);
921
903
  return;
922
904
  }
@@ -1046,9 +1028,9 @@ export class ForgeBridgeService {
1046
1028
  this.inFlight.notePhase(dispatch.lease.id, "run_once");
1047
1029
  logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1048
1030
  try {
1049
- const result = docker
1050
- ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1051
- : await this.sessions.runOnce(dispatch, sink, signal);
1031
+ const result = await runWithUnsandboxedReviewWarning(dispatch, this.config.allowUnsandboxedPrReview, sink, (warning) => logBridgeStatus(`${warning} ${ids}.`), () => docker
1032
+ ? this.sandboxRuntime.runOnce(dispatch, sink, signal)
1033
+ : this.sessions.runOnce(dispatch, sink, signal));
1052
1034
  if (docker) {
1053
1035
  await this.flushCleanupReports().catch(() => undefined);
1054
1036
  }
@@ -1165,21 +1147,11 @@ export class ForgeBridgeService {
1165
1147
  await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
1166
1148
  return;
1167
1149
  }
1168
- const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
1169
- if (networkFailure) {
1170
- await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
1171
- return;
1172
- }
1173
- const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
1174
- if (providerNetworkFailure) {
1175
- await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
1176
- return;
1177
- }
1178
- const authFailure = sandboxAuthFailure(dispatch, this.config);
1179
- if (authFailure) {
1180
- await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
1181
- return;
1182
- }
1150
+ }
1151
+ const policyRefusal = offerPolicyRefusal(dispatch, this.config, () => sandboxAuthFailure(dispatch, this.config));
1152
+ if (policyRefusal) {
1153
+ await this.sendOfferDecision(dispatch, false, policyRefusal.code, policyRefusal.message);
1154
+ return;
1183
1155
  }
1184
1156
  let requestedResources = sandbox.requestedResources;
1185
1157
  let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
@@ -1191,7 +1163,7 @@ export class ForgeBridgeService {
1191
1163
  sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
1192
1164
  }
1193
1165
  catch (error) {
1194
- await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1166
+ await this.sendOfferDecision(dispatch, false, sandboxProfileRefusalCode(dispatch), error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1195
1167
  return;
1196
1168
  }
1197
1169
  }
@@ -1425,6 +1397,37 @@ export class ForgeBridgeService {
1425
1397
  logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1426
1398
  await this.invokeAck("OfferDecision", payload);
1427
1399
  }
1400
+ /**
1401
+ * The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
1402
+ * database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
1403
+ * without the owner's opt-in. Null when it may run.
1404
+ */
1405
+ async refusalBeforeRun(dispatch) {
1406
+ if (this.enforceHostDatabaseCapabilityBoundary) {
1407
+ try {
1408
+ assertHostDatabaseCapabilityBoundary();
1409
+ }
1410
+ catch (error) {
1411
+ const message = errorMessage(error);
1412
+ return failureResult(message, [{
1413
+ role: "runner",
1414
+ kind: "error",
1415
+ content: message,
1416
+ eventType: "host_database_capability_forbidden",
1417
+ }], failureFactsFromError(error, { source: "bridge" }));
1418
+ }
1419
+ }
1420
+ const capabilityFailure = await this.requiredCapabilityFailure(dispatch);
1421
+ if (capabilityFailure) {
1422
+ return failureResult(capabilityFailure, [{
1423
+ role: "runner",
1424
+ kind: "error",
1425
+ content: capabilityFailure,
1426
+ eventType: "docker_engine_unavailable",
1427
+ }], failureFactsForCode("docker_engine_unavailable"));
1428
+ }
1429
+ return prReviewPlacementRefusalResult(dispatch, this.config.allowUnsandboxedPrReview);
1430
+ }
1428
1431
  async parseDispatchOrReport(rawDispatch) {
1429
1432
  try {
1430
1433
  return parseRunOnceDispatchPacket(rawDispatch);
@@ -2046,7 +2049,7 @@ export class ForgeBridgeService {
2046
2049
  sandboxProfiles: this.config.sandboxProfiles,
2047
2050
  runnerInstanceId: this.config.runnerInstanceId,
2048
2051
  trustDomainId: this.config.trustDomainId,
2049
- executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
2052
+ executionFacilities: [...(dockerEngine?.available ? ["docker_engine"] : []), ...prReviewExecutionFacilities(this.config.allowUnsandboxedPrReview)],
2050
2053
  dockerEngine,
2051
2054
  toolchains: {
2052
2055
  ...this.hostCapabilities.toolchains,
@@ -2299,14 +2302,6 @@ function isProviderStorageUnavailable(error) {
2299
2302
  function isBridgeCallbackTimeout(error) {
2300
2303
  return errorMessage(error).startsWith("bridge_callback_timeout:");
2301
2304
  }
2302
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
2303
- const rawProcessRunner = new StreamingProviderProcessRunner();
2304
- const processSupervisors = new AttemptProcessSupervisorRegistry();
2305
- const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
2306
- const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2307
- const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2308
- return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
2309
- }
2310
2305
  export class SignalRBridgeConnectionFactory {
2311
2306
  create(config) {
2312
2307
  return new SignalRBridgeConnection(config);
@@ -2532,14 +2527,6 @@ function providerStatus(config, provider) {
2532
2527
  return Object.entries(config.providerStatuses)
2533
2528
  .find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
2534
2529
  }
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
2530
  function configuredModelsFor(provider) {
2544
2531
  const envName = `FORGE_${provider.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase()}_MODELS`;
2545
2532
  return splitCsv(process.env[envName] ?? "");
@@ -2879,21 +2866,6 @@ function containsIgnoreCase(values, value) {
2879
2866
  export function canReapManagedSandboxes(preflight) {
2880
2867
  return canRunDockerMaintenance(preflight);
2881
2868
  }
2882
- function sandboxNetworkPolicyFailure(dispatch, config) {
2883
- const sandbox = dispatch.sandbox;
2884
- if (!sandbox)
2885
- return "Protocol-v2 sandbox context is missing.";
2886
- if (sandbox.networkPolicy.mode === "open_public"
2887
- && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
2888
- return "open_public sandbox networking is not permitted by this runner policy.";
2889
- }
2890
- if (sandbox.networkPolicy.mode === "public_allowlist"
2891
- && sandbox.networkPolicy.allowedHosts.length > 0
2892
- && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
2893
- return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
2894
- }
2895
- return null;
2896
- }
2897
2869
  export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
2898
2870
  if (!requiredCapabilities.includes("docker_engine"))
2899
2871
  return null;
@@ -2930,16 +2902,6 @@ function parseReadinessProbe(value) {
2930
2902
  }
2931
2903
  return request;
2932
2904
  }
2933
- function sandboxProviderNetworkFailure(dispatch, config) {
2934
- const sandbox = dispatch.sandbox;
2935
- if (!sandbox || sandbox.networkPolicy.mode !== "offline")
2936
- return null;
2937
- const provider = dispatch.execution.provider.trim().toLowerCase();
2938
- const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
2939
- if (!isNetworkProvider)
2940
- return null;
2941
- return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
2942
- }
2943
2905
  function sandboxAuthFailure(dispatch, config) {
2944
2906
  const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2945
2907
  if (unsupported) {
@@ -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;
@@ -19,6 +23,12 @@ export interface BridgeServiceConfig {
19
23
  readonly sandboxPidCapacity: number;
20
24
  readonly dockerEnabled: boolean;
21
25
  readonly allowOpenPublicSandbox: boolean;
26
+ /**
27
+ * The runner owner accepts Forge PR reviews placed on this host, outside the Docker sandbox, where the
28
+ * provider reads author-controlled code with this user's credentials in reach. Default false: such a
29
+ * review is refused (pr-review-placement.ts).
30
+ */
31
+ readonly allowUnsandboxedPrReview?: boolean;
22
32
  readonly sandboxPublicationMode?: "bridge_push" | "shared_filesystem";
23
33
  readonly dockerExecutable: string;
24
34
  readonly dockerContext: string;
@@ -58,6 +68,12 @@ export interface BridgeServiceConfig {
58
68
  readonly supportsDraftRunOnce: boolean;
59
69
  readonly supportsDraftAttachments: boolean;
60
70
  readonly supportsDraftImageAttachments: boolean;
71
+ /**
72
+ * Where each provider-derived capability's value came from: "derived" from the provider list
73
+ * (pair or the defaults) or "explicit" (set by the user in bridge.json). A field with no entry
74
+ * comes from a bridge.json written before the marker existed, so its source is unknown.
75
+ */
76
+ readonly capabilitySources?: Readonly<Partial<Record<DerivedCapabilityField, CapabilitySource>>>;
61
77
  readonly bridgeChat: BridgeChatCapability;
62
78
  readonly version: string;
63
79
  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"];
@@ -0,0 +1,13 @@
1
+ import type { SessionService } from "../session/session.base.js";
2
+ import type { HostLoadGovernor } from "../runtime/host-load-governor.js";
3
+ import type { HostLoadSource } from "../runtime/host-load-sampler.js";
4
+ import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
5
+ /**
6
+ * The session service a bridge builds when none is injected, wired to one host load governor
7
+ * (the host runtime's): worktree builds, pre-publication validation and host runtimes all ask
8
+ * it for capacity. The governor is returned too, for the bridge's startup capacity log line.
9
+ */
10
+ export declare function createDefaultSessionService(sandboxStateRoot: string, sandboxExecutionRoot: string, dockerEngineProbe: DockerEngineProbe, hostLoad: HostLoadSource): {
11
+ readonly sessions: SessionService;
12
+ readonly hostLoadGovernor: HostLoadGovernor;
13
+ };
@@ -0,0 +1,22 @@
1
+ import { BridgeSessionService } from "../session/session.service.js";
2
+ import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
3
+ import { PrePublicationValidator } from "../session/pre-publication-validation.js";
4
+ import { HostRuntimeLeaseManager } from "../runtime/host-runtime-lease.js";
5
+ import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
6
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
7
+ import { GitWorktreeService } from "../worktree/worktree.service.js";
8
+ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
9
+ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
10
+ /**
11
+ * The session service a bridge builds when none is injected, wired to one host load governor
12
+ * (the host runtime's): worktree builds, pre-publication validation and host runtimes all ask
13
+ * it for capacity. The governor is returned too, for the bridge's startup capacity log line.
14
+ */
15
+ export function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
16
+ const rawProcessRunner = new StreamingProviderProcessRunner();
17
+ const processSupervisors = new AttemptProcessSupervisorRegistry();
18
+ const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
19
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
20
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
21
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
22
+ }
@@ -0,0 +1,22 @@
1
+ export { unmetHostRuntimeRequirements, type HostRequirementFacts } from "../runtime/host-runtime-requirements-check.js";
2
+ export { prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning } from "../session/pr-review-placement.js";
3
+ import type { RunOnceDispatchPacket } from "../session/session.types.js";
4
+ import type { BridgeServiceConfig } from "./bridge.types.js";
5
+ export interface OfferRefusal {
6
+ readonly code: string;
7
+ readonly message: string;
8
+ }
9
+ /**
10
+ * Why this runner refuses an offer on policy, after its Docker preflight passed: a Forge PR review placed
11
+ * outside the Docker sandbox without the owner's opt-in, then, for a Docker offer, its network policy, the
12
+ * provider's need for a network, and the provider's auth (`authFailure`). Null when it may take the offer.
13
+ */
14
+ export declare function offerPolicyRefusal(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig, authFailure: () => string | null): OfferRefusal | null;
15
+ /**
16
+ * The code a Docker offer is refused with when its sandbox contract cannot be profiled: a capacity wait for
17
+ * ordinary work, but for a Forge PR review the non-retryable refusal Forge remembers for this runner and head.
18
+ */
19
+ export declare function sandboxProfileRefusalCode(dispatch: RunOnceDispatchPacket): string;
20
+ /** Why this runner refuses a Docker offer under its network policy, or null. */
21
+ export declare function sandboxNetworkPolicyFailure(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig): string | null;
22
+ export declare function sandboxProviderNetworkFailure(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig): string | null;
@@ -0,0 +1,58 @@
1
+ // What a runner checks before it takes a dispatch: the host runtime requirements, a Docker offer's network
2
+ // policy, and where a Forge PR review may run (pr-review-placement.ts).
3
+ export { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
4
+ export { prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning } from "../session/pr-review-placement.js";
5
+ import { isPrReviewDispatch, prReviewPlacementRefusalResult, prReviewSandboxUnavailableCode } from "../session/pr-review-placement.js";
6
+ /**
7
+ * Why this runner refuses an offer on policy, after its Docker preflight passed: a Forge PR review placed
8
+ * outside the Docker sandbox without the owner's opt-in, then, for a Docker offer, its network policy, the
9
+ * provider's need for a network, and the provider's auth (`authFailure`). Null when it may take the offer.
10
+ */
11
+ export function offerPolicyRefusal(dispatch, config, authFailure) {
12
+ const review = prReviewPlacementRefusalResult(dispatch, config.allowUnsandboxedPrReview)?.failure;
13
+ if (review)
14
+ return { code: review.code, message: review.message };
15
+ if (dispatch.sandbox?.executionMode !== "docker")
16
+ return null;
17
+ const network = sandboxNetworkPolicyFailure(dispatch, config);
18
+ if (network)
19
+ return { code: "policy_mismatch", message: network };
20
+ const providerNetwork = sandboxProviderNetworkFailure(dispatch, config);
21
+ if (providerNetwork)
22
+ return { code: "provider_network_policy_denied", message: providerNetwork };
23
+ const auth = authFailure();
24
+ return auth ? { code: "sandbox_auth_unavailable", message: auth } : null;
25
+ }
26
+ /**
27
+ * The code a Docker offer is refused with when its sandbox contract cannot be profiled: a capacity wait for
28
+ * ordinary work, but for a Forge PR review the non-retryable refusal Forge remembers for this runner and head.
29
+ */
30
+ export function sandboxProfileRefusalCode(dispatch) {
31
+ return isPrReviewDispatch(dispatch) ? prReviewSandboxUnavailableCode : "sandbox_capacity_profile_unavailable";
32
+ }
33
+ /** Why this runner refuses a Docker offer under its network policy, or null. */
34
+ export function sandboxNetworkPolicyFailure(dispatch, config) {
35
+ const sandbox = dispatch.sandbox;
36
+ if (!sandbox)
37
+ return "Protocol-v2 sandbox context is missing.";
38
+ if (sandbox.networkPolicy.mode === "open_public"
39
+ && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
40
+ return "open_public sandbox networking is not permitted by this runner policy.";
41
+ }
42
+ if (sandbox.networkPolicy.mode === "public_allowlist"
43
+ && sandbox.networkPolicy.allowedHosts.length > 0
44
+ && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
45
+ return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
46
+ }
47
+ return null;
48
+ }
49
+ export function sandboxProviderNetworkFailure(dispatch, config) {
50
+ const sandbox = dispatch.sandbox;
51
+ if (!sandbox || sandbox.networkPolicy.mode !== "offline")
52
+ return null;
53
+ const provider = dispatch.execution.provider.trim().toLowerCase();
54
+ const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
55
+ if (!isNetworkProvider)
56
+ return null;
57
+ return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
58
+ }