@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.0098fdb4e213

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 (332) hide show
  1. package/README.md +232 -5
  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 +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  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 +13 -1
  15. package/dist/bridge/bridge.service.d.ts +169 -14
  16. package/dist/bridge/bridge.service.js +1868 -330
  17. package/dist/bridge/bridge.types.d.ts +73 -1
  18. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  19. package/dist/bridge/dispatch-result-outbox.js +87 -0
  20. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  21. package/dist/bridge/dispatch-result-worker.js +122 -0
  22. package/dist/bridge/in-flight-registry.d.ts +62 -0
  23. package/dist/bridge/in-flight-registry.js +207 -0
  24. package/dist/bridge/internals.d.ts +2 -0
  25. package/dist/bridge/internals.js +1 -0
  26. package/dist/bridge/local-yield-flag.d.ts +6 -0
  27. package/dist/bridge/local-yield-flag.js +34 -0
  28. package/dist/bridge/readiness-result-outbox.d.ts +25 -0
  29. package/dist/bridge/readiness-result-outbox.js +74 -0
  30. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  31. package/dist/bridge/readiness-result-worker.js +121 -0
  32. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  33. package/dist/bridge/runner-host-capabilities.js +110 -0
  34. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  35. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  36. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  37. package/dist/bridge/test-postgres-capability.js +120 -0
  38. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  39. package/dist/cleanup/cleanup-wip.js +66 -0
  40. package/dist/cleanup/cleanup.service.d.ts +21 -1
  41. package/dist/cleanup/cleanup.service.js +185 -143
  42. package/dist/cleanup/cleanup.types.d.ts +6 -0
  43. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  44. package/dist/cleanup/forge-owned-paths.js +53 -0
  45. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  46. package/dist/cleanup/host-runtime-ledger.js +130 -0
  47. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  48. package/dist/cleanup/managed-branch-sweep.js +111 -0
  49. package/dist/cli/cli.help.js +78 -16
  50. package/dist/cli/cli.service.d.ts +32 -15
  51. package/dist/cli/cli.service.js +206 -182
  52. package/dist/cli/idle-status.d.ts +84 -0
  53. package/dist/cli/idle-status.js +181 -0
  54. package/dist/cli/local-config.d.ts +7 -0
  55. package/dist/cli/local-config.js +36 -4
  56. package/dist/cli/provider-cli-detection.d.ts +10 -0
  57. package/dist/cli/provider-cli-detection.js +160 -0
  58. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  59. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  60. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  61. package/dist/runtime/attempt-database-broker.js +390 -0
  62. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  63. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  64. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  65. package/dist/runtime/attempt-path-operation.js +94 -0
  66. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  67. package/dist/runtime/attempt-private-directory.js +54 -0
  68. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  69. package/dist/runtime/attempt-process-supervisor.js +144 -23
  70. package/dist/runtime/canonical-source-file.d.ts +3 -0
  71. package/dist/runtime/canonical-source-file.js +54 -0
  72. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  73. package/dist/runtime/docker-engine-probe.js +340 -0
  74. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  75. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  76. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  77. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  78. package/dist/runtime/generated-output-reset.d.ts +10 -0
  79. package/dist/runtime/generated-output-reset.js +62 -8
  80. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  81. package/dist/runtime/host-database-capability-boundary.js +63 -0
  82. package/dist/runtime/host-diagnostics.d.ts +11 -0
  83. package/dist/runtime/host-diagnostics.js +192 -0
  84. package/dist/runtime/host-execution-root.d.ts +4 -0
  85. package/dist/runtime/host-execution-root.js +39 -0
  86. package/dist/runtime/host-facts.d.ts +36 -0
  87. package/dist/runtime/host-facts.js +95 -0
  88. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  89. package/dist/runtime/host-listener-inspector.js +121 -60
  90. package/dist/runtime/host-load-admission.d.ts +67 -0
  91. package/dist/runtime/host-load-admission.js +99 -0
  92. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  93. package/dist/runtime/host-load-child-environment.js +76 -0
  94. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  95. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  96. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  97. package/dist/runtime/host-load-governor-config.js +83 -0
  98. package/dist/runtime/host-load-governor.d.ts +186 -0
  99. package/dist/runtime/host-load-governor.js +632 -0
  100. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  101. package/dist/runtime/host-load-ledger-lock.js +187 -0
  102. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  103. package/dist/runtime/host-load-runtime-settings.js +80 -0
  104. package/dist/runtime/host-load-sampler.d.ts +156 -0
  105. package/dist/runtime/host-load-sampler.js +298 -0
  106. package/dist/runtime/host-load-step-class.d.ts +70 -0
  107. package/dist/runtime/host-load-step-class.js +161 -0
  108. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  109. package/dist/runtime/host-load-step-reaper.js +95 -0
  110. package/dist/runtime/host-load-step-run.d.ts +73 -0
  111. package/dist/runtime/host-load-step-run.js +102 -0
  112. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  113. package/dist/runtime/host-load-test-slot.js +81 -0
  114. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  115. package/dist/runtime/host-load-token-ledger.js +453 -0
  116. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  117. package/dist/runtime/host-load-windows-cpu.js +85 -0
  118. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  119. package/dist/runtime/host-pressure-stall.js +168 -0
  120. package/dist/runtime/host-runtime-contract.d.ts +28 -1
  121. package/dist/runtime/host-runtime-contract.js +203 -57
  122. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  123. package/dist/runtime/host-runtime-lease.js +1427 -124
  124. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  125. package/dist/runtime/host-runtime-promotion.js +107 -12
  126. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  127. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  128. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  129. package/dist/runtime/host-runtime-requirements.js +117 -0
  130. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  131. package/dist/runtime/managed-command-teardown.js +596 -0
  132. package/dist/runtime/memory-capacity.d.ts +70 -0
  133. package/dist/runtime/memory-capacity.js +123 -0
  134. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  135. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  136. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  137. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  138. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  139. package/dist/runtime/pinned-directory-process.js +61 -0
  140. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  141. package/dist/runtime/pinned-source-directory.js +94 -0
  142. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  143. package/dist/runtime/playwright-browser-cache.js +227 -0
  144. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  145. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  146. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  147. package/dist/runtime/prepared-runtime-identity.js +218 -0
  148. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  149. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  150. package/dist/runtime/runner-settings.d.ts +104 -0
  151. package/dist/runtime/runner-settings.js +236 -0
  152. package/dist/runtime/runtime-isolation-lease.js +4 -1
  153. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  154. package/dist/runtime/workspace-resource-estimator.js +174 -0
  155. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  156. package/dist/sandbox/host-capacity-broker.js +336 -0
  157. package/dist/sandbox/managed-branch.d.ts +13 -0
  158. package/dist/sandbox/managed-branch.js +36 -0
  159. package/dist/sandbox/preflight.d.ts +31 -1
  160. package/dist/sandbox/preflight.js +237 -51
  161. package/dist/sandbox/provider-auth/codex.js +11 -11
  162. package/dist/sandbox/repository-lock.d.ts +2 -1
  163. package/dist/sandbox/repository-lock.js +19 -9
  164. package/dist/sandbox/runtime.d.ts +16 -2
  165. package/dist/sandbox/runtime.js +183 -114
  166. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  167. package/dist/sandbox/sandbox-cgroups.js +42 -0
  168. package/dist/sandbox/sandbox.types.d.ts +7 -0
  169. package/dist/sandbox/workspace.service.js +2 -0
  170. package/dist/session/architect-waits.d.ts +2 -0
  171. package/dist/session/architect-waits.js +138 -0
  172. package/dist/session/managed-attempt-tools.d.ts +37 -1
  173. package/dist/session/managed-attempt-tools.js +822 -84
  174. package/dist/session/managed-build-coordinator.d.ts +5 -0
  175. package/dist/session/managed-build-coordinator.js +109 -0
  176. package/dist/session/managed-build-receipt.d.ts +26 -0
  177. package/dist/session/managed-build-receipt.js +342 -0
  178. package/dist/session/managed-command-host-load.d.ts +47 -0
  179. package/dist/session/managed-command-host-load.js +83 -0
  180. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  181. package/dist/session/managed-verification-timeouts.js +17 -0
  182. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  183. package/dist/session/mcp-argument-coercion.js +121 -0
  184. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  185. package/dist/session/phase-completion.artifacts.js +321 -45
  186. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  187. package/dist/session/phase-completion.command-validation.js +77 -0
  188. package/dist/session/phase-completion.d.ts +23 -1
  189. package/dist/session/phase-completion.helpers.d.ts +5 -0
  190. package/dist/session/phase-completion.helpers.js +43 -19
  191. package/dist/session/phase-completion.js +19 -3
  192. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  193. package/dist/session/phase-completion.mcp-args.js +156 -0
  194. package/dist/session/phase-completion.prompts.js +22 -18
  195. package/dist/session/phase-completion.runtime.d.ts +6 -10
  196. package/dist/session/phase-completion.runtime.js +214 -224
  197. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  198. package/dist/session/phase-completion.schema-parts.js +188 -0
  199. package/dist/session/phase-completion.schemas.d.ts +3 -3
  200. package/dist/session/phase-completion.schemas.js +250 -226
  201. package/dist/session/phase-completion.validation.d.ts +3 -3
  202. package/dist/session/phase-completion.validation.js +135 -89
  203. package/dist/session/pre-publication-host-load.d.ts +27 -0
  204. package/dist/session/pre-publication-host-load.js +111 -0
  205. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  206. package/dist/session/pre-publication-native-postgres.js +111 -0
  207. package/dist/session/pre-publication-pass.d.ts +61 -0
  208. package/dist/session/pre-publication-pass.js +148 -0
  209. package/dist/session/pre-publication-process.d.ts +23 -0
  210. package/dist/session/pre-publication-process.js +109 -0
  211. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  212. package/dist/session/pre-publication-skipped-tests.js +109 -0
  213. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  214. package/dist/session/pre-publication-step-execution.js +50 -0
  215. package/dist/session/pre-publication-validation.d.ts +91 -0
  216. package/dist/session/pre-publication-validation.js +670 -0
  217. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  218. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  219. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  220. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  221. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  222. package/dist/session/provider-cli/claude-background-work.js +181 -0
  223. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  224. package/dist/session/provider-cli/host-build-lock.js +30 -0
  225. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  226. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  227. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  228. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  229. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  230. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  231. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  232. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  233. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  234. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  235. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +85 -19
  237. package/dist/session/provider-cli/provider-cli.process.js +566 -283
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
  239. package/dist/session/provider-cli/provider-cli.prompts.js +211 -36
  240. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  241. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -1
  243. package/dist/session/provider-cli/provider-cli.runtime.js +83 -4
  244. package/dist/session/provider-cli/provider-cli.service.d.ts +36 -5
  245. package/dist/session/provider-cli/provider-cli.service.js +818 -99
  246. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  247. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  248. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  249. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  250. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  251. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  252. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  253. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  254. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  255. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  256. package/dist/session/provider-cli/provider-output-state.js +376 -17
  257. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  258. package/dist/session/provider-cli/provider-usage.js +28 -5
  259. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  260. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  261. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  262. package/dist/session/publishable-worktree-changes.js +193 -0
  263. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  264. package/dist/session/qa-sidecar-validation.js +28 -0
  265. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  266. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  267. package/dist/session/session-redaction.js +284 -9
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.service.d.ts +11 -2
  270. package/dist/session/session.service.js +301 -58
  271. package/dist/session/session.types.d.ts +150 -2
  272. package/dist/session/session.types.js +599 -7
  273. package/dist/session/sidecar-json-shape.d.ts +31 -0
  274. package/dist/session/sidecar-json-shape.js +217 -0
  275. package/dist/session/unreferenced-exports.d.ts +12 -0
  276. package/dist/session/unreferenced-exports.js +59 -0
  277. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  278. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  279. package/dist/shared/format/format-bytes.d.ts +1 -0
  280. package/dist/shared/format/format-bytes.js +9 -0
  281. package/dist/shared/fs/file-identity.d.ts +10 -0
  282. package/dist/shared/fs/file-identity.js +15 -0
  283. package/dist/shared/fs/replace-file.d.ts +7 -0
  284. package/dist/shared/fs/replace-file.js +33 -0
  285. package/dist/shared/git/git.js +2 -1
  286. package/dist/shared/path/path.d.ts +1 -0
  287. package/dist/shared/path/path.js +18 -0
  288. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  289. package/dist/shared/process/dotnet-toolchain.js +307 -0
  290. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  291. package/dist/shared/process/host-process-recovery.js +26 -5
  292. package/dist/shared/process/host-process-supervisor.d.ts +16 -1
  293. package/dist/shared/process/host-process-supervisor.js +124 -23
  294. package/dist/shared/process/process-tree.d.ts +52 -0
  295. package/dist/shared/process/process-tree.js +144 -0
  296. package/dist/shared/process/process.d.ts +69 -0
  297. package/dist/shared/process/process.js +223 -16
  298. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  299. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  300. package/dist/shared/process/windows-launch.d.ts +18 -0
  301. package/dist/shared/process/windows-launch.js +68 -0
  302. package/dist/shared/provider-capabilities.d.ts +3 -0
  303. package/dist/shared/provider-capabilities.js +92 -0
  304. package/dist/shared/redaction/redaction.d.ts +1 -0
  305. package/dist/shared/redaction/redaction.js +39 -3
  306. package/dist/shared/time/monotonic.d.ts +1 -0
  307. package/dist/shared/time/monotonic.js +8 -0
  308. package/dist/version.d.ts +1 -1
  309. package/dist/version.js +1 -1
  310. package/dist/worktree/dependency-warmer.d.ts +66 -9
  311. package/dist/worktree/dependency-warmer.js +609 -24
  312. package/dist/worktree/index.d.ts +1 -1
  313. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  314. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  315. package/dist/worktree/wip-git.d.ts +33 -0
  316. package/dist/worktree/wip-git.js +122 -0
  317. package/dist/worktree/wip-refs.d.ts +62 -0
  318. package/dist/worktree/wip-refs.js +119 -0
  319. package/dist/worktree/wip-restore.d.ts +38 -0
  320. package/dist/worktree/wip-restore.js +190 -0
  321. package/dist/worktree/wip-snapshot.d.ts +50 -0
  322. package/dist/worktree/wip-snapshot.js +268 -0
  323. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  324. package/dist/worktree/worktree-wip-events.js +98 -0
  325. package/dist/worktree/worktree-wip.d.ts +49 -0
  326. package/dist/worktree/worktree-wip.js +182 -0
  327. package/dist/worktree/worktree.base.d.ts +7 -1
  328. package/dist/worktree/worktree.service.d.ts +22 -2
  329. package/dist/worktree/worktree.service.js +302 -25
  330. package/dist/worktree/worktree.types.d.ts +36 -1
  331. package/package.json +8 -6
  332. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,28 +1,66 @@
1
+ import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
1
2
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { randomUUID } from "node:crypto";
5
6
  import os from "node:os";
6
7
  import { defaultForgeBridgeConfig } from "../config.js";
7
- import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
8
+ import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
8
9
  import { redactText } from "../shared/redaction/redaction.js";
9
10
  import { BridgeSessionService } from "../session/session.service.js";
10
- import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
11
+ import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
13
+ import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
11
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
12
- import { HostRuntimeLeaseManager } from "../runtime/host-runtime-lease.js";
15
+ import { PrePublicationValidator } from "../session/pre-publication-validation.js";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
+ import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
18
+ import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
+ import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
+ import { readLocalYieldFlag } from "./local-yield-flag.js";
21
+ import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
22
+ import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
23
+ import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
24
+ import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
25
+ import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
26
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
27
+ import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
13
28
  import { GitWorktreeService } from "../worktree/worktree.service.js";
14
29
  import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
15
30
  import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
16
- import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
31
+ import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
17
32
  import { forgeBridgeVersion } from "../version.js";
18
33
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
19
- import { validateSandboxContract } from "../sandbox/contract.js";
20
- import { runSandboxProcess } from "../sandbox/process.js";
21
- import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
34
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
22
35
  import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
36
+ import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
37
+ import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
38
+ import { HostLoadSampler } from "../runtime/host-load-sampler.js";
39
+ import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
40
+ import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
41
+ import { BridgeStatePublisher } from "./bridge-state-file.js";
42
+ import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
43
+ import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
44
+ export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
45
+ /**
46
+ * Protocol-v2 events are acknowledged one at a time before runOnce returns.
47
+ * Sending the complete transcript again in DispatchResult made long QA and CI
48
+ * sessions exceed SignalR's receive limit, disconnecting the bridge after the
49
+ * provider had already completed. The API combines its acknowledged streamed
50
+ * events with the terminal result, so the callback only needs the outcome and
51
+ * artifacts. Protocol v1 retains the transcript for legacy servers.
52
+ */
53
+ export function compactTerminalResult(dispatch, result) {
54
+ return dispatch.schemaVersion >= 2 && result.events.length > 0
55
+ ? { ...result, events: [] }
56
+ : result;
57
+ }
23
58
  export class ForgeBridgeService {
24
59
  config;
25
60
  connections;
61
+ hostCapabilityProbe;
62
+ chatProcessRunner;
63
+ hostLoad;
26
64
  connection = null;
27
65
  heartbeatTimer = null;
28
66
  heartbeatInFlight = false;
@@ -32,18 +70,76 @@ export class ForgeBridgeService {
32
70
  sandboxMaintenanceTimer = null;
33
71
  sandboxMaintenanceRunning = false;
34
72
  closed = null;
73
+ transportRecovery = null;
74
+ transportRecoveryGeneration = 0;
35
75
  stopped = false;
76
+ revokedReason = null;
36
77
  activeSessions = new Map();
37
78
  reservations = new Map();
38
79
  activeReadinessProbes = new Map();
80
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
81
+ inFlight = new BridgeInFlightRegistry();
82
+ readinessResultOutbox;
83
+ readinessResultFlush = null;
84
+ dispatchResultOutbox;
85
+ dispatchResultFlush = null;
86
+ dispatchResultGeneration = 0;
87
+ dispatchResultFlushedGeneration = -1;
88
+ dispatchResultHandoffs = new Map();
39
89
  preflight;
90
+ dockerEngineProbe;
40
91
  sandboxRuntime;
41
92
  sandboxResourceResolver;
42
93
  sessions;
43
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver) {
94
+ enforceHostDatabaseCapabilityBoundary;
95
+ hostCapabilities = emptyRunnerHostCapabilitySnapshot();
96
+ dockerAvailable = false;
97
+ // Decision 0014 settings push. The last applied server document (null until one
98
+ // arrives: an old server never sends one), the local `forge-bridge yield` flag,
99
+ // and the effective settings computed from both and the host's env bounds.
100
+ appliedSettingsDocument = null;
101
+ localYield = false;
102
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
103
+ forgeAckedYield = false;
104
+ publishState = () => undefined;
105
+ effectiveSettings;
106
+ settingsReport;
107
+ /** Applies run one at a time; offers wait for every apply queued before them. */
108
+ settingsTail = Promise.resolve();
109
+ // Server documents that turn yield on and are queued but not applied yet. The
110
+ // reservation commit is synchronous and can't wait for the apply, so it counts these.
111
+ pendingYieldOn = 0;
112
+ settingsStarted = null;
113
+ hostRequirementFacts() {
114
+ const facts = this.hostLoad.facts();
115
+ return {
116
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
117
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
118
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
119
+ .filter(([, tool]) => tool?.available === true)
120
+ .map(([name]) => name),
121
+ dockerAvailable: this.dockerAvailable,
122
+ browserLaunch: this.hostCapabilities.browserLaunch,
123
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
124
+ };
125
+ }
126
+ // Reaping deletes the stale ledger, so its stopped-process proof is held here
127
+ // until a Hello carrying it is accepted. A bridge restart forgets it, which
128
+ // leaves those attempts on Forge's conservative unknown-outcome path.
129
+ recoveredHostAttempts = new Map();
130
+ hostCapabilitiesDetected = false;
131
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
132
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
133
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
44
134
  this.config = config;
45
135
  this.connections = connections;
46
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot);
136
+ this.hostCapabilityProbe = hostCapabilityProbe;
137
+ this.chatProcessRunner = chatProcessRunner;
138
+ this.hostLoad = hostLoad;
139
+ this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
140
+ if (this.enforceHostDatabaseCapabilityBoundary) {
141
+ establishHostDatabaseCapabilityBoundary();
142
+ }
47
143
  this.preflight = preflight ?? new DockerPreflight({
48
144
  dockerExecutable: config.dockerExecutable,
49
145
  dockerContext: config.dockerContext,
@@ -59,17 +155,49 @@ export class ForgeBridgeService {
59
155
  runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
60
156
  requireRootless: config.requireRootlessDocker
61
157
  });
62
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
158
+ this.dockerEngineProbe = dockerEngineProbe ?? new DockerEngineProbe({
159
+ dockerExecutable: config.dockerExecutable,
160
+ dockerContext: config.dockerContext,
161
+ recovery: {
162
+ enabled: config.dockerDesktopRecoveryEnabled,
163
+ failureThreshold: config.dockerRecoveryFailureThreshold,
164
+ cooldownMs: config.dockerRecoveryCooldownMs,
165
+ startupTimeoutMs: config.dockerRecoveryStartupTimeoutMs,
166
+ canRecover: () => this.activeSessions.size === 0 && this.reservations.size === 0,
167
+ },
168
+ onStatus: logBridgeStatus,
169
+ });
170
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
171
+ this.sessions = sessions ?? defaultSessions.sessions;
172
+ // Docker sandboxes ask the same host load governor for their validation tokens.
173
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
63
174
  this.sandboxResourceResolver = sandboxResourceResolver
64
175
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
176
+ this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
177
+ this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
178
+ // With no server document and no local flag these equal today's env/default behaviour.
179
+ this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
180
+ this.settingsReport = this.effectiveSettings.report;
181
+ this.inFlight.addSource(() => [
182
+ ...reservationInFlightEntries(this.reservations),
183
+ ...sessionInFlightEntries(this.activeSessions),
184
+ ...readinessInFlightEntries(this.activeReadinessProbes),
185
+ ]);
65
186
  }
66
187
  async connectOnce() {
188
+ if (this.revokedReason !== null) {
189
+ throw new BridgeRevokedError(this.revokedReason);
190
+ }
67
191
  await this.stopConnection();
68
192
  this.stopped = false;
193
+ if (this.enforceHostDatabaseCapabilityBoundary) {
194
+ assertHostDatabaseCapabilityBoundary();
195
+ }
69
196
  const hostReap = await this.sessions.reapHostRuntime?.({
70
197
  runnerId: this.config.runnerId,
71
198
  runnerInstanceId: this.config.runnerInstanceId,
72
199
  });
200
+ this.rememberRecoveredHostAttempts(hostReap);
73
201
  if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
74
202
  logBridgeStatus(`Managed-host recovery reaped ${hostReap.reaped} stale attempt(s), protected ${hostReap.reusedPidsProtected} reused PID(s), and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
75
203
  }
@@ -80,37 +208,133 @@ export class ForgeBridgeService {
80
208
  await this.preflight.refresh();
81
209
  }
82
210
  }
211
+ await this.dockerEngineProbe.refresh(true);
212
+ if (!this.hostCapabilitiesDetected) {
213
+ this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
214
+ this.hostCapabilitiesDetected = true;
215
+ }
216
+ // Static host facts and the first load sample ride on Hello; the sampler
217
+ // keeps refreshing its cached snapshot for later heartbeats.
218
+ await this.hostLoad.start().catch(() => undefined);
219
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
220
+ await this.startSettings();
83
221
  const connection = this.connections.create(this.config);
84
222
  this.connection = connection;
223
+ this.transportRecovery = null;
85
224
  this.closed = new Promise((resolve) => {
86
- connection.onClose(() => {
225
+ connection.onClose((error) => {
87
226
  this.stopHeartbeat();
227
+ this.completeTransportRecovery(error ?? new Error("bridge connection closed"));
88
228
  this.abortActiveSessions("bridge connection closed");
89
229
  this.abortActiveReadinessProbes("bridge connection closed");
90
230
  resolve();
91
231
  });
92
232
  });
93
- connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
94
- connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
95
- connection.onStart?.((dispatch) => this.handleStart(dispatch));
233
+ connection.onReconnecting?.((error) => {
234
+ if (connection !== this.connection || this.stopped)
235
+ return;
236
+ this.stopHeartbeat();
237
+ this.beginTransportRecovery();
238
+ logBridgeStatus(`Forge connection interrupted${error ? `: ${errorMessage(error)}` : ""}. Reconnecting in place; active dispatches remain supervised...`);
239
+ });
240
+ connection.onReconnected?.(async () => {
241
+ if (connection !== this.connection || this.stopped)
242
+ return;
243
+ try {
244
+ await this.registerConnection(connection);
245
+ this.completeTransportRecovery();
246
+ this.startHeartbeat();
247
+ await this.flushDispatchResults(true).catch(error => {
248
+ logBridgeStatus(`Dispatch result replay deferred after reconnect: ${errorMessage(error)}`);
249
+ });
250
+ await this.flushReadinessResults().catch(error => {
251
+ logBridgeStatus(`Readiness result replay deferred after reconnect: ${errorMessage(error)}`);
252
+ });
253
+ await this.flushCleanupReports().catch(() => undefined);
254
+ logBridgeStatus("Forge connection restored; active dispatches remain attached to this runner process.");
255
+ }
256
+ catch (error) {
257
+ this.completeTransportRecovery(error);
258
+ logBridgeStatus(`Forge reconnect registration failed: ${errorMessage(error)}. Closing the connection for a clean retry...`);
259
+ await connection.stop().catch(() => undefined);
260
+ }
261
+ });
262
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
263
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
264
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
265
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
96
266
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
97
267
  connection.onCancel((request) => this.handleCancel(request));
98
268
  connection.onReap?.((request) => this.handleReap(request));
99
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
269
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
270
+ connection.onRevoked?.((notice) => this.handleRevoked(notice));
271
+ connection.onApplySettings?.((document) => this.handleApplySettings(document));
100
272
  await connection.start();
101
- await this.invokeAck("Hello", {
102
- version: this.config.version,
103
- protocolVersion: this.config.protocolVersion,
104
- minServerVersion: this.config.minServerVersion ?? null,
105
- runnerInstanceId: this.config.runnerInstanceId,
106
- capabilities: this.capabilities()
273
+ await this.registerConnection(connection);
274
+ await this.flushDispatchResults(true).catch(error => {
275
+ logBridgeStatus(`Dispatch result replay deferred: ${errorMessage(error)}`);
276
+ });
277
+ await this.flushReadinessResults().catch(error => {
278
+ logBridgeStatus(`Readiness result replay deferred: ${errorMessage(error)}`);
107
279
  });
108
280
  await this.flushCleanupReports();
109
281
  this.startHeartbeat();
110
282
  this.startLeaseWatchdog();
111
283
  this.startSandboxMaintenance();
112
284
  }
285
+ rememberRecoveredHostAttempts(report) {
286
+ for (const attempt of report?.recoveredAttempts ?? []) {
287
+ if (this.recoveredHostAttempts.size >= maxRecoveredHostAttempts)
288
+ break;
289
+ this.recoveredHostAttempts.set(attempt.dispatchAttemptId, attempt);
290
+ }
291
+ }
292
+ async recoveredHostAttemptsForHello() {
293
+ if (this.recoveredHostAttempts.size === 0)
294
+ return [];
295
+ // A durable terminal result outranks the stopped-process proof: it replays
296
+ // after Hello and Forge accepts the provider's real outcome instead.
297
+ const pendingResults = new Set((await this.dispatchResultOutbox.pending())
298
+ .map(entry => entry.payload.dispatchAttemptId)
299
+ .filter((id) => typeof id === "string"));
300
+ return [...this.recoveredHostAttempts.values()]
301
+ .filter(attempt => !pendingResults.has(attempt.dispatchAttemptId));
302
+ }
303
+ async registerConnection(connection) {
304
+ let storageRecoveryAttempt = 0;
305
+ while (true) {
306
+ try {
307
+ const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
308
+ const reportedYield = this.settingsReport.values.yieldToForeground;
309
+ const ack = await connection.invoke("Hello", {
310
+ version: this.config.version,
311
+ protocolVersion: this.config.protocolVersion,
312
+ minServerVersion: this.config.minServerVersion ?? null,
313
+ runnerInstanceId: this.config.runnerInstanceId,
314
+ capabilities: this.capabilities(),
315
+ recoveredHostAttempts,
316
+ });
317
+ if (!ack.accepted) {
318
+ throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
319
+ }
320
+ this.recoveredHostAttempts.clear();
321
+ this.ackYield(reportedYield);
322
+ logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
323
+ return;
324
+ }
325
+ catch (error) {
326
+ if (!isProviderStorageUnavailable(error) || storageRecoveryAttempt >= this.config.reconnectBackoffMs.length) {
327
+ throw error;
328
+ }
329
+ const backoff = this.config.reconnectBackoffMs[storageRecoveryAttempt] ?? 5000;
330
+ storageRecoveryAttempt += 1;
331
+ logBridgeStatus(`Hello reached Forge while storage was recovering. Retrying registration ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
332
+ await delay(backoff);
333
+ }
334
+ }
335
+ }
113
336
  async run(signal) {
337
+ const statePublisher = await this.startStatePublisher();
114
338
  let attempt = 0;
115
339
  try {
116
340
  while (!this.stopped && !signal?.aborted) {
@@ -126,7 +350,7 @@ export class ForgeBridgeService {
126
350
  }
127
351
  }
128
352
  catch (error) {
129
- if (this.stopped || signal?.aborted) {
353
+ if (this.stopped || signal?.aborted || this.revokedReason !== null) {
130
354
  break;
131
355
  }
132
356
  const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
@@ -142,6 +366,214 @@ export class ForgeBridgeService {
142
366
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
143
367
  }
144
368
  await this.stopConnection();
369
+ await statePublisher?.stop();
370
+ }
371
+ if (this.revokedReason !== null) {
372
+ throw new BridgeRevokedError(this.revokedReason);
373
+ }
374
+ }
375
+ async startStatePublisher() {
376
+ if (!this.config.bridgeStatePath)
377
+ return null;
378
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
379
+ inFlight: () => this.inFlight.snapshot(),
380
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
381
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
382
+ yieldApplied: () => this.effectiveSettings.yielding,
383
+ connected: () => this.connection !== null && this.transportRecovery === null,
384
+ }, { log: logBridgeStatus });
385
+ this.publishState = () => void publisher.publish();
386
+ this.inFlight.onChange(this.publishState);
387
+ await publisher.start();
388
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
389
+ return publisher;
390
+ }
391
+ /** The reason Forge gave when it removed this runner, or null while it is paired. */
392
+ get revoked() {
393
+ return this.revokedReason;
394
+ }
395
+ /**
396
+ * Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
397
+ * reconnecting; its attempts were already settled on the server, so local work is
398
+ * aborted rather than reported.
399
+ */
400
+ handleRevoked(notice) {
401
+ if (this.revokedReason !== null)
402
+ return;
403
+ const reason = typeof notice?.reason === "string" && notice.reason.trim()
404
+ ? notice.reason.trim()
405
+ : bridgeRevokedMessage;
406
+ this.revokedReason = reason;
407
+ this.stopped = true;
408
+ logBridgeStatus(reason);
409
+ this.abortActiveSessions("runner removed from Forge");
410
+ this.abortActiveReadinessProbes("runner removed from Forge");
411
+ void this.stopConnection().catch(() => undefined);
412
+ }
413
+ /** The effective settings and how they were derived, as last reported (decision 0014). */
414
+ get runnerSettings() {
415
+ return this.settingsReport;
416
+ }
417
+ runnerHostDefaults() {
418
+ return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
419
+ }
420
+ /**
421
+ * Once per bridge process: drop governor overrides an earlier process left on
422
+ * the state root, then put today's effective settings (env bounds and the local
423
+ * yield flag, no server document yet) in force.
424
+ */
425
+ async startSettings() {
426
+ this.settingsStarted ??= (async () => {
427
+ await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
428
+ logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
429
+ });
430
+ this.localYield = await this.readLocalYield();
431
+ await this.enqueueSettings({ kind: "local" });
432
+ })();
433
+ await this.settingsStarted;
434
+ }
435
+ /**
436
+ * Decision 0014 `ApplySettings`. Applies only a document newer than the one
437
+ * applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
438
+ * the applied version is acknowledged again without applying it; an older one is
439
+ * ignored.
440
+ */
441
+ async handleApplySettings(raw) {
442
+ const document = parseRunnerSettingsDocument(raw);
443
+ if (!document) {
444
+ logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
445
+ return;
446
+ }
447
+ if (document.runnerId && document.runnerId !== this.config.runnerId) {
448
+ logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
449
+ return;
450
+ }
451
+ await this.enqueueSettings({ kind: "server", document });
452
+ }
453
+ /**
454
+ * Polls the local `forge-bridge yield` flag (every heartbeat and before each
455
+ * offer decision). A change is applied at once and reported again under the
456
+ * same settings version.
457
+ */
458
+ /** Yielding now, or about to: a received yield-on that is still being applied counts. */
459
+ yieldingOrQueued() {
460
+ return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
461
+ }
462
+ async refreshLocalYield() {
463
+ if (!this.config.localYieldFlagPath)
464
+ return;
465
+ const localYield = await this.readLocalYield();
466
+ if (localYield === this.localYield)
467
+ return;
468
+ this.localYield = localYield;
469
+ logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
470
+ await this.enqueueSettings({ kind: "local" });
471
+ }
472
+ /**
473
+ * A setting the host couldn't put in force holds placement on the server, so
474
+ * every heartbeat tries the applied document again until it takes.
475
+ */
476
+ async retryFailedSettings() {
477
+ if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
478
+ return;
479
+ await this.enqueueSettings({ kind: "local" });
480
+ }
481
+ async readLocalYield() {
482
+ const flagPath = this.config.localYieldFlagPath;
483
+ return flagPath ? await readLocalYieldFlag(flagPath) : false;
484
+ }
485
+ enqueueSettings(change) {
486
+ const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
487
+ if (turnsYieldOn)
488
+ this.pendingYieldOn += 1;
489
+ const applied = this.settingsTail
490
+ .then(() => this.applySettings(change))
491
+ .finally(() => {
492
+ if (turnsYieldOn)
493
+ this.pendingYieldOn -= 1;
494
+ });
495
+ // A failed apply must not wedge later applies or the offers waiting on them.
496
+ this.settingsTail = applied.catch(error => {
497
+ logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
498
+ });
499
+ return this.settingsTail;
500
+ }
501
+ async applySettings(change) {
502
+ const applied = this.appliedSettingsDocument;
503
+ if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
504
+ if (change.document.version === applied.version) {
505
+ // The server sends the current version again at each Hello. After a reconnect it may never
506
+ // have seen this version's ack (the old connection dropped first), and its offer gate waits
507
+ // for one from this connection, so acknowledge what is in force again rather than nothing.
508
+ void this.sendSettingsApplied(this.settingsReport);
509
+ return;
510
+ }
511
+ logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
512
+ return;
513
+ }
514
+ const document = change.kind === "server" ? change.document : applied;
515
+ const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
516
+ const failures = await this.putSettingsInForce(effective);
517
+ // Report what is in force: a key the host couldn't take keeps its previous value.
518
+ const report = {
519
+ ...runnerSettingsInForce(effective.report, this.settingsReport, failures),
520
+ version: document?.version ?? null,
521
+ };
522
+ const changed = !sameRunnerSettingsReport(report, this.settingsReport);
523
+ this.appliedSettingsDocument = document;
524
+ this.effectiveSettings = effective;
525
+ this.settingsReport = report;
526
+ this.publishState();
527
+ if (change.kind === "server") {
528
+ logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
529
+ }
530
+ // Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
531
+ if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
532
+ void this.sendSettingsApplied(report);
533
+ }
534
+ }
535
+ /**
536
+ * Max attempts and the memory reserve go to host attempt admission; the governor
537
+ * budget (the yield budget while yielding) and the heavy-step limit go to the
538
+ * shared settings file every governor on the state root reads at admission.
539
+ * Neither touches admitted work. Returns the keys the host could not put in
540
+ * force (`apply_failed`); their previous values stay in force.
541
+ */
542
+ async putSettingsInForce(effective) {
543
+ const { values } = effective.report;
544
+ const rejected = [];
545
+ try {
546
+ await this.sessions.applyRunnerLimits?.({
547
+ maxConcurrentAttempts: values.maxConcurrentAttempts,
548
+ memoryReserveBytes: values.memoryReserveBytes,
549
+ });
550
+ }
551
+ catch (error) {
552
+ const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
553
+ rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
554
+ }
555
+ try {
556
+ await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
557
+ cpuBudgetFraction: effective.governorCpuBudgetFraction,
558
+ maxHeavySteps: values.maxHeavySteps,
559
+ yielding: effective.yielding,
560
+ });
561
+ }
562
+ catch (error) {
563
+ const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
564
+ rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
565
+ }
566
+ return rejected;
567
+ }
568
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
569
+ /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
570
+ async sendSettingsApplied(report) {
571
+ try {
572
+ await this.invokeAck("SettingsApplied", report);
573
+ this.ackYield(report.values.yieldToForeground);
574
+ }
575
+ catch (error) {
576
+ logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
145
577
  }
146
578
  }
147
579
  async stop() {
@@ -149,36 +581,366 @@ export class ForgeBridgeService {
149
581
  this.abortActiveSessions("bridge stopping");
150
582
  this.abortActiveReadinessProbes("bridge stopping");
151
583
  await this.stopConnection();
584
+ this.hostLoad.stop();
152
585
  await this.preflight.release();
153
586
  }
154
- async handleDispatch(rawDispatch) {
155
- const dispatch = this.parseDispatchOrReport(rawDispatch);
587
+ async handleChatTurn(rawDispatch) {
588
+ const packet = this.parseChatTurnOrReport(rawDispatch);
589
+ if (!packet) {
590
+ return;
591
+ }
592
+ if (packet.runnerInstanceId !== this.config.runnerInstanceId) {
593
+ logBridgeStatus(`Rejected Bridge Chat turn ${packet.turnId}: stale runner instance.`);
594
+ return;
595
+ }
596
+ const capabilityFailure = this.requiredChatCapabilityFailure(packet);
597
+ if (capabilityFailure) {
598
+ await this.sendStandaloneChatTerminal(packet, "failed", {
599
+ code: "bridge_chat.runner_unavailable",
600
+ message: capabilityFailure,
601
+ }).catch(() => undefined);
602
+ return;
603
+ }
604
+ const existing = this.activeSessions.get(packet.leaseId);
605
+ if (existing) {
606
+ if (existing.kind === "chat"
607
+ && existing.fencingToken === packet.fencingToken
608
+ && existing.chatRunId === packet.chatRunId
609
+ && existing.conversationId === packet.conversationId
610
+ && existing.turnId === packet.turnId) {
611
+ return;
612
+ }
613
+ await this.sendStandaloneChatTerminal(packet, "failed", {
614
+ code: "bridge_chat.stale_fencing_token",
615
+ message: "Bridge Chat turn fence conflicts with an active bridge session.",
616
+ }).catch(() => undefined);
617
+ return;
618
+ }
619
+ const controller = new AbortController();
620
+ const active = {
621
+ leaseId: packet.leaseId,
622
+ kind: "chat",
623
+ fencingToken: packet.fencingToken,
624
+ dispatchAttemptId: null,
625
+ runnerInstanceId: packet.runnerInstanceId,
626
+ leaseExpiresAt: chatTurnLeaseExpiresAt(packet),
627
+ sandboxed: false,
628
+ resources: zeroSandboxResources(),
629
+ controller,
630
+ chatRunId: packet.chatRunId,
631
+ conversationId: packet.conversationId,
632
+ turnId: packet.turnId,
633
+ providerThreadId: packet.providerThreadId ?? null,
634
+ chatSequence: 0,
635
+ terminalCallbackAttempted: false,
636
+ };
637
+ this.activeSessions.set(packet.leaseId, active);
638
+ let workspacePath = null;
639
+ let cleanupAttempted = false;
640
+ let cleanupOutcome = null;
641
+ let cleanupReported = false;
642
+ const cleanup = async () => {
643
+ if (!workspacePath || cleanupAttempted)
644
+ return null;
645
+ cleanupAttempted = true;
646
+ cleanupOutcome = await cleanupChatTurnWorkspace(workspacePath, chatRedactionSecrets(packet));
647
+ return cleanupOutcome;
648
+ };
649
+ const reportCleanup = async (outcome) => {
650
+ if (!outcome || cleanupReported)
651
+ return;
652
+ cleanupReported = true;
653
+ await this.sendChatCallback(active, "output_delta", outcome).catch(() => undefined);
654
+ };
655
+ try {
656
+ workspacePath = await this.createChatTurnWorkspace(packet);
657
+ await materializeChatTurnMetadata(packet, workspacePath);
658
+ const run = await this.runChatProviderProcess(packet, active, workspacePath);
659
+ cleanupOutcome = await cleanup();
660
+ await reportCleanup(cleanupOutcome);
661
+ if (controller.signal.aborted) {
662
+ await this.sendChatAbortTerminal(packet, active, cleanupOutcome);
663
+ return;
664
+ }
665
+ if (cleanupOutcome?.status === "failed") {
666
+ throw new Error(`chat_turn_cleanup_failed: ${cleanupOutcome.message}`);
667
+ }
668
+ if (run.result.exitCode !== 0) {
669
+ throw chatProviderExitFailure(run.command, run.result, chatRedactionSecrets(packet));
670
+ }
671
+ await this.sendChatCallback(active, "output_completed", {
672
+ code: "output_completed",
673
+ text: clip(redactText(run.output.finalMessage ?? "", chatRedactionSecrets(packet)), maxChatTerminalTextChars),
674
+ provider: packet.providerKind,
675
+ model: packet.model,
676
+ cleanup: cleanupOutcome,
677
+ });
678
+ }
679
+ catch (error) {
680
+ cleanupOutcome = cleanupOutcome ?? await cleanup();
681
+ if (active.terminalCallbackAttempted) {
682
+ return;
683
+ }
684
+ await reportCleanup(cleanupOutcome);
685
+ const payload = controller.signal.aborted
686
+ ? chatAbortPayload(controller.signal.reason, cleanupOutcome, packet)
687
+ : {
688
+ code: "provider_failed",
689
+ message: clip(redactText(errorMessage(error), chatRedactionSecrets(packet)), 2000),
690
+ cleanup: cleanupOutcome,
691
+ };
692
+ const kind = controller.signal.aborted ? chatAbortKind(controller.signal.reason) : "failed";
693
+ await this.sendChatCallback(active, kind, payload).catch(callbackError => {
694
+ logBridgeStatus(`Bridge Chat terminal callback for turn ${packet.turnId} was not accepted: ${errorMessage(callbackError)}`);
695
+ });
696
+ }
697
+ finally {
698
+ await this.releaseActiveSessionAndRefreshCapacity(packet.leaseId);
699
+ }
700
+ }
701
+ async createChatTurnWorkspace(packet) {
702
+ const root = path.join(this.config.sandboxStateRoot, "chat-turns");
703
+ await fs.promises.mkdir(root, { recursive: true });
704
+ return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
705
+ }
706
+ async runChatProviderProcess(packet, active, cwd) {
707
+ const output = createProviderOutputState(packet.providerKind);
708
+ const plan = buildChatProviderCommand(packet, cwd);
709
+ const redactionSecrets = chatRedactionSecrets(packet);
710
+ let started = false;
711
+ const result = await this.chatProcessRunner.run({
712
+ command: plan.command.command,
713
+ args: plan.command.args,
714
+ cwd,
715
+ env: {
716
+ FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
717
+ FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
718
+ ...plan.env,
719
+ },
720
+ stdin: plan.stdin,
721
+ }, {
722
+ onStarted: async () => {
723
+ started = true;
724
+ await this.sendChatCallback(active, "turn_started", {
725
+ status: "running",
726
+ provider: packet.providerKind,
727
+ model: packet.model,
728
+ command: redactText(formatProviderCliCommandForCheckpoint(plan.command), redactionSecrets),
729
+ });
730
+ },
731
+ onStdoutLine: async (line) => {
732
+ for (const event of output.consume(line)) {
733
+ await this.sendChatProviderEvent(packet, active, event, output.providerThreadId);
734
+ }
735
+ },
736
+ }, active.controller.signal);
737
+ if (started && !active.controller.signal.aborted) {
738
+ await this.sendChatCallback(active, "output_delta", {
739
+ eventType: "provider_cli_completed",
740
+ role: "runner",
741
+ kind: "checkpoint",
742
+ content: "Bridge Chat provider process exited.",
743
+ }).catch(() => undefined);
744
+ }
745
+ assertChatTurnFinished(result);
746
+ return { command: plan.command, output, result };
747
+ }
748
+ async sendChatProviderEvent(packet, active, event, providerThreadId) {
749
+ if (providerThreadId) {
750
+ active.providerThreadId = providerThreadId;
751
+ }
752
+ else if (event.eventType === "provider_thread_started") {
753
+ active.providerThreadId = providerThreadIdFromEvent(event) ?? active.providerThreadId;
754
+ }
755
+ if (event.eventType === "provider_tool_heartbeat") {
756
+ return;
757
+ }
758
+ const redactionSecrets = chatRedactionSecrets(packet);
759
+ const payload = {
760
+ role: event.role,
761
+ kind: event.kind,
762
+ eventType: event.eventType ?? "provider_event",
763
+ content: clip(redactText(event.content, redactionSecrets), maxChatEventContentChars),
764
+ data: event.data ? clip(redactText(event.data, redactionSecrets), maxChatEventContentChars) : undefined,
765
+ };
766
+ await this.sendChatCallback(active, "output_delta", payload);
767
+ }
768
+ async sendChatAbortTerminal(packet, active, cleanupOutcome) {
769
+ await this.sendChatCallback(active, chatAbortKind(active.controller.signal.reason), chatAbortPayload(active.controller.signal.reason, cleanupOutcome, packet));
770
+ }
771
+ async sendStandaloneChatTerminal(packet, kind, payload) {
772
+ const active = {
773
+ leaseId: packet.leaseId,
774
+ kind: "chat",
775
+ fencingToken: packet.fencingToken,
776
+ dispatchAttemptId: null,
777
+ runnerInstanceId: packet.runnerInstanceId,
778
+ leaseExpiresAt: new Date(Date.now() + defaultChatTurnLeaseMs).toISOString(),
779
+ sandboxed: false,
780
+ resources: zeroSandboxResources(),
781
+ controller: new AbortController(),
782
+ chatRunId: packet.chatRunId,
783
+ conversationId: packet.conversationId,
784
+ turnId: packet.turnId,
785
+ providerThreadId: packet.providerThreadId ?? null,
786
+ chatSequence: 0,
787
+ terminalCallbackAttempted: false,
788
+ };
789
+ await this.sendChatCallback(active, kind, payload);
790
+ }
791
+ async sendChatCallback(active, kind, payload = null) {
792
+ if (active.kind !== "chat" || !active.chatRunId || !active.conversationId || !active.turnId) {
793
+ throw new Error("Bridge Chat callback requires an active chat turn.");
794
+ }
795
+ const terminal = isTerminalChatTurnCallbackKind(kind);
796
+ if (terminal && active.terminalCallbackAttempted) {
797
+ return;
798
+ }
799
+ assertBridgeChatCallbackPayload(payload);
800
+ const sequence = (active.chatSequence ?? 0) + 1;
801
+ const envelope = {
802
+ callbackId: randomUUID(),
803
+ chatRunId: active.chatRunId,
804
+ conversationId: active.conversationId,
805
+ turnId: active.turnId,
806
+ leaseId: active.leaseId,
807
+ fencingToken: active.fencingToken,
808
+ runnerId: this.config.runnerId,
809
+ runnerInstanceId: active.runnerInstanceId ?? this.config.runnerInstanceId,
810
+ sequence,
811
+ eventType: kind,
812
+ redactionStatus: "redacted",
813
+ providerThreadId: active.providerThreadId ?? null,
814
+ payload,
815
+ occurredAt: new Date().toISOString(),
816
+ protocolVersion: bridgeChatProtocolVersion,
817
+ };
818
+ if (terminal) {
819
+ active.terminalCallbackAttempted = true;
820
+ }
821
+ await this.invokeChatCallbackWithRetry(envelope);
822
+ active.chatSequence = sequence;
823
+ }
824
+ async invokeChatCallbackWithRetry(envelope) {
825
+ const maxAttempts = 3;
826
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
827
+ try {
828
+ await this.invokeAck("ChatTurnCallback", envelope);
829
+ return;
830
+ }
831
+ catch (error) {
832
+ if (error instanceof BridgeCallbackRejectedError || attempt === maxAttempts - 1) {
833
+ throw error;
834
+ }
835
+ await delay(200 * (attempt + 1));
836
+ }
837
+ }
838
+ }
839
+ requiredChatCapabilityFailure(packet) {
840
+ const capability = this.bridgeChatCapability();
841
+ if (capability.availability === "unavailable" || !capability.supportsTextStreaming) {
842
+ return capability.unavailableReason ?? "Bridge Chat text capability is unavailable.";
843
+ }
844
+ if (capability.supportedProviders.length > 0
845
+ && !containsIgnoreCase(capability.supportedProviders, packet.providerKind)) {
846
+ return `Bridge Chat provider '${packet.providerKind}' is not advertised by this bridge.`;
847
+ }
848
+ if (capability.supportedModels.length > 0
849
+ && !containsIgnoreCase(capability.supportedModels, packet.model)) {
850
+ return `Bridge Chat model '${packet.model}' is not advertised by this bridge.`;
851
+ }
852
+ if (packet.requestedCapabilities.includes("cancel") && !capability.supportsCancel) {
853
+ return "Bridge Chat cancellation is not advertised by this bridge.";
854
+ }
855
+ if (packet.requestedCapabilities.includes("resume") && !capability.supportsResume) {
856
+ return "Bridge Chat resume is not advertised by this bridge.";
857
+ }
858
+ if (packet.requestedCapabilities.includes("thread_continuity")
859
+ && !capability.supportsProviderThreadContinuity) {
860
+ return "Bridge Chat provider thread continuity is not advertised by this bridge.";
861
+ }
862
+ if (packet.requestedCapabilities.includes("attachment_handoffs") && !capability.supportsAttachments) {
863
+ return "Bridge Chat attachment handoffs are not advertised by this bridge.";
864
+ }
865
+ if (packet.requestedCapabilities.includes("action_broker_grants") && !capability.supportsActionBrokerGrants) {
866
+ return "Bridge Chat action-broker grants are not advertised by this bridge.";
867
+ }
868
+ return null;
869
+ }
870
+ bridgeChatCapability() {
871
+ return bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat);
872
+ }
873
+ async handleDispatch(rawDispatch, reservationHandoff) {
874
+ const dispatch = await this.parseDispatchOrReport(rawDispatch);
156
875
  if (!dispatch) {
876
+ this.releaseReservedDispatchHandoff(reservationHandoff);
877
+ return;
878
+ }
879
+ if (this.enforceHostDatabaseCapabilityBoundary) {
880
+ try {
881
+ assertHostDatabaseCapabilityBoundary();
882
+ }
883
+ catch (error) {
884
+ const message = errorMessage(error);
885
+ await this.sendResult(dispatch, failureResult(message, [{
886
+ role: "runner",
887
+ kind: "error",
888
+ content: message,
889
+ eventType: "host_database_capability_forbidden",
890
+ }], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
891
+ this.releaseReservedDispatchHandoff(reservationHandoff);
892
+ return;
893
+ }
894
+ }
895
+ let capabilityFailure;
896
+ try {
897
+ capabilityFailure = await this.requiredCapabilityFailure(dispatch);
898
+ }
899
+ catch (error) {
900
+ this.releaseReservedDispatchHandoff(reservationHandoff);
901
+ throw error;
902
+ }
903
+ if (capabilityFailure) {
904
+ await this.sendResult(dispatch, failureResult(capabilityFailure, [{
905
+ role: "runner",
906
+ kind: "error",
907
+ content: capabilityFailure,
908
+ eventType: "docker_engine_unavailable",
909
+ }], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
910
+ this.releaseReservedDispatchHandoff(reservationHandoff);
157
911
  return;
158
912
  }
159
913
  const leaseId = dispatch.lease.id;
160
914
  const fencingToken = dispatch.lease.fencingToken;
161
915
  const redactionSecrets = exactSecrets(dispatch, this.config);
916
+ if (reservationHandoff && !this.reservedDispatchHandoffIsCurrent(reservationHandoff, dispatch)) {
917
+ await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
918
+ return;
919
+ }
162
920
  const existing = this.activeSessions.get(leaseId);
163
921
  if (existing) {
164
922
  if (existing.fencingToken === fencingToken) {
923
+ this.releaseReservedDispatchHandoff(reservationHandoff);
165
924
  return;
166
925
  }
167
- await this.sendResult(dispatch, failureResult("Dispatch fence conflicts with an active bridge session.")).catch(() => undefined);
926
+ await this.sendResult(dispatch, failureResult("Dispatch fence conflicts with an active bridge session.", [], failureFactsForCode("bridge.dispatch_fence_conflict"))).catch(() => undefined);
927
+ this.releaseReservedDispatchHandoff(reservationHandoff);
168
928
  return;
169
929
  }
170
- const controller = new AbortController();
171
- this.activeSessions.set(leaseId, {
172
- fencingToken,
173
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
174
- runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
175
- leaseExpiresAt: dispatch.lease.expiresAt,
176
- sandboxed: dispatch.sandbox?.executionMode === "docker",
177
- resources: dispatch.sandbox?.executionMode === "docker"
178
- ? dispatch.sandbox.requestedResources
179
- : zeroSandboxResources(),
180
- controller
181
- });
930
+ const controller = reservationHandoff?.controller ?? new AbortController();
931
+ this.registerActiveDispatch(dispatch, controller);
932
+ if (reservationHandoff) {
933
+ // Promotion is synchronous with active-session registration. A qualified
934
+ // pre-start Cancel therefore sees either the cancellable reservation or
935
+ // the fully active owner; there is no cancellation-blind handoff gap.
936
+ this.releaseReservedDispatchHandoff(reservationHandoff);
937
+ }
938
+ // Server-requested runtime readiness is background maintenance. A probe may
939
+ // have passed admission during the narrow handoff between prepared-runtime
940
+ // verification and the foreground attempt's final admission. Preempt it as
941
+ // soon as real agent work arrives so the probe cannot consume the memory
942
+ // headroom that the foreground attempt is waiting to acquire.
943
+ this.deferActiveReadinessProbes();
182
944
  try {
183
945
  const normalized = this.normalizeDispatch(dispatch);
184
946
  if (normalized.sandbox) {
@@ -190,56 +952,160 @@ export class ForgeBridgeService {
190
952
  };
191
953
  await this.invokeAck("DispatchStarted", started);
192
954
  }
193
- const sink = {
194
- emit: async (event) => {
195
- if (event.eventType === "provider_cli_started") {
196
- const active = this.activeSessions.get(leaseId);
197
- if (active)
198
- active.resources = { ...active.resources, buildSlots: 0 };
199
- }
200
- try {
201
- await this.invokeAck("DispatchEvent", {
202
- leaseId,
203
- fencingToken,
204
- ...(dispatch.sandbox ? {
205
- dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
206
- runnerInstanceId: dispatch.sandbox.runnerInstanceId
207
- } : {}),
208
- event: redactRunnerDispatchEvent(event, redactionSecrets)
209
- });
210
- }
211
- catch (error) {
212
- if (isDispatchNoLongerPending(error)) {
213
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
214
- return;
215
- }
216
- throw error;
217
- }
218
- }
219
- };
220
- const result = normalized.sandbox?.executionMode === "docker"
221
- ? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
222
- : await this.sessions.runOnce(normalized, sink, controller.signal);
223
- if (normalized.sandbox?.executionMode === "docker") {
224
- await this.flushCleanupReports().catch(() => undefined);
225
- }
226
- await this.sendResult(dispatch, redactRunOnceResultPacket(result, redactionSecrets));
955
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
956
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
957
+ const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
958
+ this.inFlight.notePhase(leaseId, "result_delivery");
959
+ await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
227
960
  }
228
961
  catch (error) {
229
962
  const summary = controller.signal.aborted
230
963
  ? `Dispatch cancelled: ${String(controller.signal.reason ?? "cancelled")}`
231
964
  : redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
232
- const failureEventType = infrastructureFailureEventType(summary);
965
+ const failureFacts = failureFactsFromError(error, {
966
+ cancelled: controller.signal.aborted,
967
+ source: "bridge",
968
+ });
969
+ const failureEventType = failureFacts.category === "unknown" ? null : failureFacts.code;
233
970
  const failureEvents = failureEventType ? [{
234
971
  role: "runner",
235
972
  kind: "error",
236
973
  content: summary,
237
974
  eventType: failureEventType,
238
975
  }] : [];
239
- await this.sendResult(dispatch, failureResult(summary, failureEvents)).catch(() => undefined);
976
+ await this.sendResult(dispatch, failureResult(summary, failureEvents, failureFacts)).catch(() => undefined);
977
+ }
978
+ finally {
979
+ await this.releaseActiveSessionAndRefreshCapacity(leaseId);
980
+ }
981
+ }
982
+ registerActiveDispatch(dispatch, controller) {
983
+ this.activeSessions.set(dispatch.lease.id, {
984
+ leaseId: dispatch.lease.id,
985
+ kind: "dispatch",
986
+ fencingToken: dispatch.lease.fencingToken,
987
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
988
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
989
+ leaseExpiresAt: dispatch.lease.expiresAt,
990
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
991
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
992
+ controller
993
+ });
994
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
995
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
996
+ }
997
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
998
+ const leaseId = dispatch.lease.id;
999
+ return {
1000
+ emit: async (event) => {
1001
+ this.inFlight.notePhase(leaseId, event.eventType);
1002
+ if (event.eventType === "provider_cli_started") {
1003
+ const active = this.activeSessions.get(leaseId);
1004
+ if (active)
1005
+ active.resources = { ...active.resources, buildSlots: 0 };
1006
+ }
1007
+ try {
1008
+ await this.invokeAck("DispatchEvent", {
1009
+ leaseId,
1010
+ fencingToken: dispatch.lease.fencingToken,
1011
+ ...(dispatch.sandbox ? {
1012
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1013
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1014
+ } : {}),
1015
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1016
+ }, {
1017
+ replayCallbackTimeout: true,
1018
+ signal: controller.signal,
1019
+ });
1020
+ }
1021
+ catch (error) {
1022
+ if (isDispatchNoLongerPending(error)) {
1023
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1024
+ return;
1025
+ }
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ };
1030
+ }
1031
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1032
+ async runDispatchOnce(dispatch, sink, signal) {
1033
+ const docker = dispatch.sandbox?.executionMode === "docker";
1034
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1035
+ const startedAt = Date.now();
1036
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1037
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1038
+ try {
1039
+ const result = docker
1040
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1041
+ : await this.sessions.runOnce(dispatch, sink, signal);
1042
+ if (docker) {
1043
+ await this.flushCleanupReports().catch(() => undefined);
1044
+ }
1045
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1046
+ return result;
1047
+ }
1048
+ catch (error) {
1049
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1050
+ throw error;
1051
+ }
1052
+ }
1053
+ reservedDispatchHandoffIsCurrent(handoff, dispatch) {
1054
+ const sandbox = dispatch.sandbox;
1055
+ const reservation = handoff.reservation;
1056
+ return sandbox !== null
1057
+ && sandbox !== undefined
1058
+ && sandbox.dispatchAttemptId === handoff.dispatchAttemptId
1059
+ && this.reservations.get(handoff.dispatchAttemptId) === reservation
1060
+ && reservation.startClaim === handoff
1061
+ && !handoff.controller.signal.aborted
1062
+ && reservation.leaseId === dispatch.lease.id
1063
+ && reservation.fencingToken === dispatch.lease.fencingToken
1064
+ && reservation.runnerInstanceId === sandbox.runnerInstanceId
1065
+ && Date.parse(reservation.reservedUntil) > Date.now();
1066
+ }
1067
+ releaseReservedDispatchHandoff(handoff) {
1068
+ if (!handoff
1069
+ || this.reservations.get(handoff.dispatchAttemptId) !== handoff.reservation
1070
+ || handoff.reservation.startClaim !== handoff)
1071
+ return;
1072
+ this.reservations.delete(handoff.dispatchAttemptId);
1073
+ }
1074
+ async releaseActiveSessionAndRefreshCapacity(leaseId, expectedDispatch) {
1075
+ if (expectedDispatch) {
1076
+ const active = this.activeSessions.get(leaseId);
1077
+ // Admission failures may arrive after a newer attempt starts on the same
1078
+ // lease. A terminal callback can release only the dispatch it identifies.
1079
+ if (!active || active.kind !== "dispatch"
1080
+ || active.fencingToken !== expectedDispatch.lease.fencingToken
1081
+ || active.dispatchAttemptId !== (expectedDispatch.sandbox?.dispatchAttemptId ?? null)
1082
+ || active.runnerInstanceId !== (expectedDispatch.sandbox?.runnerInstanceId ?? null))
1083
+ return;
1084
+ }
1085
+ if (!this.activeSessions.delete(leaseId))
1086
+ return;
1087
+ // Publish released host/runtime capacity before the terminal result can
1088
+ // enqueue the next pipeline phase. Otherwise the server may reject that
1089
+ // handoff from the previous periodic heartbeat's active reservation.
1090
+ // Publish the updated reservation counts from cached samples only. Probes
1091
+ // belong to periodic/admission heartbeats and must not outlive this bounded
1092
+ // terminal handoff. Storage recovery must not block durable result delivery.
1093
+ const controller = new AbortController();
1094
+ let timer;
1095
+ try {
1096
+ await Promise.race([
1097
+ this.sendHeartbeatSnapshot(controller.signal).catch(() => undefined),
1098
+ new Promise(resolve => {
1099
+ timer = setTimeout(() => {
1100
+ controller.abort("terminal capacity refresh deadline");
1101
+ resolve();
1102
+ }, Math.min(5000, positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000)));
1103
+ }),
1104
+ ]);
240
1105
  }
241
1106
  finally {
242
- this.activeSessions.delete(leaseId);
1107
+ if (timer)
1108
+ clearTimeout(timer);
243
1109
  }
244
1110
  }
245
1111
  async handleOffer(rawDispatch) {
@@ -247,20 +1113,19 @@ export class ForgeBridgeService {
247
1113
  if (!envelope) {
248
1114
  return;
249
1115
  }
250
- const dispatch = this.parseDispatchOrReport(envelope.dispatch);
1116
+ const dispatch = await this.parseDispatchOrReport(envelope.dispatch);
251
1117
  if (!dispatch?.sandbox
252
1118
  || dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
253
1119
  || dispatch.lease.id !== envelope.leaseId
254
1120
  || dispatch.lease.fencingToken !== envelope.fencingToken)
255
1121
  return;
256
1122
  const sandbox = dispatch.sandbox;
257
- let existing = this.reservations.get(sandbox.dispatchAttemptId);
258
- if (existing && Date.parse(existing.reservedUntil) <= Date.now()) {
259
- this.reservations.delete(sandbox.dispatchAttemptId);
260
- existing = undefined;
261
- }
1123
+ this.expireReservations(Date.now());
1124
+ const existing = this.reservations.get(sandbox.dispatchAttemptId);
262
1125
  if (existing) {
263
- const sameFence = existing.fencingToken === dispatch.lease.fencingToken;
1126
+ const sameFence = existing.leaseId === dispatch.lease.id
1127
+ && existing.fencingToken === dispatch.lease.fencingToken
1128
+ && existing.runnerInstanceId === sandbox.runnerInstanceId;
264
1129
  await this.sendOfferDecision(dispatch, sameFence, sameFence ? null : "stale_fence", sameFence ? null : "Offer fence conflicts with the existing reservation.", sameFence ? existing.reservedUntil : null, sameFence ? existing.resources : null);
265
1130
  return;
266
1131
  }
@@ -272,6 +1137,16 @@ export class ForgeBridgeService {
272
1137
  await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
273
1138
  return;
274
1139
  }
1140
+ // Decision 0014: decide under the settings Forge sent (an offer never races an
1141
+ // apply), and refuse new work while yielding to the foreground. The local flag
1142
+ // is read here too, before Forge has heard about it.
1143
+ await this.refreshLocalYield().catch(() => undefined);
1144
+ // Every apply queued so far, including one a concurrent offer or heartbeat started.
1145
+ await this.settingsTail;
1146
+ if (this.effectiveSettings.yielding) {
1147
+ await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
1148
+ return;
1149
+ }
275
1150
  const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
276
1151
  ? await this.preflight.run()
277
1152
  : this.preflight.current();
@@ -287,7 +1162,7 @@ export class ForgeBridgeService {
287
1162
  }
288
1163
  const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
289
1164
  if (providerNetworkFailure) {
290
- await this.sendOfferDecision(dispatch, false, "provider_network_unavailable", providerNetworkFailure);
1165
+ await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
291
1166
  return;
292
1167
  }
293
1168
  const authFailure = sandboxAuthFailure(dispatch, this.config);
@@ -296,15 +1171,12 @@ export class ForgeBridgeService {
296
1171
  return;
297
1172
  }
298
1173
  }
299
- const runtimeState = this.sandboxRuntime.snapshot();
300
- const usedResources = this.usedSandboxResources(runtimeState.degraded);
301
- const activeResources = this.activeSandboxResources(runtimeState.degraded);
302
- const capacity = this.sandboxResourceCapacity(preflight, activeResources);
303
1174
  let requestedResources = sandbox.requestedResources;
304
1175
  let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
1176
+ const normalizedDispatch = this.normalizeDispatch(dispatch);
305
1177
  if (sandbox.executionMode === "docker") {
306
1178
  try {
307
- const profile = await this.sandboxResourceResolver(this.normalizeDispatch(dispatch));
1179
+ const profile = await this.sandboxResourceResolver(normalizedDispatch);
308
1180
  requestedResources = profile.resources;
309
1181
  sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
310
1182
  }
@@ -313,73 +1185,171 @@ export class ForgeBridgeService {
313
1185
  return;
314
1186
  }
315
1187
  }
316
- if (sandbox.executionMode === "docker"
317
- && !canReserveSandboxResources(usedResources, requestedResources, capacity)) {
318
- await this.sendOfferDecision(dispatch, false, "capacity_unavailable", sandboxCapacityFailureMessage(usedResources, requestedResources, capacity, preflight, this.config));
319
- return;
1188
+ else if (normalizedDispatch.repo.serverLocalPath) {
1189
+ // Host execution uses the same project-derived disk reservation as Docker.
1190
+ // The API supplies a placement-time estimate; the runner can safely raise it
1191
+ // from its authoritative checkout before admitting the attempt.
1192
+ const measuredWorkspaceBytes = await estimateWorkspaceBytesFromRepo(normalizedDispatch.repo.serverLocalPath, { role: normalizedDispatch.execution.role }).catch(() => null);
1193
+ if (measuredWorkspaceBytes !== null) {
1194
+ requestedResources = {
1195
+ ...requestedResources,
1196
+ workspaceBytes: Math.max(requestedResources.workspaceBytes, measuredWorkspaceBytes),
1197
+ };
1198
+ }
320
1199
  }
321
- const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt), Date.now() + 30_000)).toISOString();
322
- this.reservations.set(sandbox.dispatchAttemptId, {
1200
+ // Resource profiling can await filesystem and Docker work. Admission needs
1201
+ // a dynamic host/daemon sample that began after profiling completed, so an
1202
+ // older in-flight heartbeat inspection cannot supply the commit decision.
1203
+ const admissionPreflight = sandbox.executionMode === "docker"
1204
+ ? await this.preflight.refreshCapacityForAdmission()
1205
+ : preflight;
1206
+ // Resource profiling and preflight may await slow filesystem or Docker I/O.
1207
+ // Re-read every mutable capacity input only after that work, then decide and
1208
+ // commit synchronously. JavaScript cannot interleave another Offer handler
1209
+ // inside this non-async method, so the ledger check and insertion are one
1210
+ // atomic event-loop turn without holding a lock across external I/O.
1211
+ const decision = this.commitOfferReservation(dispatch, requestedResources, admissionPreflight);
1212
+ await this.sendOfferDecision(dispatch, decision.accepted, decision.code, decision.message, decision.reservedUntil, decision.resources, sandboxConfigCommitSha);
1213
+ }
1214
+ commitOfferReservation(dispatch, requestedResources, preparedPreflight) {
1215
+ const sandbox = dispatch.sandbox;
1216
+ const now = Date.now();
1217
+ this.expireReservations(now);
1218
+ const existing = this.reservations.get(sandbox.dispatchAttemptId);
1219
+ if (existing) {
1220
+ const sameFence = existing.leaseId === dispatch.lease.id
1221
+ && existing.fencingToken === dispatch.lease.fencingToken
1222
+ && existing.runnerInstanceId === sandbox.runnerInstanceId;
1223
+ return {
1224
+ accepted: sameFence,
1225
+ code: sameFence ? null : "stale_fence",
1226
+ message: sameFence ? null : "Offer fence conflicts with the existing reservation.",
1227
+ reservedUntil: sameFence ? existing.reservedUntil : null,
1228
+ resources: sameFence ? existing.resources : null,
1229
+ };
1230
+ }
1231
+ if (Date.parse(dispatch.lease.expiresAt) <= now) {
1232
+ return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
1233
+ }
1234
+ // Yield may have turned on while the offer was being profiled, including a
1235
+ // yield Forge sent or the local flag set that hasn't finished applying yet.
1236
+ if (this.yieldingOrQueued()) {
1237
+ return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
1238
+ }
1239
+ if (sandbox.executionMode === "docker") {
1240
+ // A concurrent heartbeat/preflight refresh may have produced a newer
1241
+ // conservative dual-domain sample while this offer was being profiled.
1242
+ const admissionPreflight = this.preflight.current() ?? preparedPreflight;
1243
+ if (!this.config.dockerEnabled || !admissionPreflight?.healthy) {
1244
+ return rejectedOfferReservation(admissionPreflight?.unavailableCode ?? "docker_unavailable", admissionPreflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
1245
+ }
1246
+ const runtimeState = this.sandboxRuntime.snapshot();
1247
+ const usedResources = this.usedSandboxResources(runtimeState.degraded);
1248
+ const activeResources = this.activeSandboxResources(runtimeState.degraded);
1249
+ const capacity = this.sandboxResourceCapacity(admissionPreflight, activeResources);
1250
+ if (!canReserveSandboxResources(usedResources, requestedResources, capacity)) {
1251
+ return rejectedOfferReservation("capacity_unavailable", sandboxCapacityFailureMessage(usedResources, requestedResources, capacity, admissionPreflight, this.config));
1252
+ }
1253
+ }
1254
+ const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt), now + 30_000)).toISOString();
1255
+ const reservation = {
323
1256
  leaseId: dispatch.lease.id,
324
1257
  fencingToken: dispatch.lease.fencingToken,
325
1258
  runnerInstanceId: sandbox.runnerInstanceId,
326
1259
  expiresAt: dispatch.lease.expiresAt,
327
1260
  reservedUntil,
328
1261
  sandboxed: sandbox.executionMode === "docker",
329
- resources: requestedResources
330
- });
331
- await this.sendOfferDecision(dispatch, true, null, null, reservedUntil, requestedResources, sandboxConfigCommitSha);
1262
+ resources: requestedResources,
1263
+ };
1264
+ this.reservations.set(sandbox.dispatchAttemptId, reservation);
1265
+ return {
1266
+ accepted: true,
1267
+ code: null,
1268
+ message: null,
1269
+ reservedUntil,
1270
+ resources: requestedResources,
1271
+ };
332
1272
  }
333
1273
  async handleStart(rawDispatch) {
334
1274
  const envelope = parseStartEnvelope(rawDispatch);
335
1275
  if (!envelope) {
336
1276
  return;
337
1277
  }
338
- let dispatch = this.parseDispatchOrReport(envelope.dispatch);
1278
+ let dispatch = await this.parseDispatchOrReport(envelope.dispatch);
339
1279
  if (!dispatch?.sandbox
340
1280
  || dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
341
1281
  || dispatch.lease.id !== envelope.leaseId
342
1282
  || dispatch.lease.fencingToken !== envelope.fencingToken)
343
1283
  return;
1284
+ const active = this.activeSessions.get(dispatch.lease.id);
1285
+ if (active?.kind === "dispatch"
1286
+ && active.fencingToken === dispatch.lease.fencingToken
1287
+ && active.dispatchAttemptId === dispatch.sandbox.dispatchAttemptId
1288
+ && active.runnerInstanceId === dispatch.sandbox.runnerInstanceId) {
1289
+ return;
1290
+ }
344
1291
  const reservation = this.reservations.get(dispatch.sandbox.dispatchAttemptId);
345
1292
  if (!reservation
346
1293
  || reservation.leaseId !== dispatch.lease.id
347
1294
  || reservation.fencingToken !== dispatch.lease.fencingToken
348
1295
  || reservation.runnerInstanceId !== dispatch.sandbox.runnerInstanceId
349
1296
  || Date.parse(reservation.reservedUntil) <= Date.now()) {
350
- await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.")).catch(() => undefined);
1297
+ await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
351
1298
  return;
352
1299
  }
1300
+ // Claim the exact reservation before redemption or any other post-validation
1301
+ // await. A duplicate Start for the same reservation is an idempotent replay:
1302
+ // it must neither redeem a one-time grant nor disturb the original owner.
1303
+ if (reservation.startClaim)
1304
+ return;
1305
+ const startClaim = {
1306
+ dispatchAttemptId: envelope.dispatchAttemptId,
1307
+ reservation,
1308
+ controller: new AbortController(),
1309
+ };
1310
+ reservation.startClaim = startClaim;
353
1311
  if (dispatch.apiKeySecretGrant) {
354
- this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
355
- await this.sendResult(dispatch, failureResult("Start rejected because protocol-v2 packets may not contain a plaintext provider grant.")).catch(() => undefined);
1312
+ this.releaseReservedDispatchHandoff(startClaim);
1313
+ await this.sendResult(dispatch, failureResult("Start rejected because protocol-v2 packets may not contain a plaintext provider grant.", [], failureFactsForCode("contract_plaintext_secret_rejected"))).catch(() => undefined);
356
1314
  return;
357
1315
  }
358
1316
  if (dispatch.apiKeySecretGrantHandle) {
359
- const response = await this.redeemSecretGrant(dispatch);
1317
+ let response;
1318
+ try {
1319
+ response = await this.redeemSecretGrant(dispatch);
1320
+ }
1321
+ catch (error) {
1322
+ this.releaseReservedDispatchHandoff(startClaim);
1323
+ throw error;
1324
+ }
1325
+ // Redemption may yield while a qualified Cancel releases this reservation.
1326
+ // Never launch from it or remove a successor reservation after that wait.
1327
+ if (!this.reservedDispatchHandoffIsCurrent(startClaim, dispatch)) {
1328
+ await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
1329
+ return;
1330
+ }
360
1331
  const grant = response.grant;
361
1332
  if (!response.accepted
362
1333
  || !grant
363
1334
  || grant.grantId !== dispatch.apiKeySecretGrantHandle.grantId
364
1335
  || grant.provider !== dispatch.apiKeySecretGrantHandle.provider
365
1336
  || Date.parse(grant.expiresAt) <= Date.now()) {
366
- this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
367
- await this.sendResult(dispatch, failureResult(response.message ?? "Secret grant redemption was rejected.")).catch(() => undefined);
1337
+ this.releaseReservedDispatchHandoff(startClaim);
1338
+ await this.sendResult(dispatch, failureResult(response.message ?? "Secret grant redemption was rejected.", [], failureFactsForCode("bridge.api_key_secret_grant_denied"))).catch(() => undefined);
368
1339
  return;
369
1340
  }
370
1341
  dispatch = { ...dispatch, apiKeySecretGrant: grant, apiKeySecretGrantHandle: null };
371
1342
  }
372
1343
  else if (dispatch.execution.requiresApiKeySecretGrant) {
373
- this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
374
- await this.sendResult(dispatch, failureResult("Start rejected because the provider secret grant handle is missing.")).catch(() => undefined);
1344
+ this.releaseReservedDispatchHandoff(startClaim);
1345
+ await this.sendResult(dispatch, failureResult("Start rejected because the provider secret grant handle is missing.", [], failureFactsForCode("bridge.api_key_secret_grant_missing"))).catch(() => undefined);
375
1346
  return;
376
1347
  }
377
1348
  dispatch = {
378
1349
  ...dispatch,
379
1350
  sandbox: { ...dispatch.sandbox, requestedResources: reservation.resources },
380
1351
  };
381
- this.reservations.delete(envelope.dispatchAttemptId);
382
- await this.handleDispatch(dispatch);
1352
+ await this.handleDispatch(dispatch, startClaim);
383
1353
  }
384
1354
  async redeemSecretGrant(dispatch) {
385
1355
  const sandbox = dispatch.sandbox;
@@ -441,9 +1411,11 @@ export class ForgeBridgeService {
441
1411
  reservedResources: accepted ? reservedResources : null,
442
1412
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
443
1413
  };
1414
+ if (accepted)
1415
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
444
1416
  await this.invokeAck("OfferDecision", payload);
445
1417
  }
446
- parseDispatchOrReport(rawDispatch) {
1418
+ async parseDispatchOrReport(rawDispatch) {
447
1419
  try {
448
1420
  return parseRunOnceDispatchPacket(rawDispatch);
449
1421
  }
@@ -453,24 +1425,78 @@ export class ForgeBridgeService {
453
1425
  return null;
454
1426
  }
455
1427
  const summary = invalidDispatchSummary(error);
456
- void this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
1428
+ await this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
457
1429
  {
458
1430
  role: "runner",
459
1431
  kind: "error",
460
1432
  content: summary,
461
1433
  eventType: "invalid_dispatch"
462
1434
  }
463
- ])).catch(() => undefined);
1435
+ ], failureFactsForCode("invalid_dispatch"))).catch(() => undefined);
1436
+ return null;
1437
+ }
1438
+ }
1439
+ parseChatTurnOrReport(rawDispatch) {
1440
+ try {
1441
+ return parseChatTurnDispatchPacket(rawDispatch, this.bridgeChatCapability());
1442
+ }
1443
+ catch (error) {
1444
+ logBridgeStatus(invalidChatTurnSummary(error));
464
1445
  return null;
465
1446
  }
466
1447
  }
467
1448
  async handleCancel(request) {
1449
+ if (request.dispatchAttemptId !== undefined && request.dispatchAttemptId !== null) {
1450
+ // Qualified cancellation is reservation-only. In particular, a delayed
1451
+ // pre-start Cancel must not abort an active session if Start won the race.
1452
+ const reservation = this.reservations.get(request.dispatchAttemptId);
1453
+ if (reservation
1454
+ && request.runnerId === this.config.runnerId
1455
+ && request.runnerInstanceId === this.config.runnerInstanceId
1456
+ && reservation.runnerInstanceId === request.runnerInstanceId
1457
+ && reservation.leaseId === request.leaseId
1458
+ && reservation.fencingToken === request.fencingToken) {
1459
+ reservation.startClaim?.controller.abort(request.reason ?? "cancelled by server");
1460
+ this.reservations.delete(request.dispatchAttemptId);
1461
+ }
1462
+ return;
1463
+ }
468
1464
  const active = this.activeSessions.get(request.leaseId);
469
1465
  if (!active || active.fencingToken !== request.fencingToken) {
470
1466
  return;
471
1467
  }
1468
+ if (request.runnerId && request.runnerId !== this.config.runnerId) {
1469
+ return;
1470
+ }
1471
+ if (request.runnerInstanceId && request.runnerInstanceId !== (active.runnerInstanceId ?? this.config.runnerInstanceId)) {
1472
+ return;
1473
+ }
1474
+ if (active.kind === "chat" && !this.chatCancelMatchesActiveTurn(active, request)) {
1475
+ return;
1476
+ }
472
1477
  active.controller.abort(request.reason ?? "cancelled by server");
473
1478
  }
1479
+ chatCancelMatchesActiveTurn(active, request) {
1480
+ if (request.protocolVersion && request.protocolVersion !== bridgeChatProtocolVersion) {
1481
+ return false;
1482
+ }
1483
+ try {
1484
+ assertBridgeChatCallbackPayload(request.payload, "cancel payload");
1485
+ }
1486
+ catch {
1487
+ return false;
1488
+ }
1489
+ if (request.chatRunId && request.chatRunId !== active.chatRunId)
1490
+ return false;
1491
+ if (request.conversationId && request.conversationId !== active.conversationId)
1492
+ return false;
1493
+ if (request.turnId && request.turnId !== active.turnId)
1494
+ return false;
1495
+ if (request.providerThreadId && active.providerThreadId && request.providerThreadId !== active.providerThreadId) {
1496
+ return false;
1497
+ }
1498
+ return true;
1499
+ }
474
1500
  async handleReap(request) {
475
1501
  if (request.runnerId !== this.config.runnerId
476
1502
  || request.runnerInstanceId !== this.config.runnerInstanceId)
@@ -492,32 +1518,49 @@ export class ForgeBridgeService {
492
1518
  timer.unref?.();
493
1519
  let result;
494
1520
  try {
495
- if (!this.sessions.probeHostRuntime) {
496
- throw new Error("host_runtime_probe_unavailable: this bridge does not implement runtime readiness probes.");
497
- }
498
- const probe = await this.sessions.probeHostRuntime({
499
- ...request,
500
- runnerId: this.config.runnerId,
501
- repoRoot: this.config.defaultRepoRoot,
502
- cleanupWorktrees: this.config.cleanupWorktrees,
503
- }, controller.signal);
504
- result = {
1521
+ const accepted = {
505
1522
  schemaVersion: 1,
506
1523
  requestId: request.requestId,
507
1524
  fencingToken: request.fencingToken,
508
1525
  runnerInstanceId: this.config.runnerInstanceId,
509
- ...probe,
1526
+ acceptedAt: new Date().toISOString(),
510
1527
  };
1528
+ await this.invokeAck("ReadinessAccepted", accepted);
1529
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1530
+ await this.refreshLocalYield().catch(() => undefined);
1531
+ await this.settingsTail;
1532
+ if (this.yieldingOrQueued()) {
1533
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1534
+ }
1535
+ else if (this.activeSessions.size > 0) {
1536
+ result = deferredReadinessResult(request, this.config.runnerInstanceId);
1537
+ }
1538
+ else if (!this.sessions.probeHostRuntime) {
1539
+ throw new Error("host_runtime_probe_unavailable: this bridge does not implement runtime readiness probes.");
1540
+ }
1541
+ else {
1542
+ const probe = await this.sessions.probeHostRuntime(this.normalizeReadinessProbe(request), controller.signal);
1543
+ result = readinessDeferralReason(controller.signal)
1544
+ ? deferredReadinessResult(request, this.config.runnerInstanceId)
1545
+ : {
1546
+ schemaVersion: 1,
1547
+ requestId: request.requestId,
1548
+ fencingToken: request.fencingToken,
1549
+ runnerInstanceId: this.config.runnerInstanceId,
1550
+ ...probe,
1551
+ };
1552
+ }
511
1553
  }
512
1554
  catch (error) {
1555
+ const deferredReason = readinessDeferralReason(controller.signal);
513
1556
  result = {
514
1557
  schemaVersion: 1,
515
1558
  requestId: request.requestId,
516
1559
  fencingToken: request.fencingToken,
517
1560
  runnerInstanceId: this.config.runnerInstanceId,
518
1561
  status: "failed",
519
- reasonCode: "host_runtime_probe_failed",
520
- reasonMessage: errorMessage(error).slice(0, 1000),
1562
+ reasonCode: deferredReason ? "host_runtime_probe_deferred" : "host_runtime_probe_failed",
1563
+ reasonMessage: (deferredReason ?? errorMessage(error)).slice(0, 1000),
521
1564
  checkedAt: new Date().toISOString(),
522
1565
  };
523
1566
  }
@@ -525,9 +1568,69 @@ export class ForgeBridgeService {
525
1568
  clearTimeout(timer);
526
1569
  this.activeReadinessProbes.delete(request.requestId);
527
1570
  }
528
- await this.invokeAck("ReadinessResult", result).catch(() => undefined);
1571
+ try {
1572
+ await this.readinessResultOutbox.persist(result, request.expiresAt);
1573
+ }
1574
+ catch (error) {
1575
+ if (errorMessage(error).includes("runtime_readiness_result_conflict:")) {
1576
+ logBridgeStatus(`Readiness result ${request.requestId} rejected conflicting reuse of a durable request identity.`);
1577
+ await this.sendHeartbeat().catch(() => undefined);
1578
+ return;
1579
+ }
1580
+ logBridgeStatus(`Readiness result ${request.requestId} could not be persisted; attempting direct delivery: ${errorMessage(error)}`);
1581
+ await this.invokeAck("ReadinessResult", result).catch(deliveryError => {
1582
+ logBridgeStatus(`Readiness result ${request.requestId} could not be persisted or delivered: ${errorMessage(deliveryError)}`);
1583
+ });
1584
+ await this.sendHeartbeat().catch(() => undefined);
1585
+ return;
1586
+ }
1587
+ try {
1588
+ await this.flushReadinessResults();
1589
+ }
1590
+ catch (error) {
1591
+ logBridgeStatus(`Readiness result ${request.requestId} remains queued for replay: ${errorMessage(error)}`);
1592
+ }
529
1593
  await this.sendHeartbeat().catch(() => undefined);
530
1594
  }
1595
+ deferActiveReadinessProbes() {
1596
+ for (const controller of this.activeReadinessProbes.values()) {
1597
+ if (!controller.signal.aborted) {
1598
+ controller.abort("host_runtime_probe_deferred: foreground agent work took priority over background runtime readiness.");
1599
+ }
1600
+ }
1601
+ }
1602
+ async flushReadinessResults() {
1603
+ if (this.readinessResultFlush)
1604
+ return await this.readinessResultFlush;
1605
+ const flush = this.flushReadinessResultsCore();
1606
+ this.readinessResultFlush = flush;
1607
+ try {
1608
+ await flush;
1609
+ }
1610
+ finally {
1611
+ if (this.readinessResultFlush === flush)
1612
+ this.readinessResultFlush = null;
1613
+ }
1614
+ }
1615
+ async flushReadinessResultsCore() {
1616
+ for (const pending of await this.readinessResultOutbox.pending()) {
1617
+ if (Date.parse(pending.expiresAt) <= Date.now()) {
1618
+ await this.readinessResultOutbox.acknowledge(pending.result.requestId);
1619
+ continue;
1620
+ }
1621
+ try {
1622
+ await this.invokeAck("ReadinessResult", pending.result);
1623
+ await this.readinessResultOutbox.acknowledge(pending.result.requestId);
1624
+ }
1625
+ catch (error) {
1626
+ if (isReadinessNoLongerPending(error)) {
1627
+ await this.readinessResultOutbox.acknowledge(pending.result.requestId);
1628
+ continue;
1629
+ }
1630
+ throw error;
1631
+ }
1632
+ }
1633
+ }
531
1634
  abortActiveSessions(reason) {
532
1635
  for (const active of this.activeSessions.values()) {
533
1636
  active.controller.abort(reason);
@@ -539,8 +1642,42 @@ export class ForgeBridgeService {
539
1642
  controller.abort(reason);
540
1643
  this.activeReadinessProbes.clear();
541
1644
  }
1645
+ normalizeReadinessProbe(request) {
1646
+ const mapping = findRepoMapping({
1647
+ id: request.repoId,
1648
+ name: request.repoName,
1649
+ remoteUrl: request.remoteUrl,
1650
+ }, repoMappingsFor(this.config));
1651
+ const configuredPath = mapping?.localPath?.trim();
1652
+ if (!configuredPath) {
1653
+ throw new Error("bridge_repo_mapping_missing: readiness requires a matching local repository mapping.");
1654
+ }
1655
+ // Local configuration, not a path supplied by the server, grants checkout
1656
+ // authority. Equality also excludes a different child/sibling of this repo.
1657
+ const suppliedPath = request.runnerRepoLocalPath.trim();
1658
+ if (!path.isAbsolute(suppliedPath)
1659
+ || (process.platform === "win32" && path.parse(suppliedPath).root.length === 1)) {
1660
+ throw new Error("bridge_repo_mapping_mismatch: readiness requires a fully qualified checkout path.");
1661
+ }
1662
+ const localPath = path.resolve(configuredPath);
1663
+ const requestedPath = path.resolve(suppliedPath);
1664
+ const pathsMatch = process.platform === "win32"
1665
+ ? localPath.toLowerCase() === requestedPath.toLowerCase()
1666
+ : localPath === requestedPath;
1667
+ if (!pathsMatch) {
1668
+ throw new Error("bridge_repo_mapping_mismatch: readiness checkout differs from the locally configured repository.");
1669
+ }
1670
+ return {
1671
+ ...request,
1672
+ runnerId: this.config.runnerId,
1673
+ runnerRepoLocalPath: localPath,
1674
+ cloneOnDemand: false,
1675
+ repoRoot: path.dirname(localPath),
1676
+ cleanupWorktrees: this.config.cleanupWorktrees,
1677
+ };
1678
+ }
542
1679
  normalizeDispatch(dispatch) {
543
- const mapping = findRepoMapping(dispatch, repoMappingsFor(this.config));
1680
+ const mapping = findRepoMapping(dispatch.repo, repoMappingsFor(this.config));
544
1681
  const localPath = mapping?.localPath?.trim();
545
1682
  const repoRoot = localPath ? path.dirname(path.resolve(localPath)) : this.config.defaultRepoRoot;
546
1683
  const qaLaunchTarget = normalizeQaAppLaunchTarget(mapping?.qaAppLaunchTarget) ?? dispatch.qaBrowser?.launchTarget ?? null;
@@ -569,24 +1706,132 @@ export class ForgeBridgeService {
569
1706
  fencingToken: dispatch.lease.fencingToken,
570
1707
  dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
571
1708
  runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
572
- result
1709
+ // Every terminal writer, including early admission failures and exception
1710
+ // paths, crosses the same redaction boundary before outbox persistence.
1711
+ result: redactRunOnceResultPacket(result, exactSecrets(dispatch, this.config))
573
1712
  };
574
- await this.sendResultPayload(payload);
1713
+ await this.sendResultPayload(payload, () => this.releaseActiveSessionAndRefreshCapacity(dispatch.lease.id, dispatch));
575
1714
  }
576
1715
  async sendLegacyResult(leaseId, fencingToken, result) {
577
1716
  await this.sendResultPayload({ leaseId, fencingToken, result });
578
1717
  }
579
- async sendResultPayload(payload) {
1718
+ async sendResultPayload(payload, beforeDelivery) {
1719
+ // Register before persistence: replay can observe a record as soon as the
1720
+ // durable write becomes visible, even before persist() has returned.
1721
+ let releaseHandoff;
1722
+ const priorHandoff = this.dispatchResultHandoffs.get(payload.leaseId);
1723
+ const handoff = new Promise(resolve => { releaseHandoff = resolve; });
1724
+ this.dispatchResultHandoffs.set(payload.leaseId, handoff);
1725
+ let persisted = false;
1726
+ try {
1727
+ try {
1728
+ await this.dispatchResultOutbox.persist(payload);
1729
+ persisted = true;
1730
+ this.dispatchResultGeneration += 1;
1731
+ }
1732
+ catch (error) {
1733
+ logBridgeStatus(`Dispatch result ${payload.leaseId} could not be persisted; attempting direct delivery: ${errorMessage(error)}`);
1734
+ }
1735
+ await priorHandoff;
1736
+ await beforeDelivery?.();
1737
+ }
1738
+ finally {
1739
+ releaseHandoff();
1740
+ if (this.dispatchResultHandoffs.get(payload.leaseId) === handoff)
1741
+ this.dispatchResultHandoffs.delete(payload.leaseId);
1742
+ }
1743
+ if (!persisted) {
1744
+ await this.sendResultPayloadDirect(payload);
1745
+ return;
1746
+ }
1747
+ await this.flushDispatchResults().catch(error => {
1748
+ logBridgeStatus(`Dispatch result ${payload.leaseId} remains queued for replay: ${errorMessage(error)}`);
1749
+ });
1750
+ }
1751
+ async sendResultPayloadDirect(payload) {
580
1752
  try {
581
1753
  await this.invokeAck("DispatchResult", payload);
582
1754
  }
583
1755
  catch (error) {
584
- if (isDispatchNoLongerPending(error)) {
1756
+ if (isDispatchNoLongerPending(error))
585
1757
  return;
586
- }
587
1758
  throw error;
588
1759
  }
589
1760
  }
1761
+ async flushDispatchResults(force = false) {
1762
+ if (!force && this.dispatchResultGeneration === this.dispatchResultFlushedGeneration)
1763
+ return;
1764
+ if (this.dispatchResultFlush) {
1765
+ await this.dispatchResultFlush;
1766
+ if (!force && this.dispatchResultGeneration === this.dispatchResultFlushedGeneration)
1767
+ return;
1768
+ }
1769
+ const flush = this.flushDispatchResultsCore();
1770
+ this.dispatchResultFlush = flush;
1771
+ try {
1772
+ await flush;
1773
+ }
1774
+ finally {
1775
+ if (this.dispatchResultFlush === flush)
1776
+ this.dispatchResultFlush = null;
1777
+ }
1778
+ }
1779
+ async flushDispatchResultsCore() {
1780
+ const startedGeneration = this.dispatchResultGeneration;
1781
+ while (true) {
1782
+ const records = await this.dispatchResultOutbox.pending();
1783
+ for (const pending of records) {
1784
+ // Periodic heartbeats and reconnect replay share the same release
1785
+ // barrier as the terminal writer. Restart replay has no live handoff.
1786
+ while (this.dispatchResultHandoffs.has(pending.payload.leaseId)) {
1787
+ await this.dispatchResultHandoffs.get(pending.payload.leaseId);
1788
+ }
1789
+ try {
1790
+ await this.sendResultPayloadDirect(pending.payload);
1791
+ await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
1792
+ }
1793
+ catch (error) {
1794
+ if (isDispatchNoLongerPending(error)) {
1795
+ await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
1796
+ continue;
1797
+ }
1798
+ if (this.isReplacedRunnerInstanceResult(pending.payload, error)) {
1799
+ try {
1800
+ await this.dispatchResultOutbox.quarantine(pending);
1801
+ }
1802
+ catch (quarantineError) {
1803
+ // Keep the record and surface Forge's rejection: replay stays
1804
+ // deferred and a heartbeat tick does not count it as a failure.
1805
+ logBridgeStatus(`Dispatch result ${pending.payload.leaseId} from replaced runner instance ${pending.payload.runnerInstanceId} could not be quarantined: ${errorMessage(quarantineError)}`);
1806
+ throw error;
1807
+ }
1808
+ logBridgeStatus(`Quarantined dispatch result ${pending.payload.leaseId}: Forge rejected it because it belongs to replaced runner instance ${pending.payload.runnerInstanceId}. Forge's own recovery handles that instance's attempt; the redacted result is kept in ${dispatchResultQuarantineDirectory} for reconciliation.`);
1809
+ continue;
1810
+ }
1811
+ throw error;
1812
+ }
1813
+ }
1814
+ if (records.length < 3)
1815
+ break;
1816
+ }
1817
+ if (this.dispatchResultGeneration === startedGeneration) {
1818
+ this.dispatchResultFlushedGeneration = startedGeneration;
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Forge binds each result to the runner instance that ran the attempt. On an
1823
+ * authoritative connection it rejects another instance's result with
1824
+ * bridge.stale_result_instance; Forge's own recovery handles that attempt,
1825
+ * so the record can never be delivered and must not block the replay queue.
1826
+ * bridge.stale_runner_instance means this connection is not authoritative
1827
+ * and says nothing about the record, so it never quarantines.
1828
+ */
1829
+ isReplacedRunnerInstanceResult(payload, error) {
1830
+ return error instanceof BridgeCallbackRejectedError
1831
+ && error.code === "bridge.stale_result_instance"
1832
+ && typeof payload.runnerInstanceId === "string"
1833
+ && payload.runnerInstanceId.toLowerCase() !== this.config.runnerInstanceId.toLowerCase();
1834
+ }
590
1835
  startHeartbeat() {
591
1836
  this.stopHeartbeat();
592
1837
  this.consecutiveHeartbeatFailures = 0;
@@ -605,6 +1850,14 @@ export class ForgeBridgeService {
605
1850
  return;
606
1851
  this.heartbeatInFlight = true;
607
1852
  try {
1853
+ // A rejected replay is an answer from Forge, so the connection is alive:
1854
+ // an undeliverable record must not count as a heartbeat failure and
1855
+ // force reconnects. Transport failures still do.
1856
+ await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
1857
+ await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
1858
+ // The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
1859
+ await this.refreshLocalYield().catch(() => undefined);
1860
+ await this.retryFailedSettings().catch(() => undefined);
608
1861
  await this.sendHeartbeat();
609
1862
  this.consecutiveHeartbeatFailures = 0;
610
1863
  }
@@ -637,17 +1890,20 @@ export class ForgeBridgeService {
637
1890
  }
638
1891
  expireLeases() {
639
1892
  const now = Date.now();
640
- for (const [attemptId, reservation] of this.reservations) {
641
- if (Date.parse(reservation.expiresAt) <= now || Date.parse(reservation.reservedUntil) <= now) {
642
- this.reservations.delete(attemptId);
643
- }
644
- }
1893
+ this.expireReservations(now);
645
1894
  for (const active of this.activeSessions.values()) {
646
1895
  if (Date.parse(active.leaseExpiresAt) <= now && !active.controller.signal.aborted) {
647
1896
  active.controller.abort("dispatch lease expired");
648
1897
  }
649
1898
  }
650
1899
  }
1900
+ expireReservations(now) {
1901
+ for (const [attemptId, reservation] of this.reservations) {
1902
+ if (Date.parse(reservation.expiresAt) <= now || Date.parse(reservation.reservedUntil) <= now) {
1903
+ this.reservations.delete(attemptId);
1904
+ }
1905
+ }
1906
+ }
651
1907
  stopHeartbeat() {
652
1908
  if (this.heartbeatTimer) {
653
1909
  clearInterval(this.heartbeatTimer);
@@ -676,6 +1932,7 @@ export class ForgeBridgeService {
676
1932
  runnerId: this.config.runnerId,
677
1933
  runnerInstanceId: this.config.runnerInstanceId,
678
1934
  });
1935
+ this.rememberRecoveredHostAttempts(hostReap);
679
1936
  if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
680
1937
  logBridgeStatus(`Managed-host maintenance reaped ${hostReap.reaped} stale attempt(s) and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
681
1938
  }
@@ -716,22 +1973,53 @@ export class ForgeBridgeService {
716
1973
  }
717
1974
  }
718
1975
  async sendHeartbeat() {
1976
+ // Heartbeats are the recovery path for capacity-blocked work. Refresh the
1977
+ // dynamic sample before advertising it, while reusing the static Docker
1978
+ // capability snapshot established at startup or by an offer.
1979
+ if (this.config.dockerEnabled)
1980
+ await this.preflight.refreshCapacity();
1981
+ // A due probe can start a Docker Desktop recovery that runs for minutes.
1982
+ // Wait only as long as a normal probe takes, then advertise the last
1983
+ // snapshot so the server doesn't mark the runner offline meanwhile.
1984
+ const probeWait = new AbortController();
1985
+ await Promise.race([
1986
+ this.dockerEngineProbe.refresh().catch(() => undefined),
1987
+ delay(positiveFiniteNumber(this.config.heartbeatDockerProbeWaitMs ?? 15_000, 15_000), probeWait.signal),
1988
+ ]);
1989
+ probeWait.abort();
1990
+ await this.sendHeartbeatSnapshot();
1991
+ }
1992
+ async sendHeartbeatSnapshot(signal) {
1993
+ const reportedYield = this.settingsReport.values.yieldToForeground;
719
1994
  await this.invokeAck("Heartbeat", {
720
1995
  status: "online",
721
1996
  capabilities: this.capabilities(),
722
1997
  version: this.config.version,
723
1998
  protocolVersion: this.config.protocolVersion
724
- });
1999
+ }, { signal });
2000
+ this.ackYield(reportedYield);
725
2001
  }
726
2002
  capabilities() {
727
2003
  const preflight = this.preflight.current();
2004
+ const dockerEngine = this.dockerEngineProbe.current();
2005
+ this.dockerAvailable = dockerEngine?.available === true;
728
2006
  const runtimeState = this.sandboxRuntime.snapshot();
729
2007
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
730
2008
  const used = this.usedSandboxResources(runtimeState.degraded);
731
2009
  const activeResources = this.activeSandboxResources(runtimeState.degraded);
732
2010
  const capacity = this.sandboxResourceCapacity(preflight, activeResources);
2011
+ const memoryAdmission = preflight ? buildMemoryAdmissionDiagnostics({
2012
+ sampledAt: preflight.sampledAt,
2013
+ totalMemoryBytes: preflight.totalMemoryBytes,
2014
+ rawAvailableMemoryBytes: preflight.rawAvailableMemoryBytes,
2015
+ stabilizedAvailableMemoryBytes: preflight.availableMemoryBytes,
2016
+ controlPlaneMemoryBytes: process.memoryUsage().rss,
2017
+ reserveMemoryBytes: preflight.hostReserveBytes,
2018
+ committedMemoryBytes: used.memoryBytes,
2019
+ pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
2020
+ }) : null;
733
2021
  return {
734
- schemaVersion: 3,
2022
+ schemaVersion: 8,
735
2023
  activeSessionCount: this.activeSessions.size,
736
2024
  cliProviders: this.config.cliProviders,
737
2025
  providerStatuses: this.config.providerStatuses,
@@ -741,6 +2029,22 @@ export class ForgeBridgeService {
741
2029
  sandboxProfiles: this.config.sandboxProfiles,
742
2030
  runnerInstanceId: this.config.runnerInstanceId,
743
2031
  trustDomainId: this.config.trustDomainId,
2032
+ executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
2033
+ dockerEngine,
2034
+ toolchains: {
2035
+ ...this.hostCapabilities.toolchains,
2036
+ docker: {
2037
+ available: dockerEngine?.available === true,
2038
+ executable: this.config.dockerExecutable,
2039
+ version: dockerEngine?.runtimeVersion ?? null,
2040
+ },
2041
+ },
2042
+ playwrightProjects: this.hostCapabilities.playwrightProjects,
2043
+ browserLaunch: this.hostCapabilities.browserLaunch,
2044
+ providerConnectivity: this.hostCapabilities.providerConnectivity,
2045
+ testPostgres: this.hostCapabilities.testPostgres,
2046
+ host: this.hostLoad.facts(),
2047
+ load: this.hostLoad.current(),
744
2048
  maxConcurrentSandboxes: capacity.sandboxSlots,
745
2049
  reservedSandboxCount: reserved,
746
2050
  activeSandboxCount: runtimeState.active,
@@ -752,7 +2056,7 @@ export class ForgeBridgeService {
752
2056
  allowsOpenPublicSandbox: this.config.allowOpenPublicSandbox,
753
2057
  sandboxPublicationModes: [this.config.sandboxPublicationMode ?? "shared_filesystem"],
754
2058
  sandboxAuthModes: sandboxAuthModesFor(this.config),
755
- availableMemoryBytes: preflight ? Math.max(0, capacity.memoryBytes - used.memoryBytes) : null,
2059
+ availableMemoryBytes: memoryAdmission?.availableForAdmissionBytes ?? null,
756
2060
  availableCpuMillis: preflight ? Math.max(0, capacity.cpuMillis - used.cpuMillis) : null,
757
2061
  availableWorkspaceBytes: preflight ? Math.max(0, capacity.workspaceBytes - used.workspaceBytes) : null,
758
2062
  diskLow: preflight?.diskLow ?? null,
@@ -766,8 +2070,11 @@ export class ForgeBridgeService {
766
2070
  hostReserveBytes: preflight.hostReserveBytes,
767
2071
  activeReservationBytes: used.memoryBytes,
768
2072
  daemonTotalBytes: preflight.totalMemoryBytes,
769
- daemonAvailableBytes: preflight.availableMemoryBytes,
770
- availableForAdmissionBytes: Math.max(0, capacity.memoryBytes - used.memoryBytes),
2073
+ daemonAvailableBytes: preflight.rawDaemonAvailableMemoryBytes ?? 0,
2074
+ hostAvailableBytes: preflight.rawHostAvailableMemoryBytes,
2075
+ conservativeAvailableBytes: preflight.rawAvailableMemoryBytes,
2076
+ availableForAdmissionBytes: memoryAdmission.availableForAdmissionBytes,
2077
+ memoryAdmission: memoryAdmission,
771
2078
  } : null,
772
2079
  hostRuntime: this.sessions.runtimeCapacity?.() ?? null,
773
2080
  supportsApiSecretGrant: this.config.supportsApiSecretGrant,
@@ -776,9 +2083,21 @@ export class ForgeBridgeService {
776
2083
  supportsRunnerAuthoredPhaseArtifacts: this.config.supportsRunnerAuthoredPhaseArtifacts,
777
2084
  supportsDraftRunOnce: this.config.supportsDraftRunOnce,
778
2085
  supportsDraftAttachments: this.config.supportsDraftAttachments,
779
- supportsDraftImageAttachments: this.config.supportsDraftImageAttachments
2086
+ supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
2087
+ bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
2088
+ settings: { supportsServerSettings: true, ...this.settingsReport },
780
2089
  };
781
2090
  }
2091
+ async requiredCapabilityFailure(dispatch) {
2092
+ const requiredCapabilities = dispatch.qaScope?.required_capabilities ?? [];
2093
+ if (!requiredCapabilities.includes("docker_engine"))
2094
+ return null;
2095
+ const executionMode = dispatch.sandbox?.executionMode;
2096
+ if (executionMode === "docker") {
2097
+ return dockerEngineRequirementFailure(requiredCapabilities, executionMode, null);
2098
+ }
2099
+ return dockerEngineRequirementFailure(requiredCapabilities, executionMode, await this.dockerEngineProbe.refresh(true));
2100
+ }
782
2101
  usedSandboxResources(degradedReservations) {
783
2102
  const resources = [
784
2103
  ...[...this.reservations.values()]
@@ -811,9 +2130,7 @@ export class ForgeBridgeService {
811
2130
  workerMemoryLimitBytes: 0,
812
2131
  serviceMemoryLimitBytes: 0,
813
2132
  runtimeOverheadBytes: 0,
814
- memoryBytes: Math.max(0, preflight.availableMemoryBytes
815
- - (this.config.sandboxHostMemoryReserveBytes ?? 2 * 1024 ** 3)
816
- + activeResources.memoryBytes),
2133
+ memoryBytes: sandboxMemoryCommitmentCapacity(preflight, activeResources.memoryBytes),
817
2134
  workspaceBytes: Math.max(0, preflight.availableWorkspaceBytes
818
2135
  - this.config.minimumWorkspaceBytes
819
2136
  + activeResources.workspaceBytes),
@@ -821,22 +2138,96 @@ export class ForgeBridgeService {
821
2138
  buildSlots: this.config.maxConcurrentSandboxBuilds
822
2139
  };
823
2140
  }
824
- async invokeAck(methodName, payload) {
825
- const connection = this.connection;
826
- if (!connection) {
827
- throw new Error("Bridge is not connected.");
2141
+ async invokeAck(methodName, payload, options = {}) {
2142
+ let storageRecoveryAttempt = 0;
2143
+ let callbackTimeoutAttempt = 0;
2144
+ while (true) {
2145
+ if (options.signal?.aborted) {
2146
+ throw new Error(String(options.signal.reason ?? `${methodName} callback was cancelled.`));
2147
+ }
2148
+ const connection = this.connection;
2149
+ if (!connection) {
2150
+ throw new Error("Bridge is not connected.");
2151
+ }
2152
+ await this.waitForTransportRecovery(connection, this.transportRecovery, options.signal);
2153
+ const recoveryGeneration = this.transportRecoveryGeneration;
2154
+ try {
2155
+ const ack = await waitForCallbackAck(connection.invoke(methodName, payload), methodName, positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000), options.signal);
2156
+ if (!ack.accepted) {
2157
+ throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? `${methodName} callback was rejected.`);
2158
+ }
2159
+ return ack;
2160
+ }
2161
+ catch (error) {
2162
+ if (options.signal?.aborted)
2163
+ throw error;
2164
+ if (connection !== this.connection || this.stopped)
2165
+ throw error;
2166
+ const recovery = this.transportRecovery;
2167
+ if (recovery && recovery.generation > recoveryGeneration) {
2168
+ await this.waitForTransportRecovery(connection, recovery, options.signal);
2169
+ continue;
2170
+ }
2171
+ if (isProviderStorageUnavailable(error)) {
2172
+ const backoff = this.config.reconnectBackoffMs[Math.min(storageRecoveryAttempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
2173
+ storageRecoveryAttempt += 1;
2174
+ logBridgeStatus(`${methodName} reached Forge while storage was recovering. Retrying callback ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
2175
+ await delay(backoff, options.signal);
2176
+ continue;
2177
+ }
2178
+ if (options.replayCallbackTimeout && isBridgeCallbackTimeout(error)) {
2179
+ const backoff = this.config.reconnectBackoffMs[Math.min(callbackTimeoutAttempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
2180
+ callbackTimeoutAttempt += 1;
2181
+ logBridgeStatus(`${methodName} acknowledgement timed out. Replaying the idempotent callback ${callbackTimeoutAttempt} in ${formatDelay(backoff)}...`);
2182
+ await delay(backoff, options.signal);
2183
+ continue;
2184
+ }
2185
+ throw error;
2186
+ }
828
2187
  }
829
- const ack = await connection.invoke(methodName, payload);
830
- if (!ack.accepted) {
831
- throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? `${methodName} callback was rejected.`);
2188
+ }
2189
+ beginTransportRecovery() {
2190
+ if (this.transportRecovery && !this.transportRecovery.completed)
2191
+ return;
2192
+ let resolve = () => undefined;
2193
+ const promise = new Promise((complete) => { resolve = complete; });
2194
+ this.transportRecoveryGeneration += 1;
2195
+ this.transportRecovery = {
2196
+ generation: this.transportRecoveryGeneration,
2197
+ promise,
2198
+ resolve,
2199
+ completed: false,
2200
+ error: null,
2201
+ };
2202
+ }
2203
+ completeTransportRecovery(error = null) {
2204
+ const recovery = this.transportRecovery;
2205
+ if (!recovery || recovery.completed)
2206
+ return;
2207
+ recovery.completed = true;
2208
+ recovery.error = error;
2209
+ recovery.resolve();
2210
+ }
2211
+ async waitForTransportRecovery(connection, recovery, signal) {
2212
+ if (!recovery)
2213
+ return;
2214
+ if (recovery.completed) {
2215
+ if (recovery.error)
2216
+ throw recovery.error;
2217
+ return;
832
2218
  }
833
- return ack;
2219
+ await waitForPromiseOrAbort(recovery.promise, signal);
2220
+ signal?.throwIfAborted();
2221
+ if (connection !== this.connection)
2222
+ throw new Error("Bridge connection changed while recovering.");
2223
+ if (recovery.error)
2224
+ throw recovery.error;
834
2225
  }
835
2226
  async waitForClose(signal) {
836
2227
  if (!this.closed) {
837
2228
  return;
838
2229
  }
839
- await Promise.race([this.closed, abortPromise(signal)]);
2230
+ await waitForPromiseOrAbort(this.closed, signal);
840
2231
  }
841
2232
  async stopConnection() {
842
2233
  this.stopHeartbeat();
@@ -848,6 +2239,16 @@ export class ForgeBridgeService {
848
2239
  }
849
2240
  }
850
2241
  }
2242
+ /** The `run` command's exit code after Forge removed the runner. */
2243
+ export const bridgeRevokedExitCode = 3;
2244
+ export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
2245
+ /** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
2246
+ export class BridgeRevokedError extends Error {
2247
+ constructor(message = bridgeRevokedMessage) {
2248
+ super(message);
2249
+ this.name = "BridgeRevokedError";
2250
+ }
2251
+ }
851
2252
  class BridgeCallbackRejectedError extends Error {
852
2253
  code;
853
2254
  constructor(code, message) {
@@ -856,17 +2257,38 @@ class BridgeCallbackRejectedError extends Error {
856
2257
  this.name = "BridgeCallbackRejectedError";
857
2258
  }
858
2259
  }
2260
+ function deferRejectedReplay(kind) {
2261
+ return error => {
2262
+ if (!(error instanceof BridgeCallbackRejectedError))
2263
+ throw error;
2264
+ logBridgeStatus(`${kind} result replay deferred: ${errorMessage(error)}`);
2265
+ };
2266
+ }
859
2267
  function isDispatchNoLongerPending(error) {
860
2268
  if (error instanceof BridgeCallbackRejectedError) {
861
2269
  return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
862
2270
  }
863
2271
  return error instanceof Error && error.message === "Dispatch is no longer pending.";
864
2272
  }
865
- function createDefaultSessionService(sandboxStateRoot) {
2273
+ function isReadinessNoLongerPending(error) {
2274
+ return error instanceof BridgeCallbackRejectedError
2275
+ && (error.code === "bridge.stale_readiness_probe" || error.code === "bridge.stale_runner_instance");
2276
+ }
2277
+ function isProviderStorageUnavailable(error) {
2278
+ const message = errorMessage(error).toLowerCase();
2279
+ return message.includes("provider_storage_unavailable")
2280
+ || (message.includes("storage is recovering") && message.includes("503"));
2281
+ }
2282
+ function isBridgeCallbackTimeout(error) {
2283
+ return errorMessage(error).startsWith("bridge_callback_timeout:");
2284
+ }
2285
+ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
866
2286
  const rawProcessRunner = new StreamingProviderProcessRunner();
867
2287
  const processSupervisors = new AttemptProcessSupervisorRegistry();
868
2288
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
869
- return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner)), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner));
2289
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2290
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2291
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
870
2292
  }
871
2293
  export class SignalRBridgeConnectionFactory {
872
2294
  create(config) {
@@ -890,10 +2312,23 @@ export class SignalRBridgeConnection {
890
2312
  Authorization: `Bearer ${config.deviceToken}`
891
2313
  }
892
2314
  })
2315
+ .withAutomaticReconnect([...config.reconnectBackoffMs])
893
2316
  .configureLogging(LogLevel.Warning)
894
2317
  .build();
895
2318
  this.connection.on("Superseded", () => {
896
- void this.connection.stop();
2319
+ void this.connection.stop().catch(() => undefined);
2320
+ });
2321
+ }
2322
+ onApplySettings(handler) {
2323
+ this.connection.on("ApplySettings", (raw) => {
2324
+ void Promise.resolve(handler(raw)).catch(() => undefined);
2325
+ });
2326
+ }
2327
+ onRevoked(handler) {
2328
+ this.connection.on("Revoked", (raw) => {
2329
+ const notice = raw && typeof raw === "object" ? raw : {};
2330
+ handler(notice);
2331
+ void this.connection.stop().catch(() => undefined);
897
2332
  });
898
2333
  }
899
2334
  start() {
@@ -905,11 +2340,24 @@ export class SignalRBridgeConnection {
905
2340
  onClose(handler) {
906
2341
  this.connection.onclose(handler);
907
2342
  }
2343
+ onReconnecting(handler) {
2344
+ this.connection.onreconnecting(handler);
2345
+ }
2346
+ onReconnected(handler) {
2347
+ this.connection.onreconnected((connectionId) => {
2348
+ void Promise.resolve(handler(connectionId)).catch(() => undefined);
2349
+ });
2350
+ }
908
2351
  onDispatch(handler) {
909
2352
  this.connection.on("Dispatch", (raw) => {
910
2353
  void handler(raw).catch(() => undefined);
911
2354
  });
912
2355
  }
2356
+ onChatTurn(handler) {
2357
+ this.connection.on("ChatTurn", (raw) => {
2358
+ void handler(raw).catch(() => undefined);
2359
+ });
2360
+ }
913
2361
  onOffer(handler) {
914
2362
  this.connection.on("Offer", (raw) => {
915
2363
  void handler(raw).catch(() => undefined);
@@ -947,9 +2395,7 @@ export class SignalRBridgeConnection {
947
2395
  export function defaultBridgeServiceConfig(overrides = {}) {
948
2396
  const defaults = defaultForgeBridgeConfig();
949
2397
  const cliProviders = splitCsv(process.env.FORGE_CLI_PROVIDERS ?? "codex");
950
- const sandboxHostMemoryReserveDefault = process.platform === "linux"
951
- ? 2 * 1024 ** 3
952
- : 1024 ** 3;
2398
+ const configuredSandboxHostMemoryReserveBytes = optionalPositiveFiniteNumber(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES);
953
2399
  const sandboxPublicationMode = process.env.FORGE_SANDBOX_PUBLICATION_MODE === "bridge_push" ? "bridge_push" : "shared_filesystem";
954
2400
  const config = {
955
2401
  serverUrl: process.env.FORGE_URL ?? "http://localhost:5208",
@@ -964,12 +2410,19 @@ export function defaultBridgeServiceConfig(overrides = {}) {
964
2410
  sandboxPublicationMode,
965
2411
  dockerExecutable: process.env.FORGE_DOCKER_EXECUTABLE ?? "docker",
966
2412
  dockerContext: process.env.FORGE_DOCKER_CONTEXT ?? "",
2413
+ dockerDesktopRecoveryEnabled: process.env.FORGE_DOCKER_DESKTOP_AUTO_RECOVERY === "true",
2414
+ dockerRecoveryFailureThreshold: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_FAILURE_THRESHOLD ?? 3), 3),
2415
+ dockerRecoveryCooldownMs: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_COOLDOWN_MS ?? 10 * 60_000), 10 * 60_000),
2416
+ dockerRecoveryStartupTimeoutMs: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_STARTUP_TIMEOUT_MS ?? 2 * 60_000), 2 * 60_000),
967
2417
  sandboxStateRoot: process.env.FORGE_SANDBOX_STATE_ROOT ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes"),
2418
+ sandboxExecutionRoot: defaultHostExecutionRoot(),
968
2419
  requireRootlessDocker: process.env.FORGE_REQUIRE_ROOTLESS_DOCKER === "true" || process.platform === "linux",
969
2420
  diskHighWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_HIGH_WATERMARK_PERCENT ?? 85), 85),
970
2421
  diskLowWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_LOW_WATERMARK_PERCENT ?? 75), 75),
971
2422
  minimumWorkspaceBytes: positiveFiniteNumber(Number(process.env.FORGE_MINIMUM_WORKSPACE_BYTES ?? 10 * 1024 ** 3), 10 * 1024 ** 3),
972
- sandboxHostMemoryReserveBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES ?? sandboxHostMemoryReserveDefault), sandboxHostMemoryReserveDefault),
2423
+ // Undefined means preflight derives the bounded reserve from the actual
2424
+ // Docker/host capacity domain after sampling it.
2425
+ sandboxHostMemoryReserveBytes: configuredSandboxHostMemoryReserveBytes,
973
2426
  defaultSandboxWorkerMemoryLimitBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_WORKER_MEMORY_LIMIT_BYTES ?? 2 * 1024 ** 3), 2 * 1024 ** 3),
974
2427
  defaultSandboxServiceMemoryLimitBytes: nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_SERVICE_MEMORY_LIMIT_BYTES ?? 0), 0),
975
2428
  sandboxRuntimeOverheadBytes: Math.max(128 * 1024 ** 2, nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_RUNTIME_OVERHEAD_BYTES ?? 128 * 1024 ** 2), 128 * 1024 ** 2)),
@@ -995,10 +2448,12 @@ export function defaultBridgeServiceConfig(overrides = {}) {
995
2448
  supportsDraftRunOnce: true,
996
2449
  supportsDraftAttachments: true,
997
2450
  supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
2451
+ bridgeChat: bridgeChatCapabilityFor(cliProviders, providerStatusesFor(cliProviders)),
998
2452
  version: process.env.FORGE_BRIDGE_VERSION ?? forgeBridgeVersion,
999
- protocolVersion: 2,
2453
+ protocolVersion: 4,
1000
2454
  minServerVersion: null,
1001
2455
  heartbeatIntervalMs: positiveFiniteNumber(Number(process.env.FORGE_HEARTBEAT_INTERVAL_MS ?? 30_000), 30_000),
2456
+ callbackAckTimeoutMs: positiveFiniteNumber(Number(process.env.FORGE_CALLBACK_ACK_TIMEOUT_MS ?? 30_000), 30_000),
1002
2457
  reconnectBackoffMs: [1000, 2000, 5000, 10000, 30000],
1003
2458
  ...overrides
1004
2459
  };
@@ -1007,7 +2462,9 @@ export function defaultBridgeServiceConfig(overrides = {}) {
1007
2462
  providerStatuses: overrides.providerStatuses ?? providerStatusesFor(config.cliProviders),
1008
2463
  sandboxProfiles: config.sandboxProfiles ?? defaultSandboxProfiles(config.cliProviders),
1009
2464
  supportsDraftImageAttachments: (overrides.supportsDraftImageAttachments ?? true) && supportsDraftImageAttachmentsFor(config.cliProviders),
1010
- heartbeatIntervalMs: positiveFiniteNumber(config.heartbeatIntervalMs, 30_000)
2465
+ bridgeChat: overrides.bridgeChat ?? bridgeChatCapabilityFor(config.cliProviders, overrides.providerStatuses ?? providerStatusesFor(config.cliProviders), config.bridgeChat),
2466
+ heartbeatIntervalMs: positiveFiniteNumber(config.heartbeatIntervalMs, 30_000),
2467
+ callbackAckTimeoutMs: positiveFiniteNumber(config.callbackAckTimeoutMs ?? 30_000, 30_000),
1011
2468
  };
1012
2469
  }
1013
2470
  export function resolveBridgeRunnerHubUrl(serverUrl) {
@@ -1022,6 +2479,12 @@ function normalizeServerUrl(serverUrl) {
1022
2479
  function positiveFiniteNumber(value, fallback) {
1023
2480
  return Number.isFinite(value) && value > 0 ? value : fallback;
1024
2481
  }
2482
+ function optionalPositiveFiniteNumber(value) {
2483
+ if (value === undefined || value.trim().length === 0)
2484
+ return undefined;
2485
+ const parsed = Number(value);
2486
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
2487
+ }
1025
2488
  function nonNegativeFiniteNumber(value, fallback) {
1026
2489
  return Number.isFinite(value) && value >= 0 ? value : fallback;
1027
2490
  }
@@ -1126,15 +2589,32 @@ function mappingKeys(mapping) {
1126
2589
  mapping.localPath ? `path:${path.resolve(mapping.localPath).toLowerCase()}` : null
1127
2590
  ].filter((key) => Boolean(key));
1128
2591
  }
1129
- function findRepoMapping(dispatch, mappings) {
1130
- return mappings.find((mapping) => {
1131
- if (!mapping.localPath?.trim()) {
1132
- return false;
2592
+ function findRepoMapping(repo, mappings) {
2593
+ const usable = mappings.filter(mapping => Boolean(mapping.localPath?.trim()));
2594
+ const selectUnique = (candidates, identity) => {
2595
+ if (candidates.length > 1) {
2596
+ throw new Error(`bridge_repo_mapping_ambiguous: multiple local checkouts match ${identity}.`);
1133
2597
  }
1134
- return (equalsIgnoreCase(mapping.repoId, dispatch.repo.id) ||
1135
- equalsIgnoreCase(mapping.name, dispatch.repo.name) ||
1136
- (!!mapping.remoteUrl?.trim() && equalsIgnoreCase(mapping.remoteUrl, dispatch.repo.remoteUrl)));
1137
- });
2598
+ return candidates[0];
2599
+ };
2600
+ // Repository identity is authoritative. A same-name mapping for a different
2601
+ // repository must never win merely because it appears first in configuration.
2602
+ const byId = usable.filter(mapping => equalsIgnoreCase(mapping.repoId, repo.id));
2603
+ if (byId.length > 0)
2604
+ return selectUnique(byId, `repo id '${repo.id}'`);
2605
+ const byRemote = repo.remoteUrl?.trim()
2606
+ ? usable.filter(mapping => !mapping.repoId?.trim()
2607
+ && Boolean(mapping.remoteUrl?.trim())
2608
+ && equalsIgnoreCase(mapping.remoteUrl, repo.remoteUrl))
2609
+ : [];
2610
+ if (byRemote.length > 0)
2611
+ return selectUnique(byRemote, `remote '${repo.remoteUrl}'`);
2612
+ const byName = usable.filter(mapping => !mapping.repoId?.trim()
2613
+ && !mapping.remoteUrl?.trim()
2614
+ && equalsIgnoreCase(mapping.name, repo.name));
2615
+ return byName.length > 0
2616
+ ? selectUnique(byName, `repo name '${repo.name}'`)
2617
+ : undefined;
1138
2618
  }
1139
2619
  function normalizeQaAppLaunchTarget(target) {
1140
2620
  if (!target) {
@@ -1183,6 +2663,10 @@ function invalidDispatchSummary(error) {
1183
2663
  const detail = error instanceof Error ? error.message : String(error);
1184
2664
  return `Invalid bridge dispatch packet: ${detail}`;
1185
2665
  }
2666
+ function invalidChatTurnSummary(error) {
2667
+ const detail = error instanceof Error ? error.message : String(error);
2668
+ return `Invalid Bridge Chat turn packet: ${detail}`;
2669
+ }
1186
2670
  function errorMessage(error) {
1187
2671
  return error instanceof Error ? error.message : String(error);
1188
2672
  }
@@ -1192,29 +2676,220 @@ function formatDelay(ms) {
1192
2676
  }
1193
2677
  return `${ms}ms`;
1194
2678
  }
2679
+ async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
2680
+ let timeout = null;
2681
+ let rejectAbort = null;
2682
+ const expired = new Promise((_resolve, reject) => {
2683
+ timeout = setTimeout(() => {
2684
+ reject(new Error(`bridge_callback_timeout: ${methodName} callback was not acknowledged within ${formatDelay(timeoutMs)}.`));
2685
+ }, timeoutMs);
2686
+ });
2687
+ const aborted = new Promise((_resolve, reject) => {
2688
+ rejectAbort = reject;
2689
+ });
2690
+ const onAbort = () => rejectAbort?.(new Error(String(signal?.reason ?? `${methodName} callback was cancelled.`)));
2691
+ signal?.addEventListener("abort", onAbort, { once: true });
2692
+ if (signal?.aborted)
2693
+ onAbort();
2694
+ try {
2695
+ return await Promise.race(signal ? [callback, expired, aborted] : [callback, expired]);
2696
+ }
2697
+ finally {
2698
+ if (timeout)
2699
+ clearTimeout(timeout);
2700
+ signal?.removeEventListener("abort", onAbort);
2701
+ }
2702
+ }
1195
2703
  function logBridgeStatus(message) {
1196
2704
  process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
1197
2705
  }
1198
- function delay(ms, signal) {
2706
+ export function delay(ms, signal) {
1199
2707
  if (signal?.aborted) {
1200
2708
  return Promise.resolve();
1201
2709
  }
1202
2710
  return new Promise((resolve) => {
1203
- const timeout = setTimeout(resolve, ms);
1204
- signal?.addEventListener("abort", () => {
2711
+ const complete = () => {
1205
2712
  clearTimeout(timeout);
2713
+ signal?.removeEventListener("abort", complete);
1206
2714
  resolve();
1207
- }, { once: true });
2715
+ };
2716
+ const timeout = setTimeout(complete, ms);
2717
+ signal?.addEventListener("abort", complete, { once: true });
2718
+ if (signal?.aborted)
2719
+ complete();
1208
2720
  });
1209
2721
  }
1210
- function abortPromise(signal) {
2722
+ export async function waitForPromiseOrAbort(promise, signal) {
1211
2723
  if (!signal) {
1212
- return new Promise(() => undefined);
2724
+ await promise;
2725
+ return;
1213
2726
  }
1214
2727
  if (signal.aborted) {
1215
- return Promise.resolve();
2728
+ return;
2729
+ }
2730
+ let resolveAbort;
2731
+ const abort = new Promise(resolve => { resolveAbort = resolve; });
2732
+ signal.addEventListener("abort", resolveAbort, { once: true });
2733
+ try {
2734
+ await Promise.race([promise, abort]);
2735
+ }
2736
+ finally {
2737
+ signal.removeEventListener("abort", resolveAbort);
2738
+ }
2739
+ }
2740
+ // Matches the API Hello bound on settled recovered host attempts.
2741
+ const maxRecoveredHostAttempts = 128;
2742
+ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2743
+ const maxChatEventContentChars = 4000;
2744
+ const maxChatTerminalTextChars = 120_000;
2745
+ const maxChatExactSecretChars = 8 * 1024;
2746
+ async function materializeChatTurnMetadata(packet, workspacePath) {
2747
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2748
+ return;
2749
+ }
2750
+ await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
2751
+ schemaVersion: 1,
2752
+ attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
2753
+ turnId: handoff.turnId,
2754
+ attachmentId: handoff.attachmentId,
2755
+ tempFileToken: handoff.tempFileToken,
2756
+ mimeType: handoff.mimeType,
2757
+ sizeBytes: handoff.sizeBytes,
2758
+ sha256: handoff.sha256,
2759
+ fileNameDisplay: handoff.fileNameDisplay,
2760
+ expiresAt: handoff.expiresAt,
2761
+ status: handoff.status,
2762
+ })),
2763
+ actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
2764
+ grantId: grant.grantId,
2765
+ turnId: grant.turnId,
2766
+ leaseId: grant.leaseId,
2767
+ fencingToken: grant.fencingToken,
2768
+ allowedScopes: grant.allowedScopes,
2769
+ expiresAt: grant.expiresAt,
2770
+ redactionStatus: grant.redactionStatus,
2771
+ nonceHeldByBridge: true,
2772
+ })),
2773
+ }, null, 2)}\n`, "utf8");
2774
+ }
2775
+ function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
2776
+ const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
2777
+ const metadataExpiresAtMs = [
2778
+ ...packet.attachmentHandoffs.map(handoff => Date.parse(handoff.expiresAt)),
2779
+ ...packet.actionBrokerGrants.map(grant => Date.parse(grant.expiresAt)),
2780
+ ].filter(Number.isFinite);
2781
+ return new Date(Math.min(defaultExpiresAtMs, ...metadataExpiresAtMs)).toISOString();
2782
+ }
2783
+ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
2784
+ try {
2785
+ await fs.promises.rm(workspacePath, { recursive: true, force: true, maxRetries: 3 });
2786
+ return {
2787
+ status: "completed",
2788
+ eventType: "chat_turn_cleanup_completed",
2789
+ role: "runner",
2790
+ kind: "checkpoint",
2791
+ content: "Bridge Chat workspace cleanup completed.",
2792
+ };
2793
+ }
2794
+ catch (error) {
2795
+ return {
2796
+ status: "failed",
2797
+ eventType: "chat_turn_cleanup_failed",
2798
+ role: "runner",
2799
+ kind: "error",
2800
+ content: "Bridge Chat workspace cleanup failed.",
2801
+ message: clip(redactText(errorMessage(error), redactionSecrets), 1000),
2802
+ };
2803
+ }
2804
+ }
2805
+ function chatProviderExitFailure(command, result, redactionSecrets) {
2806
+ const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
2807
+ const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
2808
+ const stdout = clip(redactText(result.stdout.trim(), redactionSecrets), 1000);
2809
+ const diagnostics = [
2810
+ stderr ? `stderr: ${stderr}` : null,
2811
+ stdout ? `stdout: ${stdout}` : null,
2812
+ ].filter(Boolean).join(" ");
2813
+ return new Error(`provider_failed: ${commandText} exited with code ${result.exitCode}.${diagnostics ? ` ${diagnostics}` : ""}`);
2814
+ }
2815
+ function chatAbortKind(reason) {
2816
+ const message = typeof reason === "string" ? reason.toLowerCase() : "";
2817
+ return message.includes("expired") ? "expired" : "cancelled";
2818
+ }
2819
+ function chatAbortPayload(reason, cleanupOutcome, packet) {
2820
+ const kind = chatAbortKind(reason);
2821
+ const message = typeof reason === "string" && reason.trim()
2822
+ ? reason.trim()
2823
+ : (kind === "expired" ? "Bridge Chat turn expired." : "Bridge Chat turn cancelled.");
2824
+ return {
2825
+ code: kind === "expired" ? "chat_turn_expired" : "chat_turn_cancelled",
2826
+ message: clip(redactText(message, packet ? chatRedactionSecrets(packet) : []), 1000),
2827
+ cleanup: cleanupOutcome,
2828
+ };
2829
+ }
2830
+ function providerThreadIdFromEvent(event) {
2831
+ if (!event.data) {
2832
+ return null;
2833
+ }
2834
+ try {
2835
+ const data = JSON.parse(event.data);
2836
+ for (const key of ["threadId", "thread_id", "sessionId", "session_id", "providerThreadId"]) {
2837
+ const value = data[key];
2838
+ if (typeof value === "string") {
2839
+ const clean = value.trim();
2840
+ if (clean.length > 0 && clean.length <= bridgeChatMaxProviderThreadIdChars) {
2841
+ return clean;
2842
+ }
2843
+ }
2844
+ }
2845
+ }
2846
+ catch {
2847
+ return null;
2848
+ }
2849
+ return null;
2850
+ }
2851
+ function chatRedactionSecrets(packet) {
2852
+ return [
2853
+ packet.chatRunId,
2854
+ packet.conversationId,
2855
+ packet.turnId,
2856
+ packet.leaseId,
2857
+ packet.fencingToken,
2858
+ packet.runnerInstanceId,
2859
+ packet.providerThreadId,
2860
+ ...packet.attachmentHandoffs.flatMap((handoff) => [
2861
+ handoff.attachmentId,
2862
+ handoff.tempFileToken,
2863
+ ]),
2864
+ ...packet.actionBrokerGrants.flatMap((grant) => [
2865
+ grant.grantId,
2866
+ grant.nonce,
2867
+ ]),
2868
+ ...packet.messages.flatMap((message) => boundedChatSecretFragments(message.content)),
2869
+ ...packet.contextRefs.flatMap((ref) => [
2870
+ ...boundedChatSecretFragments(ref.title ?? ""),
2871
+ ...boundedChatSecretFragments(ref.summary ?? ""),
2872
+ ]),
2873
+ ].filter((value) => typeof value === "string" && value.length > 0);
2874
+ }
2875
+ function boundedChatSecretFragments(value) {
2876
+ const clean = value.trim();
2877
+ if (!clean) {
2878
+ return [];
1216
2879
  }
1217
- return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
2880
+ if (clean.length <= maxChatExactSecretChars) {
2881
+ return [clean];
2882
+ }
2883
+ const half = Math.floor(maxChatExactSecretChars / 2);
2884
+ return [clean.slice(0, half), clean.slice(clean.length - half)];
2885
+ }
2886
+ function safePathComponent(value) {
2887
+ const clean = value.trim().replace(/[^a-zA-Z0-9_.-]+/gu, "-").replace(/^-+|-+$/gu, "");
2888
+ return clean || "chat-turn";
2889
+ }
2890
+ function containsIgnoreCase(values, value) {
2891
+ const normalized = value.trim().toLowerCase();
2892
+ return values.some((candidate) => candidate.trim().toLowerCase() === normalized);
1218
2893
  }
1219
2894
  export function canReapManagedSandboxes(preflight) {
1220
2895
  return canRunDockerMaintenance(preflight);
@@ -1234,24 +2909,15 @@ function sandboxNetworkPolicyFailure(dispatch, config) {
1234
2909
  }
1235
2910
  return null;
1236
2911
  }
1237
- function infrastructureFailureEventType(summary) {
1238
- if (summary.startsWith("worktree_prepare_failed:"))
1239
- return "worktree_prepare_failed";
1240
- if (summary.startsWith("provider_start_unavailable:"))
1241
- return "provider_start_unavailable";
1242
- if (summary.startsWith("host_port_collision:"))
1243
- return "host_port_collision";
1244
- if (summary.startsWith("host_runtime_process_exited:"))
1245
- return "host_runtime_process_exited";
1246
- if (summary.startsWith("host_runtime_listener_timeout:"))
1247
- return "host_runtime_listener_timeout";
1248
- if (summary.startsWith("host_runtime_http_readiness_timeout:"))
1249
- return "host_runtime_http_readiness_timeout";
1250
- if (summary.startsWith("attempt_process_supervisor_start_failed:"))
1251
- return "attempt_process_supervisor_start_failed";
1252
- if (summary.startsWith("attempt_process_supervisor_start_timeout:"))
1253
- return "attempt_process_supervisor_start_timeout";
1254
- return null;
2912
+ export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
2913
+ if (!requiredCapabilities.includes("docker_engine"))
2914
+ return null;
2915
+ if (executionMode === "docker") {
2916
+ return "docker_engine_unavailable: docker_engine is not exposed inside Forge agent sandboxes; use a managed host runner with Docker-daemon access.";
2917
+ }
2918
+ return capability?.available
2919
+ ? null
2920
+ : `docker_engine_unavailable: ${capability?.unavailableReason ?? "Docker daemon is unreachable from the bridge process."}`;
1255
2921
  }
1256
2922
  function parseReadinessProbe(value) {
1257
2923
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -1308,143 +2974,15 @@ function sandboxAuthFailure(dispatch, config) {
1308
2974
  const doctor = adapter.doctor();
1309
2975
  return doctor.available ? null : doctor.message;
1310
2976
  }
1311
- export function canReserveSandboxResources(used, requested, capacity) {
1312
- return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
1313
- && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
1314
- && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
1315
- && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
1316
- && used.pids + requested.pids <= capacity.pids
1317
- && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
1318
- }
1319
- export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
1320
- const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
1321
- if (requested.sandboxSlots > availableSlots) {
1322
- return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
1323
- }
1324
- const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
1325
- if (requested.memoryBytes > availableMemoryBytes) {
1326
- return [
1327
- `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
1328
- `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
1329
- `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
1330
- `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
1331
- `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
1332
- ].join(" ");
1333
- }
1334
- const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
1335
- if (requested.cpuMillis > availableCpuMillis) {
1336
- return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
1337
- }
1338
- const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
1339
- if (requested.workspaceBytes > availableWorkspaceBytes) {
1340
- return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
1341
- }
1342
- const availablePids = Math.max(0, capacity.pids - used.pids);
1343
- if (requested.pids > availablePids) {
1344
- return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
1345
- }
1346
- const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
1347
- return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
1348
- }
1349
- function formatBytes(bytes) {
1350
- if (!Number.isFinite(bytes) || bytes <= 0)
1351
- return "0 B";
1352
- const units = ["B", "KiB", "MiB", "GiB", "TiB"];
1353
- const power = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
1354
- const value = bytes / 1024 ** power;
1355
- return `${value >= 10 || power === 0 ? value.toFixed(0) : value.toFixed(2)} ${units[power]}`;
1356
- }
1357
- function sumSandboxResources(resources) {
1358
- return resources.reduce((total, resource) => ({
1359
- sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
1360
- cpuMillis: total.cpuMillis + resource.cpuMillis,
1361
- workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
1362
- serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
1363
- runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
1364
- memoryBytes: total.memoryBytes + resource.memoryBytes,
1365
- workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
1366
- pids: total.pids + resource.pids,
1367
- buildSlots: total.buildSlots + resource.buildSlots
1368
- }), zeroSandboxResources());
1369
- }
1370
- function zeroSandboxResources() {
2977
+ function rejectedOfferReservation(code, message) {
1371
2978
  return {
1372
- sandboxSlots: 0,
1373
- cpuMillis: 0,
1374
- workerMemoryLimitBytes: 0,
1375
- serviceMemoryLimitBytes: 0,
1376
- runtimeOverheadBytes: 0,
1377
- memoryBytes: 0,
1378
- workspaceBytes: 0,
1379
- pids: 0,
1380
- buildSlots: 0,
2979
+ accepted: false,
2980
+ code,
2981
+ message,
2982
+ reservedUntil: null,
2983
+ resources: null,
1381
2984
  };
1382
2985
  }
1383
- function defaultSandboxResources() {
1384
- return {
1385
- sandboxSlots: 1,
1386
- cpuMillis: 2000,
1387
- workerMemoryLimitBytes: 2 * 1024 ** 3,
1388
- serviceMemoryLimitBytes: 0,
1389
- runtimeOverheadBytes: 128 * 1024 ** 2,
1390
- memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
1391
- workspaceBytes: 10 * 1024 ** 3,
1392
- pids: 512,
1393
- buildSlots: 0
1394
- };
1395
- }
1396
- export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
1397
- const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
1398
- const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
1399
- + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
1400
- return {
1401
- ...requested,
1402
- serviceMemoryLimitBytes,
1403
- runtimeOverheadBytes,
1404
- memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
1405
- };
1406
- }
1407
- export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
1408
- const repoPath = dispatch.repo.serverLocalPath;
1409
- const sandbox = dispatch.sandbox;
1410
- if (!repoPath || !sandbox) {
1411
- throw new Error("Sandbox admission needs a mapped repository.");
1412
- }
1413
- const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
1414
- const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
1415
- if (!configCommitSha) {
1416
- throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
1417
- }
1418
- const contractResult = await runSandboxProcess({
1419
- command: "git",
1420
- args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
1421
- timeoutMs: 30_000,
1422
- maxOutputBytes: 1024 * 1024,
1423
- });
1424
- if (contractResult.exitCode !== 0) {
1425
- throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
1426
- }
1427
- const contract = validateSandboxContract(contractResult.stdout);
1428
- return {
1429
- resources: resolveDynamicSandboxResources(sandbox.requestedResources, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
1430
- sandboxConfigCommitSha: configCommitSha,
1431
- };
1432
- }
1433
- async function resolveFirstGitCommit(repoPath, refs) {
1434
- for (const ref of refs) {
1435
- const result = await runSandboxProcess({
1436
- command: "git",
1437
- args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
1438
- timeoutMs: 30_000,
1439
- maxOutputBytes: 1024 * 1024,
1440
- });
1441
- const commitSha = result.stdout.trim().toLowerCase();
1442
- if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
1443
- return commitSha;
1444
- }
1445
- }
1446
- return null;
1447
- }
1448
2986
  function parseOfferEnvelope(value) {
1449
2987
  return parseDispatchEnvelope(value);
1450
2988
  }