@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 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 (381) hide show
  1. package/README.md +306 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +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 +18 -1
  15. package/dist/bridge/bridge.service.d.ts +216 -4
  16. package/dist/bridge/bridge.service.js +2574 -90
  17. package/dist/bridge/bridge.types.d.ts +245 -2
  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 +33 -2
  41. package/dist/cleanup/cleanup.service.js +477 -3
  42. package/dist/cleanup/cleanup.types.d.ts +16 -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/index.d.ts +1 -1
  48. package/dist/cleanup/index.js +1 -1
  49. package/dist/cleanup/internals.d.ts +2 -2
  50. package/dist/cleanup/internals.js +1 -1
  51. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  52. package/dist/cleanup/managed-branch-sweep.js +111 -0
  53. package/dist/cli/cli.help.d.ts +2 -0
  54. package/dist/cli/cli.help.js +279 -0
  55. package/dist/cli/cli.service.d.ts +69 -12
  56. package/dist/cli/cli.service.js +557 -382
  57. package/dist/cli/idle-status.d.ts +84 -0
  58. package/dist/cli/idle-status.js +181 -0
  59. package/dist/cli/local-config.d.ts +13 -0
  60. package/dist/cli/local-config.js +82 -6
  61. package/dist/cli/provider-cli-detection.d.ts +10 -0
  62. package/dist/cli/provider-cli-detection.js +160 -0
  63. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  64. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  65. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  66. package/dist/runtime/attempt-database-broker.js +390 -0
  67. package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
  68. package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
  69. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  70. package/dist/runtime/attempt-path-operation.js +94 -0
  71. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  72. package/dist/runtime/attempt-private-directory.js +54 -0
  73. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  74. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  75. package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
  76. package/dist/runtime/attempt-process-supervisor.js +471 -0
  77. package/dist/runtime/canonical-source-file.d.ts +3 -0
  78. package/dist/runtime/canonical-source-file.js +54 -0
  79. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  80. package/dist/runtime/docker-engine-probe.js +340 -0
  81. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  82. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  83. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  84. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  85. package/dist/runtime/generated-output-reset.d.ts +20 -0
  86. package/dist/runtime/generated-output-reset.js +157 -0
  87. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  88. package/dist/runtime/host-database-capability-boundary.js +63 -0
  89. package/dist/runtime/host-diagnostics.d.ts +11 -0
  90. package/dist/runtime/host-diagnostics.js +192 -0
  91. package/dist/runtime/host-execution-root.d.ts +4 -0
  92. package/dist/runtime/host-execution-root.js +39 -0
  93. package/dist/runtime/host-facts.d.ts +36 -0
  94. package/dist/runtime/host-facts.js +95 -0
  95. package/dist/runtime/host-listener-inspector.d.ts +51 -0
  96. package/dist/runtime/host-listener-inspector.js +385 -0
  97. package/dist/runtime/host-load-admission.d.ts +67 -0
  98. package/dist/runtime/host-load-admission.js +99 -0
  99. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  100. package/dist/runtime/host-load-child-environment.js +76 -0
  101. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  102. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  103. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  104. package/dist/runtime/host-load-governor-config.js +83 -0
  105. package/dist/runtime/host-load-governor.d.ts +186 -0
  106. package/dist/runtime/host-load-governor.js +632 -0
  107. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  108. package/dist/runtime/host-load-ledger-lock.js +187 -0
  109. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  110. package/dist/runtime/host-load-runtime-settings.js +80 -0
  111. package/dist/runtime/host-load-sampler.d.ts +156 -0
  112. package/dist/runtime/host-load-sampler.js +298 -0
  113. package/dist/runtime/host-load-step-class.d.ts +70 -0
  114. package/dist/runtime/host-load-step-class.js +161 -0
  115. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  116. package/dist/runtime/host-load-step-reaper.js +95 -0
  117. package/dist/runtime/host-load-step-run.d.ts +73 -0
  118. package/dist/runtime/host-load-step-run.js +102 -0
  119. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  120. package/dist/runtime/host-load-test-slot.js +81 -0
  121. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  122. package/dist/runtime/host-load-token-ledger.js +453 -0
  123. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  124. package/dist/runtime/host-load-windows-cpu.js +85 -0
  125. package/dist/runtime/host-port-broker.d.ts +76 -0
  126. package/dist/runtime/host-port-broker.js +333 -0
  127. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  128. package/dist/runtime/host-pressure-stall.js +168 -0
  129. package/dist/runtime/host-runtime-contract.d.ts +74 -0
  130. package/dist/runtime/host-runtime-contract.js +846 -0
  131. package/dist/runtime/host-runtime-lease.d.ts +287 -0
  132. package/dist/runtime/host-runtime-lease.js +2763 -0
  133. package/dist/runtime/host-runtime-promotion.d.ts +55 -0
  134. package/dist/runtime/host-runtime-promotion.js +254 -0
  135. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  136. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  137. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  138. package/dist/runtime/host-runtime-requirements.js +117 -0
  139. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  140. package/dist/runtime/managed-command-teardown.js +596 -0
  141. package/dist/runtime/memory-capacity.d.ts +70 -0
  142. package/dist/runtime/memory-capacity.js +123 -0
  143. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  144. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  145. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  146. package/dist/runtime/node-host-runtime-adapter.js +286 -0
  147. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  148. package/dist/runtime/pinned-directory-process.js +61 -0
  149. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  150. package/dist/runtime/pinned-source-directory.js +94 -0
  151. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  152. package/dist/runtime/playwright-browser-cache.js +227 -0
  153. package/dist/runtime/playwright-host-runtime-adapter.d.ts +39 -0
  154. package/dist/runtime/playwright-host-runtime-adapter.js +274 -0
  155. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  156. package/dist/runtime/prepared-runtime-identity.js +218 -0
  157. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  158. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  159. package/dist/runtime/runner-settings.d.ts +104 -0
  160. package/dist/runtime/runner-settings.js +236 -0
  161. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  162. package/dist/runtime/runtime-isolation-lease.js +161 -0
  163. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  164. package/dist/runtime/workspace-resource-estimator.js +174 -0
  165. package/dist/sandbox/command-runner.d.ts +4 -0
  166. package/dist/sandbox/command-runner.js +47 -0
  167. package/dist/sandbox/contract.d.ts +5 -0
  168. package/dist/sandbox/contract.js +276 -0
  169. package/dist/sandbox/event-budget.d.ts +11 -0
  170. package/dist/sandbox/event-budget.js +27 -0
  171. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  172. package/dist/sandbox/host-capacity-broker.js +336 -0
  173. package/dist/sandbox/image-policy.d.ts +35 -0
  174. package/dist/sandbox/image-policy.js +247 -0
  175. package/dist/sandbox/index.d.ts +5 -0
  176. package/dist/sandbox/index.js +5 -0
  177. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  178. package/dist/sandbox/lease-watchdog.js +67 -0
  179. package/dist/sandbox/managed-branch.d.ts +13 -0
  180. package/dist/sandbox/managed-branch.js +36 -0
  181. package/dist/sandbox/preflight.d.ts +84 -0
  182. package/dist/sandbox/preflight.js +521 -0
  183. package/dist/sandbox/process.d.ts +20 -0
  184. package/dist/sandbox/process.js +209 -0
  185. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  186. package/dist/sandbox/provider-auth/codex.js +212 -0
  187. package/dist/sandbox/repository-lock.d.ts +6 -0
  188. package/dist/sandbox/repository-lock.js +129 -0
  189. package/dist/sandbox/runtime.d.ts +311 -0
  190. package/dist/sandbox/runtime.js +2407 -0
  191. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  192. package/dist/sandbox/sandbox-cgroups.js +42 -0
  193. package/dist/sandbox/sandbox.types.d.ts +93 -0
  194. package/dist/sandbox/sandbox.types.js +1 -0
  195. package/dist/sandbox/smoke.d.ts +76 -0
  196. package/dist/sandbox/smoke.js +380 -0
  197. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  198. package/dist/sandbox/worker-supervisor.js +36 -0
  199. package/dist/sandbox/worker.d.ts +1 -0
  200. package/dist/sandbox/worker.js +225 -0
  201. package/dist/sandbox/workspace.service.d.ts +13 -0
  202. package/dist/sandbox/workspace.service.js +74 -0
  203. package/dist/session/architect-waits.d.ts +2 -0
  204. package/dist/session/architect-waits.js +138 -0
  205. package/dist/session/managed-attempt-tools.d.ts +48 -0
  206. package/dist/session/managed-attempt-tools.js +1299 -0
  207. package/dist/session/managed-build-coordinator.d.ts +5 -0
  208. package/dist/session/managed-build-coordinator.js +109 -0
  209. package/dist/session/managed-build-receipt.d.ts +26 -0
  210. package/dist/session/managed-build-receipt.js +342 -0
  211. package/dist/session/managed-command-host-load.d.ts +47 -0
  212. package/dist/session/managed-command-host-load.js +83 -0
  213. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  214. package/dist/session/managed-verification-timeouts.js +17 -0
  215. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  216. package/dist/session/mcp-argument-coercion.js +121 -0
  217. package/dist/session/phase-completion.artifacts.d.ts +34 -0
  218. package/dist/session/phase-completion.artifacts.js +903 -0
  219. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  220. package/dist/session/phase-completion.command-validation.js +77 -0
  221. package/dist/session/phase-completion.d.ts +65 -42
  222. package/dist/session/phase-completion.helpers.d.ts +117 -0
  223. package/dist/session/phase-completion.helpers.js +708 -0
  224. package/dist/session/phase-completion.js +130 -3007
  225. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  226. package/dist/session/phase-completion.mcp-args.js +156 -0
  227. package/dist/session/phase-completion.prompts.d.ts +14 -0
  228. package/dist/session/phase-completion.prompts.js +238 -0
  229. package/dist/session/phase-completion.runtime.d.ts +43 -0
  230. package/dist/session/phase-completion.runtime.js +721 -0
  231. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  232. package/dist/session/phase-completion.schema-parts.js +188 -0
  233. package/dist/session/phase-completion.schemas.d.ts +3 -0
  234. package/dist/session/phase-completion.schemas.js +836 -0
  235. package/dist/session/phase-completion.validation.d.ts +37 -0
  236. package/dist/session/phase-completion.validation.js +874 -0
  237. package/dist/session/pre-publication-host-load.d.ts +27 -0
  238. package/dist/session/pre-publication-host-load.js +111 -0
  239. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  240. package/dist/session/pre-publication-native-postgres.js +111 -0
  241. package/dist/session/pre-publication-pass.d.ts +61 -0
  242. package/dist/session/pre-publication-pass.js +148 -0
  243. package/dist/session/pre-publication-process.d.ts +23 -0
  244. package/dist/session/pre-publication-process.js +109 -0
  245. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  246. package/dist/session/pre-publication-skipped-tests.js +109 -0
  247. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  248. package/dist/session/pre-publication-step-execution.js +50 -0
  249. package/dist/session/pre-publication-validation.d.ts +91 -0
  250. package/dist/session/pre-publication-validation.js +670 -0
  251. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  252. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  253. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  254. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  255. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  256. package/dist/session/provider-cli/claude-background-work.js +181 -0
  257. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  258. package/dist/session/provider-cli/host-build-lock.js +30 -0
  259. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  260. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  261. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
  262. package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
  263. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  264. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  265. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  266. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  267. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  268. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  269. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  270. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  271. package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
  272. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  273. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  274. package/dist/session/provider-cli/provider-cli.process.d.ts +114 -0
  275. package/dist/session/provider-cli/provider-cli.process.js +757 -0
  276. package/dist/session/provider-cli/provider-cli.prompts.d.ts +62 -0
  277. package/dist/session/provider-cli/provider-cli.prompts.js +770 -0
  278. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  279. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  280. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  281. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  282. package/dist/session/provider-cli/provider-cli.runtime.d.ts +30 -0
  283. package/dist/session/provider-cli/provider-cli.runtime.js +120 -0
  284. package/dist/session/provider-cli/provider-cli.service.d.ts +53 -53
  285. package/dist/session/provider-cli/provider-cli.service.js +1299 -2523
  286. package/dist/session/provider-cli/provider-cli.types.d.ts +38 -0
  287. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  288. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  289. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  290. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  291. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  292. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  293. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  294. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  295. package/dist/session/provider-cli/provider-output-state.d.ts +40 -0
  296. package/dist/session/provider-cli/provider-output-state.js +832 -0
  297. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  298. package/dist/session/provider-cli/provider-usage.js +28 -5
  299. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  300. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  301. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  302. package/dist/session/publishable-worktree-changes.js +193 -0
  303. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  304. package/dist/session/qa-sidecar-validation.js +28 -0
  305. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  306. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  307. package/dist/session/session-redaction.d.ts +3 -0
  308. package/dist/session/session-redaction.js +298 -0
  309. package/dist/session/session.base.d.ts +14 -1
  310. package/dist/session/session.service.d.ts +17 -2
  311. package/dist/session/session.service.js +708 -60
  312. package/dist/session/session.types.d.ts +327 -3
  313. package/dist/session/session.types.js +951 -10
  314. package/dist/session/sidecar-json-shape.d.ts +31 -0
  315. package/dist/session/sidecar-json-shape.js +217 -0
  316. package/dist/session/unreferenced-exports.d.ts +12 -0
  317. package/dist/session/unreferenced-exports.js +59 -0
  318. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  319. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  320. package/dist/shared/format/format-bytes.d.ts +1 -0
  321. package/dist/shared/format/format-bytes.js +9 -0
  322. package/dist/shared/fs/file-identity.d.ts +10 -0
  323. package/dist/shared/fs/file-identity.js +15 -0
  324. package/dist/shared/fs/replace-file.d.ts +7 -0
  325. package/dist/shared/fs/replace-file.js +33 -0
  326. package/dist/shared/git/git.js +2 -1
  327. package/dist/shared/path/path.d.ts +1 -0
  328. package/dist/shared/path/path.js +21 -1
  329. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  330. package/dist/shared/process/dotnet-toolchain.js +307 -0
  331. package/dist/shared/process/host-process-recovery.d.ts +23 -0
  332. package/dist/shared/process/host-process-recovery.js +99 -0
  333. package/dist/shared/process/host-process-supervisor.d.ts +72 -0
  334. package/dist/shared/process/host-process-supervisor.js +383 -0
  335. package/dist/shared/process/process-tree.d.ts +52 -0
  336. package/dist/shared/process/process-tree.js +144 -0
  337. package/dist/shared/process/process.d.ts +70 -0
  338. package/dist/shared/process/process.js +224 -16
  339. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  340. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  341. package/dist/shared/process/windows-launch.d.ts +26 -0
  342. package/dist/shared/process/windows-launch.js +109 -0
  343. package/dist/shared/provider-capabilities.d.ts +4 -0
  344. package/dist/shared/provider-capabilities.js +95 -0
  345. package/dist/shared/redaction/redaction.d.ts +1 -0
  346. package/dist/shared/redaction/redaction.js +47 -4
  347. package/dist/shared/time/monotonic.d.ts +1 -0
  348. package/dist/shared/time/monotonic.js +8 -0
  349. package/dist/version.d.ts +1 -1
  350. package/dist/version.js +1 -1
  351. package/dist/worktree/artifact-injector.d.ts +3 -2
  352. package/dist/worktree/artifact-injector.js +82 -10
  353. package/dist/worktree/dependency-warmer.d.ts +78 -1
  354. package/dist/worktree/dependency-warmer.js +731 -13
  355. package/dist/worktree/index.d.ts +2 -1
  356. package/dist/worktree/index.js +1 -0
  357. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  358. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  359. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  360. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  361. package/dist/worktree/wip-git.d.ts +33 -0
  362. package/dist/worktree/wip-git.js +122 -0
  363. package/dist/worktree/wip-refs.d.ts +62 -0
  364. package/dist/worktree/wip-refs.js +119 -0
  365. package/dist/worktree/wip-restore.d.ts +38 -0
  366. package/dist/worktree/wip-restore.js +190 -0
  367. package/dist/worktree/wip-snapshot.d.ts +50 -0
  368. package/dist/worktree/wip-snapshot.js +268 -0
  369. package/dist/worktree/worktree-paths.d.ts +4 -0
  370. package/dist/worktree/worktree-paths.js +30 -0
  371. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  372. package/dist/worktree/worktree-wip-events.js +98 -0
  373. package/dist/worktree/worktree-wip.d.ts +49 -0
  374. package/dist/worktree/worktree-wip.js +182 -0
  375. package/dist/worktree/worktree.base.d.ts +10 -1
  376. package/dist/worktree/worktree.service.d.ts +30 -4
  377. package/dist/worktree/worktree.service.js +379 -54
  378. package/dist/worktree/worktree.types.d.ts +38 -1
  379. package/package.json +12 -7
  380. package/runtime/windows-job-supervisor.ps1 +722 -0
  381. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,49 +1,340 @@
1
- import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
1
+ import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
2
+ import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import os from "node:os";
4
7
  import { defaultForgeBridgeConfig } from "../config.js";
5
- import { redactSecrets, redactText } from "../shared/redaction/redaction.js";
8
+ import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
+ import { redactText } from "../shared/redaction/redaction.js";
6
10
  import { BridgeSessionService } from "../session/session.service.js";
7
- import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.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";
14
+ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.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";
28
+ import { GitWorktreeService } from "../worktree/worktree.service.js";
29
+ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
30
+ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
31
+ import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
8
32
  import { forgeBridgeVersion } from "../version.js";
33
+ import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
34
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
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
+ }
9
58
  export class ForgeBridgeService {
10
59
  config;
11
- sessions;
12
60
  connections;
61
+ hostCapabilityProbe;
62
+ chatProcessRunner;
63
+ hostLoad;
13
64
  connection = null;
14
65
  heartbeatTimer = null;
66
+ heartbeatInFlight = false;
67
+ consecutiveHeartbeatFailures = 0;
68
+ reconnectingFromHeartbeatFailure = false;
69
+ leaseWatchdogTimer = null;
70
+ sandboxMaintenanceTimer = null;
71
+ sandboxMaintenanceRunning = false;
15
72
  closed = null;
73
+ transportRecovery = null;
74
+ transportRecoveryGeneration = 0;
16
75
  stopped = false;
76
+ revokedReason = null;
17
77
  activeSessions = new Map();
18
- constructor(config, sessions = new BridgeSessionService(), connections = new SignalRBridgeConnectionFactory()) {
78
+ reservations = new Map();
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();
89
+ preflight;
90
+ dockerEngineProbe;
91
+ sandboxRuntime;
92
+ sandboxResourceResolver;
93
+ sessions;
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) })) {
19
134
  this.config = config;
20
- this.sessions = sessions;
21
135
  this.connections = connections;
136
+ this.hostCapabilityProbe = hostCapabilityProbe;
137
+ this.chatProcessRunner = chatProcessRunner;
138
+ this.hostLoad = hostLoad;
139
+ this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
140
+ if (this.enforceHostDatabaseCapabilityBoundary) {
141
+ establishHostDatabaseCapabilityBoundary();
142
+ }
143
+ this.preflight = preflight ?? new DockerPreflight({
144
+ dockerExecutable: config.dockerExecutable,
145
+ dockerContext: config.dockerContext,
146
+ stateRoot: config.sandboxStateRoot,
147
+ runnerInstanceId: config.runnerInstanceId,
148
+ maxConcurrentSandboxes: config.maxConcurrentSandboxes,
149
+ diskHighWatermarkPercent: config.diskHighWatermarkPercent,
150
+ diskLowWatermarkPercent: config.diskLowWatermarkPercent,
151
+ minimumWorkspaceBytes: config.minimumWorkspaceBytes,
152
+ hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
153
+ defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
154
+ defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
155
+ runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
156
+ requireRootless: config.requireRootlessDocker
157
+ });
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);
174
+ this.sandboxResourceResolver = sandboxResourceResolver
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
+ ]);
22
186
  }
23
187
  async connectOnce() {
188
+ if (this.revokedReason !== null) {
189
+ throw new BridgeRevokedError(this.revokedReason);
190
+ }
24
191
  await this.stopConnection();
25
192
  this.stopped = false;
193
+ if (this.enforceHostDatabaseCapabilityBoundary) {
194
+ assertHostDatabaseCapabilityBoundary();
195
+ }
196
+ const hostReap = await this.sessions.reapHostRuntime?.({
197
+ runnerId: this.config.runnerId,
198
+ runnerInstanceId: this.config.runnerInstanceId,
199
+ });
200
+ this.rememberRecoveredHostAttempts(hostReap);
201
+ if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
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.`);
203
+ }
204
+ if (this.config.dockerEnabled) {
205
+ const preflight = await this.preflight.refresh();
206
+ if (canReapManagedSandboxes(preflight)) {
207
+ await this.sandboxRuntime.reap({ diskLow: preflight.diskLow });
208
+ await this.preflight.refresh();
209
+ }
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();
26
221
  const connection = this.connections.create(this.config);
27
222
  this.connection = connection;
223
+ this.transportRecovery = null;
28
224
  this.closed = new Promise((resolve) => {
29
- connection.onClose(() => {
225
+ connection.onClose((error) => {
30
226
  this.stopHeartbeat();
227
+ this.completeTransportRecovery(error ?? new Error("bridge connection closed"));
31
228
  this.abortActiveSessions("bridge connection closed");
229
+ this.abortActiveReadinessProbes("bridge connection closed");
32
230
  resolve();
33
231
  });
34
232
  });
35
- connection.onDispatch((dispatch) => this.handleDispatch(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)));
266
+ connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
36
267
  connection.onCancel((request) => this.handleCancel(request));
268
+ connection.onReap?.((request) => this.handleReap(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));
37
272
  await connection.start();
38
- await this.invokeAck("Hello", {
39
- version: this.config.version,
40
- protocolVersion: this.config.protocolVersion,
41
- minServerVersion: this.config.minServerVersion ?? null,
42
- 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)}`);
43
279
  });
280
+ await this.flushCleanupReports();
44
281
  this.startHeartbeat();
282
+ this.startLeaseWatchdog();
283
+ this.startSandboxMaintenance();
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
+ }
45
335
  }
46
336
  async run(signal) {
337
+ const statePublisher = await this.startStatePublisher();
47
338
  let attempt = 0;
48
339
  try {
49
340
  while (!this.stopped && !signal?.aborted) {
@@ -59,7 +350,7 @@ export class ForgeBridgeService {
59
350
  }
60
351
  }
61
352
  catch (error) {
62
- if (this.stopped || signal?.aborted) {
353
+ if (this.stopped || signal?.aborted || this.revokedReason !== null) {
63
354
  break;
64
355
  }
65
356
  const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
@@ -72,62 +363,1059 @@ export class ForgeBridgeService {
72
363
  finally {
73
364
  if (signal?.aborted) {
74
365
  this.abortActiveSessions(String(signal.reason ?? "bridge stopping"));
366
+ this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
75
367
  }
76
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.`);
77
577
  }
78
578
  }
79
579
  async stop() {
80
580
  this.stopped = true;
81
581
  this.abortActiveSessions("bridge stopping");
582
+ this.abortActiveReadinessProbes("bridge stopping");
82
583
  await this.stopConnection();
584
+ this.hostLoad.stop();
585
+ await this.preflight.release();
83
586
  }
84
- async handleDispatch(rawDispatch) {
85
- 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);
86
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);
87
911
  return;
88
912
  }
89
913
  const leaseId = dispatch.lease.id;
90
914
  const fencingToken = dispatch.lease.fencingToken;
91
915
  const redactionSecrets = exactSecrets(dispatch, this.config);
92
- if (this.activeSessions.has(leaseId)) {
93
- await this.sendResult(leaseId, fencingToken, failureResult("Dispatch is already active on this bridge.")).catch(() => undefined);
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);
94
918
  return;
95
919
  }
96
- const controller = new AbortController();
97
- this.activeSessions.set(leaseId, { fencingToken, controller });
920
+ const existing = this.activeSessions.get(leaseId);
921
+ if (existing) {
922
+ if (existing.fencingToken === fencingToken) {
923
+ this.releaseReservedDispatchHandoff(reservationHandoff);
924
+ return;
925
+ }
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);
928
+ return;
929
+ }
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();
98
944
  try {
99
945
  const normalized = this.normalizeDispatch(dispatch);
100
- const result = await this.sessions.runOnce(normalized, {
101
- emit: async (event) => {
102
- try {
103
- await this.invokeAck("DispatchEvent", {
104
- leaseId,
105
- fencingToken,
106
- event: redactSecrets(event, redactionSecrets)
107
- });
108
- }
109
- catch (error) {
110
- if (isDispatchNoLongerPending(error)) {
111
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
112
- return;
113
- }
114
- throw error;
115
- }
116
- }
117
- }, controller.signal);
118
- await this.sendResult(leaseId, fencingToken, redactSecrets(result, redactionSecrets));
946
+ if (normalized.sandbox) {
947
+ const started = {
948
+ dispatchAttemptId: normalized.sandbox.dispatchAttemptId,
949
+ leaseId,
950
+ fencingToken,
951
+ runnerInstanceId: normalized.sandbox.runnerInstanceId
952
+ };
953
+ await this.invokeAck("DispatchStarted", started);
954
+ }
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));
119
960
  }
120
961
  catch (error) {
121
962
  const summary = controller.signal.aborted
122
963
  ? `Dispatch cancelled: ${String(controller.signal.reason ?? "cancelled")}`
123
964
  : redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
124
- await this.sendResult(leaseId, fencingToken, failureResult(summary)).catch(() => undefined);
965
+ const failureFacts = failureFactsFromError(error, {
966
+ cancelled: controller.signal.aborted,
967
+ source: "bridge",
968
+ });
969
+ const failureEventType = failureFacts.category === "unknown" ? null : failureFacts.code;
970
+ const failureEvents = failureEventType ? [{
971
+ role: "runner",
972
+ kind: "error",
973
+ content: summary,
974
+ eventType: failureEventType,
975
+ }] : [];
976
+ await this.sendResult(dispatch, failureResult(summary, failureEvents, failureFacts)).catch(() => undefined);
125
977
  }
126
978
  finally {
127
- this.activeSessions.delete(leaseId);
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;
128
1051
  }
129
1052
  }
130
- parseDispatchOrReport(rawDispatch) {
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
+ ]);
1105
+ }
1106
+ finally {
1107
+ if (timer)
1108
+ clearTimeout(timer);
1109
+ }
1110
+ }
1111
+ async handleOffer(rawDispatch) {
1112
+ const envelope = parseOfferEnvelope(rawDispatch);
1113
+ if (!envelope) {
1114
+ return;
1115
+ }
1116
+ const dispatch = await this.parseDispatchOrReport(envelope.dispatch);
1117
+ if (!dispatch?.sandbox
1118
+ || dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
1119
+ || dispatch.lease.id !== envelope.leaseId
1120
+ || dispatch.lease.fencingToken !== envelope.fencingToken)
1121
+ return;
1122
+ const sandbox = dispatch.sandbox;
1123
+ this.expireReservations(Date.now());
1124
+ const existing = this.reservations.get(sandbox.dispatchAttemptId);
1125
+ if (existing) {
1126
+ const sameFence = existing.leaseId === dispatch.lease.id
1127
+ && existing.fencingToken === dispatch.lease.fencingToken
1128
+ && existing.runnerInstanceId === sandbox.runnerInstanceId;
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);
1130
+ return;
1131
+ }
1132
+ if (sandbox.runnerInstanceId !== this.config.runnerInstanceId) {
1133
+ await this.sendOfferDecision(dispatch, false, "stale_runner_instance", "Offer targets a different runner process instance.");
1134
+ return;
1135
+ }
1136
+ if (Date.parse(envelope.expiresAt) <= Date.now()) {
1137
+ await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
1138
+ return;
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
+ }
1150
+ const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
1151
+ ? await this.preflight.run()
1152
+ : this.preflight.current();
1153
+ if (sandbox.executionMode === "docker") {
1154
+ if (!this.config.dockerEnabled || !preflight?.healthy) {
1155
+ await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
1156
+ return;
1157
+ }
1158
+ const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
1159
+ if (networkFailure) {
1160
+ await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
1161
+ return;
1162
+ }
1163
+ const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
1164
+ if (providerNetworkFailure) {
1165
+ await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
1166
+ return;
1167
+ }
1168
+ const authFailure = sandboxAuthFailure(dispatch, this.config);
1169
+ if (authFailure) {
1170
+ await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
1171
+ return;
1172
+ }
1173
+ }
1174
+ let requestedResources = sandbox.requestedResources;
1175
+ let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
1176
+ const normalizedDispatch = this.normalizeDispatch(dispatch);
1177
+ if (sandbox.executionMode === "docker") {
1178
+ try {
1179
+ const profile = await this.sandboxResourceResolver(normalizedDispatch);
1180
+ requestedResources = profile.resources;
1181
+ sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
1182
+ }
1183
+ catch (error) {
1184
+ await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1185
+ return;
1186
+ }
1187
+ }
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
+ }
1199
+ }
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 = {
1256
+ leaseId: dispatch.lease.id,
1257
+ fencingToken: dispatch.lease.fencingToken,
1258
+ runnerInstanceId: sandbox.runnerInstanceId,
1259
+ expiresAt: dispatch.lease.expiresAt,
1260
+ reservedUntil,
1261
+ sandboxed: sandbox.executionMode === "docker",
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
+ };
1272
+ }
1273
+ async handleStart(rawDispatch) {
1274
+ const envelope = parseStartEnvelope(rawDispatch);
1275
+ if (!envelope) {
1276
+ return;
1277
+ }
1278
+ let dispatch = await this.parseDispatchOrReport(envelope.dispatch);
1279
+ if (!dispatch?.sandbox
1280
+ || dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
1281
+ || dispatch.lease.id !== envelope.leaseId
1282
+ || dispatch.lease.fencingToken !== envelope.fencingToken)
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
+ }
1291
+ const reservation = this.reservations.get(dispatch.sandbox.dispatchAttemptId);
1292
+ if (!reservation
1293
+ || reservation.leaseId !== dispatch.lease.id
1294
+ || reservation.fencingToken !== dispatch.lease.fencingToken
1295
+ || reservation.runnerInstanceId !== dispatch.sandbox.runnerInstanceId
1296
+ || Date.parse(reservation.reservedUntil) <= Date.now()) {
1297
+ await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
1298
+ return;
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;
1311
+ if (dispatch.apiKeySecretGrant) {
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);
1314
+ return;
1315
+ }
1316
+ if (dispatch.apiKeySecretGrantHandle) {
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
+ }
1331
+ const grant = response.grant;
1332
+ if (!response.accepted
1333
+ || !grant
1334
+ || grant.grantId !== dispatch.apiKeySecretGrantHandle.grantId
1335
+ || grant.provider !== dispatch.apiKeySecretGrantHandle.provider
1336
+ || Date.parse(grant.expiresAt) <= Date.now()) {
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);
1339
+ return;
1340
+ }
1341
+ dispatch = { ...dispatch, apiKeySecretGrant: grant, apiKeySecretGrantHandle: null };
1342
+ }
1343
+ else if (dispatch.execution.requiresApiKeySecretGrant) {
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);
1346
+ return;
1347
+ }
1348
+ dispatch = {
1349
+ ...dispatch,
1350
+ sandbox: { ...dispatch.sandbox, requestedResources: reservation.resources },
1351
+ };
1352
+ await this.handleDispatch(dispatch, startClaim);
1353
+ }
1354
+ async redeemSecretGrant(dispatch) {
1355
+ const sandbox = dispatch.sandbox;
1356
+ const handle = dispatch.apiKeySecretGrantHandle;
1357
+ const connection = this.connection;
1358
+ if (!connection)
1359
+ return { accepted: false, code: "bridge.disconnected", message: "Bridge is disconnected.", grant: null };
1360
+ return await connection.invoke("RedeemSecretGrant", {
1361
+ dispatchAttemptId: sandbox.dispatchAttemptId,
1362
+ leaseId: dispatch.lease.id,
1363
+ fencingToken: dispatch.lease.fencingToken,
1364
+ runnerInstanceId: sandbox.runnerInstanceId,
1365
+ grantId: handle.grantId
1366
+ });
1367
+ }
1368
+ async redeemPublishGrant(request, signal) {
1369
+ if (signal?.aborted)
1370
+ throw new Error(String(signal.reason ?? "publication cancelled"));
1371
+ const connection = this.connection;
1372
+ if (!connection)
1373
+ throw new Error("sandbox_output_publish_forbidden: bridge is disconnected.");
1374
+ const response = await connection.invoke("RedeemPublishGrant", request);
1375
+ if (!response.accepted || !response.credential) {
1376
+ throw new Error(`sandbox_output_publish_forbidden: ${response.message ?? response.code ?? "publication grant redemption was rejected"}`);
1377
+ }
1378
+ return response.credential;
1379
+ }
1380
+ async handleLeaseUpdate(request) {
1381
+ if (request.runnerInstanceId !== this.config.runnerInstanceId) {
1382
+ return;
1383
+ }
1384
+ const reservation = this.reservations.get(request.dispatchAttemptId);
1385
+ if (reservation && reservation.leaseId === request.leaseId && reservation.fencingToken === request.fencingToken) {
1386
+ reservation.expiresAt = request.expiresAt;
1387
+ }
1388
+ const active = this.activeSessions.get(request.leaseId);
1389
+ if (active && active.fencingToken === request.fencingToken && active.dispatchAttemptId === request.dispatchAttemptId) {
1390
+ active.leaseExpiresAt = request.expiresAt;
1391
+ if (active.sandboxed) {
1392
+ await this.sandboxRuntime.updateLease(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
1393
+ }
1394
+ else {
1395
+ await this.sessions.updateLease?.(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
1396
+ }
1397
+ }
1398
+ }
1399
+ async sendOfferDecision(dispatch, accepted, code = null, message = null, reservedUntil = null, reservedResources = null, sandboxConfigCommitSha = null) {
1400
+ if (!dispatch.sandbox)
1401
+ return;
1402
+ const payload = {
1403
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1404
+ leaseId: dispatch.lease.id,
1405
+ fencingToken: dispatch.lease.fencingToken,
1406
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId,
1407
+ accepted,
1408
+ code,
1409
+ message,
1410
+ reservedUntil: accepted ? reservedUntil ?? dispatch.lease.expiresAt : null,
1411
+ reservedResources: accepted ? reservedResources : null,
1412
+ sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1413
+ };
1414
+ if (accepted)
1415
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1416
+ await this.invokeAck("OfferDecision", payload);
1417
+ }
1418
+ async parseDispatchOrReport(rawDispatch) {
131
1419
  try {
132
1420
  return parseRunOnceDispatchPacket(rawDispatch);
133
1421
  }
@@ -137,23 +1425,211 @@ export class ForgeBridgeService {
137
1425
  return null;
138
1426
  }
139
1427
  const summary = invalidDispatchSummary(error);
140
- void this.sendResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
1428
+ await this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
141
1429
  {
142
1430
  role: "runner",
143
1431
  kind: "error",
144
1432
  content: summary,
145
1433
  eventType: "invalid_dispatch"
146
1434
  }
147
- ])).catch(() => undefined);
1435
+ ], failureFactsForCode("invalid_dispatch"))).catch(() => undefined);
148
1436
  return null;
149
1437
  }
150
1438
  }
151
- async handleCancel(request) {
152
- const active = this.activeSessions.get(request.leaseId);
153
- if (!active || active.fencingToken !== request.fencingToken) {
154
- return;
1439
+ parseChatTurnOrReport(rawDispatch) {
1440
+ try {
1441
+ return parseChatTurnDispatchPacket(rawDispatch, this.bridgeChatCapability());
1442
+ }
1443
+ catch (error) {
1444
+ logBridgeStatus(invalidChatTurnSummary(error));
1445
+ return null;
1446
+ }
1447
+ }
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
+ }
1464
+ const active = this.activeSessions.get(request.leaseId);
1465
+ if (!active || active.fencingToken !== request.fencingToken) {
1466
+ return;
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
+ }
1477
+ active.controller.abort(request.reason ?? "cancelled by server");
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
+ }
1500
+ async handleReap(request) {
1501
+ if (request.runnerId !== this.config.runnerId
1502
+ || request.runnerInstanceId !== this.config.runnerInstanceId)
1503
+ return;
1504
+ await this.runSandboxMaintenance();
1505
+ await this.sendHeartbeat();
1506
+ }
1507
+ async handleReadinessProbe(rawRequest) {
1508
+ const request = parseReadinessProbe(rawRequest);
1509
+ if (!request || request.runnerInstanceId !== this.config.runnerInstanceId)
1510
+ return;
1511
+ const existing = this.activeReadinessProbes.get(request.requestId);
1512
+ if (existing)
1513
+ return;
1514
+ const controller = new AbortController();
1515
+ this.activeReadinessProbes.set(request.requestId, controller);
1516
+ const deadlineMs = Date.parse(request.expiresAt) - Date.now();
1517
+ const timer = setTimeout(() => controller.abort("readiness probe expired"), Math.max(0, deadlineMs));
1518
+ timer.unref?.();
1519
+ let result;
1520
+ try {
1521
+ const accepted = {
1522
+ schemaVersion: 1,
1523
+ requestId: request.requestId,
1524
+ fencingToken: request.fencingToken,
1525
+ runnerInstanceId: this.config.runnerInstanceId,
1526
+ acceptedAt: new Date().toISOString(),
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
+ }
1553
+ }
1554
+ catch (error) {
1555
+ const deferredReason = readinessDeferralReason(controller.signal);
1556
+ result = {
1557
+ schemaVersion: 1,
1558
+ requestId: request.requestId,
1559
+ fencingToken: request.fencingToken,
1560
+ runnerInstanceId: this.config.runnerInstanceId,
1561
+ status: "failed",
1562
+ reasonCode: deferredReason ? "host_runtime_probe_deferred" : "host_runtime_probe_failed",
1563
+ reasonMessage: (deferredReason ?? errorMessage(error)).slice(0, 1000),
1564
+ checkedAt: new Date().toISOString(),
1565
+ };
1566
+ }
1567
+ finally {
1568
+ clearTimeout(timer);
1569
+ this.activeReadinessProbes.delete(request.requestId);
1570
+ }
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
+ }
1593
+ await this.sendHeartbeat().catch(() => undefined);
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
+ }
155
1632
  }
156
- active.controller.abort(request.reason ?? "cancelled by server");
157
1633
  }
158
1634
  abortActiveSessions(reason) {
159
1635
  for (const active of this.activeSessions.values()) {
@@ -161,8 +1637,47 @@ export class ForgeBridgeService {
161
1637
  }
162
1638
  this.activeSessions.clear();
163
1639
  }
1640
+ abortActiveReadinessProbes(reason) {
1641
+ for (const controller of this.activeReadinessProbes.values())
1642
+ controller.abort(reason);
1643
+ this.activeReadinessProbes.clear();
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
+ }
164
1679
  normalizeDispatch(dispatch) {
165
- const mapping = findRepoMapping(dispatch, repoMappingsFor(this.config));
1680
+ const mapping = findRepoMapping(dispatch.repo, repoMappingsFor(this.config));
166
1681
  const localPath = mapping?.localPath?.trim();
167
1682
  const repoRoot = localPath ? path.dirname(path.resolve(localPath)) : this.config.defaultRepoRoot;
168
1683
  const qaLaunchTarget = normalizeQaAppLaunchTarget(mapping?.qaAppLaunchTarget) ?? dispatch.qaBrowser?.launchTarget ?? null;
@@ -185,47 +1700,326 @@ export class ForgeBridgeService {
185
1700
  : dispatch.qaBrowser
186
1701
  };
187
1702
  }
188
- async sendResult(leaseId, fencingToken, result) {
1703
+ async sendResult(dispatch, result) {
189
1704
  const payload = {
190
- leaseId,
191
- fencingToken,
192
- result
1705
+ leaseId: dispatch.lease.id,
1706
+ fencingToken: dispatch.lease.fencingToken,
1707
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
1708
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
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))
193
1712
  };
1713
+ await this.sendResultPayload(payload, () => this.releaseActiveSessionAndRefreshCapacity(dispatch.lease.id, dispatch));
1714
+ }
1715
+ async sendLegacyResult(leaseId, fencingToken, result) {
1716
+ await this.sendResultPayload({ leaseId, fencingToken, result });
1717
+ }
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) {
194
1752
  try {
195
1753
  await this.invokeAck("DispatchResult", payload);
196
1754
  }
197
1755
  catch (error) {
198
- if (isDispatchNoLongerPending(error)) {
1756
+ if (isDispatchNoLongerPending(error))
199
1757
  return;
200
- }
201
1758
  throw error;
202
1759
  }
203
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
+ }
204
1835
  startHeartbeat() {
205
1836
  this.stopHeartbeat();
1837
+ this.consecutiveHeartbeatFailures = 0;
1838
+ this.reconnectingFromHeartbeatFailure = false;
206
1839
  const intervalMs = positiveFiniteNumber(this.config.heartbeatIntervalMs, 30_000);
207
1840
  this.heartbeatTimer = setInterval(() => {
208
- this.sendHeartbeat().catch(() => undefined);
1841
+ void this.heartbeatTick();
209
1842
  }, intervalMs);
210
1843
  this.heartbeatTimer.unref?.();
211
1844
  }
1845
+ async heartbeatTick() {
1846
+ if (this.heartbeatInFlight || this.reconnectingFromHeartbeatFailure)
1847
+ return;
1848
+ const connection = this.connection;
1849
+ if (!connection)
1850
+ return;
1851
+ this.heartbeatInFlight = true;
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);
1861
+ await this.sendHeartbeat();
1862
+ this.consecutiveHeartbeatFailures = 0;
1863
+ }
1864
+ catch (error) {
1865
+ if (connection !== this.connection || this.stopped)
1866
+ return;
1867
+ this.consecutiveHeartbeatFailures += 1;
1868
+ logBridgeStatus(`Heartbeat ${this.consecutiveHeartbeatFailures} failed: ${errorMessage(error)}.`);
1869
+ if (this.consecutiveHeartbeatFailures < 2)
1870
+ return;
1871
+ this.reconnectingFromHeartbeatFailure = true;
1872
+ this.stopHeartbeat();
1873
+ logBridgeStatus("Heartbeat failed twice. Closing the stale connection so the Bridge can reconnect...");
1874
+ await connection.stop().catch(() => undefined);
1875
+ }
1876
+ finally {
1877
+ this.heartbeatInFlight = false;
1878
+ }
1879
+ }
1880
+ startLeaseWatchdog() {
1881
+ this.stopLeaseWatchdog();
1882
+ this.leaseWatchdogTimer = setInterval(() => this.expireLeases(), 1000);
1883
+ this.leaseWatchdogTimer.unref?.();
1884
+ }
1885
+ stopLeaseWatchdog() {
1886
+ if (this.leaseWatchdogTimer) {
1887
+ clearInterval(this.leaseWatchdogTimer);
1888
+ this.leaseWatchdogTimer = null;
1889
+ }
1890
+ }
1891
+ expireLeases() {
1892
+ const now = Date.now();
1893
+ this.expireReservations(now);
1894
+ for (const active of this.activeSessions.values()) {
1895
+ if (Date.parse(active.leaseExpiresAt) <= now && !active.controller.signal.aborted) {
1896
+ active.controller.abort("dispatch lease expired");
1897
+ }
1898
+ }
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
+ }
212
1907
  stopHeartbeat() {
213
1908
  if (this.heartbeatTimer) {
214
1909
  clearInterval(this.heartbeatTimer);
215
1910
  this.heartbeatTimer = null;
216
1911
  }
217
1912
  }
1913
+ startSandboxMaintenance() {
1914
+ this.stopSandboxMaintenance();
1915
+ this.sandboxMaintenanceTimer = setInterval(() => {
1916
+ this.runSandboxMaintenance().catch(() => undefined);
1917
+ }, 60_000);
1918
+ this.sandboxMaintenanceTimer.unref?.();
1919
+ }
1920
+ stopSandboxMaintenance() {
1921
+ if (this.sandboxMaintenanceTimer) {
1922
+ clearInterval(this.sandboxMaintenanceTimer);
1923
+ this.sandboxMaintenanceTimer = null;
1924
+ }
1925
+ }
1926
+ async runSandboxMaintenance() {
1927
+ if (this.sandboxMaintenanceRunning)
1928
+ return;
1929
+ this.sandboxMaintenanceRunning = true;
1930
+ try {
1931
+ const hostReap = await this.sessions.reapHostRuntime?.({
1932
+ runnerId: this.config.runnerId,
1933
+ runnerInstanceId: this.config.runnerInstanceId,
1934
+ });
1935
+ this.rememberRecoveredHostAttempts(hostReap);
1936
+ if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
1937
+ logBridgeStatus(`Managed-host maintenance reaped ${hostReap.reaped} stale attempt(s) and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
1938
+ }
1939
+ if (this.config.dockerEnabled) {
1940
+ const preflight = await this.preflight.refresh();
1941
+ if (canReapManagedSandboxes(preflight)) {
1942
+ const attemptSnapshot = await this.readAttemptSnapshot();
1943
+ await this.sandboxRuntime.reap({ diskLow: preflight.diskLow, attemptSnapshot });
1944
+ await this.flushCleanupReports();
1945
+ }
1946
+ }
1947
+ }
1948
+ finally {
1949
+ this.sandboxMaintenanceRunning = false;
1950
+ }
1951
+ }
1952
+ async readAttemptSnapshot() {
1953
+ const connection = this.connection;
1954
+ if (!connection)
1955
+ throw new Error("Bridge is not connected.");
1956
+ const response = await connection.invoke("AttemptSnapshot", {
1957
+ runnerInstanceId: this.config.runnerInstanceId
1958
+ });
1959
+ if (!response.accepted) {
1960
+ throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
1961
+ }
1962
+ return response.attempts ?? [];
1963
+ }
1964
+ async flushCleanupReports() {
1965
+ if (!this.sandboxRuntime.pendingCleanupReports || !this.sandboxRuntime.acknowledgeCleanupReport)
1966
+ return;
1967
+ for (const report of await this.sandboxRuntime.pendingCleanupReports()) {
1968
+ await this.invokeAck("CleanupReport", {
1969
+ runnerInstanceId: this.config.runnerInstanceId,
1970
+ report
1971
+ });
1972
+ await this.sandboxRuntime.acknowledgeCleanupReport(report.reportId);
1973
+ }
1974
+ }
218
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;
219
1994
  await this.invokeAck("Heartbeat", {
220
1995
  status: "online",
221
1996
  capabilities: this.capabilities(),
222
1997
  version: this.config.version,
223
1998
  protocolVersion: this.config.protocolVersion
224
- });
1999
+ }, { signal });
2000
+ this.ackYield(reportedYield);
225
2001
  }
226
2002
  capabilities() {
2003
+ const preflight = this.preflight.current();
2004
+ const dockerEngine = this.dockerEngineProbe.current();
2005
+ this.dockerAvailable = dockerEngine?.available === true;
2006
+ const runtimeState = this.sandboxRuntime.snapshot();
2007
+ const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
2008
+ const used = this.usedSandboxResources(runtimeState.degraded);
2009
+ const activeResources = this.activeSandboxResources(runtimeState.degraded);
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;
227
2021
  return {
228
- schemaVersion: 2,
2022
+ schemaVersion: 8,
229
2023
  activeSessionCount: this.activeSessions.size,
230
2024
  cliProviders: this.config.cliProviders,
231
2025
  providerStatuses: this.config.providerStatuses,
@@ -233,38 +2027,228 @@ export class ForgeBridgeService {
233
2027
  repoMappings: repoMappingsFor(this.config),
234
2028
  os: this.config.os,
235
2029
  sandboxProfiles: this.config.sandboxProfiles,
2030
+ runnerInstanceId: this.config.runnerInstanceId,
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(),
2048
+ maxConcurrentSandboxes: capacity.sandboxSlots,
2049
+ reservedSandboxCount: reserved,
2050
+ activeSandboxCount: runtimeState.active,
2051
+ startingSandboxCount: runtimeState.starting,
2052
+ degradedReservationCount: runtimeState.degraded,
2053
+ sandboxRuntimes: preflight?.healthy ? ["docker"] : [],
2054
+ sandboxRuntimeVersion: preflight?.runtimeVersion ?? null,
2055
+ sandboxFeatures: preflight?.features ?? null,
2056
+ allowsOpenPublicSandbox: this.config.allowOpenPublicSandbox,
2057
+ sandboxPublicationModes: [this.config.sandboxPublicationMode ?? "shared_filesystem"],
2058
+ sandboxAuthModes: sandboxAuthModesFor(this.config),
2059
+ availableMemoryBytes: memoryAdmission?.availableForAdmissionBytes ?? null,
2060
+ availableCpuMillis: preflight ? Math.max(0, capacity.cpuMillis - used.cpuMillis) : null,
2061
+ availableWorkspaceBytes: preflight ? Math.max(0, capacity.workspaceBytes - used.workspaceBytes) : null,
2062
+ diskLow: preflight?.diskLow ?? null,
2063
+ preflightGeneration: preflight?.generation ?? 0,
2064
+ sandboxUnavailableCode: this.config.dockerEnabled ? preflight?.unavailableCode ?? null : "docker_disabled",
2065
+ sandboxUnavailableReason: this.config.dockerEnabled ? preflight?.unavailableReason ?? null : "Docker sandboxing is disabled by runner configuration.",
2066
+ sandboxMemoryCapacity: preflight ? {
2067
+ defaultWorkerMemoryLimitBytes: this.config.defaultSandboxWorkerMemoryLimitBytes,
2068
+ defaultServiceMemoryLimitBytes: this.config.defaultSandboxServiceMemoryLimitBytes,
2069
+ runtimeOverheadBytes: this.config.sandboxRuntimeOverheadBytes,
2070
+ hostReserveBytes: preflight.hostReserveBytes,
2071
+ activeReservationBytes: used.memoryBytes,
2072
+ daemonTotalBytes: preflight.totalMemoryBytes,
2073
+ daemonAvailableBytes: preflight.rawDaemonAvailableMemoryBytes ?? 0,
2074
+ hostAvailableBytes: preflight.rawHostAvailableMemoryBytes,
2075
+ conservativeAvailableBytes: preflight.rawAvailableMemoryBytes,
2076
+ availableForAdmissionBytes: memoryAdmission.availableForAdmissionBytes,
2077
+ memoryAdmission: memoryAdmission,
2078
+ } : null,
2079
+ hostRuntime: this.sessions.runtimeCapacity?.() ?? null,
236
2080
  supportsApiSecretGrant: this.config.supportsApiSecretGrant,
237
2081
  supportsManagedWorktrees: this.config.supportsManagedWorktrees,
238
2082
  supportsManagedForgeArtifacts: this.config.supportsManagedForgeArtifacts,
239
2083
  supportsRunnerAuthoredPhaseArtifacts: this.config.supportsRunnerAuthoredPhaseArtifacts,
240
- supportsDraftRunOnce: this.config.supportsDraftRunOnce
2084
+ supportsDraftRunOnce: this.config.supportsDraftRunOnce,
2085
+ supportsDraftAttachments: this.config.supportsDraftAttachments,
2086
+ supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
2087
+ bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
2088
+ settings: { supportsServerSettings: true, ...this.settingsReport },
241
2089
  };
242
2090
  }
243
- async invokeAck(methodName, payload) {
244
- const connection = this.connection;
245
- if (!connection) {
246
- throw new Error("Bridge is not connected.");
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
+ }
2101
+ usedSandboxResources(degradedReservations) {
2102
+ const resources = [
2103
+ ...[...this.reservations.values()]
2104
+ .filter(reservation => reservation.sandboxed)
2105
+ .map(reservation => reservation.resources),
2106
+ ...[...this.activeSessions.values()]
2107
+ .filter(session => session.sandboxed)
2108
+ .map(session => session.resources),
2109
+ ...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
2110
+ ];
2111
+ return sumSandboxResources(resources);
2112
+ }
2113
+ activeSandboxResources(degradedReservations) {
2114
+ return sumSandboxResources([
2115
+ ...[...this.activeSessions.values()]
2116
+ .filter(session => session.sandboxed)
2117
+ .map(session => session.resources),
2118
+ ...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
2119
+ ]);
2120
+ }
2121
+ sandboxResourceCapacity(preflight, activeResources) {
2122
+ if (!preflight)
2123
+ return zeroSandboxResources();
2124
+ return {
2125
+ // Host free memory and disk already reflect active containers. Add their
2126
+ // commitments back to form a stable total capacity, then subtract them
2127
+ // exactly once in usedSandboxResources.
2128
+ sandboxSlots: Math.min(this.config.maxConcurrentSandboxes, preflight.maxConcurrentSandboxes + activeResources.sandboxSlots),
2129
+ cpuMillis: preflight.availableCpuMillis,
2130
+ workerMemoryLimitBytes: 0,
2131
+ serviceMemoryLimitBytes: 0,
2132
+ runtimeOverheadBytes: 0,
2133
+ memoryBytes: sandboxMemoryCommitmentCapacity(preflight, activeResources.memoryBytes),
2134
+ workspaceBytes: Math.max(0, preflight.availableWorkspaceBytes
2135
+ - this.config.minimumWorkspaceBytes
2136
+ + activeResources.workspaceBytes),
2137
+ pids: this.config.sandboxPidCapacity,
2138
+ buildSlots: this.config.maxConcurrentSandboxBuilds
2139
+ };
2140
+ }
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
+ }
247
2187
  }
248
- const ack = await connection.invoke(methodName, payload);
249
- if (!ack.accepted) {
250
- 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;
251
2218
  }
252
- 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;
253
2225
  }
254
2226
  async waitForClose(signal) {
255
2227
  if (!this.closed) {
256
2228
  return;
257
2229
  }
258
- await Promise.race([this.closed, abortPromise(signal)]);
2230
+ await waitForPromiseOrAbort(this.closed, signal);
259
2231
  }
260
2232
  async stopConnection() {
261
2233
  this.stopHeartbeat();
2234
+ this.stopLeaseWatchdog();
2235
+ this.stopSandboxMaintenance();
262
2236
  if (this.connection) {
263
2237
  await this.connection.stop().catch(() => undefined);
264
2238
  this.connection = null;
265
2239
  }
266
2240
  }
267
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
+ }
268
2252
  class BridgeCallbackRejectedError extends Error {
269
2253
  code;
270
2254
  constructor(code, message) {
@@ -273,12 +2257,39 @@ class BridgeCallbackRejectedError extends Error {
273
2257
  this.name = "BridgeCallbackRejectedError";
274
2258
  }
275
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
+ }
276
2267
  function isDispatchNoLongerPending(error) {
277
2268
  if (error instanceof BridgeCallbackRejectedError) {
278
2269
  return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
279
2270
  }
280
2271
  return error instanceof Error && error.message === "Dispatch is no longer pending.";
281
2272
  }
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) {
2286
+ const rawProcessRunner = new StreamingProviderProcessRunner();
2287
+ const processSupervisors = new AttemptProcessSupervisorRegistry();
2288
+ const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(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 };
2292
+ }
282
2293
  export class SignalRBridgeConnectionFactory {
283
2294
  create(config) {
284
2295
  return new SignalRBridgeConnection(config);
@@ -293,10 +2304,32 @@ export class SignalRBridgeConnection {
293
2304
  url.searchParams.set("runnerId", config.runnerId);
294
2305
  this.connection = new HubConnectionBuilder()
295
2306
  .withUrl(url.toString(), {
296
- accessTokenFactory: () => config.deviceToken
2307
+ // Query-string access tokens are intentionally rejected by the API. The bridge is
2308
+ // a Node CLI, so use long polling where Authorization headers are carried on each
2309
+ // HTTP request instead of relying on browser/WebSocket token fallbacks.
2310
+ transport: HttpTransportType.LongPolling,
2311
+ headers: {
2312
+ Authorization: `Bearer ${config.deviceToken}`
2313
+ }
297
2314
  })
2315
+ .withAutomaticReconnect([...config.reconnectBackoffMs])
298
2316
  .configureLogging(LogLevel.Warning)
299
2317
  .build();
2318
+ this.connection.on("Superseded", () => {
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);
2332
+ });
300
2333
  }
301
2334
  start() {
302
2335
  return this.connection.start();
@@ -307,16 +2340,54 @@ export class SignalRBridgeConnection {
307
2340
  onClose(handler) {
308
2341
  this.connection.onclose(handler);
309
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
+ }
310
2351
  onDispatch(handler) {
311
2352
  this.connection.on("Dispatch", (raw) => {
312
2353
  void handler(raw).catch(() => undefined);
313
2354
  });
314
2355
  }
2356
+ onChatTurn(handler) {
2357
+ this.connection.on("ChatTurn", (raw) => {
2358
+ void handler(raw).catch(() => undefined);
2359
+ });
2360
+ }
2361
+ onOffer(handler) {
2362
+ this.connection.on("Offer", (raw) => {
2363
+ void handler(raw).catch(() => undefined);
2364
+ });
2365
+ }
2366
+ onStart(handler) {
2367
+ this.connection.on("Start", (raw) => {
2368
+ void handler(raw).catch(() => undefined);
2369
+ });
2370
+ }
2371
+ onLeaseUpdate(handler) {
2372
+ this.connection.on("LeaseUpdate", (request) => {
2373
+ void handler(request).catch(() => undefined);
2374
+ });
2375
+ }
315
2376
  onCancel(handler) {
316
2377
  this.connection.on("Cancel", (request) => {
317
2378
  void handler(request).catch(() => undefined);
318
2379
  });
319
2380
  }
2381
+ onReap(handler) {
2382
+ this.connection.on("Reap", (request) => {
2383
+ void handler(request).catch(() => undefined);
2384
+ });
2385
+ }
2386
+ onReadinessProbe(handler) {
2387
+ this.connection.on("ReadinessProbe", (request) => {
2388
+ void handler(request).catch(() => undefined);
2389
+ });
2390
+ }
320
2391
  invoke(methodName, payload) {
321
2392
  return this.connection.invoke(methodName, payload);
322
2393
  }
@@ -324,9 +2395,42 @@ export class SignalRBridgeConnection {
324
2395
  export function defaultBridgeServiceConfig(overrides = {}) {
325
2396
  const defaults = defaultForgeBridgeConfig();
326
2397
  const cliProviders = splitCsv(process.env.FORGE_CLI_PROVIDERS ?? "codex");
2398
+ const configuredSandboxHostMemoryReserveBytes = optionalPositiveFiniteNumber(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES);
2399
+ const sandboxPublicationMode = process.env.FORGE_SANDBOX_PUBLICATION_MODE === "bridge_push" ? "bridge_push" : "shared_filesystem";
327
2400
  const config = {
328
2401
  serverUrl: process.env.FORGE_URL ?? "http://localhost:5208",
329
2402
  runnerId: process.env.FORGE_RUNNER_ID ?? "",
2403
+ runnerInstanceId: process.env.FORGE_RUNNER_INSTANCE_ID ?? randomUUID(),
2404
+ trustDomainId: process.env.FORGE_TRUST_DOMAIN_ID ?? "default",
2405
+ maxConcurrentSandboxes: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOXES ?? 3), 3),
2406
+ maxConcurrentSandboxBuilds: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOX_BUILDS ?? 1), 1),
2407
+ sandboxPidCapacity: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_PID_CAPACITY ?? 2048), 2048),
2408
+ dockerEnabled: process.env.FORGE_DOCKER_SANDBOX !== "false",
2409
+ allowOpenPublicSandbox: process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX === "true",
2410
+ sandboxPublicationMode,
2411
+ dockerExecutable: process.env.FORGE_DOCKER_EXECUTABLE ?? "docker",
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),
2417
+ sandboxStateRoot: process.env.FORGE_SANDBOX_STATE_ROOT ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes"),
2418
+ sandboxExecutionRoot: defaultHostExecutionRoot(),
2419
+ requireRootlessDocker: process.env.FORGE_REQUIRE_ROOTLESS_DOCKER === "true" || process.platform === "linux",
2420
+ diskHighWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_HIGH_WATERMARK_PERCENT ?? 85), 85),
2421
+ diskLowWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_LOW_WATERMARK_PERCENT ?? 75), 75),
2422
+ minimumWorkspaceBytes: positiveFiniteNumber(Number(process.env.FORGE_MINIMUM_WORKSPACE_BYTES ?? 10 * 1024 ** 3), 10 * 1024 ** 3),
2423
+ // Undefined means preflight derives the bounded reserve from the actual
2424
+ // Docker/host capacity domain after sampling it.
2425
+ sandboxHostMemoryReserveBytes: configuredSandboxHostMemoryReserveBytes,
2426
+ defaultSandboxWorkerMemoryLimitBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_WORKER_MEMORY_LIMIT_BYTES ?? 2 * 1024 ** 3), 2 * 1024 ** 3),
2427
+ defaultSandboxServiceMemoryLimitBytes: nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_SERVICE_MEMORY_LIMIT_BYTES ?? 0), 0),
2428
+ sandboxRuntimeOverheadBytes: Math.max(128 * 1024 ** 2, nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_RUNTIME_OVERHEAD_BYTES ?? 128 * 1024 ** 2), 128 * 1024 ** 2)),
2429
+ sandboxMemorySampleIntervalMs: Math.min(30_000, Math.max(250, positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_MEMORY_SAMPLE_INTERVAL_MS ?? 1000), 1000))),
2430
+ imageRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_COUNT ?? 3), 3),
2431
+ imageRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_TTL_MS ?? 7 * 24 * 60 * 60 * 1000), 7 * 24 * 60 * 60 * 1000),
2432
+ auditRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_COUNT ?? 200), 200),
2433
+ auditRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_TTL_MS ?? 30 * 24 * 60 * 60 * 1000), 30 * 24 * 60 * 60 * 1000),
330
2434
  deviceToken: process.env.FORGE_DEVICE_TOKEN ?? "",
331
2435
  deviceName: process.env.FORGE_DEVICE_NAME ?? "",
332
2436
  defaultRepoRoot: process.env.FORGE_REPO_ROOT ?? defaults.defaultRepoRoot,
@@ -342,17 +2446,25 @@ export function defaultBridgeServiceConfig(overrides = {}) {
342
2446
  supportsManagedForgeArtifacts: true,
343
2447
  supportsRunnerAuthoredPhaseArtifacts: true,
344
2448
  supportsDraftRunOnce: true,
2449
+ supportsDraftAttachments: true,
2450
+ supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
2451
+ bridgeChat: bridgeChatCapabilityFor(cliProviders, providerStatusesFor(cliProviders)),
345
2452
  version: process.env.FORGE_BRIDGE_VERSION ?? forgeBridgeVersion,
346
- protocolVersion: 1,
2453
+ protocolVersion: 4,
347
2454
  minServerVersion: null,
348
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),
349
2457
  reconnectBackoffMs: [1000, 2000, 5000, 10000, 30000],
350
2458
  ...overrides
351
2459
  };
352
2460
  return {
353
2461
  ...config,
2462
+ providerStatuses: overrides.providerStatuses ?? providerStatusesFor(config.cliProviders),
354
2463
  sandboxProfiles: config.sandboxProfiles ?? defaultSandboxProfiles(config.cliProviders),
355
- heartbeatIntervalMs: positiveFiniteNumber(config.heartbeatIntervalMs, 30_000)
2464
+ supportsDraftImageAttachments: (overrides.supportsDraftImageAttachments ?? true) && supportsDraftImageAttachmentsFor(config.cliProviders),
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),
356
2468
  };
357
2469
  }
358
2470
  export function resolveBridgeRunnerHubUrl(serverUrl) {
@@ -367,9 +2479,42 @@ function normalizeServerUrl(serverUrl) {
367
2479
  function positiveFiniteNumber(value, fallback) {
368
2480
  return Number.isFinite(value) && value > 0 ? value : fallback;
369
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
+ }
2488
+ function nonNegativeFiniteNumber(value, fallback) {
2489
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
2490
+ }
370
2491
  function providerStatusesFor(providers) {
371
2492
  return Object.fromEntries(providers.map((provider) => [provider, { signedIn: true, version: "", models: configuredModelsFor(provider) }]));
372
2493
  }
2494
+ function sandboxAuthModesFor(config) {
2495
+ return Object.fromEntries(config.cliProviders.map((provider) => {
2496
+ const modes = ["api_key"];
2497
+ if (sandboxBridgeCliAuthAvailable(config, provider)) {
2498
+ modes.push("bridge_cli");
2499
+ }
2500
+ return [provider, modes];
2501
+ }));
2502
+ }
2503
+ function sandboxBridgeCliAuthAvailable(config, provider) {
2504
+ if (provider.trim().toLowerCase() !== "codex") {
2505
+ return false;
2506
+ }
2507
+ const status = providerStatus(config, provider);
2508
+ if (status?.signedIn === false) {
2509
+ return false;
2510
+ }
2511
+ return codexSandboxProviderAuthAdapter.doctor().available;
2512
+ }
2513
+ function providerStatus(config, provider) {
2514
+ const normalized = provider.trim().toLowerCase();
2515
+ return Object.entries(config.providerStatuses)
2516
+ .find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
2517
+ }
373
2518
  function defaultSandboxProfiles(providers, platform = process.platform) {
374
2519
  if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
375
2520
  return ["none"];
@@ -444,15 +2589,32 @@ function mappingKeys(mapping) {
444
2589
  mapping.localPath ? `path:${path.resolve(mapping.localPath).toLowerCase()}` : null
445
2590
  ].filter((key) => Boolean(key));
446
2591
  }
447
- function findRepoMapping(dispatch, mappings) {
448
- return mappings.find((mapping) => {
449
- if (!mapping.localPath?.trim()) {
450
- 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}.`);
451
2597
  }
452
- return (equalsIgnoreCase(mapping.repoId, dispatch.repo.id) ||
453
- equalsIgnoreCase(mapping.name, dispatch.repo.name) ||
454
- (!!mapping.remoteUrl?.trim() && equalsIgnoreCase(mapping.remoteUrl, dispatch.repo.remoteUrl)));
455
- });
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;
456
2618
  }
457
2619
  function normalizeQaAppLaunchTarget(target) {
458
2620
  if (!target) {
@@ -464,10 +2626,11 @@ function normalizeQaAppLaunchTarget(target) {
464
2626
  command: cleanString(target.command),
465
2627
  working_directory: cleanString(target.working_directory),
466
2628
  ready_url: cleanString(target.ready_url),
2629
+ managed_runtime_port: cleanString(target.managed_runtime_port),
467
2630
  routes,
468
2631
  notes: cleanString(target.notes)
469
2632
  };
470
- return normalized.url || normalized.command || normalized.ready_url || routes.length > 0
2633
+ return normalized.url || normalized.command || normalized.ready_url || normalized.managed_runtime_port
471
2634
  ? normalized
472
2635
  : null;
473
2636
  }
@@ -500,6 +2663,10 @@ function invalidDispatchSummary(error) {
500
2663
  const detail = error instanceof Error ? error.message : String(error);
501
2664
  return `Invalid bridge dispatch packet: ${detail}`;
502
2665
  }
2666
+ function invalidChatTurnSummary(error) {
2667
+ const detail = error instanceof Error ? error.message : String(error);
2668
+ return `Invalid Bridge Chat turn packet: ${detail}`;
2669
+ }
503
2670
  function errorMessage(error) {
504
2671
  return error instanceof Error ? error.message : String(error);
505
2672
  }
@@ -509,33 +2676,350 @@ function formatDelay(ms) {
509
2676
  }
510
2677
  return `${ms}ms`;
511
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
+ }
512
2703
  function logBridgeStatus(message) {
513
2704
  process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
514
2705
  }
515
- function delay(ms, signal) {
2706
+ export function delay(ms, signal) {
516
2707
  if (signal?.aborted) {
517
2708
  return Promise.resolve();
518
2709
  }
519
2710
  return new Promise((resolve) => {
520
- const timeout = setTimeout(resolve, ms);
521
- signal?.addEventListener("abort", () => {
2711
+ const complete = () => {
522
2712
  clearTimeout(timeout);
2713
+ signal?.removeEventListener("abort", complete);
523
2714
  resolve();
524
- }, { once: true });
2715
+ };
2716
+ const timeout = setTimeout(complete, ms);
2717
+ signal?.addEventListener("abort", complete, { once: true });
2718
+ if (signal?.aborted)
2719
+ complete();
525
2720
  });
526
2721
  }
527
- function abortPromise(signal) {
2722
+ export async function waitForPromiseOrAbort(promise, signal) {
528
2723
  if (!signal) {
529
- return new Promise(() => undefined);
2724
+ await promise;
2725
+ return;
530
2726
  }
531
2727
  if (signal.aborted) {
532
- 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;
533
2749
  }
534
- return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
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");
535
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 [];
2879
+ }
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);
2893
+ }
2894
+ export function canReapManagedSandboxes(preflight) {
2895
+ return canRunDockerMaintenance(preflight);
2896
+ }
2897
+ function sandboxNetworkPolicyFailure(dispatch, config) {
2898
+ const sandbox = dispatch.sandbox;
2899
+ if (!sandbox)
2900
+ return "Protocol-v2 sandbox context is missing.";
2901
+ if (sandbox.networkPolicy.mode === "open_public"
2902
+ && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
2903
+ return "open_public sandbox networking is not permitted by this runner policy.";
2904
+ }
2905
+ if (sandbox.networkPolicy.mode === "public_allowlist"
2906
+ && sandbox.networkPolicy.allowedHosts.length > 0
2907
+ && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
2908
+ return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
2909
+ }
2910
+ return null;
2911
+ }
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."}`;
2921
+ }
2922
+ function parseReadinessProbe(value) {
2923
+ if (!value || typeof value !== "object" || Array.isArray(value))
2924
+ return null;
2925
+ const request = value;
2926
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
2927
+ const bounded = (candidate, maximum) => typeof candidate === "string" && candidate.trim().length > 0 && candidate.length <= maximum;
2928
+ if (request.schemaVersion !== 1
2929
+ || !uuid.test(request.requestId ?? "")
2930
+ || !uuid.test(request.fencingToken ?? "")
2931
+ || !uuid.test(request.userId ?? "")
2932
+ || !uuid.test(request.projectId ?? "")
2933
+ || !uuid.test(request.repoId ?? "")
2934
+ || !uuid.test(request.runnerInstanceId ?? "")
2935
+ || !Number.isInteger(request.attempt) || (request.attempt ?? 0) < 1
2936
+ || !bounded(request.repoName, 160)
2937
+ || typeof request.remoteUrl !== "string" || request.remoteUrl.length > 2048
2938
+ || !bounded(request.defaultBranch, 512)
2939
+ || typeof request.cloneOnDemand !== "boolean"
2940
+ || !bounded(request.runnerRepoLocalPath, 4096)
2941
+ || !bounded(request.revision, 512)
2942
+ || !Number.isFinite(Date.parse(request.expiresAt ?? ""))
2943
+ || Date.parse(request.expiresAt ?? "") <= Date.now()) {
2944
+ return null;
2945
+ }
2946
+ return request;
2947
+ }
2948
+ function sandboxProviderNetworkFailure(dispatch, config) {
2949
+ const sandbox = dispatch.sandbox;
2950
+ if (!sandbox || sandbox.networkPolicy.mode !== "offline")
2951
+ return null;
2952
+ const provider = dispatch.execution.provider.trim().toLowerCase();
2953
+ const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
2954
+ if (!isNetworkProvider)
2955
+ return null;
2956
+ return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
2957
+ }
2958
+ function sandboxAuthFailure(dispatch, config) {
2959
+ const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2960
+ if (unsupported) {
2961
+ return unsupported;
2962
+ }
2963
+ if (dispatch.execution.authKind.trim().toLowerCase() !== "bridge_cli") {
2964
+ return null;
2965
+ }
2966
+ const status = providerStatus(config, dispatch.execution.provider);
2967
+ if (status?.signedIn === false) {
2968
+ return `${dispatch.execution.provider} Local CLI is not signed in on this runner.`;
2969
+ }
2970
+ const adapter = sandboxProviderAuthAdapterFor(dispatch.execution.provider, dispatch.execution.authKind);
2971
+ if (!adapter) {
2972
+ return `${dispatch.execution.provider} Local CLI auth is not portable into Docker yet.`;
2973
+ }
2974
+ const doctor = adapter.doctor();
2975
+ return doctor.available ? null : doctor.message;
2976
+ }
2977
+ function rejectedOfferReservation(code, message) {
2978
+ return {
2979
+ accepted: false,
2980
+ code,
2981
+ message,
2982
+ reservedUntil: null,
2983
+ resources: null,
2984
+ };
2985
+ }
2986
+ function parseOfferEnvelope(value) {
2987
+ return parseDispatchEnvelope(value);
2988
+ }
2989
+ function parseStartEnvelope(value) {
2990
+ return parseDispatchEnvelope(value);
2991
+ }
2992
+ function parseDispatchEnvelope(value) {
2993
+ if (!value || typeof value !== "object" || Array.isArray(value))
2994
+ return null;
2995
+ const envelope = value;
2996
+ if (envelope.schemaVersion !== 1
2997
+ || typeof envelope.dispatchAttemptId !== "string"
2998
+ || typeof envelope.leaseId !== "string"
2999
+ || typeof envelope.fencingToken !== "string"
3000
+ || typeof envelope.runnerInstanceId !== "string"
3001
+ || typeof envelope.expiresAt !== "string"
3002
+ || !envelope.dispatch)
3003
+ return null;
3004
+ return {
3005
+ dispatchAttemptId: envelope.dispatchAttemptId,
3006
+ leaseId: envelope.leaseId,
3007
+ fencingToken: envelope.fencingToken,
3008
+ runnerInstanceId: envelope.runnerInstanceId,
3009
+ expiresAt: envelope.expiresAt,
3010
+ dispatch: envelope.dispatch
3011
+ };
3012
+ }
3013
+ const maxAttachmentExactSecretLength = 8 * 1024;
536
3014
  function exactSecrets(dispatch, config) {
537
3015
  return [
538
3016
  dispatch.apiKeySecretGrant?.secret,
539
- config.deviceToken
3017
+ config.deviceToken,
3018
+ ...boundedAttachmentExactSecrets(dispatch)
540
3019
  ].filter((secret) => typeof secret === "string" && secret.length > 0);
541
3020
  }
3021
+ function boundedAttachmentExactSecrets(dispatch) {
3022
+ return (dispatch.draft?.attachments ?? [])
3023
+ .flatMap((attachment) => [attachment.textContent, attachment.contentBase64])
3024
+ .filter((secret) => typeof secret === "string" && secret.length > 0 && secret.length <= maxAttachmentExactSecretLength);
3025
+ }