@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0fedbc5c9ef7

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 (269) hide show
  1. package/README.md +146 -3
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +31 -1
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  33. package/dist/bridge/windows-bash-resolution.js +153 -0
  34. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  35. package/dist/cleanup/cleanup-wip.js +66 -0
  36. package/dist/cleanup/cleanup.service.d.ts +20 -1
  37. package/dist/cleanup/cleanup.service.js +150 -169
  38. package/dist/cleanup/cleanup.types.d.ts +6 -0
  39. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  40. package/dist/cleanup/forge-owned-paths.js +53 -0
  41. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  42. package/dist/cleanup/host-runtime-ledger.js +130 -0
  43. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  44. package/dist/cleanup/managed-branch-sweep.js +111 -0
  45. package/dist/cli/cli.help.js +74 -12
  46. package/dist/cli/cli.service.d.ts +19 -10
  47. package/dist/cli/cli.service.js +152 -187
  48. package/dist/cli/idle-status.d.ts +84 -0
  49. package/dist/cli/idle-status.js +181 -0
  50. package/dist/cli/local-config.d.ts +6 -0
  51. package/dist/cli/local-config.js +32 -4
  52. package/dist/cli/provider-cli-detection.d.ts +10 -0
  53. package/dist/cli/provider-cli-detection.js +160 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  55. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  56. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  57. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  58. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  59. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  60. package/dist/runtime/attempt-process-supervisor.js +12 -6
  61. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  62. package/dist/runtime/docker-engine-probe.js +7 -0
  63. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  64. package/dist/runtime/dotnet-build-outputs.js +402 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  66. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  67. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  68. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  69. package/dist/runtime/host-facts.d.ts +2 -1
  70. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  71. package/dist/runtime/host-listener-inspector.js +84 -3
  72. package/dist/runtime/host-load-admission.d.ts +72 -0
  73. package/dist/runtime/host-load-admission.js +99 -0
  74. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  75. package/dist/runtime/host-load-child-environment.js +76 -0
  76. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  77. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  78. package/dist/runtime/host-load-governor-config.d.ts +61 -0
  79. package/dist/runtime/host-load-governor-config.js +86 -0
  80. package/dist/runtime/host-load-governor.d.ts +193 -0
  81. package/dist/runtime/host-load-governor.js +662 -0
  82. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  83. package/dist/runtime/host-load-ledger-lock.js +187 -0
  84. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  85. package/dist/runtime/host-load-runtime-settings.js +80 -0
  86. package/dist/runtime/host-load-sampler.d.ts +75 -2
  87. package/dist/runtime/host-load-sampler.js +142 -8
  88. package/dist/runtime/host-load-step-class.d.ts +70 -0
  89. package/dist/runtime/host-load-step-class.js +161 -0
  90. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  91. package/dist/runtime/host-load-step-reaper.js +95 -0
  92. package/dist/runtime/host-load-step-run.d.ts +73 -0
  93. package/dist/runtime/host-load-step-run.js +102 -0
  94. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  95. package/dist/runtime/host-load-test-slot.js +88 -0
  96. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  97. package/dist/runtime/host-load-token-ledger.js +453 -0
  98. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  99. package/dist/runtime/host-load-windows-cpu.js +85 -0
  100. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  101. package/dist/runtime/host-pressure-stall.js +48 -1
  102. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  103. package/dist/runtime/host-runtime-contract.js +33 -2
  104. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  105. package/dist/runtime/host-runtime-lease.js +408 -294
  106. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  107. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  108. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  109. package/dist/runtime/host-runtime-promotion.js +355 -14
  110. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  111. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  112. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  113. package/dist/runtime/host-runtime-requirements.js +117 -0
  114. package/dist/runtime/managed-command-teardown.js +5 -16
  115. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  116. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  117. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  119. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  120. package/dist/runtime/prepared-runtime-identity.js +130 -9
  121. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  122. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  123. package/dist/runtime/runner-settings.d.ts +104 -0
  124. package/dist/runtime/runner-settings.js +236 -0
  125. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  126. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  127. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  128. package/dist/sandbox/host-capacity-broker.js +336 -0
  129. package/dist/sandbox/managed-branch.d.ts +13 -0
  130. package/dist/sandbox/managed-branch.js +90 -0
  131. package/dist/sandbox/provider-auth/codex.js +11 -11
  132. package/dist/sandbox/runtime.d.ts +10 -1
  133. package/dist/sandbox/runtime.js +47 -8
  134. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  135. package/dist/sandbox/sandbox-cgroups.js +42 -0
  136. package/dist/session/architect-waits.d.ts +2 -0
  137. package/dist/session/architect-waits.js +138 -0
  138. package/dist/session/managed-attempt-tools.d.ts +2 -7
  139. package/dist/session/managed-attempt-tools.js +207 -121
  140. package/dist/session/managed-build-coordinator.d.ts +16 -0
  141. package/dist/session/managed-build-coordinator.js +10 -0
  142. package/dist/session/managed-build-receipt.d.ts +5 -0
  143. package/dist/session/managed-build-receipt.js +8 -3
  144. package/dist/session/managed-command-host-load.d.ts +47 -0
  145. package/dist/session/managed-command-host-load.js +83 -0
  146. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  147. package/dist/session/mcp-argument-coercion.js +121 -0
  148. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  149. package/dist/session/phase-completion.artifacts.js +96 -26
  150. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  151. package/dist/session/phase-completion.command-validation.js +77 -0
  152. package/dist/session/phase-completion.d.ts +12 -0
  153. package/dist/session/phase-completion.helpers.js +13 -12
  154. package/dist/session/phase-completion.js +5 -0
  155. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  156. package/dist/session/phase-completion.mcp-args.js +156 -0
  157. package/dist/session/phase-completion.prompts.js +6 -1
  158. package/dist/session/phase-completion.runtime.d.ts +5 -11
  159. package/dist/session/phase-completion.runtime.js +91 -215
  160. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  161. package/dist/session/phase-completion.schema-parts.js +188 -0
  162. package/dist/session/phase-completion.schemas.d.ts +3 -3
  163. package/dist/session/phase-completion.schemas.js +208 -231
  164. package/dist/session/phase-completion.validation.d.ts +2 -3
  165. package/dist/session/phase-completion.validation.js +49 -93
  166. package/dist/session/pre-publication-host-load.d.ts +27 -0
  167. package/dist/session/pre-publication-host-load.js +111 -0
  168. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  169. package/dist/session/pre-publication-native-postgres.js +111 -0
  170. package/dist/session/pre-publication-pass.d.ts +61 -0
  171. package/dist/session/pre-publication-pass.js +148 -0
  172. package/dist/session/pre-publication-process.d.ts +3 -0
  173. package/dist/session/pre-publication-process.js +31 -19
  174. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  175. package/dist/session/pre-publication-step-execution.js +50 -0
  176. package/dist/session/pre-publication-validation.d.ts +37 -21
  177. package/dist/session/pre-publication-validation.js +221 -182
  178. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  179. package/dist/session/provider-cli/claude-background-work.js +181 -0
  180. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  181. package/dist/session/provider-cli/host-build-lock.js +30 -0
  182. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  183. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  185. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  190. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  191. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  192. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  193. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  196. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  197. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  198. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  205. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  206. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  207. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  208. package/dist/session/provider-cli/provider-output-state.js +6 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  211. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  212. package/dist/session/qa-sidecar-validation.js +28 -0
  213. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  214. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  215. package/dist/session/session-redaction.js +31 -181
  216. package/dist/session/session.base.d.ts +9 -1
  217. package/dist/session/session.service.d.ts +15 -2
  218. package/dist/session/session.service.js +246 -88
  219. package/dist/session/session.types.d.ts +4 -0
  220. package/dist/session/session.types.js +7 -7
  221. package/dist/session/sidecar-json-shape.d.ts +31 -0
  222. package/dist/session/sidecar-json-shape.js +217 -0
  223. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  224. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  225. package/dist/shared/fs/file-identity.d.ts +10 -0
  226. package/dist/shared/fs/file-identity.js +15 -0
  227. package/dist/shared/fs/replace-file.d.ts +7 -0
  228. package/dist/shared/fs/replace-file.js +33 -0
  229. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  230. package/dist/shared/process/host-process-recovery.js +23 -3
  231. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  232. package/dist/shared/process/host-process-supervisor.js +67 -15
  233. package/dist/shared/process/process-tree.d.ts +52 -0
  234. package/dist/shared/process/process-tree.js +144 -0
  235. package/dist/shared/process/process.d.ts +67 -0
  236. package/dist/shared/process/process.js +213 -11
  237. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  238. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  239. package/dist/shared/process/windows-launch.d.ts +18 -0
  240. package/dist/shared/process/windows-launch.js +68 -0
  241. package/dist/shared/provider-capabilities.js +14 -7
  242. package/dist/version.d.ts +1 -1
  243. package/dist/version.js +1 -1
  244. package/dist/worktree/dependency-warmer.d.ts +25 -0
  245. package/dist/worktree/dependency-warmer.js +46 -10
  246. package/dist/worktree/orphan-relink.d.ts +19 -0
  247. package/dist/worktree/orphan-relink.js +106 -0
  248. package/dist/worktree/wip-git.d.ts +42 -0
  249. package/dist/worktree/wip-git.js +139 -0
  250. package/dist/worktree/wip-refs.d.ts +77 -0
  251. package/dist/worktree/wip-refs.js +146 -0
  252. package/dist/worktree/wip-restore.d.ts +46 -0
  253. package/dist/worktree/wip-restore.js +280 -0
  254. package/dist/worktree/wip-snapshot.d.ts +53 -0
  255. package/dist/worktree/wip-snapshot.js +270 -0
  256. package/dist/worktree/worktree-inputs.d.ts +8 -0
  257. package/dist/worktree/worktree-inputs.js +134 -0
  258. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  259. package/dist/worktree/worktree-origin-sync.js +128 -0
  260. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  261. package/dist/worktree/worktree-wip-events.js +115 -0
  262. package/dist/worktree/worktree-wip.d.ts +51 -0
  263. package/dist/worktree/worktree-wip.js +190 -0
  264. package/dist/worktree/worktree.base.d.ts +7 -1
  265. package/dist/worktree/worktree.service.d.ts +36 -5
  266. package/dist/worktree/worktree.service.js +126 -155
  267. package/dist/worktree/worktree.types.d.ts +42 -0
  268. package/package.json +2 -2
  269. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -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, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } 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,16 +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
38
  import { HostLoadSampler } from "../runtime/host-load-sampler.js";
37
- import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
39
+ import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
38
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, };
39
45
  /**
40
46
  * Protocol-v2 events are acknowledged one at a time before runOnce returns.
41
47
  * Sending the complete transcript again in DispatchResult made long QA and CI
@@ -63,13 +69,17 @@ export class ForgeBridgeService {
63
69
  leaseWatchdogTimer = null;
64
70
  sandboxMaintenanceTimer = null;
65
71
  sandboxMaintenanceRunning = false;
72
+ attemptSnapshotPending = null;
66
73
  closed = null;
67
74
  transportRecovery = null;
68
75
  transportRecoveryGeneration = 0;
69
76
  stopped = false;
77
+ revokedReason = null;
70
78
  activeSessions = new Map();
71
79
  reservations = new Map();
72
80
  activeReadinessProbes = new Map();
81
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
82
+ inFlight = new BridgeInFlightRegistry();
73
83
  readinessResultOutbox;
74
84
  readinessResultFlush = null;
75
85
  dispatchResultOutbox;
@@ -84,12 +94,44 @@ export class ForgeBridgeService {
84
94
  sessions;
85
95
  enforceHostDatabaseCapabilityBoundary;
86
96
  hostCapabilities = emptyRunnerHostCapabilitySnapshot();
97
+ dockerAvailable = false;
98
+ // Decision 0014 settings push. The last applied server document (null until one
99
+ // arrives: an old server never sends one), the local `forge-bridge yield` flag,
100
+ // and the effective settings computed from both and the host's env bounds.
101
+ appliedSettingsDocument = null;
102
+ localYield = false;
103
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
104
+ forgeAckedYield = false;
105
+ publishState = () => undefined;
106
+ effectiveSettings;
107
+ settingsReport;
108
+ /** Applies run one at a time; offers wait for every apply queued before them. */
109
+ settingsTail = Promise.resolve();
110
+ // Server documents that turn yield on and are queued but not applied yet. The
111
+ // reservation commit is synchronous and can't wait for the apply, so it counts these.
112
+ pendingYieldOn = 0;
113
+ settingsStarted = null;
114
+ hostRequirementFacts() {
115
+ const facts = this.hostLoad.facts();
116
+ return {
117
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
118
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
119
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
120
+ .filter(([, tool]) => tool?.available === true)
121
+ .map(([name]) => name),
122
+ dockerAvailable: this.dockerAvailable,
123
+ browserLaunch: this.hostCapabilities.browserLaunch,
124
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
125
+ };
126
+ }
87
127
  // Reaping deletes the stale ledger, so its stopped-process proof is held here
88
128
  // until a Hello carrying it is accepted. A bridge restart forgets it, which
89
129
  // leaves those attempts on Forge's conservative unknown-outcome path.
90
130
  recoveredHostAttempts = new Map();
91
131
  hostCapabilitiesDetected = false;
92
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
132
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
133
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
134
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
93
135
  this.config = config;
94
136
  this.connections = connections;
95
137
  this.hostCapabilityProbe = hostCapabilityProbe;
@@ -126,14 +168,27 @@ export class ForgeBridgeService {
126
168
  },
127
169
  onStatus: logBridgeStatus,
128
170
  });
129
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
130
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
171
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
172
+ this.sessions = sessions ?? defaultSessions.sessions;
173
+ // Docker sandboxes ask the same host load governor for their validation tokens.
174
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
131
175
  this.sandboxResourceResolver = sandboxResourceResolver
132
176
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
133
177
  this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
134
178
  this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
179
+ // With no server document and no local flag these equal today's env/default behaviour.
180
+ this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
181
+ this.settingsReport = this.effectiveSettings.report;
182
+ this.inFlight.addSource(() => [
183
+ ...reservationInFlightEntries(this.reservations),
184
+ ...sessionInFlightEntries(this.activeSessions),
185
+ ...readinessInFlightEntries(this.activeReadinessProbes),
186
+ ]);
135
187
  }
136
188
  async connectOnce() {
189
+ if (this.revokedReason !== null) {
190
+ throw new BridgeRevokedError(this.revokedReason);
191
+ }
137
192
  await this.stopConnection();
138
193
  this.stopped = false;
139
194
  if (this.enforceHostDatabaseCapabilityBoundary) {
@@ -162,6 +217,8 @@ export class ForgeBridgeService {
162
217
  // Static host facts and the first load sample ride on Hello; the sampler
163
218
  // keeps refreshing its cached snapshot for later heartbeats.
164
219
  await this.hostLoad.start().catch(() => undefined);
220
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
221
+ await this.startSettings();
165
222
  const connection = this.connections.create(this.config);
166
223
  this.connection = connection;
167
224
  this.transportRecovery = null;
@@ -203,14 +260,16 @@ export class ForgeBridgeService {
203
260
  await connection.stop().catch(() => undefined);
204
261
  }
205
262
  });
206
- connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
207
- connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
208
- connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
209
- connection.onStart?.((dispatch) => this.handleStart(dispatch));
263
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
264
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
265
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
266
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
210
267
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
211
268
  connection.onCancel((request) => this.handleCancel(request));
212
269
  connection.onReap?.((request) => this.handleReap(request));
213
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
270
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
271
+ connection.onRevoked?.((notice) => this.handleRevoked(notice));
272
+ connection.onApplySettings?.((document) => this.handleApplySettings(document));
214
273
  await connection.start();
215
274
  await this.registerConnection(connection);
216
275
  await this.flushDispatchResults(true).catch(error => {
@@ -247,6 +306,7 @@ export class ForgeBridgeService {
247
306
  while (true) {
248
307
  try {
249
308
  const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
309
+ const reportedYield = this.settingsReport.values.yieldToForeground;
250
310
  const ack = await connection.invoke("Hello", {
251
311
  version: this.config.version,
252
312
  protocolVersion: this.config.protocolVersion,
@@ -259,6 +319,7 @@ export class ForgeBridgeService {
259
319
  throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
260
320
  }
261
321
  this.recoveredHostAttempts.clear();
322
+ this.ackYield(reportedYield);
262
323
  logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
263
324
  return;
264
325
  }
@@ -274,6 +335,7 @@ export class ForgeBridgeService {
274
335
  }
275
336
  }
276
337
  async run(signal) {
338
+ const statePublisher = await this.startStatePublisher();
277
339
  let attempt = 0;
278
340
  try {
279
341
  while (!this.stopped && !signal?.aborted) {
@@ -289,7 +351,7 @@ export class ForgeBridgeService {
289
351
  }
290
352
  }
291
353
  catch (error) {
292
- if (this.stopped || signal?.aborted) {
354
+ if (this.stopped || signal?.aborted || this.revokedReason !== null) {
293
355
  break;
294
356
  }
295
357
  const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
@@ -305,6 +367,214 @@ export class ForgeBridgeService {
305
367
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
306
368
  }
307
369
  await this.stopConnection();
370
+ await statePublisher?.stop();
371
+ }
372
+ if (this.revokedReason !== null) {
373
+ throw new BridgeRevokedError(this.revokedReason);
374
+ }
375
+ }
376
+ async startStatePublisher() {
377
+ if (!this.config.bridgeStatePath)
378
+ return null;
379
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
380
+ inFlight: () => this.inFlight.snapshot(),
381
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
382
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
383
+ yieldApplied: () => this.effectiveSettings.yielding,
384
+ connected: () => this.connection !== null && this.transportRecovery === null,
385
+ }, { log: logBridgeStatus });
386
+ this.publishState = () => void publisher.publish();
387
+ this.inFlight.onChange(this.publishState);
388
+ await publisher.start();
389
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
390
+ return publisher;
391
+ }
392
+ /** The reason Forge gave when it removed this runner, or null while it is paired. */
393
+ get revoked() {
394
+ return this.revokedReason;
395
+ }
396
+ /**
397
+ * Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
398
+ * reconnecting; its attempts were already settled on the server, so local work is
399
+ * aborted rather than reported.
400
+ */
401
+ handleRevoked(notice) {
402
+ if (this.revokedReason !== null)
403
+ return;
404
+ const reason = typeof notice?.reason === "string" && notice.reason.trim()
405
+ ? notice.reason.trim()
406
+ : bridgeRevokedMessage;
407
+ this.revokedReason = reason;
408
+ this.stopped = true;
409
+ logBridgeStatus(reason);
410
+ this.abortActiveSessions("runner removed from Forge");
411
+ this.abortActiveReadinessProbes("runner removed from Forge");
412
+ void this.stopConnection().catch(() => undefined);
413
+ }
414
+ /** The effective settings and how they were derived, as last reported (decision 0014). */
415
+ get runnerSettings() {
416
+ return this.settingsReport;
417
+ }
418
+ runnerHostDefaults() {
419
+ return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
420
+ }
421
+ /**
422
+ * Once per bridge process: drop governor overrides an earlier process left on
423
+ * the state root, then put today's effective settings (env bounds and the local
424
+ * yield flag, no server document yet) in force.
425
+ */
426
+ async startSettings() {
427
+ this.settingsStarted ??= (async () => {
428
+ await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
429
+ logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
430
+ });
431
+ this.localYield = await this.readLocalYield();
432
+ await this.enqueueSettings({ kind: "local" });
433
+ })();
434
+ await this.settingsStarted;
435
+ }
436
+ /**
437
+ * Decision 0014 `ApplySettings`. Applies only a document newer than the one
438
+ * applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
439
+ * the applied version is acknowledged again without applying it; an older one is
440
+ * ignored.
441
+ */
442
+ async handleApplySettings(raw) {
443
+ const document = parseRunnerSettingsDocument(raw);
444
+ if (!document) {
445
+ logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
446
+ return;
447
+ }
448
+ if (document.runnerId && document.runnerId !== this.config.runnerId) {
449
+ logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
450
+ return;
451
+ }
452
+ await this.enqueueSettings({ kind: "server", document });
453
+ }
454
+ /**
455
+ * Polls the local `forge-bridge yield` flag (every heartbeat and before each
456
+ * offer decision). A change is applied at once and reported again under the
457
+ * same settings version.
458
+ */
459
+ /** Yielding now, or about to: a received yield-on that is still being applied counts. */
460
+ yieldingOrQueued() {
461
+ return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
462
+ }
463
+ async refreshLocalYield() {
464
+ if (!this.config.localYieldFlagPath)
465
+ return;
466
+ const localYield = await this.readLocalYield();
467
+ if (localYield === this.localYield)
468
+ return;
469
+ this.localYield = localYield;
470
+ logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
471
+ await this.enqueueSettings({ kind: "local" });
472
+ }
473
+ /**
474
+ * A setting the host couldn't put in force holds placement on the server, so
475
+ * every heartbeat tries the applied document again until it takes.
476
+ */
477
+ async retryFailedSettings() {
478
+ if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
479
+ return;
480
+ await this.enqueueSettings({ kind: "local" });
481
+ }
482
+ async readLocalYield() {
483
+ const flagPath = this.config.localYieldFlagPath;
484
+ return flagPath ? await readLocalYieldFlag(flagPath) : false;
485
+ }
486
+ enqueueSettings(change) {
487
+ const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
488
+ if (turnsYieldOn)
489
+ this.pendingYieldOn += 1;
490
+ const applied = this.settingsTail
491
+ .then(() => this.applySettings(change))
492
+ .finally(() => {
493
+ if (turnsYieldOn)
494
+ this.pendingYieldOn -= 1;
495
+ });
496
+ // A failed apply must not wedge later applies or the offers waiting on them.
497
+ this.settingsTail = applied.catch(error => {
498
+ logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
499
+ });
500
+ return this.settingsTail;
501
+ }
502
+ async applySettings(change) {
503
+ const applied = this.appliedSettingsDocument;
504
+ if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
505
+ if (change.document.version === applied.version) {
506
+ // The server sends the current version again at each Hello. After a reconnect it may never
507
+ // have seen this version's ack (the old connection dropped first), and its offer gate waits
508
+ // for one from this connection, so acknowledge what is in force again rather than nothing.
509
+ void this.sendSettingsApplied(this.settingsReport);
510
+ return;
511
+ }
512
+ logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
513
+ return;
514
+ }
515
+ const document = change.kind === "server" ? change.document : applied;
516
+ const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
517
+ const failures = await this.putSettingsInForce(effective);
518
+ // Report what is in force: a key the host couldn't take keeps its previous value.
519
+ const report = {
520
+ ...runnerSettingsInForce(effective.report, this.settingsReport, failures),
521
+ version: document?.version ?? null,
522
+ };
523
+ const changed = !sameRunnerSettingsReport(report, this.settingsReport);
524
+ this.appliedSettingsDocument = document;
525
+ this.effectiveSettings = effective;
526
+ this.settingsReport = report;
527
+ this.publishState();
528
+ if (change.kind === "server") {
529
+ logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
530
+ }
531
+ // Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
532
+ if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
533
+ void this.sendSettingsApplied(report);
534
+ }
535
+ }
536
+ /**
537
+ * Max attempts and the memory reserve go to host attempt admission; the governor
538
+ * budget (the yield budget while yielding) and the heavy-step limit go to the
539
+ * shared settings file every governor on the state root reads at admission.
540
+ * Neither touches admitted work. Returns the keys the host could not put in
541
+ * force (`apply_failed`); their previous values stay in force.
542
+ */
543
+ async putSettingsInForce(effective) {
544
+ const { values } = effective.report;
545
+ const rejected = [];
546
+ try {
547
+ await this.sessions.applyRunnerLimits?.({
548
+ maxConcurrentAttempts: values.maxConcurrentAttempts,
549
+ memoryReserveBytes: values.memoryReserveBytes,
550
+ });
551
+ }
552
+ catch (error) {
553
+ const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
554
+ rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
555
+ }
556
+ try {
557
+ await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
558
+ cpuBudgetFraction: effective.governorCpuBudgetFraction,
559
+ maxHeavySteps: values.maxHeavySteps,
560
+ yielding: effective.yielding,
561
+ });
562
+ }
563
+ catch (error) {
564
+ const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
565
+ rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
566
+ }
567
+ return rejected;
568
+ }
569
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
570
+ /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
571
+ async sendSettingsApplied(report) {
572
+ try {
573
+ await this.invokeAck("SettingsApplied", report);
574
+ this.ackYield(report.values.yieldToForeground);
575
+ }
576
+ catch (error) {
577
+ logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
308
578
  }
309
579
  }
310
580
  async stop() {
@@ -434,9 +704,18 @@ export class ForgeBridgeService {
434
704
  await fs.promises.mkdir(root, { recursive: true });
435
705
  return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
436
706
  }
707
+ /** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
708
+ async lookAtChatGiphyFrames(packet, active, cwd) {
709
+ return await lookAtChatGiphyFrames(packet, cwd, {
710
+ runner: this.chatProcessRunner,
711
+ signal: active.controller.signal,
712
+ log: logBridgeStatus,
713
+ takeFrames: async (request) => await this.connection?.invoke(chatTurnGiphyFramesMethod, request) ?? { accepted: false },
714
+ });
715
+ }
437
716
  async runChatProviderProcess(packet, active, cwd) {
438
717
  const output = createProviderOutputState(packet.providerKind);
439
- const plan = buildChatProviderCommand(packet, cwd);
718
+ const plan = buildChatProviderCommand(packet, cwd, await this.lookAtChatGiphyFrames(packet, active, cwd));
440
719
  const redactionSecrets = chatRedactionSecrets(packet);
441
720
  let started = false;
442
721
  const result = await this.chatProcessRunner.run({
@@ -446,6 +725,7 @@ export class ForgeBridgeService {
446
725
  env: {
447
726
  FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
448
727
  FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
728
+ ...plan.env,
449
729
  },
450
730
  stdin: plan.stdin,
451
731
  }, {
@@ -472,6 +752,7 @@ export class ForgeBridgeService {
472
752
  content: "Bridge Chat provider process exited.",
473
753
  }).catch(() => undefined);
474
754
  }
755
+ assertChatTurnFinished(result);
475
756
  return { command: plan.command, output, result };
476
757
  }
477
758
  async sendChatProviderEvent(packet, active, event, providerThreadId) {
@@ -657,19 +938,7 @@ export class ForgeBridgeService {
657
938
  return;
658
939
  }
659
940
  const controller = reservationHandoff?.controller ?? new AbortController();
660
- this.activeSessions.set(leaseId, {
661
- leaseId,
662
- kind: "dispatch",
663
- fencingToken,
664
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
665
- runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
666
- leaseExpiresAt: dispatch.lease.expiresAt,
667
- sandboxed: dispatch.sandbox?.executionMode === "docker",
668
- resources: dispatch.sandbox?.executionMode === "docker"
669
- ? dispatch.sandbox.requestedResources
670
- : zeroSandboxResources(),
671
- controller
672
- });
941
+ this.registerActiveDispatch(dispatch, controller);
673
942
  if (reservationHandoff) {
674
943
  // Promotion is synchronous with active-session registration. A qualified
675
944
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -693,43 +962,10 @@ export class ForgeBridgeService {
693
962
  };
694
963
  await this.invokeAck("DispatchStarted", started);
695
964
  }
696
- const sink = {
697
- emit: async (event) => {
698
- if (event.eventType === "provider_cli_started") {
699
- const active = this.activeSessions.get(leaseId);
700
- if (active)
701
- active.resources = { ...active.resources, buildSlots: 0 };
702
- }
703
- try {
704
- await this.invokeAck("DispatchEvent", {
705
- leaseId,
706
- fencingToken,
707
- ...(dispatch.sandbox ? {
708
- dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
709
- runnerInstanceId: dispatch.sandbox.runnerInstanceId
710
- } : {}),
711
- event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
712
- }, {
713
- replayCallbackTimeout: true,
714
- signal: controller.signal,
715
- });
716
- }
717
- catch (error) {
718
- if (isDispatchNoLongerPending(error)) {
719
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
720
- return;
721
- }
722
- throw error;
723
- }
724
- }
725
- };
726
- const result = normalized.sandbox?.executionMode === "docker"
727
- ? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
728
- : await this.sessions.runOnce(normalized, sink, controller.signal);
729
- if (normalized.sandbox?.executionMode === "docker") {
730
- await this.flushCleanupReports().catch(() => undefined);
731
- }
965
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
966
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
732
967
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
968
+ this.inFlight.notePhase(leaseId, "result_delivery");
733
969
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
734
970
  }
735
971
  catch (error) {
@@ -753,6 +989,77 @@ export class ForgeBridgeService {
753
989
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
754
990
  }
755
991
  }
992
+ registerActiveDispatch(dispatch, controller) {
993
+ this.activeSessions.set(dispatch.lease.id, {
994
+ leaseId: dispatch.lease.id,
995
+ kind: "dispatch",
996
+ fencingToken: dispatch.lease.fencingToken,
997
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
998
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
999
+ leaseExpiresAt: dispatch.lease.expiresAt,
1000
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
1001
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
1002
+ controller
1003
+ });
1004
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
1005
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
1006
+ }
1007
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
1008
+ const leaseId = dispatch.lease.id;
1009
+ return {
1010
+ emit: async (event) => {
1011
+ this.inFlight.notePhase(leaseId, event.eventType);
1012
+ if (event.eventType === "provider_cli_started") {
1013
+ const active = this.activeSessions.get(leaseId);
1014
+ if (active)
1015
+ active.resources = { ...active.resources, buildSlots: 0 };
1016
+ }
1017
+ try {
1018
+ await this.invokeAck("DispatchEvent", {
1019
+ leaseId,
1020
+ fencingToken: dispatch.lease.fencingToken,
1021
+ ...(dispatch.sandbox ? {
1022
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1023
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1024
+ } : {}),
1025
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1026
+ }, {
1027
+ replayCallbackTimeout: true,
1028
+ signal: controller.signal,
1029
+ });
1030
+ }
1031
+ catch (error) {
1032
+ if (isDispatchNoLongerPending(error)) {
1033
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1034
+ return;
1035
+ }
1036
+ throw error;
1037
+ }
1038
+ }
1039
+ };
1040
+ }
1041
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1042
+ async runDispatchOnce(dispatch, sink, signal) {
1043
+ const docker = dispatch.sandbox?.executionMode === "docker";
1044
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1045
+ const startedAt = Date.now();
1046
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1047
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1048
+ try {
1049
+ const result = docker
1050
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1051
+ : await this.sessions.runOnce(dispatch, sink, signal);
1052
+ if (docker) {
1053
+ await this.flushCleanupReports().catch(() => undefined);
1054
+ }
1055
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1056
+ return result;
1057
+ }
1058
+ catch (error) {
1059
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1060
+ throw error;
1061
+ }
1062
+ }
756
1063
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
757
1064
  const sandbox = dispatch.sandbox;
758
1065
  const reservation = handoff.reservation;
@@ -840,6 +1147,16 @@ export class ForgeBridgeService {
840
1147
  await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
841
1148
  return;
842
1149
  }
1150
+ // Decision 0014: decide under the settings Forge sent (an offer never races an
1151
+ // apply), and refuse new work while yielding to the foreground. The local flag
1152
+ // is read here too, before Forge has heard about it.
1153
+ await this.refreshLocalYield().catch(() => undefined);
1154
+ // Every apply queued so far, including one a concurrent offer or heartbeat started.
1155
+ await this.settingsTail;
1156
+ if (this.effectiveSettings.yielding) {
1157
+ await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
1158
+ return;
1159
+ }
843
1160
  const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
844
1161
  ? await this.preflight.run()
845
1162
  : this.preflight.current();
@@ -924,6 +1241,11 @@ export class ForgeBridgeService {
924
1241
  if (Date.parse(dispatch.lease.expiresAt) <= now) {
925
1242
  return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
926
1243
  }
1244
+ // Yield may have turned on while the offer was being profiled, including a
1245
+ // yield Forge sent or the local flag set that hasn't finished applying yet.
1246
+ if (this.yieldingOrQueued()) {
1247
+ return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
1248
+ }
927
1249
  if (sandbox.executionMode === "docker") {
928
1250
  // A concurrent heartbeat/preflight refresh may have produced a newer
929
1251
  // conservative dual-domain sample while this offer was being profiled.
@@ -1099,6 +1421,8 @@ export class ForgeBridgeService {
1099
1421
  reservedResources: accepted ? reservedResources : null,
1100
1422
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1101
1423
  };
1424
+ if (accepted)
1425
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1102
1426
  await this.invokeAck("OfferDecision", payload);
1103
1427
  }
1104
1428
  async parseDispatchOrReport(rawDispatch) {
@@ -1212,7 +1536,13 @@ export class ForgeBridgeService {
1212
1536
  acceptedAt: new Date().toISOString(),
1213
1537
  };
1214
1538
  await this.invokeAck("ReadinessAccepted", accepted);
1215
- if (this.activeSessions.size > 0) {
1539
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1540
+ await this.refreshLocalYield().catch(() => undefined);
1541
+ await this.settingsTail;
1542
+ if (this.yieldingOrQueued()) {
1543
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1544
+ }
1545
+ else if (this.activeSessions.size > 0) {
1216
1546
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1217
1547
  }
1218
1548
  else if (!this.sessions.probeHostRuntime) {
@@ -1535,6 +1865,9 @@ export class ForgeBridgeService {
1535
1865
  // force reconnects. Transport failures still do.
1536
1866
  await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
1537
1867
  await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
1868
+ // The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
1869
+ await this.refreshLocalYield().catch(() => undefined);
1870
+ await this.retryFailedSettings().catch(() => undefined);
1538
1871
  await this.sendHeartbeat();
1539
1872
  this.consecutiveHeartbeatFailures = 0;
1540
1873
  }
@@ -1590,7 +1923,8 @@ export class ForgeBridgeService {
1590
1923
  startSandboxMaintenance() {
1591
1924
  this.stopSandboxMaintenance();
1592
1925
  this.sandboxMaintenanceTimer = setInterval(() => {
1593
- this.runSandboxMaintenance().catch(() => undefined);
1926
+ this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
1927
+ logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
1594
1928
  }, 60_000);
1595
1929
  this.sandboxMaintenanceTimer.unref?.();
1596
1930
  }
@@ -1630,9 +1964,15 @@ export class ForgeBridgeService {
1630
1964
  const connection = this.connection;
1631
1965
  if (!connection)
1632
1966
  throw new Error("Bridge is not connected.");
1633
- const response = await connection.invoke("AttemptSnapshot", {
1634
- runnerInstanceId: this.config.runnerInstanceId
1635
- });
1967
+ // Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
1968
+ const pending = { connection, generation: this.transportRecoveryGeneration };
1969
+ if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
1970
+ throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
1971
+ this.attemptSnapshotPending = pending;
1972
+ const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
1973
+ invocation.finally(() => { if (this.attemptSnapshotPending === pending)
1974
+ this.attemptSnapshotPending = null; }).catch(() => undefined);
1975
+ const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
1636
1976
  if (!response.accepted) {
1637
1977
  throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
1638
1978
  }
@@ -1667,16 +2007,19 @@ export class ForgeBridgeService {
1667
2007
  await this.sendHeartbeatSnapshot();
1668
2008
  }
1669
2009
  async sendHeartbeatSnapshot(signal) {
2010
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1670
2011
  await this.invokeAck("Heartbeat", {
1671
2012
  status: "online",
1672
2013
  capabilities: this.capabilities(),
1673
2014
  version: this.config.version,
1674
2015
  protocolVersion: this.config.protocolVersion
1675
2016
  }, { signal });
2017
+ this.ackYield(reportedYield);
1676
2018
  }
1677
2019
  capabilities() {
1678
2020
  const preflight = this.preflight.current();
1679
2021
  const dockerEngine = this.dockerEngineProbe.current();
2022
+ this.dockerAvailable = dockerEngine?.available === true;
1680
2023
  const runtimeState = this.sandboxRuntime.snapshot();
1681
2024
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
1682
2025
  const used = this.usedSandboxResources(runtimeState.degraded);
@@ -1693,7 +2036,7 @@ export class ForgeBridgeService {
1693
2036
  pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
1694
2037
  }) : null;
1695
2038
  return {
1696
- schemaVersion: 7,
2039
+ schemaVersion: 8,
1697
2040
  activeSessionCount: this.activeSessions.size,
1698
2041
  cliProviders: this.config.cliProviders,
1699
2042
  providerStatuses: this.config.providerStatuses,
@@ -1716,6 +2059,7 @@ export class ForgeBridgeService {
1716
2059
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1717
2060
  browserLaunch: this.hostCapabilities.browserLaunch,
1718
2061
  providerConnectivity: this.hostCapabilities.providerConnectivity,
2062
+ testPostgres: this.hostCapabilities.testPostgres,
1719
2063
  host: this.hostLoad.facts(),
1720
2064
  load: this.hostLoad.current(),
1721
2065
  maxConcurrentSandboxes: capacity.sandboxSlots,
@@ -1757,7 +2101,8 @@ export class ForgeBridgeService {
1757
2101
  supportsDraftRunOnce: this.config.supportsDraftRunOnce,
1758
2102
  supportsDraftAttachments: this.config.supportsDraftAttachments,
1759
2103
  supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
1760
- bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
2104
+ bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
2105
+ settings: { supportsServerSettings: true, ...this.settingsReport },
1761
2106
  };
1762
2107
  }
1763
2108
  async requiredCapabilityFailure(dispatch) {
@@ -1911,6 +2256,16 @@ export class ForgeBridgeService {
1911
2256
  }
1912
2257
  }
1913
2258
  }
2259
+ /** The `run` command's exit code after Forge removed the runner. */
2260
+ export const bridgeRevokedExitCode = 3;
2261
+ export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
2262
+ /** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
2263
+ export class BridgeRevokedError extends Error {
2264
+ constructor(message = bridgeRevokedMessage) {
2265
+ super(message);
2266
+ this.name = "BridgeRevokedError";
2267
+ }
2268
+ }
1914
2269
  class BridgeCallbackRejectedError extends Error {
1915
2270
  code;
1916
2271
  constructor(code, message) {
@@ -1944,11 +2299,13 @@ function isProviderStorageUnavailable(error) {
1944
2299
  function isBridgeCallbackTimeout(error) {
1945
2300
  return errorMessage(error).startsWith("bridge_callback_timeout:");
1946
2301
  }
1947
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
2302
+ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
1948
2303
  const rawProcessRunner = new StreamingProviderProcessRunner();
1949
2304
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1950
2305
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
1951
- 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)));
2306
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2307
+ 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);
2308
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
1952
2309
  }
1953
2310
  export class SignalRBridgeConnectionFactory {
1954
2311
  create(config) {
@@ -1979,6 +2336,18 @@ export class SignalRBridgeConnection {
1979
2336
  void this.connection.stop().catch(() => undefined);
1980
2337
  });
1981
2338
  }
2339
+ onApplySettings(handler) {
2340
+ this.connection.on("ApplySettings", (raw) => {
2341
+ void Promise.resolve(handler(raw)).catch(() => undefined);
2342
+ });
2343
+ }
2344
+ onRevoked(handler) {
2345
+ this.connection.on("Revoked", (raw) => {
2346
+ const notice = raw && typeof raw === "object" ? raw : {};
2347
+ handler(notice);
2348
+ void this.connection.stop().catch(() => undefined);
2349
+ });
2350
+ }
1982
2351
  start() {
1983
2352
  return this.connection.start();
1984
2353
  }
@@ -2319,10 +2688,7 @@ function errorMessage(error) {
2319
2688
  return error instanceof Error ? error.message : String(error);
2320
2689
  }
2321
2690
  function formatDelay(ms) {
2322
- if (ms >= 1000 && ms % 1000 === 0) {
2323
- return `${ms / 1000}s`;
2324
- }
2325
- return `${ms}ms`;
2691
+ return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
2326
2692
  }
2327
2693
  async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
2328
2694
  let timeout = null;
@@ -2391,36 +2757,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2391
2757
  const maxChatEventContentChars = 4000;
2392
2758
  const maxChatTerminalTextChars = 120_000;
2393
2759
  const maxChatExactSecretChars = 8 * 1024;
2394
- const chatTurnMetadataFileName = "forge-chat-metadata.json";
2395
- async function materializeChatTurnMetadata(packet, workspacePath) {
2396
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2397
- return;
2398
- }
2399
- await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
2400
- schemaVersion: 1,
2401
- attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
2402
- turnId: handoff.turnId,
2403
- attachmentId: handoff.attachmentId,
2404
- tempFileToken: handoff.tempFileToken,
2405
- mimeType: handoff.mimeType,
2406
- sizeBytes: handoff.sizeBytes,
2407
- sha256: handoff.sha256,
2408
- fileNameDisplay: handoff.fileNameDisplay,
2409
- expiresAt: handoff.expiresAt,
2410
- status: handoff.status,
2411
- })),
2412
- actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
2413
- grantId: grant.grantId,
2414
- turnId: grant.turnId,
2415
- leaseId: grant.leaseId,
2416
- fencingToken: grant.fencingToken,
2417
- allowedScopes: grant.allowedScopes,
2418
- expiresAt: grant.expiresAt,
2419
- redactionStatus: grant.redactionStatus,
2420
- nonceHeldByBridge: true,
2421
- })),
2422
- }, null, 2)}\n`, "utf8");
2423
- }
2424
2760
  function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
2425
2761
  const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
2426
2762
  const metadataExpiresAtMs = [
@@ -2451,113 +2787,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
2451
2787
  };
2452
2788
  }
2453
2789
  }
2454
- function buildChatProviderCommand(packet, cwd) {
2455
- const provider = packet.providerKind.trim().toLowerCase();
2456
- const model = packet.model.trim();
2457
- const prompt = buildChatPrompt(packet);
2458
- const resumeThreadId = packet.providerThreadId?.trim() || null;
2459
- if (provider === "codex") {
2460
- const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
2461
- if (resumeThreadId) {
2462
- args.push("--cd", cwd, "resume");
2463
- }
2464
- args.push("--model", model, "--json");
2465
- if (!resumeThreadId) {
2466
- args.push("--cd", cwd);
2467
- }
2468
- args.push("--skip-git-repo-check");
2469
- if (resumeThreadId) {
2470
- args.push(resumeThreadId);
2471
- }
2472
- args.push("-");
2473
- return { command: { command: "codex", args }, stdin: prompt };
2474
- }
2475
- if (provider === "cursor") {
2476
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
2477
- if (resumeThreadId) {
2478
- args.push("--resume", resumeThreadId);
2479
- }
2480
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
2481
- return { command: { command: "cursor-agent", args } };
2482
- }
2483
- if (provider === "claude") {
2484
- const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
2485
- if (resumeThreadId) {
2486
- args.push("--resume", resumeThreadId);
2487
- }
2488
- return { command: { command: "claude", args }, stdin: prompt };
2489
- }
2490
- return {
2491
- command: {
2492
- command: provider,
2493
- args: ["--model", model, prompt],
2494
- },
2495
- };
2496
- }
2497
- function buildChatPrompt(packet) {
2498
- const messages = packet.messages
2499
- .map((message, index) => {
2500
- const role = message.role.trim() || `message-${index + 1}`;
2501
- return `[${role}]\n${message.content}`;
2502
- })
2503
- .join("\n\n");
2504
- const contextRefs = packet.contextRefs.length === 0
2505
- ? ""
2506
- : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
2507
- const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
2508
- const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
2509
- return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
2510
- }).join("\n\n")}`;
2511
- const continuation = packet.providerThreadId
2512
- ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
2513
- : "";
2514
- const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
2515
- return `You are handling a Forge Bridge Chat turn.
2516
-
2517
- Conversation ID: ${packet.conversationId}
2518
- Turn ID: ${packet.turnId}
2519
- Provider: ${packet.providerKind}
2520
- Model: ${packet.model}${continuation}${boundedMetadata}
2521
-
2522
- # Conversation
2523
-
2524
- ${messages}${contextRefs}
2525
- `;
2526
- }
2527
- function buildChatBoundedMetadataPrompt(packet) {
2528
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2529
- return "";
2530
- }
2531
- const sections = [
2532
- `\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.`,
2533
- ];
2534
- if (packet.attachmentHandoffs.length > 0) {
2535
- sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
2536
- `${index + 1}. turnId: ${handoff.turnId}`,
2537
- ` attachmentId: ${handoff.attachmentId}`,
2538
- ` tempFileToken: ${handoff.tempFileToken}`,
2539
- ` mimeType: ${handoff.mimeType}`,
2540
- ` sizeBytes: ${handoff.sizeBytes}`,
2541
- ` sha256: ${handoff.sha256}`,
2542
- ` fileNameDisplay: ${handoff.fileNameDisplay}`,
2543
- ` expiresAt: ${handoff.expiresAt}`,
2544
- ` status: ${handoff.status}`,
2545
- ].join("\n")).join("\n\n")}`);
2546
- }
2547
- if (packet.actionBrokerGrants.length > 0) {
2548
- sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
2549
- `${index + 1}. grantId: ${grant.grantId}`,
2550
- ` turnId: ${grant.turnId}`,
2551
- ` leaseId: ${grant.leaseId}`,
2552
- ` fencingToken: ${grant.fencingToken}`,
2553
- ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
2554
- ` expiresAt: ${grant.expiresAt}`,
2555
- ` redactionStatus: ${grant.redactionStatus}`,
2556
- " nonce: held by bridge",
2557
- ].join("\n")).join("\n\n")}`);
2558
- }
2559
- return sections.join("\n\n");
2560
- }
2561
2790
  function chatProviderExitFailure(command, result, redactionSecrets) {
2562
2791
  const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
2563
2792
  const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
@@ -2701,24 +2930,6 @@ function parseReadinessProbe(value) {
2701
2930
  }
2702
2931
  return request;
2703
2932
  }
2704
- function deferredReadinessResult(request, runnerInstanceId) {
2705
- return {
2706
- schemaVersion: 1,
2707
- requestId: request.requestId,
2708
- fencingToken: request.fencingToken,
2709
- runnerInstanceId,
2710
- status: "failed",
2711
- reasonCode: "host_runtime_probe_deferred",
2712
- reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
2713
- checkedAt: new Date().toISOString(),
2714
- };
2715
- }
2716
- function readinessDeferralReason(signal) {
2717
- if (!signal.aborted)
2718
- return null;
2719
- const reason = errorMessage(signal.reason);
2720
- return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
2721
- }
2722
2933
  function sandboxProviderNetworkFailure(dispatch, config) {
2723
2934
  const sandbox = dispatch.sandbox;
2724
2935
  if (!sandbox || sandbox.networkPolicy.mode !== "offline")
@@ -2757,151 +2968,6 @@ function rejectedOfferReservation(code, message) {
2757
2968
  resources: null,
2758
2969
  };
2759
2970
  }
2760
- export function canReserveSandboxResources(used, requested, capacity) {
2761
- return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
2762
- && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
2763
- && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
2764
- && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
2765
- && used.pids + requested.pids <= capacity.pids
2766
- && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
2767
- }
2768
- export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
2769
- const ambientCapacity = preflight.availableMemoryBytes
2770
- - preflight.hostReserveBytes
2771
- + activeMemoryBytes;
2772
- const commitmentCapacity = preflight.totalMemoryBytes
2773
- - preflight.hostReserveBytes;
2774
- return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
2775
- }
2776
- export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
2777
- const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
2778
- if (requested.sandboxSlots > availableSlots) {
2779
- return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
2780
- }
2781
- const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
2782
- if (requested.memoryBytes > availableMemoryBytes) {
2783
- return [
2784
- `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
2785
- `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
2786
- `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
2787
- `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
2788
- `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
2789
- ].join(" ");
2790
- }
2791
- const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
2792
- if (requested.cpuMillis > availableCpuMillis) {
2793
- return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
2794
- }
2795
- const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
2796
- if (requested.workspaceBytes > availableWorkspaceBytes) {
2797
- return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
2798
- }
2799
- const availablePids = Math.max(0, capacity.pids - used.pids);
2800
- if (requested.pids > availablePids) {
2801
- return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
2802
- }
2803
- const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
2804
- return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
2805
- }
2806
- function sumSandboxResources(resources) {
2807
- return resources.reduce((total, resource) => ({
2808
- sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
2809
- cpuMillis: total.cpuMillis + resource.cpuMillis,
2810
- workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
2811
- serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
2812
- runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
2813
- memoryBytes: total.memoryBytes + resource.memoryBytes,
2814
- workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
2815
- pids: total.pids + resource.pids,
2816
- buildSlots: total.buildSlots + resource.buildSlots
2817
- }), zeroSandboxResources());
2818
- }
2819
- function zeroSandboxResources() {
2820
- return {
2821
- sandboxSlots: 0,
2822
- cpuMillis: 0,
2823
- workerMemoryLimitBytes: 0,
2824
- serviceMemoryLimitBytes: 0,
2825
- runtimeOverheadBytes: 0,
2826
- memoryBytes: 0,
2827
- workspaceBytes: 0,
2828
- pids: 0,
2829
- buildSlots: 0,
2830
- };
2831
- }
2832
- function defaultSandboxResources() {
2833
- return {
2834
- sandboxSlots: 1,
2835
- cpuMillis: 2000,
2836
- workerMemoryLimitBytes: 2 * 1024 ** 3,
2837
- serviceMemoryLimitBytes: 0,
2838
- runtimeOverheadBytes: 128 * 1024 ** 2,
2839
- memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
2840
- workspaceBytes: 10 * 1024 ** 3,
2841
- pids: 512,
2842
- buildSlots: 0
2843
- };
2844
- }
2845
- export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
2846
- const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
2847
- const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
2848
- + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
2849
- return {
2850
- ...requested,
2851
- serviceMemoryLimitBytes,
2852
- runtimeOverheadBytes,
2853
- memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
2854
- };
2855
- }
2856
- export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
2857
- const repoPath = dispatch.repo.serverLocalPath;
2858
- const sandbox = dispatch.sandbox;
2859
- if (!repoPath || !sandbox) {
2860
- throw new Error("Sandbox admission needs a mapped repository.");
2861
- }
2862
- const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
2863
- const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
2864
- if (!configCommitSha) {
2865
- throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
2866
- }
2867
- const contractResult = await runSandboxProcess({
2868
- command: "git",
2869
- args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
2870
- timeoutMs: 30_000,
2871
- maxOutputBytes: 1024 * 1024,
2872
- });
2873
- if (contractResult.exitCode !== 0) {
2874
- throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
2875
- }
2876
- const contract = validateSandboxContract(contractResult.stdout);
2877
- const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
2878
- role: dispatch.execution.role,
2879
- serviceCount: contract.contract.services.length,
2880
- browser: contract.contract.browser,
2881
- });
2882
- return {
2883
- resources: resolveDynamicSandboxResources({
2884
- ...sandbox.requestedResources,
2885
- workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
2886
- }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
2887
- sandboxConfigCommitSha: configCommitSha,
2888
- };
2889
- }
2890
- async function resolveFirstGitCommit(repoPath, refs) {
2891
- for (const ref of refs) {
2892
- const result = await runSandboxProcess({
2893
- command: "git",
2894
- args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
2895
- timeoutMs: 30_000,
2896
- maxOutputBytes: 1024 * 1024,
2897
- });
2898
- const commitSha = result.stdout.trim().toLowerCase();
2899
- if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
2900
- return commitSha;
2901
- }
2902
- }
2903
- return null;
2904
- }
2905
2971
  function parseOfferEnvelope(value) {
2906
2972
  return parseDispatchEnvelope(value);
2907
2973
  }