@loucompanion/forge-bridge 0.1.4-dev.04a1e5b9e484 → 0.1.4-dev.176dfdaf5020

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 (272) hide show
  1. package/README.md +145 -4
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +76 -14
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +77 -5
  103. package/dist/runtime/host-runtime-lease.js +328 -136
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  107. package/dist/runtime/host-runtime-promotion.js +48 -0
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  113. package/dist/runtime/managed-command-teardown.js +596 -0
  114. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  115. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  116. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  117. package/dist/runtime/playwright-browser-cache.js +227 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  119. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  120. package/dist/runtime/runner-settings.d.ts +104 -0
  121. package/dist/runtime/runner-settings.js +236 -0
  122. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  123. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  124. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  125. package/dist/sandbox/host-capacity-broker.js +336 -0
  126. package/dist/sandbox/managed-branch.d.ts +13 -0
  127. package/dist/sandbox/managed-branch.js +90 -0
  128. package/dist/sandbox/provider-auth/codex.js +11 -11
  129. package/dist/sandbox/runtime.d.ts +10 -1
  130. package/dist/sandbox/runtime.js +47 -8
  131. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  132. package/dist/sandbox/sandbox-cgroups.js +42 -0
  133. package/dist/session/architect-waits.d.ts +2 -0
  134. package/dist/session/architect-waits.js +138 -0
  135. package/dist/session/managed-attempt-tools.d.ts +27 -7
  136. package/dist/session/managed-attempt-tools.js +406 -123
  137. package/dist/session/managed-build-coordinator.d.ts +17 -1
  138. package/dist/session/managed-build-coordinator.js +14 -1
  139. package/dist/session/managed-build-receipt.d.ts +5 -0
  140. package/dist/session/managed-build-receipt.js +8 -3
  141. package/dist/session/managed-command-host-load.d.ts +47 -0
  142. package/dist/session/managed-command-host-load.js +83 -0
  143. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  144. package/dist/session/mcp-argument-coercion.js +121 -0
  145. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  146. package/dist/session/phase-completion.artifacts.js +100 -26
  147. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  148. package/dist/session/phase-completion.command-validation.js +77 -0
  149. package/dist/session/phase-completion.d.ts +12 -0
  150. package/dist/session/phase-completion.helpers.js +13 -12
  151. package/dist/session/phase-completion.js +5 -0
  152. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  153. package/dist/session/phase-completion.mcp-args.js +156 -0
  154. package/dist/session/phase-completion.prompts.js +6 -1
  155. package/dist/session/phase-completion.runtime.d.ts +5 -11
  156. package/dist/session/phase-completion.runtime.js +111 -230
  157. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  158. package/dist/session/phase-completion.schema-parts.js +188 -0
  159. package/dist/session/phase-completion.schemas.d.ts +3 -3
  160. package/dist/session/phase-completion.schemas.js +208 -231
  161. package/dist/session/phase-completion.validation.d.ts +2 -3
  162. package/dist/session/phase-completion.validation.js +49 -93
  163. package/dist/session/pre-publication-host-load.d.ts +27 -0
  164. package/dist/session/pre-publication-host-load.js +111 -0
  165. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  166. package/dist/session/pre-publication-native-postgres.js +111 -0
  167. package/dist/session/pre-publication-pass.d.ts +61 -0
  168. package/dist/session/pre-publication-pass.js +148 -0
  169. package/dist/session/pre-publication-process.d.ts +23 -0
  170. package/dist/session/pre-publication-process.js +109 -0
  171. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  172. package/dist/session/pre-publication-skipped-tests.js +109 -0
  173. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  174. package/dist/session/pre-publication-step-execution.js +50 -0
  175. package/dist/session/pre-publication-validation.d.ts +37 -21
  176. package/dist/session/pre-publication-validation.js +228 -219
  177. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  178. package/dist/session/provider-cli/claude-background-work.js +181 -0
  179. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  180. package/dist/session/provider-cli/host-build-lock.js +30 -0
  181. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  182. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  183. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  184. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  185. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  186. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  188. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  190. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  191. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  192. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  193. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  194. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  195. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  196. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  197. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  198. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  199. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  201. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  203. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  205. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  206. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  207. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  208. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  209. package/dist/session/provider-cli/provider-output-state.js +15 -0
  210. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  211. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  212. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  213. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  214. package/dist/session/publishable-worktree-changes.js +193 -0
  215. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  216. package/dist/session/qa-sidecar-validation.js +28 -0
  217. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  218. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  219. package/dist/session/session-redaction.js +31 -181
  220. package/dist/session/session.base.d.ts +9 -1
  221. package/dist/session/session.service.d.ts +11 -2
  222. package/dist/session/session.service.js +189 -69
  223. package/dist/session/session.types.d.ts +3 -0
  224. package/dist/session/session.types.js +15 -3
  225. package/dist/session/sidecar-json-shape.d.ts +31 -0
  226. package/dist/session/sidecar-json-shape.js +217 -0
  227. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  228. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  229. package/dist/shared/fs/file-identity.d.ts +10 -0
  230. package/dist/shared/fs/file-identity.js +15 -0
  231. package/dist/shared/fs/replace-file.d.ts +7 -0
  232. package/dist/shared/fs/replace-file.js +33 -0
  233. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  234. package/dist/shared/process/host-process-recovery.js +23 -3
  235. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  236. package/dist/shared/process/host-process-supervisor.js +67 -15
  237. package/dist/shared/process/process-tree.d.ts +52 -0
  238. package/dist/shared/process/process-tree.js +144 -0
  239. package/dist/shared/process/process.d.ts +67 -0
  240. package/dist/shared/process/process.js +213 -11
  241. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  242. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  243. package/dist/shared/process/windows-launch.d.ts +18 -0
  244. package/dist/shared/process/windows-launch.js +68 -0
  245. package/dist/shared/provider-capabilities.js +14 -7
  246. package/dist/version.d.ts +1 -1
  247. package/dist/version.js +1 -1
  248. package/dist/worktree/dependency-warmer.d.ts +25 -0
  249. package/dist/worktree/dependency-warmer.js +120 -10
  250. package/dist/worktree/orphan-relink.d.ts +19 -0
  251. package/dist/worktree/orphan-relink.js +106 -0
  252. package/dist/worktree/wip-git.d.ts +33 -0
  253. package/dist/worktree/wip-git.js +122 -0
  254. package/dist/worktree/wip-refs.d.ts +62 -0
  255. package/dist/worktree/wip-refs.js +119 -0
  256. package/dist/worktree/wip-restore.d.ts +38 -0
  257. package/dist/worktree/wip-restore.js +190 -0
  258. package/dist/worktree/wip-snapshot.d.ts +50 -0
  259. package/dist/worktree/wip-snapshot.js +268 -0
  260. package/dist/worktree/worktree-inputs.d.ts +8 -0
  261. package/dist/worktree/worktree-inputs.js +134 -0
  262. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  263. package/dist/worktree/worktree-origin-sync.js +127 -0
  264. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  265. package/dist/worktree/worktree-wip-events.js +98 -0
  266. package/dist/worktree/worktree-wip.d.ts +50 -0
  267. package/dist/worktree/worktree-wip.js +185 -0
  268. package/dist/worktree/worktree.base.d.ts +7 -1
  269. package/dist/worktree/worktree.service.d.ts +36 -5
  270. package/dist/worktree/worktree.service.js +124 -155
  271. package/dist/worktree/worktree.types.d.ts +38 -0
  272. package/package.json +2 -2
@@ -1,3 +1,4 @@
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";
@@ -7,12 +8,16 @@ import { defaultForgeBridgeConfig } from "../config.js";
7
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 { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } from "../session/provider-cli/provider-cli.prompts.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";
12
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
13
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
14
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
15
- import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
+ import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
18
+ import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
+ import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
+ import { readLocalYieldFlag } from "./local-yield-flag.js";
16
21
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
17
22
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
18
23
  import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
@@ -26,15 +31,17 @@ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegist
26
31
  import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
27
32
  import { forgeBridgeVersion } from "../version.js";
28
33
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
29
- import { validateSandboxContract } from "../sandbox/contract.js";
30
- import { runSandboxProcess } from "../sandbox/process.js";
31
- import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
34
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
32
35
  import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
33
36
  import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
34
- import { formatBytes } from "../shared/format/format-bytes.js";
35
37
  import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
36
- import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
37
- import { FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
38
+ import { HostLoadSampler } from "../runtime/host-load-sampler.js";
39
+ import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
40
+ import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
41
+ import { BridgeStatePublisher } from "./bridge-state-file.js";
42
+ import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
43
+ import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
44
+ export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
38
45
  /**
39
46
  * Protocol-v2 events are acknowledged one at a time before runOnce returns.
40
47
  * Sending the complete transcript again in DispatchResult made long QA and CI
@@ -53,6 +60,7 @@ export class ForgeBridgeService {
53
60
  connections;
54
61
  hostCapabilityProbe;
55
62
  chatProcessRunner;
63
+ hostLoad;
56
64
  connection = null;
57
65
  heartbeatTimer = null;
58
66
  heartbeatInFlight = false;
@@ -65,9 +73,12 @@ export class ForgeBridgeService {
65
73
  transportRecovery = null;
66
74
  transportRecoveryGeneration = 0;
67
75
  stopped = false;
76
+ revokedReason = null;
68
77
  activeSessions = new Map();
69
78
  reservations = new Map();
70
79
  activeReadinessProbes = new Map();
80
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
81
+ inFlight = new BridgeInFlightRegistry();
71
82
  readinessResultOutbox;
72
83
  readinessResultFlush = null;
73
84
  dispatchResultOutbox;
@@ -82,16 +93,49 @@ export class ForgeBridgeService {
82
93
  sessions;
83
94
  enforceHostDatabaseCapabilityBoundary;
84
95
  hostCapabilities = emptyRunnerHostCapabilitySnapshot();
96
+ dockerAvailable = false;
97
+ // Decision 0014 settings push. The last applied server document (null until one
98
+ // arrives: an old server never sends one), the local `forge-bridge yield` flag,
99
+ // and the effective settings computed from both and the host's env bounds.
100
+ appliedSettingsDocument = null;
101
+ localYield = false;
102
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
103
+ forgeAckedYield = false;
104
+ publishState = () => undefined;
105
+ effectiveSettings;
106
+ settingsReport;
107
+ /** Applies run one at a time; offers wait for every apply queued before them. */
108
+ settingsTail = Promise.resolve();
109
+ // Server documents that turn yield on and are queued but not applied yet. The
110
+ // reservation commit is synchronous and can't wait for the apply, so it counts these.
111
+ pendingYieldOn = 0;
112
+ settingsStarted = null;
113
+ hostRequirementFacts() {
114
+ const facts = this.hostLoad.facts();
115
+ return {
116
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
117
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
118
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
119
+ .filter(([, tool]) => tool?.available === true)
120
+ .map(([name]) => name),
121
+ dockerAvailable: this.dockerAvailable,
122
+ browserLaunch: this.hostCapabilities.browserLaunch,
123
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
124
+ };
125
+ }
85
126
  // Reaping deletes the stale ledger, so its stopped-process proof is held here
86
127
  // until a Hello carrying it is accepted. A bridge restart forgets it, which
87
128
  // leaves those attempts on Forge's conservative unknown-outcome path.
88
129
  recoveredHostAttempts = new Map();
89
130
  hostCapabilitiesDetected = false;
90
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox) {
131
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
132
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
133
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
91
134
  this.config = config;
92
135
  this.connections = connections;
93
136
  this.hostCapabilityProbe = hostCapabilityProbe;
94
137
  this.chatProcessRunner = chatProcessRunner;
138
+ this.hostLoad = hostLoad;
95
139
  this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
96
140
  if (this.enforceHostDatabaseCapabilityBoundary) {
97
141
  establishHostDatabaseCapabilityBoundary();
@@ -123,14 +167,27 @@ export class ForgeBridgeService {
123
167
  },
124
168
  onStatus: logBridgeStatus,
125
169
  });
126
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
127
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
170
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
171
+ this.sessions = sessions ?? defaultSessions.sessions;
172
+ // Docker sandboxes ask the same host load governor for their validation tokens.
173
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
128
174
  this.sandboxResourceResolver = sandboxResourceResolver
129
175
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
130
176
  this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
131
177
  this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
178
+ // With no server document and no local flag these equal today's env/default behaviour.
179
+ this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
180
+ this.settingsReport = this.effectiveSettings.report;
181
+ this.inFlight.addSource(() => [
182
+ ...reservationInFlightEntries(this.reservations),
183
+ ...sessionInFlightEntries(this.activeSessions),
184
+ ...readinessInFlightEntries(this.activeReadinessProbes),
185
+ ]);
132
186
  }
133
187
  async connectOnce() {
188
+ if (this.revokedReason !== null) {
189
+ throw new BridgeRevokedError(this.revokedReason);
190
+ }
134
191
  await this.stopConnection();
135
192
  this.stopped = false;
136
193
  if (this.enforceHostDatabaseCapabilityBoundary) {
@@ -156,6 +213,11 @@ export class ForgeBridgeService {
156
213
  this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
157
214
  this.hostCapabilitiesDetected = true;
158
215
  }
216
+ // Static host facts and the first load sample ride on Hello; the sampler
217
+ // keeps refreshing its cached snapshot for later heartbeats.
218
+ await this.hostLoad.start().catch(() => undefined);
219
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
220
+ await this.startSettings();
159
221
  const connection = this.connections.create(this.config);
160
222
  this.connection = connection;
161
223
  this.transportRecovery = null;
@@ -197,14 +259,16 @@ export class ForgeBridgeService {
197
259
  await connection.stop().catch(() => undefined);
198
260
  }
199
261
  });
200
- connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
201
- connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
202
- connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
203
- connection.onStart?.((dispatch) => this.handleStart(dispatch));
262
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
263
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
264
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
265
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
204
266
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
205
267
  connection.onCancel((request) => this.handleCancel(request));
206
268
  connection.onReap?.((request) => this.handleReap(request));
207
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
269
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
270
+ connection.onRevoked?.((notice) => this.handleRevoked(notice));
271
+ connection.onApplySettings?.((document) => this.handleApplySettings(document));
208
272
  await connection.start();
209
273
  await this.registerConnection(connection);
210
274
  await this.flushDispatchResults(true).catch(error => {
@@ -241,6 +305,7 @@ export class ForgeBridgeService {
241
305
  while (true) {
242
306
  try {
243
307
  const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
308
+ const reportedYield = this.settingsReport.values.yieldToForeground;
244
309
  const ack = await connection.invoke("Hello", {
245
310
  version: this.config.version,
246
311
  protocolVersion: this.config.protocolVersion,
@@ -253,6 +318,7 @@ export class ForgeBridgeService {
253
318
  throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
254
319
  }
255
320
  this.recoveredHostAttempts.clear();
321
+ this.ackYield(reportedYield);
256
322
  logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
257
323
  return;
258
324
  }
@@ -268,6 +334,7 @@ export class ForgeBridgeService {
268
334
  }
269
335
  }
270
336
  async run(signal) {
337
+ const statePublisher = await this.startStatePublisher();
271
338
  let attempt = 0;
272
339
  try {
273
340
  while (!this.stopped && !signal?.aborted) {
@@ -283,7 +350,7 @@ export class ForgeBridgeService {
283
350
  }
284
351
  }
285
352
  catch (error) {
286
- if (this.stopped || signal?.aborted) {
353
+ if (this.stopped || signal?.aborted || this.revokedReason !== null) {
287
354
  break;
288
355
  }
289
356
  const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
@@ -299,6 +366,214 @@ export class ForgeBridgeService {
299
366
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
300
367
  }
301
368
  await this.stopConnection();
369
+ await statePublisher?.stop();
370
+ }
371
+ if (this.revokedReason !== null) {
372
+ throw new BridgeRevokedError(this.revokedReason);
373
+ }
374
+ }
375
+ async startStatePublisher() {
376
+ if (!this.config.bridgeStatePath)
377
+ return null;
378
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
379
+ inFlight: () => this.inFlight.snapshot(),
380
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
381
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
382
+ yieldApplied: () => this.effectiveSettings.yielding,
383
+ connected: () => this.connection !== null && this.transportRecovery === null,
384
+ }, { log: logBridgeStatus });
385
+ this.publishState = () => void publisher.publish();
386
+ this.inFlight.onChange(this.publishState);
387
+ await publisher.start();
388
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
389
+ return publisher;
390
+ }
391
+ /** The reason Forge gave when it removed this runner, or null while it is paired. */
392
+ get revoked() {
393
+ return this.revokedReason;
394
+ }
395
+ /**
396
+ * Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
397
+ * reconnecting; its attempts were already settled on the server, so local work is
398
+ * aborted rather than reported.
399
+ */
400
+ handleRevoked(notice) {
401
+ if (this.revokedReason !== null)
402
+ return;
403
+ const reason = typeof notice?.reason === "string" && notice.reason.trim()
404
+ ? notice.reason.trim()
405
+ : bridgeRevokedMessage;
406
+ this.revokedReason = reason;
407
+ this.stopped = true;
408
+ logBridgeStatus(reason);
409
+ this.abortActiveSessions("runner removed from Forge");
410
+ this.abortActiveReadinessProbes("runner removed from Forge");
411
+ void this.stopConnection().catch(() => undefined);
412
+ }
413
+ /** The effective settings and how they were derived, as last reported (decision 0014). */
414
+ get runnerSettings() {
415
+ return this.settingsReport;
416
+ }
417
+ runnerHostDefaults() {
418
+ return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
419
+ }
420
+ /**
421
+ * Once per bridge process: drop governor overrides an earlier process left on
422
+ * the state root, then put today's effective settings (env bounds and the local
423
+ * yield flag, no server document yet) in force.
424
+ */
425
+ async startSettings() {
426
+ this.settingsStarted ??= (async () => {
427
+ await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
428
+ logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
429
+ });
430
+ this.localYield = await this.readLocalYield();
431
+ await this.enqueueSettings({ kind: "local" });
432
+ })();
433
+ await this.settingsStarted;
434
+ }
435
+ /**
436
+ * Decision 0014 `ApplySettings`. Applies only a document newer than the one
437
+ * applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
438
+ * the applied version is acknowledged again without applying it; an older one is
439
+ * ignored.
440
+ */
441
+ async handleApplySettings(raw) {
442
+ const document = parseRunnerSettingsDocument(raw);
443
+ if (!document) {
444
+ logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
445
+ return;
446
+ }
447
+ if (document.runnerId && document.runnerId !== this.config.runnerId) {
448
+ logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
449
+ return;
450
+ }
451
+ await this.enqueueSettings({ kind: "server", document });
452
+ }
453
+ /**
454
+ * Polls the local `forge-bridge yield` flag (every heartbeat and before each
455
+ * offer decision). A change is applied at once and reported again under the
456
+ * same settings version.
457
+ */
458
+ /** Yielding now, or about to: a received yield-on that is still being applied counts. */
459
+ yieldingOrQueued() {
460
+ return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
461
+ }
462
+ async refreshLocalYield() {
463
+ if (!this.config.localYieldFlagPath)
464
+ return;
465
+ const localYield = await this.readLocalYield();
466
+ if (localYield === this.localYield)
467
+ return;
468
+ this.localYield = localYield;
469
+ logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
470
+ await this.enqueueSettings({ kind: "local" });
471
+ }
472
+ /**
473
+ * A setting the host couldn't put in force holds placement on the server, so
474
+ * every heartbeat tries the applied document again until it takes.
475
+ */
476
+ async retryFailedSettings() {
477
+ if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
478
+ return;
479
+ await this.enqueueSettings({ kind: "local" });
480
+ }
481
+ async readLocalYield() {
482
+ const flagPath = this.config.localYieldFlagPath;
483
+ return flagPath ? await readLocalYieldFlag(flagPath) : false;
484
+ }
485
+ enqueueSettings(change) {
486
+ const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
487
+ if (turnsYieldOn)
488
+ this.pendingYieldOn += 1;
489
+ const applied = this.settingsTail
490
+ .then(() => this.applySettings(change))
491
+ .finally(() => {
492
+ if (turnsYieldOn)
493
+ this.pendingYieldOn -= 1;
494
+ });
495
+ // A failed apply must not wedge later applies or the offers waiting on them.
496
+ this.settingsTail = applied.catch(error => {
497
+ logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
498
+ });
499
+ return this.settingsTail;
500
+ }
501
+ async applySettings(change) {
502
+ const applied = this.appliedSettingsDocument;
503
+ if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
504
+ if (change.document.version === applied.version) {
505
+ // The server sends the current version again at each Hello. After a reconnect it may never
506
+ // have seen this version's ack (the old connection dropped first), and its offer gate waits
507
+ // for one from this connection, so acknowledge what is in force again rather than nothing.
508
+ void this.sendSettingsApplied(this.settingsReport);
509
+ return;
510
+ }
511
+ logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
512
+ return;
513
+ }
514
+ const document = change.kind === "server" ? change.document : applied;
515
+ const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
516
+ const failures = await this.putSettingsInForce(effective);
517
+ // Report what is in force: a key the host couldn't take keeps its previous value.
518
+ const report = {
519
+ ...runnerSettingsInForce(effective.report, this.settingsReport, failures),
520
+ version: document?.version ?? null,
521
+ };
522
+ const changed = !sameRunnerSettingsReport(report, this.settingsReport);
523
+ this.appliedSettingsDocument = document;
524
+ this.effectiveSettings = effective;
525
+ this.settingsReport = report;
526
+ this.publishState();
527
+ if (change.kind === "server") {
528
+ logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
529
+ }
530
+ // Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
531
+ if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
532
+ void this.sendSettingsApplied(report);
533
+ }
534
+ }
535
+ /**
536
+ * Max attempts and the memory reserve go to host attempt admission; the governor
537
+ * budget (the yield budget while yielding) and the heavy-step limit go to the
538
+ * shared settings file every governor on the state root reads at admission.
539
+ * Neither touches admitted work. Returns the keys the host could not put in
540
+ * force (`apply_failed`); their previous values stay in force.
541
+ */
542
+ async putSettingsInForce(effective) {
543
+ const { values } = effective.report;
544
+ const rejected = [];
545
+ try {
546
+ await this.sessions.applyRunnerLimits?.({
547
+ maxConcurrentAttempts: values.maxConcurrentAttempts,
548
+ memoryReserveBytes: values.memoryReserveBytes,
549
+ });
550
+ }
551
+ catch (error) {
552
+ const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
553
+ rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
554
+ }
555
+ try {
556
+ await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
557
+ cpuBudgetFraction: effective.governorCpuBudgetFraction,
558
+ maxHeavySteps: values.maxHeavySteps,
559
+ yielding: effective.yielding,
560
+ });
561
+ }
562
+ catch (error) {
563
+ const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
564
+ rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
565
+ }
566
+ return rejected;
567
+ }
568
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
569
+ /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
570
+ async sendSettingsApplied(report) {
571
+ try {
572
+ await this.invokeAck("SettingsApplied", report);
573
+ this.ackYield(report.values.yieldToForeground);
574
+ }
575
+ catch (error) {
576
+ logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
302
577
  }
303
578
  }
304
579
  async stop() {
@@ -306,6 +581,7 @@ export class ForgeBridgeService {
306
581
  this.abortActiveSessions("bridge stopping");
307
582
  this.abortActiveReadinessProbes("bridge stopping");
308
583
  await this.stopConnection();
584
+ this.hostLoad.stop();
309
585
  await this.preflight.release();
310
586
  }
311
587
  async handleChatTurn(rawDispatch) {
@@ -439,6 +715,7 @@ export class ForgeBridgeService {
439
715
  env: {
440
716
  FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
441
717
  FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
718
+ ...plan.env,
442
719
  },
443
720
  stdin: plan.stdin,
444
721
  }, {
@@ -465,6 +742,7 @@ export class ForgeBridgeService {
465
742
  content: "Bridge Chat provider process exited.",
466
743
  }).catch(() => undefined);
467
744
  }
745
+ assertChatTurnFinished(result);
468
746
  return { command: plan.command, output, result };
469
747
  }
470
748
  async sendChatProviderEvent(packet, active, event, providerThreadId) {
@@ -650,19 +928,7 @@ export class ForgeBridgeService {
650
928
  return;
651
929
  }
652
930
  const controller = reservationHandoff?.controller ?? new AbortController();
653
- this.activeSessions.set(leaseId, {
654
- leaseId,
655
- kind: "dispatch",
656
- fencingToken,
657
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
658
- runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
659
- leaseExpiresAt: dispatch.lease.expiresAt,
660
- sandboxed: dispatch.sandbox?.executionMode === "docker",
661
- resources: dispatch.sandbox?.executionMode === "docker"
662
- ? dispatch.sandbox.requestedResources
663
- : zeroSandboxResources(),
664
- controller
665
- });
931
+ this.registerActiveDispatch(dispatch, controller);
666
932
  if (reservationHandoff) {
667
933
  // Promotion is synchronous with active-session registration. A qualified
668
934
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -686,43 +952,10 @@ export class ForgeBridgeService {
686
952
  };
687
953
  await this.invokeAck("DispatchStarted", started);
688
954
  }
689
- const sink = {
690
- emit: async (event) => {
691
- if (event.eventType === "provider_cli_started") {
692
- const active = this.activeSessions.get(leaseId);
693
- if (active)
694
- active.resources = { ...active.resources, buildSlots: 0 };
695
- }
696
- try {
697
- await this.invokeAck("DispatchEvent", {
698
- leaseId,
699
- fencingToken,
700
- ...(dispatch.sandbox ? {
701
- dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
702
- runnerInstanceId: dispatch.sandbox.runnerInstanceId
703
- } : {}),
704
- event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
705
- }, {
706
- replayCallbackTimeout: true,
707
- signal: controller.signal,
708
- });
709
- }
710
- catch (error) {
711
- if (isDispatchNoLongerPending(error)) {
712
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
713
- return;
714
- }
715
- throw error;
716
- }
717
- }
718
- };
719
- const result = normalized.sandbox?.executionMode === "docker"
720
- ? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
721
- : await this.sessions.runOnce(normalized, sink, controller.signal);
722
- if (normalized.sandbox?.executionMode === "docker") {
723
- await this.flushCleanupReports().catch(() => undefined);
724
- }
955
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
956
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
725
957
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
958
+ this.inFlight.notePhase(leaseId, "result_delivery");
726
959
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
727
960
  }
728
961
  catch (error) {
@@ -746,6 +979,77 @@ export class ForgeBridgeService {
746
979
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
747
980
  }
748
981
  }
982
+ registerActiveDispatch(dispatch, controller) {
983
+ this.activeSessions.set(dispatch.lease.id, {
984
+ leaseId: dispatch.lease.id,
985
+ kind: "dispatch",
986
+ fencingToken: dispatch.lease.fencingToken,
987
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
988
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
989
+ leaseExpiresAt: dispatch.lease.expiresAt,
990
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
991
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
992
+ controller
993
+ });
994
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
995
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
996
+ }
997
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
998
+ const leaseId = dispatch.lease.id;
999
+ return {
1000
+ emit: async (event) => {
1001
+ this.inFlight.notePhase(leaseId, event.eventType);
1002
+ if (event.eventType === "provider_cli_started") {
1003
+ const active = this.activeSessions.get(leaseId);
1004
+ if (active)
1005
+ active.resources = { ...active.resources, buildSlots: 0 };
1006
+ }
1007
+ try {
1008
+ await this.invokeAck("DispatchEvent", {
1009
+ leaseId,
1010
+ fencingToken: dispatch.lease.fencingToken,
1011
+ ...(dispatch.sandbox ? {
1012
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1013
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1014
+ } : {}),
1015
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1016
+ }, {
1017
+ replayCallbackTimeout: true,
1018
+ signal: controller.signal,
1019
+ });
1020
+ }
1021
+ catch (error) {
1022
+ if (isDispatchNoLongerPending(error)) {
1023
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1024
+ return;
1025
+ }
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ };
1030
+ }
1031
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1032
+ async runDispatchOnce(dispatch, sink, signal) {
1033
+ const docker = dispatch.sandbox?.executionMode === "docker";
1034
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1035
+ const startedAt = Date.now();
1036
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1037
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1038
+ try {
1039
+ const result = docker
1040
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1041
+ : await this.sessions.runOnce(dispatch, sink, signal);
1042
+ if (docker) {
1043
+ await this.flushCleanupReports().catch(() => undefined);
1044
+ }
1045
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1046
+ return result;
1047
+ }
1048
+ catch (error) {
1049
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1050
+ throw error;
1051
+ }
1052
+ }
749
1053
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
750
1054
  const sandbox = dispatch.sandbox;
751
1055
  const reservation = handoff.reservation;
@@ -833,6 +1137,16 @@ export class ForgeBridgeService {
833
1137
  await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
834
1138
  return;
835
1139
  }
1140
+ // Decision 0014: decide under the settings Forge sent (an offer never races an
1141
+ // apply), and refuse new work while yielding to the foreground. The local flag
1142
+ // is read here too, before Forge has heard about it.
1143
+ await this.refreshLocalYield().catch(() => undefined);
1144
+ // Every apply queued so far, including one a concurrent offer or heartbeat started.
1145
+ await this.settingsTail;
1146
+ if (this.effectiveSettings.yielding) {
1147
+ await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
1148
+ return;
1149
+ }
836
1150
  const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
837
1151
  ? await this.preflight.run()
838
1152
  : this.preflight.current();
@@ -917,6 +1231,11 @@ export class ForgeBridgeService {
917
1231
  if (Date.parse(dispatch.lease.expiresAt) <= now) {
918
1232
  return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
919
1233
  }
1234
+ // Yield may have turned on while the offer was being profiled, including a
1235
+ // yield Forge sent or the local flag set that hasn't finished applying yet.
1236
+ if (this.yieldingOrQueued()) {
1237
+ return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
1238
+ }
920
1239
  if (sandbox.executionMode === "docker") {
921
1240
  // A concurrent heartbeat/preflight refresh may have produced a newer
922
1241
  // conservative dual-domain sample while this offer was being profiled.
@@ -1092,6 +1411,8 @@ export class ForgeBridgeService {
1092
1411
  reservedResources: accepted ? reservedResources : null,
1093
1412
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1094
1413
  };
1414
+ if (accepted)
1415
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1095
1416
  await this.invokeAck("OfferDecision", payload);
1096
1417
  }
1097
1418
  async parseDispatchOrReport(rawDispatch) {
@@ -1205,7 +1526,13 @@ export class ForgeBridgeService {
1205
1526
  acceptedAt: new Date().toISOString(),
1206
1527
  };
1207
1528
  await this.invokeAck("ReadinessAccepted", accepted);
1208
- if (this.activeSessions.size > 0) {
1529
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1530
+ await this.refreshLocalYield().catch(() => undefined);
1531
+ await this.settingsTail;
1532
+ if (this.yieldingOrQueued()) {
1533
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1534
+ }
1535
+ else if (this.activeSessions.size > 0) {
1209
1536
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1210
1537
  }
1211
1538
  else if (!this.sessions.probeHostRuntime) {
@@ -1468,6 +1795,19 @@ export class ForgeBridgeService {
1468
1795
  await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
1469
1796
  continue;
1470
1797
  }
1798
+ if (this.isReplacedRunnerInstanceResult(pending.payload, error)) {
1799
+ try {
1800
+ await this.dispatchResultOutbox.quarantine(pending);
1801
+ }
1802
+ catch (quarantineError) {
1803
+ // Keep the record and surface Forge's rejection: replay stays
1804
+ // deferred and a heartbeat tick does not count it as a failure.
1805
+ logBridgeStatus(`Dispatch result ${pending.payload.leaseId} from replaced runner instance ${pending.payload.runnerInstanceId} could not be quarantined: ${errorMessage(quarantineError)}`);
1806
+ throw error;
1807
+ }
1808
+ logBridgeStatus(`Quarantined dispatch result ${pending.payload.leaseId}: Forge rejected it because it belongs to replaced runner instance ${pending.payload.runnerInstanceId}. Forge's own recovery handles that instance's attempt; the redacted result is kept in ${dispatchResultQuarantineDirectory} for reconciliation.`);
1809
+ continue;
1810
+ }
1471
1811
  throw error;
1472
1812
  }
1473
1813
  }
@@ -1478,6 +1818,20 @@ export class ForgeBridgeService {
1478
1818
  this.dispatchResultFlushedGeneration = startedGeneration;
1479
1819
  }
1480
1820
  }
1821
+ /**
1822
+ * Forge binds each result to the runner instance that ran the attempt. On an
1823
+ * authoritative connection it rejects another instance's result with
1824
+ * bridge.stale_result_instance; Forge's own recovery handles that attempt,
1825
+ * so the record can never be delivered and must not block the replay queue.
1826
+ * bridge.stale_runner_instance means this connection is not authoritative
1827
+ * and says nothing about the record, so it never quarantines.
1828
+ */
1829
+ isReplacedRunnerInstanceResult(payload, error) {
1830
+ return error instanceof BridgeCallbackRejectedError
1831
+ && error.code === "bridge.stale_result_instance"
1832
+ && typeof payload.runnerInstanceId === "string"
1833
+ && payload.runnerInstanceId.toLowerCase() !== this.config.runnerInstanceId.toLowerCase();
1834
+ }
1481
1835
  startHeartbeat() {
1482
1836
  this.stopHeartbeat();
1483
1837
  this.consecutiveHeartbeatFailures = 0;
@@ -1496,8 +1850,14 @@ export class ForgeBridgeService {
1496
1850
  return;
1497
1851
  this.heartbeatInFlight = true;
1498
1852
  try {
1499
- await this.flushDispatchResults();
1500
- await this.flushReadinessResults();
1853
+ // A rejected replay is an answer from Forge, so the connection is alive:
1854
+ // an undeliverable record must not count as a heartbeat failure and
1855
+ // force reconnects. Transport failures still do.
1856
+ await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
1857
+ await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
1858
+ // The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
1859
+ await this.refreshLocalYield().catch(() => undefined);
1860
+ await this.retryFailedSettings().catch(() => undefined);
1501
1861
  await this.sendHeartbeat();
1502
1862
  this.consecutiveHeartbeatFailures = 0;
1503
1863
  }
@@ -1630,16 +1990,19 @@ export class ForgeBridgeService {
1630
1990
  await this.sendHeartbeatSnapshot();
1631
1991
  }
1632
1992
  async sendHeartbeatSnapshot(signal) {
1993
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1633
1994
  await this.invokeAck("Heartbeat", {
1634
1995
  status: "online",
1635
1996
  capabilities: this.capabilities(),
1636
1997
  version: this.config.version,
1637
1998
  protocolVersion: this.config.protocolVersion
1638
1999
  }, { signal });
2000
+ this.ackYield(reportedYield);
1639
2001
  }
1640
2002
  capabilities() {
1641
2003
  const preflight = this.preflight.current();
1642
2004
  const dockerEngine = this.dockerEngineProbe.current();
2005
+ this.dockerAvailable = dockerEngine?.available === true;
1643
2006
  const runtimeState = this.sandboxRuntime.snapshot();
1644
2007
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
1645
2008
  const used = this.usedSandboxResources(runtimeState.degraded);
@@ -1656,7 +2019,7 @@ export class ForgeBridgeService {
1656
2019
  pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
1657
2020
  }) : null;
1658
2021
  return {
1659
- schemaVersion: 6,
2022
+ schemaVersion: 8,
1660
2023
  activeSessionCount: this.activeSessions.size,
1661
2024
  cliProviders: this.config.cliProviders,
1662
2025
  providerStatuses: this.config.providerStatuses,
@@ -1679,6 +2042,9 @@ export class ForgeBridgeService {
1679
2042
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1680
2043
  browserLaunch: this.hostCapabilities.browserLaunch,
1681
2044
  providerConnectivity: this.hostCapabilities.providerConnectivity,
2045
+ testPostgres: this.hostCapabilities.testPostgres,
2046
+ host: this.hostLoad.facts(),
2047
+ load: this.hostLoad.current(),
1682
2048
  maxConcurrentSandboxes: capacity.sandboxSlots,
1683
2049
  reservedSandboxCount: reserved,
1684
2050
  activeSandboxCount: runtimeState.active,
@@ -1718,7 +2084,8 @@ export class ForgeBridgeService {
1718
2084
  supportsDraftRunOnce: this.config.supportsDraftRunOnce,
1719
2085
  supportsDraftAttachments: this.config.supportsDraftAttachments,
1720
2086
  supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
1721
- bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
2087
+ bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
2088
+ settings: { supportsServerSettings: true, ...this.settingsReport },
1722
2089
  };
1723
2090
  }
1724
2091
  async requiredCapabilityFailure(dispatch) {
@@ -1872,6 +2239,16 @@ export class ForgeBridgeService {
1872
2239
  }
1873
2240
  }
1874
2241
  }
2242
+ /** The `run` command's exit code after Forge removed the runner. */
2243
+ export const bridgeRevokedExitCode = 3;
2244
+ export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
2245
+ /** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
2246
+ export class BridgeRevokedError extends Error {
2247
+ constructor(message = bridgeRevokedMessage) {
2248
+ super(message);
2249
+ this.name = "BridgeRevokedError";
2250
+ }
2251
+ }
1875
2252
  class BridgeCallbackRejectedError extends Error {
1876
2253
  code;
1877
2254
  constructor(code, message) {
@@ -1880,6 +2257,13 @@ class BridgeCallbackRejectedError extends Error {
1880
2257
  this.name = "BridgeCallbackRejectedError";
1881
2258
  }
1882
2259
  }
2260
+ function deferRejectedReplay(kind) {
2261
+ return error => {
2262
+ if (!(error instanceof BridgeCallbackRejectedError))
2263
+ throw error;
2264
+ logBridgeStatus(`${kind} result replay deferred: ${errorMessage(error)}`);
2265
+ };
2266
+ }
1883
2267
  function isDispatchNoLongerPending(error) {
1884
2268
  if (error instanceof BridgeCallbackRejectedError) {
1885
2269
  return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
@@ -1898,11 +2282,13 @@ function isProviderStorageUnavailable(error) {
1898
2282
  function isBridgeCallbackTimeout(error) {
1899
2283
  return errorMessage(error).startsWith("bridge_callback_timeout:");
1900
2284
  }
1901
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
2285
+ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
1902
2286
  const rawProcessRunner = new StreamingProviderProcessRunner();
1903
2287
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1904
2288
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
1905
- return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback))), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot)));
2289
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2290
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2291
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
1906
2292
  }
1907
2293
  export class SignalRBridgeConnectionFactory {
1908
2294
  create(config) {
@@ -1933,6 +2319,18 @@ export class SignalRBridgeConnection {
1933
2319
  void this.connection.stop().catch(() => undefined);
1934
2320
  });
1935
2321
  }
2322
+ onApplySettings(handler) {
2323
+ this.connection.on("ApplySettings", (raw) => {
2324
+ void Promise.resolve(handler(raw)).catch(() => undefined);
2325
+ });
2326
+ }
2327
+ onRevoked(handler) {
2328
+ this.connection.on("Revoked", (raw) => {
2329
+ const notice = raw && typeof raw === "object" ? raw : {};
2330
+ handler(notice);
2331
+ void this.connection.stop().catch(() => undefined);
2332
+ });
2333
+ }
1936
2334
  start() {
1937
2335
  return this.connection.start();
1938
2336
  }
@@ -2345,7 +2743,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2345
2743
  const maxChatEventContentChars = 4000;
2346
2744
  const maxChatTerminalTextChars = 120_000;
2347
2745
  const maxChatExactSecretChars = 8 * 1024;
2348
- const chatTurnMetadataFileName = "forge-chat-metadata.json";
2349
2746
  async function materializeChatTurnMetadata(packet, workspacePath) {
2350
2747
  if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2351
2748
  return;
@@ -2405,113 +2802,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
2405
2802
  };
2406
2803
  }
2407
2804
  }
2408
- function buildChatProviderCommand(packet, cwd) {
2409
- const provider = packet.providerKind.trim().toLowerCase();
2410
- const model = packet.model.trim();
2411
- const prompt = buildChatPrompt(packet);
2412
- const resumeThreadId = packet.providerThreadId?.trim() || null;
2413
- if (provider === "codex") {
2414
- const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
2415
- if (resumeThreadId) {
2416
- args.push("--cd", cwd, "resume");
2417
- }
2418
- args.push("--model", model, "--json");
2419
- if (!resumeThreadId) {
2420
- args.push("--cd", cwd);
2421
- }
2422
- args.push("--skip-git-repo-check");
2423
- if (resumeThreadId) {
2424
- args.push(resumeThreadId);
2425
- }
2426
- args.push("-");
2427
- return { command: { command: "codex", args }, stdin: prompt };
2428
- }
2429
- if (provider === "cursor") {
2430
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
2431
- if (resumeThreadId) {
2432
- args.push("--resume", resumeThreadId);
2433
- }
2434
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
2435
- return { command: { command: "cursor-agent", args } };
2436
- }
2437
- if (provider === "claude") {
2438
- const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
2439
- if (resumeThreadId) {
2440
- args.push("--resume", resumeThreadId);
2441
- }
2442
- return { command: { command: "claude", args }, stdin: prompt };
2443
- }
2444
- return {
2445
- command: {
2446
- command: provider,
2447
- args: ["--model", model, prompt],
2448
- },
2449
- };
2450
- }
2451
- function buildChatPrompt(packet) {
2452
- const messages = packet.messages
2453
- .map((message, index) => {
2454
- const role = message.role.trim() || `message-${index + 1}`;
2455
- return `[${role}]\n${message.content}`;
2456
- })
2457
- .join("\n\n");
2458
- const contextRefs = packet.contextRefs.length === 0
2459
- ? ""
2460
- : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
2461
- const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
2462
- const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
2463
- return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
2464
- }).join("\n\n")}`;
2465
- const continuation = packet.providerThreadId
2466
- ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
2467
- : "";
2468
- const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
2469
- return `You are handling a Forge Bridge Chat turn.
2470
-
2471
- Conversation ID: ${packet.conversationId}
2472
- Turn ID: ${packet.turnId}
2473
- Provider: ${packet.providerKind}
2474
- Model: ${packet.model}${continuation}${boundedMetadata}
2475
-
2476
- # Conversation
2477
-
2478
- ${messages}${contextRefs}
2479
- `;
2480
- }
2481
- function buildChatBoundedMetadataPrompt(packet) {
2482
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2483
- return "";
2484
- }
2485
- const sections = [
2486
- `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
2487
- ];
2488
- if (packet.attachmentHandoffs.length > 0) {
2489
- sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
2490
- `${index + 1}. turnId: ${handoff.turnId}`,
2491
- ` attachmentId: ${handoff.attachmentId}`,
2492
- ` tempFileToken: ${handoff.tempFileToken}`,
2493
- ` mimeType: ${handoff.mimeType}`,
2494
- ` sizeBytes: ${handoff.sizeBytes}`,
2495
- ` sha256: ${handoff.sha256}`,
2496
- ` fileNameDisplay: ${handoff.fileNameDisplay}`,
2497
- ` expiresAt: ${handoff.expiresAt}`,
2498
- ` status: ${handoff.status}`,
2499
- ].join("\n")).join("\n\n")}`);
2500
- }
2501
- if (packet.actionBrokerGrants.length > 0) {
2502
- sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
2503
- `${index + 1}. grantId: ${grant.grantId}`,
2504
- ` turnId: ${grant.turnId}`,
2505
- ` leaseId: ${grant.leaseId}`,
2506
- ` fencingToken: ${grant.fencingToken}`,
2507
- ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
2508
- ` expiresAt: ${grant.expiresAt}`,
2509
- ` redactionStatus: ${grant.redactionStatus}`,
2510
- " nonce: held by bridge",
2511
- ].join("\n")).join("\n\n")}`);
2512
- }
2513
- return sections.join("\n\n");
2514
- }
2515
2805
  function chatProviderExitFailure(command, result, redactionSecrets) {
2516
2806
  const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
2517
2807
  const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
@@ -2655,24 +2945,6 @@ function parseReadinessProbe(value) {
2655
2945
  }
2656
2946
  return request;
2657
2947
  }
2658
- function deferredReadinessResult(request, runnerInstanceId) {
2659
- return {
2660
- schemaVersion: 1,
2661
- requestId: request.requestId,
2662
- fencingToken: request.fencingToken,
2663
- runnerInstanceId,
2664
- status: "failed",
2665
- reasonCode: "host_runtime_probe_deferred",
2666
- reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
2667
- checkedAt: new Date().toISOString(),
2668
- };
2669
- }
2670
- function readinessDeferralReason(signal) {
2671
- if (!signal.aborted)
2672
- return null;
2673
- const reason = errorMessage(signal.reason);
2674
- return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
2675
- }
2676
2948
  function sandboxProviderNetworkFailure(dispatch, config) {
2677
2949
  const sandbox = dispatch.sandbox;
2678
2950
  if (!sandbox || sandbox.networkPolicy.mode !== "offline")
@@ -2711,151 +2983,6 @@ function rejectedOfferReservation(code, message) {
2711
2983
  resources: null,
2712
2984
  };
2713
2985
  }
2714
- export function canReserveSandboxResources(used, requested, capacity) {
2715
- return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
2716
- && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
2717
- && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
2718
- && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
2719
- && used.pids + requested.pids <= capacity.pids
2720
- && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
2721
- }
2722
- export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
2723
- const ambientCapacity = preflight.availableMemoryBytes
2724
- - preflight.hostReserveBytes
2725
- + activeMemoryBytes;
2726
- const commitmentCapacity = preflight.totalMemoryBytes
2727
- - preflight.hostReserveBytes;
2728
- return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
2729
- }
2730
- export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
2731
- const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
2732
- if (requested.sandboxSlots > availableSlots) {
2733
- return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
2734
- }
2735
- const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
2736
- if (requested.memoryBytes > availableMemoryBytes) {
2737
- return [
2738
- `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
2739
- `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
2740
- `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
2741
- `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
2742
- `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
2743
- ].join(" ");
2744
- }
2745
- const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
2746
- if (requested.cpuMillis > availableCpuMillis) {
2747
- return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
2748
- }
2749
- const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
2750
- if (requested.workspaceBytes > availableWorkspaceBytes) {
2751
- return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
2752
- }
2753
- const availablePids = Math.max(0, capacity.pids - used.pids);
2754
- if (requested.pids > availablePids) {
2755
- return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
2756
- }
2757
- const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
2758
- return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
2759
- }
2760
- function sumSandboxResources(resources) {
2761
- return resources.reduce((total, resource) => ({
2762
- sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
2763
- cpuMillis: total.cpuMillis + resource.cpuMillis,
2764
- workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
2765
- serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
2766
- runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
2767
- memoryBytes: total.memoryBytes + resource.memoryBytes,
2768
- workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
2769
- pids: total.pids + resource.pids,
2770
- buildSlots: total.buildSlots + resource.buildSlots
2771
- }), zeroSandboxResources());
2772
- }
2773
- function zeroSandboxResources() {
2774
- return {
2775
- sandboxSlots: 0,
2776
- cpuMillis: 0,
2777
- workerMemoryLimitBytes: 0,
2778
- serviceMemoryLimitBytes: 0,
2779
- runtimeOverheadBytes: 0,
2780
- memoryBytes: 0,
2781
- workspaceBytes: 0,
2782
- pids: 0,
2783
- buildSlots: 0,
2784
- };
2785
- }
2786
- function defaultSandboxResources() {
2787
- return {
2788
- sandboxSlots: 1,
2789
- cpuMillis: 2000,
2790
- workerMemoryLimitBytes: 2 * 1024 ** 3,
2791
- serviceMemoryLimitBytes: 0,
2792
- runtimeOverheadBytes: 128 * 1024 ** 2,
2793
- memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
2794
- workspaceBytes: 10 * 1024 ** 3,
2795
- pids: 512,
2796
- buildSlots: 0
2797
- };
2798
- }
2799
- export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
2800
- const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
2801
- const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
2802
- + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
2803
- return {
2804
- ...requested,
2805
- serviceMemoryLimitBytes,
2806
- runtimeOverheadBytes,
2807
- memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
2808
- };
2809
- }
2810
- export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
2811
- const repoPath = dispatch.repo.serverLocalPath;
2812
- const sandbox = dispatch.sandbox;
2813
- if (!repoPath || !sandbox) {
2814
- throw new Error("Sandbox admission needs a mapped repository.");
2815
- }
2816
- const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
2817
- const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
2818
- if (!configCommitSha) {
2819
- throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
2820
- }
2821
- const contractResult = await runSandboxProcess({
2822
- command: "git",
2823
- args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
2824
- timeoutMs: 30_000,
2825
- maxOutputBytes: 1024 * 1024,
2826
- });
2827
- if (contractResult.exitCode !== 0) {
2828
- throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
2829
- }
2830
- const contract = validateSandboxContract(contractResult.stdout);
2831
- const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
2832
- role: dispatch.execution.role,
2833
- serviceCount: contract.contract.services.length,
2834
- browser: contract.contract.browser,
2835
- });
2836
- return {
2837
- resources: resolveDynamicSandboxResources({
2838
- ...sandbox.requestedResources,
2839
- workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
2840
- }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
2841
- sandboxConfigCommitSha: configCommitSha,
2842
- };
2843
- }
2844
- async function resolveFirstGitCommit(repoPath, refs) {
2845
- for (const ref of refs) {
2846
- const result = await runSandboxProcess({
2847
- command: "git",
2848
- args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
2849
- timeoutMs: 30_000,
2850
- maxOutputBytes: 1024 * 1024,
2851
- });
2852
- const commitSha = result.stdout.trim().toLowerCase();
2853
- if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
2854
- return commitSha;
2855
- }
2856
- }
2857
- return null;
2858
- }
2859
2986
  function parseOfferEnvelope(value) {
2860
2987
  return parseDispatchEnvelope(value);
2861
2988
  }