@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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