@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.15efe2d7309f

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 (271) hide show
  1. package/README.md +146 -3
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +31 -1
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  33. package/dist/bridge/windows-bash-resolution.js +153 -0
  34. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  35. package/dist/cleanup/cleanup-wip.js +66 -0
  36. package/dist/cleanup/cleanup.service.d.ts +20 -1
  37. package/dist/cleanup/cleanup.service.js +150 -169
  38. package/dist/cleanup/cleanup.types.d.ts +6 -0
  39. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  40. package/dist/cleanup/forge-owned-paths.js +53 -0
  41. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  42. package/dist/cleanup/host-runtime-ledger.js +130 -0
  43. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  44. package/dist/cleanup/managed-branch-sweep.js +111 -0
  45. package/dist/cli/cli.help.js +74 -12
  46. package/dist/cli/cli.service.d.ts +19 -10
  47. package/dist/cli/cli.service.js +152 -187
  48. package/dist/cli/idle-status.d.ts +84 -0
  49. package/dist/cli/idle-status.js +181 -0
  50. package/dist/cli/local-config.d.ts +6 -0
  51. package/dist/cli/local-config.js +32 -4
  52. package/dist/cli/provider-cli-detection.d.ts +10 -0
  53. package/dist/cli/provider-cli-detection.js +160 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  55. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  56. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  57. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  58. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  59. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  60. package/dist/runtime/attempt-process-supervisor.js +12 -6
  61. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  62. package/dist/runtime/docker-engine-probe.js +7 -0
  63. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  64. package/dist/runtime/dotnet-build-outputs.js +402 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  66. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  67. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  68. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  69. package/dist/runtime/host-facts.d.ts +2 -1
  70. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  71. package/dist/runtime/host-listener-inspector.js +84 -3
  72. package/dist/runtime/host-load-admission.d.ts +72 -0
  73. package/dist/runtime/host-load-admission.js +99 -0
  74. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  75. package/dist/runtime/host-load-child-environment.js +76 -0
  76. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  77. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  78. package/dist/runtime/host-load-governor-config.d.ts +61 -0
  79. package/dist/runtime/host-load-governor-config.js +86 -0
  80. package/dist/runtime/host-load-governor.d.ts +193 -0
  81. package/dist/runtime/host-load-governor.js +662 -0
  82. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  83. package/dist/runtime/host-load-ledger-lock.js +187 -0
  84. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  85. package/dist/runtime/host-load-runtime-settings.js +80 -0
  86. package/dist/runtime/host-load-sampler.d.ts +75 -2
  87. package/dist/runtime/host-load-sampler.js +142 -8
  88. package/dist/runtime/host-load-step-class.d.ts +70 -0
  89. package/dist/runtime/host-load-step-class.js +161 -0
  90. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  91. package/dist/runtime/host-load-step-reaper.js +95 -0
  92. package/dist/runtime/host-load-step-run.d.ts +73 -0
  93. package/dist/runtime/host-load-step-run.js +102 -0
  94. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  95. package/dist/runtime/host-load-test-slot.js +88 -0
  96. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  97. package/dist/runtime/host-load-token-ledger.js +453 -0
  98. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  99. package/dist/runtime/host-load-windows-cpu.js +85 -0
  100. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  101. package/dist/runtime/host-pressure-stall.js +48 -1
  102. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  103. package/dist/runtime/host-runtime-contract.js +39 -6
  104. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  105. package/dist/runtime/host-runtime-lease.js +408 -294
  106. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  107. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  108. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  109. package/dist/runtime/host-runtime-promotion.js +355 -14
  110. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  111. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  112. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  113. package/dist/runtime/host-runtime-requirements.js +117 -0
  114. package/dist/runtime/managed-command-teardown.js +5 -16
  115. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  116. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  117. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  119. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  120. package/dist/runtime/prepared-runtime-identity.js +130 -9
  121. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  122. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  123. package/dist/runtime/runner-settings.d.ts +104 -0
  124. package/dist/runtime/runner-settings.js +236 -0
  125. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  126. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  127. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  128. package/dist/sandbox/host-capacity-broker.js +336 -0
  129. package/dist/sandbox/managed-branch.d.ts +13 -0
  130. package/dist/sandbox/managed-branch.js +90 -0
  131. package/dist/sandbox/provider-auth/codex.js +11 -11
  132. package/dist/sandbox/runtime.d.ts +10 -1
  133. package/dist/sandbox/runtime.js +47 -8
  134. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  135. package/dist/sandbox/sandbox-cgroups.js +42 -0
  136. package/dist/session/architect-waits.d.ts +2 -0
  137. package/dist/session/architect-waits.js +138 -0
  138. package/dist/session/managed-attempt-tools.d.ts +2 -7
  139. package/dist/session/managed-attempt-tools.js +207 -121
  140. package/dist/session/managed-build-coordinator.d.ts +16 -0
  141. package/dist/session/managed-build-coordinator.js +10 -0
  142. package/dist/session/managed-build-receipt.d.ts +5 -0
  143. package/dist/session/managed-build-receipt.js +8 -3
  144. package/dist/session/managed-command-host-load.d.ts +47 -0
  145. package/dist/session/managed-command-host-load.js +83 -0
  146. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  147. package/dist/session/mcp-argument-coercion.js +121 -0
  148. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  149. package/dist/session/phase-completion.artifacts.js +96 -26
  150. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  151. package/dist/session/phase-completion.command-validation.js +77 -0
  152. package/dist/session/phase-completion.d.ts +12 -0
  153. package/dist/session/phase-completion.helpers.js +13 -12
  154. package/dist/session/phase-completion.js +5 -0
  155. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  156. package/dist/session/phase-completion.mcp-args.js +156 -0
  157. package/dist/session/phase-completion.prompts.js +6 -1
  158. package/dist/session/phase-completion.runtime.d.ts +5 -11
  159. package/dist/session/phase-completion.runtime.js +91 -215
  160. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  161. package/dist/session/phase-completion.schema-parts.js +188 -0
  162. package/dist/session/phase-completion.schemas.d.ts +3 -3
  163. package/dist/session/phase-completion.schemas.js +208 -231
  164. package/dist/session/phase-completion.validation.d.ts +2 -3
  165. package/dist/session/phase-completion.validation.js +49 -93
  166. package/dist/session/pre-publication-host-load.d.ts +27 -0
  167. package/dist/session/pre-publication-host-load.js +111 -0
  168. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  169. package/dist/session/pre-publication-native-postgres.js +111 -0
  170. package/dist/session/pre-publication-pass.d.ts +61 -0
  171. package/dist/session/pre-publication-pass.js +148 -0
  172. package/dist/session/pre-publication-process.d.ts +3 -0
  173. package/dist/session/pre-publication-process.js +31 -19
  174. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  175. package/dist/session/pre-publication-step-execution.js +50 -0
  176. package/dist/session/pre-publication-validation.d.ts +37 -21
  177. package/dist/session/pre-publication-validation.js +221 -182
  178. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  179. package/dist/session/provider-cli/claude-background-work.js +181 -0
  180. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  181. package/dist/session/provider-cli/host-build-lock.js +30 -0
  182. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  183. package/dist/session/provider-cli/pre-publication-repair.js +277 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  185. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  190. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  191. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  192. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
  193. package/dist/session/provider-cli/provider-cli.prompts.js +109 -32
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  196. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  197. package/dist/session/provider-cli/provider-cli.service.js +106 -181
  198. package/dist/session/provider-cli/provider-cli.types.d.ts +35 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  205. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  206. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  207. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  208. package/dist/session/provider-cli/provider-output-state.js +6 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  211. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  212. package/dist/session/qa-sidecar-validation.js +28 -0
  213. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  214. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  215. package/dist/session/session-host-project.d.ts +22 -0
  216. package/dist/session/session-host-project.js +98 -0
  217. package/dist/session/session-redaction.js +31 -181
  218. package/dist/session/session.base.d.ts +9 -1
  219. package/dist/session/session.service.d.ts +15 -2
  220. package/dist/session/session.service.js +246 -138
  221. package/dist/session/session.types.d.ts +4 -0
  222. package/dist/session/session.types.js +7 -7
  223. package/dist/session/sidecar-json-shape.d.ts +31 -0
  224. package/dist/session/sidecar-json-shape.js +217 -0
  225. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  226. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  227. package/dist/shared/fs/file-identity.d.ts +10 -0
  228. package/dist/shared/fs/file-identity.js +15 -0
  229. package/dist/shared/fs/replace-file.d.ts +7 -0
  230. package/dist/shared/fs/replace-file.js +33 -0
  231. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  232. package/dist/shared/process/host-process-recovery.js +23 -3
  233. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  234. package/dist/shared/process/host-process-supervisor.js +67 -15
  235. package/dist/shared/process/process-tree.d.ts +52 -0
  236. package/dist/shared/process/process-tree.js +144 -0
  237. package/dist/shared/process/process.d.ts +67 -0
  238. package/dist/shared/process/process.js +213 -11
  239. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  240. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  241. package/dist/shared/process/windows-launch.d.ts +18 -0
  242. package/dist/shared/process/windows-launch.js +68 -0
  243. package/dist/shared/provider-capabilities.js +14 -7
  244. package/dist/version.d.ts +1 -1
  245. package/dist/version.js +1 -1
  246. package/dist/worktree/dependency-warmer.d.ts +25 -0
  247. package/dist/worktree/dependency-warmer.js +46 -10
  248. package/dist/worktree/orphan-relink.d.ts +19 -0
  249. package/dist/worktree/orphan-relink.js +106 -0
  250. package/dist/worktree/wip-git.d.ts +58 -0
  251. package/dist/worktree/wip-git.js +182 -0
  252. package/dist/worktree/wip-refs.d.ts +85 -0
  253. package/dist/worktree/wip-refs.js +169 -0
  254. package/dist/worktree/wip-restore.d.ts +51 -0
  255. package/dist/worktree/wip-restore.js +324 -0
  256. package/dist/worktree/wip-snapshot.d.ts +53 -0
  257. package/dist/worktree/wip-snapshot.js +270 -0
  258. package/dist/worktree/worktree-inputs.d.ts +8 -0
  259. package/dist/worktree/worktree-inputs.js +134 -0
  260. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  261. package/dist/worktree/worktree-origin-sync.js +128 -0
  262. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  263. package/dist/worktree/worktree-wip-events.js +148 -0
  264. package/dist/worktree/worktree-wip.d.ts +57 -0
  265. package/dist/worktree/worktree-wip.js +200 -0
  266. package/dist/worktree/worktree.base.d.ts +7 -1
  267. package/dist/worktree/worktree.service.d.ts +36 -5
  268. package/dist/worktree/worktree.service.js +127 -155
  269. package/dist/worktree/worktree.types.d.ts +47 -0
  270. package/package.json +2 -2
  271. package/runtime/windows-listener-owner.ps1 +12 -1
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,11 +65,13 @@ 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.
62
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
+
63
75
  Show or change the saved server without editing `bridge.json`:
64
76
 
65
77
  ```bash
@@ -129,6 +141,137 @@ enters a ten-minute cooldown after an unsuccessful attempt. Remote `DOCKER_HOST`
129
141
  restarted. Operators can tune the bounded policy with `FORGE_DOCKER_RECOVERY_FAILURE_THRESHOLD`,
130
142
  `FORGE_DOCKER_RECOVERY_COOLDOWN_MS`, and `FORGE_DOCKER_RECOVERY_STARTUP_TIMEOUT_MS`.
131
143
 
144
+ ## Runner limits and yield
145
+
146
+ Forge owns each runner's limits (Settings → Runners → Limits) and pushes them to the bridge, which
147
+ applies them without a restart and without stopping admitted work: max attempts and the memory reserve
148
+ apply at the next attempt admission, the CPU budget, yield budget and max heavy steps at the next heavy
149
+ step. Host env vars only bound the server's values and are reported back to Forge: a ceiling on
150
+ capacity (`FORGE_HOST_MAX_CONCURRENT_ATTEMPTS`, `FORGE_HOST_CPU_BUDGET_PERCENT`,
151
+ `FORGE_HOST_LOAD_CPU_BUDGET_FRACTION`, `FORGE_HOST_MAX_HEAVY_STEPS`) and a floor on the reserve
152
+ (`FORGE_HOST_MEMORY_RESERVE_BYTES`). Without a server value, the env var or the bridge default applies.
153
+ The CPU budget, yield budget and heavy-step limit take effect only with `FORGE_HOST_LOAD_GOVERNOR=on`.
154
+ They gate on Linux PSI. Windows has no PSI, so a Windows bridge estimates CPU pressure from whole-host
155
+ CPU use and reports it with `pressureSource: "windows_estimate"` (decision 0021). Forge's Load column
156
+ and the budgets then work there too. Without either signal, the governor falls back to one heavy step at a time.
157
+
158
+ Two or more attempts on one host take turns at the host test slot (decision 0018): builds, test runs,
159
+ Playwright, pre-publication checks and the ASP.NET runtime build each wait for it in one host-wide queue,
160
+ foreground first, then first come, first served, across the bridge and every completion MCP server. Plain
161
+ managed commands and dependency installs never wait for it. A waiting step reports who holds the slot
162
+ (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
163
+ `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
164
+ A holder that crashes or stalls keeps the slot only until the host load ledger takes its token back (its
165
+ process tree stopped, its lease fenced, or attempt teardown). `FORGE_HOST_LOAD_TEST_SLOTS` sets how many
166
+ run at once (default 1; `0` turns the slot off).
167
+
168
+ Yield this machine to foreground work (for example while gaming) from the host itself:
169
+
170
+ ```bash
171
+ forge-bridge yield on
172
+ forge-bridge yield status
173
+ forge-bridge yield off
174
+ ```
175
+
176
+ While yielding, the bridge takes no new attempts and heavy steps of running attempts use the yield CPU
177
+ budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
178
+ in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
179
+
180
+ ## Restarting or updating the bridge safely
181
+
182
+ Restarting `forge-bridge connect` kills everything it is running, including work that has no agent
183
+ process yet: an accepted offer waiting for Start, host-runtime admission, worktree and dependency
184
+ preparation, prepared-runtime probes, pre-publication validation and teardown. Forge then records the
185
+ attempt's outcome as unknown. Checking for agent processes is not enough, so the running bridge
186
+ publishes its in-flight work to `bridge.state.json` next to `bridge.json` (pid, runner instance, a
187
+ heartbeat refreshed every 5 seconds, and each in-flight item with its ids, phase and start time), and
188
+ `forge-bridge status --idle` reads it. Each bridge reads and rewrites the file while it holds a lock
189
+ the operating system owns and frees when the bridge exits (an abstract socket on Linux, a named pipe
190
+ on Windows, a flock on `bridge.state.json.lock` on macOS), so a second bridge on the same config always
191
+ sees the first one's record and reports the conflict, and a stopping bridge never writes its "stopped"
192
+ record over a newer bridge's. A bridge that can't publish (a failed write, or the lock held by another
193
+ process for more than 5 seconds) leaves `bridge.state.json.unpublished.<id>.json` instead of touching
194
+ the shared record, and a record missing any field reads as unknown, so neither can read as idle:
195
+
196
+ | Exit code | Verdict | Meaning |
197
+ |---:|---|---|
198
+ | 0 | `idle` | A live bridge reported a fresh heartbeat with nothing in flight. |
199
+ | 1 | `busy` | Work is in flight; restarting now would kill it. |
200
+ | 2 | | Usage error. |
201
+ | 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`. |
202
+ | 4 | `not_running` | The recorded bridge process has exited. Nothing to interrupt, but it is not an idle report. |
203
+ | 5 | `not_yielding` | With `--require-yield`: nothing in flight, but Forge has not acknowledged yield from this bridge, so placement can still pick it. |
204
+
205
+ `--json` prints the verdict, the reason, the heartbeat age, the pid check, the yield state (`yielding`:
206
+ acknowledged by Forge; `yieldApplied`: applied by the bridge) and the in-flight list. `--wait <seconds>`
207
+ keeps checking until the bridge is idle, its process has exited, or the time is up, so a file briefly
208
+ held by antivirus or the indexer doesn't end the wait; `--wait 0` checks once, like no `--wait`.
209
+ Against a bridge older than this check (no state file) it waits out the full time; check once without
210
+ `--wait` first.
211
+
212
+ What yield does and doesn't stop:
213
+
214
+ - It stops new attempts: the bridge refuses Offers while yielding (Forge re-places them), and Forge
215
+ stops placing work on the runner once it has acknowledged the yield (the next heartbeat or settings
216
+ report, at most about 30 seconds). `--require-yield` waits for that acknowledgement.
217
+ - It defers background runtime-readiness probes; Forge retries them after yield is off.
218
+ - It doesn't stop a Bridge Chat turn whose chat lease is already bound to this runner: Forge has no
219
+ retry for a refused turn, so the bridge runs it, and `status --idle` reports it as busy until it ends.
220
+ - It doesn't stop a legacy `Dispatch`, which Forge sends only to protocol-1 bridges. This bridge
221
+ registers a newer protocol, so it receives Offer and Start instead. A legacy dispatch is still
222
+ counted as busy.
223
+ - Attempts already running finish normally.
224
+
225
+ Restart procedure: yield, wait for idle, restart, then turn yield off once the new bridge has connected
226
+ (the flag file survives the restart, so the new bridge starts yielded and takes no work until then).
227
+ If the wait fails, turn yield off again so the runner doesn't stay out of placement, or leave it on
228
+ deliberately and retry later.
229
+ Run the commands as the same user and with the same `FORGE_BRIDGE_CONFIG` as the bridge so they use its
230
+ `bridge.json`, `bridge.yield.json` and `bridge.state.json`. On Windows, a shell inside an MSIX-packaged
231
+ app can have `%APPDATA%` writes virtualized away from the bridge; `--require-yield` catches that, because
232
+ the yield has to be applied by the bridge and acknowledged by Forge.
233
+
234
+ Linux or macOS:
235
+
236
+ ```bash
237
+ forge-bridge yield on
238
+ if forge-bridge status --idle --require-yield --wait 3600; then
239
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
240
+ forge-bridge yield off # once the new bridge has connected
241
+ else
242
+ code=$?
243
+ forge-bridge yield off # don't leave the runner out of placement
244
+ echo "Bridge is not idle (exit $code); not restarting." >&2
245
+ fi
246
+ ```
247
+
248
+ Windows PowerShell:
249
+
250
+ ```powershell
251
+ forge-bridge yield on
252
+ forge-bridge status --idle --require-yield --wait 3600
253
+ $code = $LASTEXITCODE
254
+ if ($code -eq 0) {
255
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
256
+ forge-bridge yield off # once the new bridge has connected
257
+ } else {
258
+ forge-bridge yield off # don't leave the runner out of placement
259
+ Write-Error "Bridge is not idle (exit $code); not restarting."
260
+ }
261
+ ```
262
+
263
+ The bridge also logs each accepted offer, each accepted dispatch and the start and end of each run,
264
+ with the dispatch attempt, lease, session and cycle ids.
265
+
266
+ ## Pre-publication repair
267
+
268
+ Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
269
+ `.forge/validation/ci-parity.v1.json`. A failed check does not stop the pass: the other checks still
270
+ run, except those that need what failed (the OpenAPI export and E2E after a .NET compile failure, E2E
271
+ after a failed runtime restart). The provider thread then gets one in-place repair turn that lists
272
+ every failed check. A Work Order holds after `FORGE_PREPUBLICATION_REPAIR_TURNS` repair turns (a whole
273
+ number from 1, capped at 10; default 4) if validation still fails.
274
+
132
275
  ## Docker sandbox runners
133
276
 
134
277
  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:
@@ -190,9 +333,9 @@ Production shared runners require a Linux rootless Docker daemon. Docker Desktop
190
333
 
191
334
  Before selecting `sandbox_required`, save the full approved 40- or 64-character Git commit SHA in the project's Sandbox policy dialog. The server persists that SHA on the immutable attempt and the bridge reads `.forge/forge.sandbox.yml`, `.forge/Dockerfile`, and the tracked build context only from that commit. API-key dispatches carry an opaque one-time grant handle; the authenticated current runner instance redeems it after reservation, and plaintext stays out of offers, database payloads, Docker metadata, and host-persisted control files.
192
335
 
193
- 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 Profile Settings. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
336
+ 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.
194
337
 
195
- 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 Profile Settings before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Profile Settings 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.
338
+ 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.
196
339
 
197
340
  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.
198
341
 
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The AI's one look at the GIFs a user sent (GIPHY in Chat). Frames never ride in the dispatch packet,
3
+ * which goes through Forge's database outbox: at turn start the bridge takes them once from the API's
4
+ * in-memory store, shows them to a throwaway Claude call that keeps no session and has no tools, and gives
5
+ * the main turn only that call's short description. The main turn never gets the frames, and nothing the
6
+ * look call saw is written to disk by the bridge. The look call is built and run with the other provider
7
+ * launches, in `bridge-chat-provider-command.ts`.
8
+ */
9
+ import type { ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
10
+ /** The hub method that hands a turn its GIF frames, once. */
11
+ export declare const chatTurnGiphyFramesMethod = "ChatTurnGiphyFrames";
12
+ /** The API hands out at most four stills a GIF; any more are ignored. */
13
+ export declare const maxChatGiphyLookFrames = 4;
14
+ export interface ChatTurnGiphyFrameSet {
15
+ readonly giphyId: string;
16
+ readonly title: string;
17
+ readonly altText?: string | null;
18
+ /** Base64 JPEG stills. */
19
+ readonly frames: readonly string[];
20
+ }
21
+ export interface ChatTurnGiphyFramesResponse {
22
+ readonly accepted: boolean;
23
+ readonly gifs?: readonly ChatTurnGiphyFrameSet[] | null;
24
+ readonly code?: string | null;
25
+ }
26
+ export interface ChatGiphyLook {
27
+ readonly title: string;
28
+ readonly description: string;
29
+ }
30
+ export interface ChatGiphyLookDependencies {
31
+ /** Calls the hub's frames method. */
32
+ readonly takeFrames: (request: {
33
+ leaseId: string;
34
+ fencingToken: string;
35
+ turnId: string;
36
+ /** The packet's `giphyFramesThroughSeq`: frames only for GIFs sent at or before it. */
37
+ throughSeq: number;
38
+ }) => Promise<ChatTurnGiphyFramesResponse>;
39
+ readonly runner: ProviderProcessRunner;
40
+ readonly signal?: AbortSignal;
41
+ readonly log?: (message: string) => void;
42
+ }
43
+ /** One stream-json user message: what to do, then the frames as base64 JPEG image blocks. */
44
+ export declare function chatGiphyLookStdin(title: string, altText: string | null, frames: readonly string[]): string;
45
+ /** The look call's answer, from its stream-json `result` event, as one short line. */
46
+ export declare function chatGiphyLookDescription(stdoutLines: readonly string[]): string | null;
47
+ /** What the main turn reads about the GIFs, after the conversation. It never gets the frames. */
48
+ export declare function chatGiphyLookPromptSection(looks: readonly ChatGiphyLook[]): string;
@@ -0,0 +1,55 @@
1
+ /** The hub method that hands a turn its GIF frames, once. */
2
+ export const chatTurnGiphyFramesMethod = "ChatTurnGiphyFrames";
3
+ const maxDescriptionChars = 600;
4
+ /** The API hands out at most four stills a GIF; any more are ignored. */
5
+ export const maxChatGiphyLookFrames = 4;
6
+ /** One stream-json user message: what to do, then the frames as base64 JPEG image blocks. */
7
+ export function chatGiphyLookStdin(title, altText, frames) {
8
+ const about = altText ? `"${oneLine(title)}" (alt text: "${oneLine(altText)}")` : `"${oneLine(title)}"`;
9
+ const text = `These are ${frames.length} evenly spaced frames of a GIF from GIPHY, ${about}, that a user sent in a chat. `
10
+ + "Describe what happens in the GIF in one or two plain sentences, for someone who can't see it. "
11
+ + "Reply with the description only.";
12
+ return `${JSON.stringify({
13
+ type: "user",
14
+ message: {
15
+ role: "user",
16
+ content: [
17
+ { type: "text", text },
18
+ ...frames.map(data => ({ type: "image", source: { type: "base64", media_type: "image/jpeg", data } })),
19
+ ],
20
+ },
21
+ })}\n`;
22
+ }
23
+ /** The look call's answer, from its stream-json `result` event, as one short line. */
24
+ export function chatGiphyLookDescription(stdoutLines) {
25
+ for (const line of [...stdoutLines].reverse()) {
26
+ if (!line.trim().startsWith("{"))
27
+ continue;
28
+ try {
29
+ const event = JSON.parse(line);
30
+ if (event.type !== "result")
31
+ continue;
32
+ if (event.is_error === true || typeof event.result !== "string")
33
+ return null;
34
+ const text = oneLine(event.result);
35
+ return text ? clip(text, maxDescriptionChars) : null;
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ }
41
+ return null;
42
+ }
43
+ /** What the main turn reads about the GIFs, after the conversation. It never gets the frames. */
44
+ export function chatGiphyLookPromptSection(looks) {
45
+ if (looks.length === 0)
46
+ return "";
47
+ const lines = looks.map(look => `- "${oneLine(look.title)}": ${look.description}`);
48
+ return `\n\n# What the sent GIFs show\n\nA separate look at frames of the GIFs sent since your last reply:\n${lines.join("\n")}`;
49
+ }
50
+ function oneLine(value) {
51
+ return value.replace(/\s+/g, " ").replaceAll("\"", "'").trim();
52
+ }
53
+ function clip(value, max) {
54
+ return value.length <= max ? value : `${value.slice(0, max - 1).trimEnd()}…`;
55
+ }
@@ -0,0 +1,40 @@
1
+ import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ChatGiphyLook, type ChatGiphyLookDependencies } from "./bridge-chat-giphy-look.js";
3
+ export { chatTurnGiphyFramesMethod, type ChatGiphyLook, type ChatTurnGiphyFramesResponse } from "./bridge-chat-giphy-look.js";
4
+ import { type ChatTurnDispatchPacket } from "./bridge-chat.types.js";
5
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
6
+ export declare const chatTurnMetadataFileName = "forge-chat-metadata.json";
7
+ /**
8
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
9
+ * turn never delivered its answer, so it must not be reported as one.
10
+ */
11
+ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunResult, "terminalStopReason">): void;
12
+ export interface ChatProviderCommandPlan {
13
+ readonly command: ProviderCliCommand;
14
+ readonly stdin?: string;
15
+ /**
16
+ * Provider environment: the host's .NET build lock (host-build-lock.ts), Codex's own home, and
17
+ * the headless background-work restrictions for Claude.
18
+ */
19
+ readonly env?: Readonly<Record<string, string>>;
20
+ }
21
+ /** `giphyLooks` are the descriptions of the turn's sent GIFs from the look call; never their frames. */
22
+ export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string, giphyLooks?: readonly ChatGiphyLook[]): ChatProviderCommandPlan;
23
+ /** Writes the turn-scoped handoff metadata file: opaque handles only, no attachment content or grant nonces. */
24
+ export declare function materializeChatTurnMetadata(packet: ChatTurnDispatchPacket, workspacePath: string): Promise<void>;
25
+ /**
26
+ * Looks at the turn's sent GIFs. Returns no looks, so the turn goes ahead with the GIFs as text only, when
27
+ * none are waiting, the turn's provider is not Claude (Codex has no image input over stdin), the frames are
28
+ * gone, or a look fails.
29
+ */
30
+ export declare function lookAtChatGiphyFrames(packet: ChatTurnDispatchPacket, cwd: string, dependencies: ChatGiphyLookDependencies): Promise<readonly ChatGiphyLook[]>;
31
+ /**
32
+ * `claude -p` that keeps no session (`--no-session-persistence`), reads one stream-json user message with
33
+ * the frames as image blocks on stdin, and has no tools (`--tools ""`), no MCP servers and none of the host
34
+ * user's settings.
35
+ */
36
+ export declare function buildChatGiphyLookCommand(model: string, cwd: string): {
37
+ readonly command: string;
38
+ readonly args: readonly string[];
39
+ readonly env: Readonly<Record<string, string>>;
40
+ };
@@ -0,0 +1,230 @@
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 fs from "node:fs";
7
+ import path from "node:path";
8
+ import { claudeHeadlessEnvironment, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
9
+ import { hostDotnetBuildLockEnvironment, hostDotnetBuildLockInstruction } from "../session/provider-cli/host-build-lock.js";
10
+ import { claudeIsolatedLaunchArgs, providerUserConfigIsolationUnsupported, providerUserConfigIsolationEnv } from "../session/provider-cli/provider-user-config-isolation.js";
11
+ import { codexSandboxModeForPlatform, providerEffort } from "../session/provider-cli/provider-cli.prompts.js";
12
+ import { chatGiphyLookDescription, chatGiphyLookPromptSection, chatGiphyLookStdin, maxChatGiphyLookFrames, } from "./bridge-chat-giphy-look.js";
13
+ export { chatTurnGiphyFramesMethod } from "./bridge-chat-giphy-look.js";
14
+ import { chatProviderKind } from "./bridge-chat.types.js";
15
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
16
+ export const chatTurnMetadataFileName = "forge-chat-metadata.json";
17
+ /**
18
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
19
+ * turn never delivered its answer, so it must not be reported as one.
20
+ */
21
+ export function assertChatTurnFinished(result) {
22
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
23
+ throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
24
+ }
25
+ }
26
+ /** `giphyLooks` are the descriptions of the turn's sent GIFs from the look call; never their frames. */
27
+ export function buildChatProviderCommand(packet, cwd, giphyLooks = []) {
28
+ // The provider kind picks the CLI and its effort levels; an auth-path suffix such as `:bridge` does not.
29
+ const provider = chatProviderKind(packet.providerKind);
30
+ const model = packet.model.trim();
31
+ const prompt = buildChatPrompt(packet, giphyLooks);
32
+ const resumeThreadId = packet.providerThreadId?.trim() || null;
33
+ // Levels the provider does not accept are dropped, so the CLI keeps its own default.
34
+ const effort = providerEffort(provider, packet.effort);
35
+ if (provider === "codex") {
36
+ const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
37
+ if (resumeThreadId) {
38
+ args.push("--cd", cwd, "resume");
39
+ }
40
+ args.push("--model", model);
41
+ if (effort) {
42
+ args.push("-c", `model_reasoning_effort=${JSON.stringify(effort)}`);
43
+ }
44
+ args.push("--json");
45
+ if (!resumeThreadId) {
46
+ args.push("--cd", cwd);
47
+ }
48
+ args.push("--skip-git-repo-check");
49
+ if (resumeThreadId) {
50
+ args.push(resumeThreadId);
51
+ }
52
+ args.push("-");
53
+ // Codex runs with Forge's own CODEX_HOME, not the user's ~/.codex (provider-user-config-isolation.ts).
54
+ return { command: { command: "codex", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...providerUserConfigIsolationEnv("codex") } };
55
+ }
56
+ if (provider === "claude") {
57
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model];
58
+ if (effort) {
59
+ args.push("--effort", effort);
60
+ }
61
+ // Only Forge's context and no MCP servers (provider-user-config-isolation.ts).
62
+ args.push("--permission-mode", "bypassPermissions", ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }));
63
+ if (resumeThreadId) {
64
+ args.push("--resume", resumeThreadId);
65
+ }
66
+ return { command: { command: "claude", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...claudeHeadlessEnvironment } };
67
+ }
68
+ // cursor-agent and other CLIs can't be kept from the host user's own configuration.
69
+ throw providerUserConfigIsolationUnsupported(packet.providerKind);
70
+ }
71
+ function buildChatPrompt(packet, giphyLooks) {
72
+ const messages = packet.messages
73
+ .map((message, index) => {
74
+ const role = message.role.trim() || `message-${index + 1}`;
75
+ return `[${role}]\n${message.content}`;
76
+ })
77
+ .join("\n\n");
78
+ const contextRefs = packet.contextRefs.length === 0
79
+ ? ""
80
+ : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
81
+ const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
82
+ const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
83
+ return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
84
+ }).join("\n\n")}`;
85
+ const continuation = packet.providerThreadId
86
+ ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
87
+ : "";
88
+ const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
89
+ // Chat turns run on the bridge's host, so they follow its .NET build lock like session turns.
90
+ const buildLock = hostDotnetBuildLockInstruction(process.env, "chat");
91
+ const hostRules = buildLock ? `\n\n# Host rules\n${buildLock}` : "";
92
+ return `You are handling a Forge Bridge Chat turn.
93
+
94
+ Conversation ID: ${packet.conversationId}
95
+ Turn ID: ${packet.turnId}
96
+ Provider: ${packet.providerKind}
97
+ Model: ${packet.model}${continuation}${boundedMetadata}${hostRules}
98
+
99
+ # Conversation
100
+
101
+ ${messages}${chatGiphyLookPromptSection(giphyLooks)}${contextRefs}
102
+ `;
103
+ }
104
+ function buildChatBoundedMetadataPrompt(packet) {
105
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
106
+ return "";
107
+ }
108
+ const sections = [
109
+ `\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.`,
110
+ ];
111
+ if (packet.attachmentHandoffs.length > 0) {
112
+ sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
113
+ `${index + 1}. turnId: ${handoff.turnId}`,
114
+ ` attachmentId: ${handoff.attachmentId}`,
115
+ ` tempFileToken: ${handoff.tempFileToken}`,
116
+ ` mimeType: ${handoff.mimeType}`,
117
+ ` sizeBytes: ${handoff.sizeBytes}`,
118
+ ` sha256: ${handoff.sha256}`,
119
+ ` fileNameDisplay: ${handoff.fileNameDisplay}`,
120
+ ` expiresAt: ${handoff.expiresAt}`,
121
+ ` status: ${handoff.status}`,
122
+ ].join("\n")).join("\n\n")}`);
123
+ }
124
+ if (packet.actionBrokerGrants.length > 0) {
125
+ sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
126
+ `${index + 1}. grantId: ${grant.grantId}`,
127
+ ` turnId: ${grant.turnId}`,
128
+ ` leaseId: ${grant.leaseId}`,
129
+ ` fencingToken: ${grant.fencingToken}`,
130
+ ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
131
+ ` expiresAt: ${grant.expiresAt}`,
132
+ ` redactionStatus: ${grant.redactionStatus}`,
133
+ " nonce: held by bridge",
134
+ ].join("\n")).join("\n\n")}`);
135
+ }
136
+ return sections.join("\n\n");
137
+ }
138
+ /** Writes the turn-scoped handoff metadata file: opaque handles only, no attachment content or grant nonces. */
139
+ export async function materializeChatTurnMetadata(packet, workspacePath) {
140
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
141
+ return;
142
+ }
143
+ await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
144
+ schemaVersion: 1,
145
+ attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
146
+ turnId: handoff.turnId,
147
+ attachmentId: handoff.attachmentId,
148
+ tempFileToken: handoff.tempFileToken,
149
+ mimeType: handoff.mimeType,
150
+ sizeBytes: handoff.sizeBytes,
151
+ sha256: handoff.sha256,
152
+ fileNameDisplay: handoff.fileNameDisplay,
153
+ expiresAt: handoff.expiresAt,
154
+ status: handoff.status,
155
+ })),
156
+ actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
157
+ grantId: grant.grantId,
158
+ turnId: grant.turnId,
159
+ leaseId: grant.leaseId,
160
+ fencingToken: grant.fencingToken,
161
+ allowedScopes: grant.allowedScopes,
162
+ expiresAt: grant.expiresAt,
163
+ redactionStatus: grant.redactionStatus,
164
+ nonceHeldByBridge: true,
165
+ })),
166
+ }, null, 2)}\n`, "utf8");
167
+ }
168
+ /**
169
+ * Looks at the turn's sent GIFs. Returns no looks, so the turn goes ahead with the GIFs as text only, when
170
+ * none are waiting, the turn's provider is not Claude (Codex has no image input over stdin), the frames are
171
+ * gone, or a look fails.
172
+ */
173
+ export async function lookAtChatGiphyFrames(packet, cwd, dependencies) {
174
+ if (!packet.giphyFramesPending || packet.giphyFramesThroughSeq === undefined || chatProviderKind(packet.providerKind) !== "claude") {
175
+ return [];
176
+ }
177
+ let response;
178
+ try {
179
+ response = await dependencies.takeFrames({
180
+ leaseId: packet.leaseId,
181
+ fencingToken: packet.fencingToken,
182
+ turnId: packet.turnId,
183
+ throughSeq: packet.giphyFramesThroughSeq,
184
+ });
185
+ }
186
+ catch (error) {
187
+ dependencies.log?.(`GIF frames for turn ${packet.turnId} were not available: ${error instanceof Error ? error.message : String(error)}`);
188
+ return [];
189
+ }
190
+ const looks = [];
191
+ for (const gif of response.accepted ? response.gifs ?? [] : []) {
192
+ if (dependencies.signal?.aborted)
193
+ break;
194
+ const frames = gif.frames.slice(0, maxChatGiphyLookFrames);
195
+ if (frames.length === 0)
196
+ continue;
197
+ const plan = buildChatGiphyLookCommand(packet.model, cwd);
198
+ const lines = [];
199
+ const result = await dependencies.runner.run({ command: plan.command, args: plan.args, cwd, env: plan.env, stdin: chatGiphyLookStdin(gif.title, gif.altText ?? null, frames), captureOutput: false }, { onStdoutLine: line => { lines.push(line); } }, dependencies.signal).catch(() => null);
200
+ const description = result?.exitCode === 0 ? chatGiphyLookDescription(lines) : null;
201
+ if (description) {
202
+ looks.push({ title: gif.title, description });
203
+ }
204
+ else {
205
+ dependencies.log?.(`The look at a GIF for turn ${packet.turnId} gave no description; it stays text only.`);
206
+ }
207
+ }
208
+ return looks;
209
+ }
210
+ /**
211
+ * `claude -p` that keeps no session (`--no-session-persistence`), reads one stream-json user message with
212
+ * the frames as image blocks on stdin, and has no tools (`--tools ""`), no MCP servers and none of the host
213
+ * user's settings.
214
+ */
215
+ export function buildChatGiphyLookCommand(model, cwd) {
216
+ return {
217
+ command: "claude",
218
+ args: [
219
+ "-p",
220
+ "--no-session-persistence",
221
+ "--input-format", "stream-json",
222
+ "--output-format", "stream-json",
223
+ "--verbose",
224
+ "--model", model.trim(),
225
+ "--tools", "",
226
+ ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }),
227
+ ],
228
+ env: { ...claudeHeadlessEnvironment },
229
+ };
230
+ }
@@ -35,10 +35,25 @@ 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[];
41
46
  readonly actionBrokerGrants: readonly ChatActionBrokerGrant[];
47
+ /**
48
+ * How many sent GIFs have frames waiting for the AI's one look; absent when none or from older servers.
49
+ * The frames never ride in the packet: the bridge takes them once through the hub's `ChatTurnGiphyFrames`.
50
+ */
51
+ readonly giphyFramesPending?: number;
52
+ /**
53
+ * The newest message `Seq` the packet's messages read, present with `giphyFramesPending`. It goes back with
54
+ * `ChatTurnGiphyFrames` so the API hands out only frames of GIFs this turn's messages include.
55
+ */
56
+ readonly giphyFramesThroughSeq?: number;
42
57
  }
43
58
  export interface ChatTurnMessage {
44
59
  readonly role: string;
@@ -107,5 +122,10 @@ export interface ChatTurnCancelPacket {
107
122
  export declare function unavailableBridgeChatCapability(protocolVersion?: string, unavailableCode?: string | null, unavailableReason?: string | null): BridgeChatCapability;
108
123
  export declare function normalizeBridgeChatCapability(value: BridgeChatCapability | null | undefined): BridgeChatCapability;
109
124
  export declare function parseChatTurnDispatchPacket(value: unknown, capability?: BridgeChatCapability): ChatTurnDispatchPacket;
125
+ /**
126
+ * The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
127
+ * Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
128
+ */
129
+ export declare function chatProviderKind(provider: string): string;
110
130
  export declare function isTerminalChatTurnCallbackKind(kind: ChatTurnCallbackKind): boolean;
111
131
  export declare function assertBridgeChatCallbackPayload(value: unknown, label?: string): void;