@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
package/README.md CHANGED
@@ -23,6 +23,16 @@ forge-bridge status
23
23
  forge-bridge connect --server <forge-url> --runner-id <runner-id> --device-token <device-token>
24
24
  ```
25
25
 
26
+ To pair, open **Settings → Runners → Connect a bridge** in Forge and run the command it shows:
27
+
28
+ ```bash
29
+ forge-bridge pair <code> --server <forge-url>
30
+ ```
31
+
32
+ The runner name, provider CLIs and repo folder chosen in that dialog come back with the claim
33
+ and are saved to `bridge.json`; `--repo-root` and `--cli-provider` on the command line win over
34
+ them. `bridge.json` holds the device token, so the bridge writes it with mode `0600`.
35
+
26
36
  The bridge can also read connection settings from environment variables:
27
37
 
28
38
  - `FORGE_URL`
@@ -55,7 +65,7 @@ The bridge auto-detects these provider CLIs on `PATH` and advertises the ones it
55
65
 
56
66
  Claude Code notes:
57
67
 
58
- - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. `CLAUDE_CONFIG_DIR` is passed through if you keep config outside `~/.claude`.
68
+ - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. Forge doesn't pass `CLAUDE_CONFIG_DIR` to Claude Code, so it signs in from `~/.claude` (`%USERPROFILE%\.claude` on Windows) or with an Anthropic API key Forge grants; sign in there, not in a custom config directory.
59
69
  - Forge pipes the prompt on stdin, runs with `--permission-mode bypassPermissions` inside the managed worktree, and registers its completion MCP server through a temporary `--mcp-config` file outside the worktree with `--strict-mcp-config`, so user-level MCP servers are not loaded into unattended runs. Forge tools appear to the model as `mcp__forge__<tool>`.
60
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.
61
71
  - Claude runs in host mode only. Docker sandbox placement currently supports Codex only.
@@ -129,6 +139,137 @@ enters a ten-minute cooldown after an unsuccessful attempt. Remote `DOCKER_HOST`
129
139
  restarted. Operators can tune the bounded policy with `FORGE_DOCKER_RECOVERY_FAILURE_THRESHOLD`,
130
140
  `FORGE_DOCKER_RECOVERY_COOLDOWN_MS`, and `FORGE_DOCKER_RECOVERY_STARTUP_TIMEOUT_MS`.
131
141
 
142
+ ## Runner limits and yield
143
+
144
+ Forge owns each runner's limits (Settings → Runners → Limits) and pushes them to the bridge, which
145
+ applies them without a restart and without stopping admitted work: max attempts and the memory reserve
146
+ apply at the next attempt admission, the CPU budget, yield budget and max heavy steps at the next heavy
147
+ step. Host env vars only bound the server's values and are reported back to Forge: a ceiling on
148
+ capacity (`FORGE_HOST_MAX_CONCURRENT_ATTEMPTS`, `FORGE_HOST_CPU_BUDGET_PERCENT`,
149
+ `FORGE_HOST_LOAD_CPU_BUDGET_FRACTION`, `FORGE_HOST_MAX_HEAVY_STEPS`) and a floor on the reserve
150
+ (`FORGE_HOST_MEMORY_RESERVE_BYTES`). Without a server value, the env var or the bridge default applies.
151
+ The CPU budget, yield budget and heavy-step limit take effect only with `FORGE_HOST_LOAD_GOVERNOR=on`.
152
+ They gate on Linux PSI. Windows has no PSI, so a Windows bridge estimates CPU pressure from whole-host
153
+ CPU use and reports it with `pressureSource: "windows_estimate"` (decision 0021). Forge's Load column
154
+ and the budgets then work there too. Without either signal, the governor falls back to one heavy step at a time.
155
+
156
+ Two or more attempts on one host take turns at the host test slot (decision 0018): builds, test runs,
157
+ Playwright, pre-publication checks and the ASP.NET runtime build each wait for it in one host-wide queue,
158
+ foreground first, then first come, first served, across the bridge and every completion MCP server. Plain
159
+ managed commands and dependency installs never wait for it. A waiting step reports who holds the slot
160
+ (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
161
+ `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
162
+ 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
+
166
+ Yield this machine to foreground work (for example while gaming) from the host itself:
167
+
168
+ ```bash
169
+ forge-bridge yield on
170
+ forge-bridge yield status
171
+ forge-bridge yield off
172
+ ```
173
+
174
+ While yielding, the bridge takes no new attempts and heavy steps of running attempts use the yield CPU
175
+ budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
176
+ in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
177
+
178
+ ## Restarting or updating the bridge safely
179
+
180
+ Restarting `forge-bridge connect` kills everything it is running, including work that has no agent
181
+ process yet: an accepted offer waiting for Start, host-runtime admission, worktree and dependency
182
+ preparation, prepared-runtime probes, pre-publication validation and teardown. Forge then records the
183
+ attempt's outcome as unknown. Checking for agent processes is not enough, so the running bridge
184
+ publishes its in-flight work to `bridge.state.json` next to `bridge.json` (pid, runner instance, a
185
+ heartbeat refreshed every 5 seconds, and each in-flight item with its ids, phase and start time), and
186
+ `forge-bridge status --idle` reads it. Each bridge reads and rewrites the file while it holds a lock
187
+ the operating system owns and frees when the bridge exits (an abstract socket on Linux, a named pipe
188
+ on Windows, a flock on `bridge.state.json.lock` on macOS), so a second bridge on the same config always
189
+ sees the first one's record and reports the conflict, and a stopping bridge never writes its "stopped"
190
+ record over a newer bridge's. A bridge that can't publish (a failed write, or the lock held by another
191
+ process for more than 5 seconds) leaves `bridge.state.json.unpublished.<id>.json` instead of touching
192
+ the shared record, and a record missing any field reads as unknown, so neither can read as idle:
193
+
194
+ | Exit code | Verdict | Meaning |
195
+ |---:|---|---|
196
+ | 0 | `idle` | A live bridge reported a fresh heartbeat with nothing in flight. |
197
+ | 1 | `busy` | Work is in flight; restarting now would kill it. |
198
+ | 2 | | Usage error. |
199
+ | 3 | `stale` / `unknown` | Old heartbeat (hung bridge or reused pid), missing or unreadable state file, two bridge processes publishing to one config, or the bridge is shutting down. Idle can't be confirmed. A bridge older than this check writes no state file, so it reads as `unknown`. |
200
+ | 4 | `not_running` | The recorded bridge process has exited. Nothing to interrupt, but it is not an idle report. |
201
+ | 5 | `not_yielding` | With `--require-yield`: nothing in flight, but Forge has not acknowledged yield from this bridge, so placement can still pick it. |
202
+
203
+ `--json` prints the verdict, the reason, the heartbeat age, the pid check, the yield state (`yielding`:
204
+ acknowledged by Forge; `yieldApplied`: applied by the bridge) and the in-flight list. `--wait <seconds>`
205
+ keeps checking until the bridge is idle, its process has exited, or the time is up, so a file briefly
206
+ held by antivirus or the indexer doesn't end the wait; `--wait 0` checks once, like no `--wait`.
207
+ Against a bridge older than this check (no state file) it waits out the full time; check once without
208
+ `--wait` first.
209
+
210
+ What yield does and doesn't stop:
211
+
212
+ - It stops new attempts: the bridge refuses Offers while yielding (Forge re-places them), and Forge
213
+ stops placing work on the runner once it has acknowledged the yield (the next heartbeat or settings
214
+ report, at most about 30 seconds). `--require-yield` waits for that acknowledgement.
215
+ - It defers background runtime-readiness probes; Forge retries them after yield is off.
216
+ - It doesn't stop a Bridge Chat turn whose chat lease is already bound to this runner: Forge has no
217
+ retry for a refused turn, so the bridge runs it, and `status --idle` reports it as busy until it ends.
218
+ - It doesn't stop a legacy `Dispatch`, which Forge sends only to protocol-1 bridges. This bridge
219
+ registers a newer protocol, so it receives Offer and Start instead. A legacy dispatch is still
220
+ counted as busy.
221
+ - Attempts already running finish normally.
222
+
223
+ Restart procedure: yield, wait for idle, restart, then turn yield off once the new bridge has connected
224
+ (the flag file survives the restart, so the new bridge starts yielded and takes no work until then).
225
+ If the wait fails, turn yield off again so the runner doesn't stay out of placement, or leave it on
226
+ deliberately and retry later.
227
+ Run the commands as the same user and with the same `FORGE_BRIDGE_CONFIG` as the bridge so they use its
228
+ `bridge.json`, `bridge.yield.json` and `bridge.state.json`. On Windows, a shell inside an MSIX-packaged
229
+ app can have `%APPDATA%` writes virtualized away from the bridge; `--require-yield` catches that, because
230
+ the yield has to be applied by the bridge and acknowledged by Forge.
231
+
232
+ Linux or macOS:
233
+
234
+ ```bash
235
+ forge-bridge yield on
236
+ if forge-bridge status --idle --require-yield --wait 3600; then
237
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
238
+ forge-bridge yield off # once the new bridge has connected
239
+ else
240
+ code=$?
241
+ forge-bridge yield off # don't leave the runner out of placement
242
+ echo "Bridge is not idle (exit $code); not restarting." >&2
243
+ fi
244
+ ```
245
+
246
+ Windows PowerShell:
247
+
248
+ ```powershell
249
+ forge-bridge yield on
250
+ forge-bridge status --idle --require-yield --wait 3600
251
+ $code = $LASTEXITCODE
252
+ if ($code -eq 0) {
253
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
254
+ forge-bridge yield off # once the new bridge has connected
255
+ } else {
256
+ forge-bridge yield off # don't leave the runner out of placement
257
+ Write-Error "Bridge is not idle (exit $code); not restarting."
258
+ }
259
+ ```
260
+
261
+ The bridge also logs each accepted offer, each accepted dispatch and the start and end of each run,
262
+ with the dispatch attempt, lease, session and cycle ids.
263
+
264
+ ## Pre-publication repair
265
+
266
+ Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
267
+ `.forge/validation/ci-parity.v1.json`. A failed check does not stop the pass: the other checks still
268
+ run, except those that need what failed (the OpenAPI export and E2E after a .NET compile failure, E2E
269
+ after a failed runtime restart). The provider thread then gets one in-place repair turn that lists
270
+ every failed check. A Work Order holds after `FORGE_PREPUBLICATION_REPAIR_TURNS` repair turns (a whole
271
+ number from 1, capped at 10; default 4) if validation still fails.
272
+
132
273
  ## Docker sandbox runners
133
274
 
134
275
  Protocol-v2 bridges preflight Docker before advertising the `docker` sandbox runtime. Validate a repository contract and the local runner before enabling a project's `sandbox_required` policy:
@@ -0,0 +1,19 @@
1
+ import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ChatTurnDispatchPacket } from "./bridge-chat.types.js";
3
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
4
+ export declare const chatTurnMetadataFileName = "forge-chat-metadata.json";
5
+ /**
6
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
7
+ * turn never delivered its answer, so it must not be reported as one.
8
+ */
9
+ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunResult, "terminalStopReason">): void;
10
+ export interface ChatProviderCommandPlan {
11
+ readonly command: ProviderCliCommand;
12
+ readonly stdin?: string;
13
+ /**
14
+ * Provider environment: the host's .NET build lock (host-build-lock.ts), Codex's own home, and
15
+ * the headless background-work restrictions for Claude.
16
+ */
17
+ readonly env?: Readonly<Record<string, string>>;
18
+ }
19
+ export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string): ChatProviderCommandPlan;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Builds the provider command for a Bridge Chat turn: the CLI invocation for the turn's provider
3
+ * and the prompt that carries the conversation, its context references and its bounded handoff
4
+ * metadata.
5
+ */
6
+ import { claudeHeadlessEnvironment, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
+ import { hostDotnetBuildLockEnvironment, hostDotnetBuildLockInstruction } from "../session/provider-cli/host-build-lock.js";
8
+ import { claudeIsolatedLaunchArgs, providerUserConfigIsolationUnsupported, providerUserConfigIsolationEnv } from "../session/provider-cli/provider-user-config-isolation.js";
9
+ import { codexSandboxModeForPlatform, providerEffort } from "../session/provider-cli/provider-cli.prompts.js";
10
+ import { chatProviderKind } from "./bridge-chat.types.js";
11
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
12
+ export const chatTurnMetadataFileName = "forge-chat-metadata.json";
13
+ /**
14
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
15
+ * turn never delivered its answer, so it must not be reported as one.
16
+ */
17
+ export function assertChatTurnFinished(result) {
18
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
19
+ throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
20
+ }
21
+ }
22
+ export function buildChatProviderCommand(packet, cwd) {
23
+ // The provider kind picks the CLI and its effort levels; an auth-path suffix such as `:bridge` does not.
24
+ const provider = chatProviderKind(packet.providerKind);
25
+ const model = packet.model.trim();
26
+ const prompt = buildChatPrompt(packet);
27
+ const resumeThreadId = packet.providerThreadId?.trim() || null;
28
+ // Levels the provider does not accept are dropped, so the CLI keeps its own default.
29
+ const effort = providerEffort(provider, packet.effort);
30
+ if (provider === "codex") {
31
+ const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
32
+ if (resumeThreadId) {
33
+ args.push("--cd", cwd, "resume");
34
+ }
35
+ args.push("--model", model);
36
+ if (effort) {
37
+ args.push("-c", `model_reasoning_effort=${JSON.stringify(effort)}`);
38
+ }
39
+ args.push("--json");
40
+ if (!resumeThreadId) {
41
+ args.push("--cd", cwd);
42
+ }
43
+ args.push("--skip-git-repo-check");
44
+ if (resumeThreadId) {
45
+ args.push(resumeThreadId);
46
+ }
47
+ args.push("-");
48
+ // Codex runs with Forge's own CODEX_HOME, not the user's ~/.codex (provider-user-config-isolation.ts).
49
+ return { command: { command: "codex", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...providerUserConfigIsolationEnv("codex") } };
50
+ }
51
+ if (provider === "claude") {
52
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model];
53
+ if (effort) {
54
+ args.push("--effort", effort);
55
+ }
56
+ // Only Forge's context and no MCP servers (provider-user-config-isolation.ts).
57
+ args.push("--permission-mode", "bypassPermissions", ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }));
58
+ if (resumeThreadId) {
59
+ args.push("--resume", resumeThreadId);
60
+ }
61
+ return { command: { command: "claude", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...claudeHeadlessEnvironment } };
62
+ }
63
+ // cursor-agent and other CLIs can't be kept from the host user's own configuration.
64
+ throw providerUserConfigIsolationUnsupported(packet.providerKind);
65
+ }
66
+ function buildChatPrompt(packet) {
67
+ const messages = packet.messages
68
+ .map((message, index) => {
69
+ const role = message.role.trim() || `message-${index + 1}`;
70
+ return `[${role}]\n${message.content}`;
71
+ })
72
+ .join("\n\n");
73
+ const contextRefs = packet.contextRefs.length === 0
74
+ ? ""
75
+ : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
76
+ const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
77
+ const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
78
+ return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
79
+ }).join("\n\n")}`;
80
+ const continuation = packet.providerThreadId
81
+ ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
82
+ : "";
83
+ const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
84
+ // Chat turns run on the bridge's host, so they follow its .NET build lock like session turns.
85
+ const buildLock = hostDotnetBuildLockInstruction(process.env, "chat");
86
+ const hostRules = buildLock ? `\n\n# Host rules\n${buildLock}` : "";
87
+ return `You are handling a Forge Bridge Chat turn.
88
+
89
+ Conversation ID: ${packet.conversationId}
90
+ Turn ID: ${packet.turnId}
91
+ Provider: ${packet.providerKind}
92
+ Model: ${packet.model}${continuation}${boundedMetadata}${hostRules}
93
+
94
+ # Conversation
95
+
96
+ ${messages}${contextRefs}
97
+ `;
98
+ }
99
+ function buildChatBoundedMetadataPrompt(packet) {
100
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
101
+ return "";
102
+ }
103
+ const sections = [
104
+ `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
105
+ ];
106
+ if (packet.attachmentHandoffs.length > 0) {
107
+ sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
108
+ `${index + 1}. turnId: ${handoff.turnId}`,
109
+ ` attachmentId: ${handoff.attachmentId}`,
110
+ ` tempFileToken: ${handoff.tempFileToken}`,
111
+ ` mimeType: ${handoff.mimeType}`,
112
+ ` sizeBytes: ${handoff.sizeBytes}`,
113
+ ` sha256: ${handoff.sha256}`,
114
+ ` fileNameDisplay: ${handoff.fileNameDisplay}`,
115
+ ` expiresAt: ${handoff.expiresAt}`,
116
+ ` status: ${handoff.status}`,
117
+ ].join("\n")).join("\n\n")}`);
118
+ }
119
+ if (packet.actionBrokerGrants.length > 0) {
120
+ sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
121
+ `${index + 1}. grantId: ${grant.grantId}`,
122
+ ` turnId: ${grant.turnId}`,
123
+ ` leaseId: ${grant.leaseId}`,
124
+ ` fencingToken: ${grant.fencingToken}`,
125
+ ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
126
+ ` expiresAt: ${grant.expiresAt}`,
127
+ ` redactionStatus: ${grant.redactionStatus}`,
128
+ " nonce: held by bridge",
129
+ ].join("\n")).join("\n\n")}`);
130
+ }
131
+ return sections.join("\n\n");
132
+ }
@@ -35,6 +35,11 @@ export interface ChatTurnDispatchPacket {
35
35
  readonly contextRefs: readonly ChatTurnContextRef[];
36
36
  readonly idempotencyKey: string;
37
37
  readonly providerThreadId?: string | null;
38
+ /**
39
+ * The Chat role's reasoning effort for this provider and model, or null for the provider default.
40
+ * Older servers omit it. The command builder drops levels the provider does not accept.
41
+ */
42
+ readonly effort?: string | null;
38
43
  readonly protocolVersion: typeof bridgeChatProtocolVersion;
39
44
  readonly requestedCapabilities: readonly BridgeChatRequestedCapability[];
40
45
  readonly attachmentHandoffs: readonly ChatAttachmentHandoffHandle[];
@@ -107,5 +112,10 @@ export interface ChatTurnCancelPacket {
107
112
  export declare function unavailableBridgeChatCapability(protocolVersion?: string, unavailableCode?: string | null, unavailableReason?: string | null): BridgeChatCapability;
108
113
  export declare function normalizeBridgeChatCapability(value: BridgeChatCapability | null | undefined): BridgeChatCapability;
109
114
  export declare function parseChatTurnDispatchPacket(value: unknown, capability?: BridgeChatCapability): ChatTurnDispatchPacket;
115
+ /**
116
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
117
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
118
+ */
119
+ export declare function chatProviderKind(provider: string): string;
110
120
  export declare function isTerminalChatTurnCallbackKind(kind: ChatTurnCallbackKind): boolean;
111
121
  export declare function assertBridgeChatCallbackPayload(value: unknown, label?: string): void;
@@ -87,18 +87,26 @@ export function parseChatTurnDispatchPacket(value, capability = unavailableBridg
87
87
  leaseId,
88
88
  fencingToken,
89
89
  runnerInstanceId: requiredUuid(packet, "runnerInstanceId"),
90
- providerKind: requiredString(packet, "providerKind").trim().toLowerCase(),
90
+ providerKind: requiredProviderKind(packet),
91
91
  model: requiredString(packet, "model").trim(),
92
92
  messages,
93
93
  contextRefs,
94
94
  idempotencyKey: requiredString(packet, "idempotencyKey").trim(),
95
95
  providerThreadId: optionalString(packet, "providerThreadId", bridgeChatMaxProviderThreadIdChars),
96
+ effort: optionalString(packet, "effort")?.toLowerCase() ?? null,
96
97
  protocolVersion: bridgeChatProtocolVersion,
97
98
  requestedCapabilities,
98
99
  attachmentHandoffs,
99
100
  actionBrokerGrants,
100
101
  };
101
102
  }
103
+ /**
104
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
105
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
106
+ */
107
+ export function chatProviderKind(provider) {
108
+ return (provider.split(":", 1)[0] ?? "").trim().toLowerCase();
109
+ }
102
110
  export function isTerminalChatTurnCallbackKind(kind) {
103
111
  return kind === "output_completed" || kind === "failed" || kind === "cancelled" || kind === "expired";
104
112
  }
@@ -304,6 +312,13 @@ function requiredUuid(source, key) {
304
312
  }
305
313
  return value;
306
314
  }
315
+ function requiredProviderKind(source) {
316
+ const kind = chatProviderKind(requiredString(source, "providerKind"));
317
+ if (kind.length === 0) {
318
+ throw new Error("providerKind must be a non-empty string.");
319
+ }
320
+ return kind;
321
+ }
307
322
  function requiredString(source, key) {
308
323
  const value = source[key];
309
324
  if (typeof value !== "string" || value.trim().length === 0) {
@@ -0,0 +1,161 @@
1
+ import { type InFlightEntry } from "./in-flight-registry.js";
2
+ import { type BridgeStateLockOptions } from "./bridge-state-lock.js";
3
+ import { type UnpublishedMarker } from "./bridge-state-unpublished.js";
4
+ export { isProcessAlive } from "./bridge-state-io.js";
5
+ export declare const bridgeStateSchemaVersion = 1;
6
+ export declare const defaultStatePublishIntervalMs = 5000;
7
+ export interface BridgeStateFile {
8
+ readonly schemaVersion: typeof bridgeStateSchemaVersion;
9
+ readonly pid: number;
10
+ readonly runnerId: string;
11
+ readonly runnerInstanceId: string;
12
+ readonly version: string;
13
+ /** "running" while connect runs; "stopped" once it has shut down cleanly. */
14
+ readonly state: "running" | "stopped";
15
+ readonly startedAt: string;
16
+ readonly updatedAt: string;
17
+ readonly publishIntervalMs: number;
18
+ readonly connected: boolean;
19
+ /** Yield (local flag or Forge's toggle) that Forge has acknowledged: placement no longer picks this runner. */
20
+ readonly yielding: boolean;
21
+ /** Yield the bridge applies, acknowledged by Forge or not yet. */
22
+ readonly yieldApplied?: boolean;
23
+ /** Another live bridge process publishing to the same file, as last seen by this one. */
24
+ readonly conflict?: BridgeStateConflict | null;
25
+ /** Random per publisher: whose record this is, so a stopping bridge never finalizes another's. */
26
+ readonly publisherId?: string;
27
+ readonly inFlight: readonly InFlightEntry[];
28
+ }
29
+ export interface BridgeStateConflict {
30
+ readonly pid: number;
31
+ readonly runnerInstanceId: string;
32
+ readonly seenAt: string;
33
+ }
34
+ export type BridgeStateRead = {
35
+ readonly kind: "ok";
36
+ readonly state: BridgeStateFile;
37
+ /** Publishers that could not publish their latest state; present only when there are any. */
38
+ readonly unpublished?: readonly UnpublishedMarker[];
39
+ } | {
40
+ readonly kind: "missing";
41
+ } | {
42
+ readonly kind: "invalid";
43
+ readonly error: string;
44
+ };
45
+ export type BridgeIdleVerdict = "idle" | "busy" | "not_yielding" | "stale" | "unknown" | "not_running";
46
+ export declare const bridgeIdleExitCodes: Readonly<Record<BridgeIdleVerdict, number>>;
47
+ export interface BridgeIdleEvaluation {
48
+ readonly verdict: BridgeIdleVerdict;
49
+ readonly exitCode: number;
50
+ readonly reason: string;
51
+ readonly heartbeatAgeMs: number | null;
52
+ readonly staleAfterMs: number;
53
+ readonly pidAlive: boolean | null;
54
+ readonly state: BridgeStateFile | null;
55
+ }
56
+ /** `<config dir>/<config name>.state.json`, e.g. `~/.config/forge/bridge.state.json` beside `bridge.json`. */
57
+ export declare function bridgeStatePathFor(configPath: string): string;
58
+ /**
59
+ * Writes the state atomically: a temp file in the same folder, then a rename over the
60
+ * old one. On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an
61
+ * antivirus scanner has the target open, so it retries briefly.
62
+ */
63
+ export declare function writeBridgeStateFile(statePath: string, state: BridgeStateFile): Promise<void>;
64
+ /** The record and any live publisher's unpublished marker: what `status --idle` evaluates. */
65
+ export declare function readBridgeStateFile(statePath: string): Promise<BridgeStateRead>;
66
+ /** The record alone, as a publisher reads it before writing the next one. */
67
+ export declare function readBridgeStateRecord(statePath: string): Promise<BridgeStateRead>;
68
+ /** Removes the record so readers report unknown. Only a publisher holding the lock, over its own record. */
69
+ export declare function removeBridgeStateFile(statePath: string): Promise<void>;
70
+ export declare function staleAfterMsFor(state: Pick<BridgeStateFile, "publishIntervalMs"> | null): number;
71
+ /**
72
+ * Idle only when a live bridge process published a fresh heartbeat with nothing in
73
+ * flight. A dead pid, a stale heartbeat, a clean stop or an unreadable file is never
74
+ * reported as idle: each has its own verdict and a non-zero exit code.
75
+ */
76
+ export declare function evaluateBridgeIdle(read: BridgeStateRead, options: {
77
+ readonly now: number;
78
+ readonly pidAlive: (pid: number) => boolean;
79
+ readonly requireYield?: boolean;
80
+ }): BridgeIdleEvaluation;
81
+ export interface BridgeStateIdentity {
82
+ readonly runnerId: string;
83
+ readonly runnerInstanceId: string;
84
+ readonly version: string;
85
+ }
86
+ export interface BridgeStateSource {
87
+ inFlight(): readonly InFlightEntry[];
88
+ yielding(): boolean;
89
+ yieldApplied?(): boolean;
90
+ connected(): boolean;
91
+ }
92
+ export interface BridgeStatePublisherOptions {
93
+ readonly intervalMs?: number;
94
+ readonly now?: () => Date;
95
+ readonly pid?: number;
96
+ readonly write?: (statePath: string, state: BridgeStateFile) => Promise<void>;
97
+ readonly read?: (statePath: string) => Promise<BridgeStateRead>;
98
+ readonly pidAlive?: (pid: number) => boolean;
99
+ readonly log?: (message: string) => void;
100
+ /** Removes this publisher's own record after a write under the lock failed (fail closed). */
101
+ readonly invalidate?: (statePath: string) => Promise<void>;
102
+ /** Records that this publisher could not publish (fail closed without touching the shared record). */
103
+ readonly markUnpublished?: (statePath: string, marker: UnpublishedMarker) => Promise<void>;
104
+ readonly lock?: BridgeStateLockOptions;
105
+ }
106
+ /**
107
+ * Keeps the state file current while connect runs: on every in-flight change
108
+ * (coalesced) and on a heartbeat timer. Each publish reads the current record and
109
+ * writes the next one under the state file's lock. A failed publish removes the
110
+ * record, so readers report unknown instead of trusting the last one; failures are
111
+ * logged once per streak and never reach the bridge.
112
+ */
113
+ export declare class BridgeStatePublisher {
114
+ private readonly statePath;
115
+ private readonly identity;
116
+ private readonly source;
117
+ private readonly options;
118
+ private readonly intervalMs;
119
+ private readonly now;
120
+ private readonly startedAt;
121
+ private readonly publisherId;
122
+ private timer;
123
+ private writing;
124
+ private dirty;
125
+ private stopped;
126
+ private failing;
127
+ private conflict;
128
+ private unpublishedSince;
129
+ private sweptExitedMarkers;
130
+ constructor(statePath: string, identity: BridgeStateIdentity, source: BridgeStateSource, options?: BridgeStatePublisherOptions);
131
+ start(): Promise<void>;
132
+ /** Publishes now, or right after the write in progress. */
133
+ publish(): Promise<void>;
134
+ /** Stops the heartbeat and records a clean stop, only over this publisher's own record. */
135
+ stop(): Promise<void>;
136
+ snapshot(state?: BridgeStateFile["state"]): BridgeStateFile;
137
+ private get pid();
138
+ private read;
139
+ private writeLoop;
140
+ /**
141
+ * Reads the record and writes the next one while holding the lock, so no other publisher
142
+ * writes in between: a second bridge always sees the first one's record (and publishes the
143
+ * conflict), and a stopping bridge's "stopped" record never lands over a newer bridge's.
144
+ */
145
+ private publishRecord;
146
+ /**
147
+ * The last record may say idle while new work starts. This publisher's marker makes readers
148
+ * report unknown; while it holds the lock it also removes its own record, never another's.
149
+ */
150
+ private failClosed;
151
+ private clearUnpublished;
152
+ private noteFailure;
153
+ private ownsRecord;
154
+ /**
155
+ * Two `connect` processes on one config would overwrite each other's record, and the
156
+ * last writer could be the idle one. Each remembers the other live, fresh writer it saw
157
+ * until that writer is gone or would read as stale, and publishes it as a conflict.
158
+ */
159
+ private noteConflict;
160
+ }
161
+ export declare function formatAge(ms: number): string;