@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  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 +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  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 +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -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.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  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-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -1,46 +1,42 @@
1
- import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
2
1
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
3
2
  import fs from "node:fs";
4
3
  import path from "node:path";
5
4
  import { randomUUID } from "node:crypto";
6
5
  import os from "node:os";
7
6
  import { defaultForgeBridgeConfig } from "../config.js";
8
- import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
7
+ import { bridgeChatCapabilityFor, defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
8
  import { redactText } from "../shared/redaction/redaction.js";
10
- import { BridgeSessionService } from "../session/session.service.js";
11
- import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
- import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
9
+ import { formatProviderCliCommandForCheckpoint, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
10
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } from "./bridge-chat-provider-command.js";
13
11
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
12
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
- import { PrePublicationValidator } from "../session/pre-publication-validation.js";
13
+ import { describeHostTestSlotCapacity } from "../runtime/host-load-governor.js";
16
14
  import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
- import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
18
- import { computeEffectiveRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
15
+ import { createDefaultSessionService } from "./default-session-service.js";
16
+ import { hostCapacityLimitDefaults, } from "../runtime/host-runtime-lease.js";
17
+ import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
18
  import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
19
  import { readLocalYieldFlag } from "./local-yield-flag.js";
21
20
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
22
21
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
23
22
  import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
24
23
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
25
- import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
26
- import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
27
24
  import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
28
- import { GitWorktreeService } from "../worktree/worktree.service.js";
29
- import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
30
- import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
31
25
  import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
32
26
  import { forgeBridgeVersion } from "../version.js";
33
27
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
34
- import { validateSandboxContract } from "../sandbox/contract.js";
35
- import { runSandboxProcess } from "../sandbox/process.js";
36
- import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
28
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
37
29
  import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
38
30
  import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
39
- import { formatBytes } from "../shared/format/format-bytes.js";
40
31
  import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
41
32
  import { HostLoadSampler } from "../runtime/host-load-sampler.js";
42
- import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
33
+ import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
43
34
  import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
35
+ import { BridgeStatePublisher } from "./bridge-state-file.js";
36
+ import { offerPolicyRefusal, prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning, sandboxProfileRefusalCode, unmetHostRuntimeRequirements, } from "./dispatch-offer-policy.js";
37
+ import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
38
+ import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
39
+ export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
44
40
  /**
45
41
  * Protocol-v2 events are acknowledged one at a time before runOnce returns.
46
42
  * Sending the complete transcript again in DispatchResult made long QA and CI
@@ -68,6 +64,7 @@ export class ForgeBridgeService {
68
64
  leaseWatchdogTimer = null;
69
65
  sandboxMaintenanceTimer = null;
70
66
  sandboxMaintenanceRunning = false;
67
+ attemptSnapshotPending = null;
71
68
  closed = null;
72
69
  transportRecovery = null;
73
70
  transportRecoveryGeneration = 0;
@@ -76,6 +73,8 @@ export class ForgeBridgeService {
76
73
  activeSessions = new Map();
77
74
  reservations = new Map();
78
75
  activeReadinessProbes = new Map();
76
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
77
+ inFlight = new BridgeInFlightRegistry();
79
78
  readinessResultOutbox;
80
79
  readinessResultFlush = null;
81
80
  dispatchResultOutbox;
@@ -96,6 +95,9 @@ export class ForgeBridgeService {
96
95
  // and the effective settings computed from both and the host's env bounds.
97
96
  appliedSettingsDocument = null;
98
97
  localYield = false;
98
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
99
+ forgeAckedYield = false;
100
+ publishState = () => undefined;
99
101
  effectiveSettings;
100
102
  settingsReport;
101
103
  /** Applies run one at a time; offers wait for every apply queued before them. */
@@ -122,6 +124,8 @@ export class ForgeBridgeService {
122
124
  // leaves those attempts on Forge's conservative unknown-outcome path.
123
125
  recoveredHostAttempts = new Map();
124
126
  hostCapabilitiesDetected = false;
127
+ /** The default session service's host load governor, for the startup capacity log line. */
128
+ hostLoadGovernor;
125
129
  constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
126
130
  // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
127
131
  hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
@@ -163,6 +167,7 @@ export class ForgeBridgeService {
163
167
  });
164
168
  const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
165
169
  this.sessions = sessions ?? defaultSessions.sessions;
170
+ this.hostLoadGovernor = defaultSessions?.hostLoadGovernor ?? null;
166
171
  // Docker sandboxes ask the same host load governor for their validation tokens.
167
172
  this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
168
173
  this.sandboxResourceResolver = sandboxResourceResolver
@@ -172,6 +177,18 @@ export class ForgeBridgeService {
172
177
  // With no server document and no local flag these equal today's env/default behaviour.
173
178
  this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
174
179
  this.settingsReport = this.effectiveSettings.report;
180
+ this.inFlight.addSource(() => [
181
+ ...reservationInFlightEntries(this.reservations),
182
+ ...sessionInFlightEntries(this.activeSessions),
183
+ ...readinessInFlightEntries(this.activeReadinessProbes),
184
+ ]);
185
+ }
186
+ /** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
187
+ async detectHostCapabilities() {
188
+ this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
189
+ this.hostCapabilitiesDetected = true;
190
+ if (this.hostLoadGovernor?.enabled)
191
+ logBridgeStatus(describeHostTestSlotCapacity(this.hostLoadGovernor.testSlotCapacity()));
175
192
  }
176
193
  async connectOnce() {
177
194
  if (this.revokedReason !== null) {
@@ -198,10 +215,8 @@ export class ForgeBridgeService {
198
215
  }
199
216
  }
200
217
  await this.dockerEngineProbe.refresh(true);
201
- if (!this.hostCapabilitiesDetected) {
202
- this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
203
- this.hostCapabilitiesDetected = true;
204
- }
218
+ if (!this.hostCapabilitiesDetected)
219
+ await this.detectHostCapabilities();
205
220
  // Static host facts and the first load sample ride on Hello; the sampler
206
221
  // keeps refreshing its cached snapshot for later heartbeats.
207
222
  await this.hostLoad.start().catch(() => undefined);
@@ -248,14 +263,14 @@ export class ForgeBridgeService {
248
263
  await connection.stop().catch(() => undefined);
249
264
  }
250
265
  });
251
- connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
252
- connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
253
- connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
254
- connection.onStart?.((dispatch) => this.handleStart(dispatch));
266
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
267
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
268
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
269
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
255
270
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
256
271
  connection.onCancel((request) => this.handleCancel(request));
257
272
  connection.onReap?.((request) => this.handleReap(request));
258
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
273
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
259
274
  connection.onRevoked?.((notice) => this.handleRevoked(notice));
260
275
  connection.onApplySettings?.((document) => this.handleApplySettings(document));
261
276
  await connection.start();
@@ -294,6 +309,7 @@ export class ForgeBridgeService {
294
309
  while (true) {
295
310
  try {
296
311
  const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
312
+ const reportedYield = this.settingsReport.values.yieldToForeground;
297
313
  const ack = await connection.invoke("Hello", {
298
314
  version: this.config.version,
299
315
  protocolVersion: this.config.protocolVersion,
@@ -306,6 +322,7 @@ export class ForgeBridgeService {
306
322
  throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
307
323
  }
308
324
  this.recoveredHostAttempts.clear();
325
+ this.ackYield(reportedYield);
309
326
  logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
310
327
  return;
311
328
  }
@@ -321,6 +338,7 @@ export class ForgeBridgeService {
321
338
  }
322
339
  }
323
340
  async run(signal) {
341
+ const statePublisher = await this.startStatePublisher();
324
342
  let attempt = 0;
325
343
  try {
326
344
  while (!this.stopped && !signal?.aborted) {
@@ -352,11 +370,28 @@ export class ForgeBridgeService {
352
370
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
353
371
  }
354
372
  await this.stopConnection();
373
+ await statePublisher?.stop();
355
374
  }
356
375
  if (this.revokedReason !== null) {
357
376
  throw new BridgeRevokedError(this.revokedReason);
358
377
  }
359
378
  }
379
+ async startStatePublisher() {
380
+ if (!this.config.bridgeStatePath)
381
+ return null;
382
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
383
+ inFlight: () => this.inFlight.snapshot(),
384
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
385
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
386
+ yieldApplied: () => this.effectiveSettings.yielding,
387
+ connected: () => this.connection !== null && this.transportRecovery === null,
388
+ }, { log: logBridgeStatus });
389
+ this.publishState = () => void publisher.publish();
390
+ this.inFlight.onChange(this.publishState);
391
+ await publisher.start();
392
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
393
+ return publisher;
394
+ }
360
395
  /** The reason Forge gave when it removed this runner, or null while it is paired. */
361
396
  get revoked() {
362
397
  return this.revokedReason;
@@ -492,6 +527,7 @@ export class ForgeBridgeService {
492
527
  this.appliedSettingsDocument = document;
493
528
  this.effectiveSettings = effective;
494
529
  this.settingsReport = report;
530
+ this.publishState();
495
531
  if (change.kind === "server") {
496
532
  logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
497
533
  }
@@ -533,10 +569,12 @@ export class ForgeBridgeService {
533
569
  }
534
570
  return rejected;
535
571
  }
572
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
536
573
  /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
537
574
  async sendSettingsApplied(report) {
538
575
  try {
539
576
  await this.invokeAck("SettingsApplied", report);
577
+ this.ackYield(report.values.yieldToForeground);
540
578
  }
541
579
  catch (error) {
542
580
  logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
@@ -669,9 +707,18 @@ export class ForgeBridgeService {
669
707
  await fs.promises.mkdir(root, { recursive: true });
670
708
  return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
671
709
  }
710
+ /** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
711
+ async lookAtChatGiphyFrames(packet, active, cwd) {
712
+ return await lookAtChatGiphyFrames(packet, cwd, {
713
+ runner: this.chatProcessRunner,
714
+ signal: active.controller.signal,
715
+ log: logBridgeStatus,
716
+ takeFrames: async (request) => await this.connection?.invoke(chatTurnGiphyFramesMethod, request) ?? { accepted: false },
717
+ });
718
+ }
672
719
  async runChatProviderProcess(packet, active, cwd) {
673
720
  const output = createProviderOutputState(packet.providerKind);
674
- const plan = buildChatProviderCommand(packet, cwd);
721
+ const plan = buildChatProviderCommand(packet, cwd, await this.lookAtChatGiphyFrames(packet, active, cwd));
675
722
  const redactionSecrets = chatRedactionSecrets(packet);
676
723
  let started = false;
677
724
  const result = await this.chatProcessRunner.run({
@@ -842,37 +889,16 @@ export class ForgeBridgeService {
842
889
  this.releaseReservedDispatchHandoff(reservationHandoff);
843
890
  return;
844
891
  }
845
- if (this.enforceHostDatabaseCapabilityBoundary) {
846
- try {
847
- assertHostDatabaseCapabilityBoundary();
848
- }
849
- catch (error) {
850
- const message = errorMessage(error);
851
- await this.sendResult(dispatch, failureResult(message, [{
852
- role: "runner",
853
- kind: "error",
854
- content: message,
855
- eventType: "host_database_capability_forbidden",
856
- }], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
857
- this.releaseReservedDispatchHandoff(reservationHandoff);
858
- return;
859
- }
860
- }
861
- let capabilityFailure;
892
+ let refusal;
862
893
  try {
863
- capabilityFailure = await this.requiredCapabilityFailure(dispatch);
894
+ refusal = await this.refusalBeforeRun(dispatch);
864
895
  }
865
896
  catch (error) {
866
897
  this.releaseReservedDispatchHandoff(reservationHandoff);
867
898
  throw error;
868
899
  }
869
- if (capabilityFailure) {
870
- await this.sendResult(dispatch, failureResult(capabilityFailure, [{
871
- role: "runner",
872
- kind: "error",
873
- content: capabilityFailure,
874
- eventType: "docker_engine_unavailable",
875
- }], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
900
+ if (refusal) {
901
+ await this.sendResult(dispatch, refusal).catch(() => undefined);
876
902
  this.releaseReservedDispatchHandoff(reservationHandoff);
877
903
  return;
878
904
  }
@@ -894,19 +920,7 @@ export class ForgeBridgeService {
894
920
  return;
895
921
  }
896
922
  const controller = reservationHandoff?.controller ?? new AbortController();
897
- this.activeSessions.set(leaseId, {
898
- leaseId,
899
- kind: "dispatch",
900
- fencingToken,
901
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
902
- runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
903
- leaseExpiresAt: dispatch.lease.expiresAt,
904
- sandboxed: dispatch.sandbox?.executionMode === "docker",
905
- resources: dispatch.sandbox?.executionMode === "docker"
906
- ? dispatch.sandbox.requestedResources
907
- : zeroSandboxResources(),
908
- controller
909
- });
923
+ this.registerActiveDispatch(dispatch, controller);
910
924
  if (reservationHandoff) {
911
925
  // Promotion is synchronous with active-session registration. A qualified
912
926
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -930,43 +944,10 @@ export class ForgeBridgeService {
930
944
  };
931
945
  await this.invokeAck("DispatchStarted", started);
932
946
  }
933
- const sink = {
934
- emit: async (event) => {
935
- if (event.eventType === "provider_cli_started") {
936
- const active = this.activeSessions.get(leaseId);
937
- if (active)
938
- active.resources = { ...active.resources, buildSlots: 0 };
939
- }
940
- try {
941
- await this.invokeAck("DispatchEvent", {
942
- leaseId,
943
- fencingToken,
944
- ...(dispatch.sandbox ? {
945
- dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
946
- runnerInstanceId: dispatch.sandbox.runnerInstanceId
947
- } : {}),
948
- event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
949
- }, {
950
- replayCallbackTimeout: true,
951
- signal: controller.signal,
952
- });
953
- }
954
- catch (error) {
955
- if (isDispatchNoLongerPending(error)) {
956
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
957
- return;
958
- }
959
- throw error;
960
- }
961
- }
962
- };
963
- const result = normalized.sandbox?.executionMode === "docker"
964
- ? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
965
- : await this.sessions.runOnce(normalized, sink, controller.signal);
966
- if (normalized.sandbox?.executionMode === "docker") {
967
- await this.flushCleanupReports().catch(() => undefined);
968
- }
947
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
948
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
969
949
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
950
+ this.inFlight.notePhase(leaseId, "result_delivery");
970
951
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
971
952
  }
972
953
  catch (error) {
@@ -990,6 +971,77 @@ export class ForgeBridgeService {
990
971
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
991
972
  }
992
973
  }
974
+ registerActiveDispatch(dispatch, controller) {
975
+ this.activeSessions.set(dispatch.lease.id, {
976
+ leaseId: dispatch.lease.id,
977
+ kind: "dispatch",
978
+ fencingToken: dispatch.lease.fencingToken,
979
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
980
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
981
+ leaseExpiresAt: dispatch.lease.expiresAt,
982
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
983
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
984
+ controller
985
+ });
986
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
987
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
988
+ }
989
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
990
+ const leaseId = dispatch.lease.id;
991
+ return {
992
+ emit: async (event) => {
993
+ this.inFlight.notePhase(leaseId, event.eventType);
994
+ if (event.eventType === "provider_cli_started") {
995
+ const active = this.activeSessions.get(leaseId);
996
+ if (active)
997
+ active.resources = { ...active.resources, buildSlots: 0 };
998
+ }
999
+ try {
1000
+ await this.invokeAck("DispatchEvent", {
1001
+ leaseId,
1002
+ fencingToken: dispatch.lease.fencingToken,
1003
+ ...(dispatch.sandbox ? {
1004
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1005
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1006
+ } : {}),
1007
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1008
+ }, {
1009
+ replayCallbackTimeout: true,
1010
+ signal: controller.signal,
1011
+ });
1012
+ }
1013
+ catch (error) {
1014
+ if (isDispatchNoLongerPending(error)) {
1015
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1016
+ return;
1017
+ }
1018
+ throw error;
1019
+ }
1020
+ }
1021
+ };
1022
+ }
1023
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1024
+ async runDispatchOnce(dispatch, sink, signal) {
1025
+ const docker = dispatch.sandbox?.executionMode === "docker";
1026
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1027
+ const startedAt = Date.now();
1028
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1029
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1030
+ try {
1031
+ const result = await runWithUnsandboxedReviewWarning(dispatch, this.config.allowUnsandboxedPrReview, sink, (warning) => logBridgeStatus(`${warning} ${ids}.`), () => docker
1032
+ ? this.sandboxRuntime.runOnce(dispatch, sink, signal)
1033
+ : this.sessions.runOnce(dispatch, sink, signal));
1034
+ if (docker) {
1035
+ await this.flushCleanupReports().catch(() => undefined);
1036
+ }
1037
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1038
+ return result;
1039
+ }
1040
+ catch (error) {
1041
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1042
+ throw error;
1043
+ }
1044
+ }
993
1045
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
994
1046
  const sandbox = dispatch.sandbox;
995
1047
  const reservation = handoff.reservation;
@@ -1095,21 +1147,11 @@ export class ForgeBridgeService {
1095
1147
  await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
1096
1148
  return;
1097
1149
  }
1098
- const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
1099
- if (networkFailure) {
1100
- await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
1101
- return;
1102
- }
1103
- const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
1104
- if (providerNetworkFailure) {
1105
- await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
1106
- return;
1107
- }
1108
- const authFailure = sandboxAuthFailure(dispatch, this.config);
1109
- if (authFailure) {
1110
- await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
1111
- return;
1112
- }
1150
+ }
1151
+ const policyRefusal = offerPolicyRefusal(dispatch, this.config, () => sandboxAuthFailure(dispatch, this.config));
1152
+ if (policyRefusal) {
1153
+ await this.sendOfferDecision(dispatch, false, policyRefusal.code, policyRefusal.message);
1154
+ return;
1113
1155
  }
1114
1156
  let requestedResources = sandbox.requestedResources;
1115
1157
  let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
@@ -1121,7 +1163,7 @@ export class ForgeBridgeService {
1121
1163
  sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
1122
1164
  }
1123
1165
  catch (error) {
1124
- await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1166
+ await this.sendOfferDecision(dispatch, false, sandboxProfileRefusalCode(dispatch), error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1125
1167
  return;
1126
1168
  }
1127
1169
  }
@@ -1351,8 +1393,41 @@ export class ForgeBridgeService {
1351
1393
  reservedResources: accepted ? reservedResources : null,
1352
1394
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1353
1395
  };
1396
+ if (accepted)
1397
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1354
1398
  await this.invokeAck("OfferDecision", payload);
1355
1399
  }
1400
+ /**
1401
+ * The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
1402
+ * database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
1403
+ * without the owner's opt-in. Null when it may run.
1404
+ */
1405
+ async refusalBeforeRun(dispatch) {
1406
+ if (this.enforceHostDatabaseCapabilityBoundary) {
1407
+ try {
1408
+ assertHostDatabaseCapabilityBoundary();
1409
+ }
1410
+ catch (error) {
1411
+ const message = errorMessage(error);
1412
+ return failureResult(message, [{
1413
+ role: "runner",
1414
+ kind: "error",
1415
+ content: message,
1416
+ eventType: "host_database_capability_forbidden",
1417
+ }], failureFactsFromError(error, { source: "bridge" }));
1418
+ }
1419
+ }
1420
+ const capabilityFailure = await this.requiredCapabilityFailure(dispatch);
1421
+ if (capabilityFailure) {
1422
+ return failureResult(capabilityFailure, [{
1423
+ role: "runner",
1424
+ kind: "error",
1425
+ content: capabilityFailure,
1426
+ eventType: "docker_engine_unavailable",
1427
+ }], failureFactsForCode("docker_engine_unavailable"));
1428
+ }
1429
+ return prReviewPlacementRefusalResult(dispatch, this.config.allowUnsandboxedPrReview);
1430
+ }
1356
1431
  async parseDispatchOrReport(rawDispatch) {
1357
1432
  try {
1358
1433
  return parseRunOnceDispatchPacket(rawDispatch);
@@ -1464,7 +1539,13 @@ export class ForgeBridgeService {
1464
1539
  acceptedAt: new Date().toISOString(),
1465
1540
  };
1466
1541
  await this.invokeAck("ReadinessAccepted", accepted);
1467
- if (this.activeSessions.size > 0) {
1542
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1543
+ await this.refreshLocalYield().catch(() => undefined);
1544
+ await this.settingsTail;
1545
+ if (this.yieldingOrQueued()) {
1546
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1547
+ }
1548
+ else if (this.activeSessions.size > 0) {
1468
1549
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1469
1550
  }
1470
1551
  else if (!this.sessions.probeHostRuntime) {
@@ -1845,7 +1926,8 @@ export class ForgeBridgeService {
1845
1926
  startSandboxMaintenance() {
1846
1927
  this.stopSandboxMaintenance();
1847
1928
  this.sandboxMaintenanceTimer = setInterval(() => {
1848
- this.runSandboxMaintenance().catch(() => undefined);
1929
+ this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
1930
+ logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
1849
1931
  }, 60_000);
1850
1932
  this.sandboxMaintenanceTimer.unref?.();
1851
1933
  }
@@ -1885,9 +1967,15 @@ export class ForgeBridgeService {
1885
1967
  const connection = this.connection;
1886
1968
  if (!connection)
1887
1969
  throw new Error("Bridge is not connected.");
1888
- const response = await connection.invoke("AttemptSnapshot", {
1889
- runnerInstanceId: this.config.runnerInstanceId
1890
- });
1970
+ // Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
1971
+ const pending = { connection, generation: this.transportRecoveryGeneration };
1972
+ if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
1973
+ throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
1974
+ this.attemptSnapshotPending = pending;
1975
+ const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
1976
+ invocation.finally(() => { if (this.attemptSnapshotPending === pending)
1977
+ this.attemptSnapshotPending = null; }).catch(() => undefined);
1978
+ const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
1891
1979
  if (!response.accepted) {
1892
1980
  throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
1893
1981
  }
@@ -1922,12 +2010,14 @@ export class ForgeBridgeService {
1922
2010
  await this.sendHeartbeatSnapshot();
1923
2011
  }
1924
2012
  async sendHeartbeatSnapshot(signal) {
2013
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1925
2014
  await this.invokeAck("Heartbeat", {
1926
2015
  status: "online",
1927
2016
  capabilities: this.capabilities(),
1928
2017
  version: this.config.version,
1929
2018
  protocolVersion: this.config.protocolVersion
1930
2019
  }, { signal });
2020
+ this.ackYield(reportedYield);
1931
2021
  }
1932
2022
  capabilities() {
1933
2023
  const preflight = this.preflight.current();
@@ -1959,7 +2049,7 @@ export class ForgeBridgeService {
1959
2049
  sandboxProfiles: this.config.sandboxProfiles,
1960
2050
  runnerInstanceId: this.config.runnerInstanceId,
1961
2051
  trustDomainId: this.config.trustDomainId,
1962
- executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
2052
+ executionFacilities: [...(dockerEngine?.available ? ["docker_engine"] : []), ...prReviewExecutionFacilities(this.config.allowUnsandboxedPrReview)],
1963
2053
  dockerEngine,
1964
2054
  toolchains: {
1965
2055
  ...this.hostCapabilities.toolchains,
@@ -2169,25 +2259,6 @@ export class ForgeBridgeService {
2169
2259
  }
2170
2260
  }
2171
2261
  }
2172
- function runnerYieldingMessage(report) {
2173
- const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
2174
- return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
2175
- }
2176
- function describeRunnerSettings(report) {
2177
- const { values } = report;
2178
- const parts = [
2179
- `max attempts ${values.maxConcurrentAttempts}`,
2180
- `CPU budget ${values.cpuBudgetPercent}%`,
2181
- `yield budget ${values.yieldCpuBudgetPercent}%`,
2182
- `memory reserve ${formatBytes(values.memoryReserveBytes)}`,
2183
- `heavy steps ${values.maxHeavySteps ?? "budget only"}`,
2184
- `yield ${values.yieldToForeground ? "on" : "off"}`,
2185
- ];
2186
- const capped = report.bounds
2187
- .filter(bound => report.sources[bound.key] === "host_env")
2188
- .map(bound => `${bound.envVar}=${bound.value}`);
2189
- return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
2190
- }
2191
2262
  /** The `run` command's exit code after Forge removed the runner. */
2192
2263
  export const bridgeRevokedExitCode = 3;
2193
2264
  export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
@@ -2231,14 +2302,6 @@ function isProviderStorageUnavailable(error) {
2231
2302
  function isBridgeCallbackTimeout(error) {
2232
2303
  return errorMessage(error).startsWith("bridge_callback_timeout:");
2233
2304
  }
2234
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
2235
- const rawProcessRunner = new StreamingProviderProcessRunner();
2236
- const processSupervisors = new AttemptProcessSupervisorRegistry();
2237
- const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
2238
- const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2239
- const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2240
- return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
2241
- }
2242
2305
  export class SignalRBridgeConnectionFactory {
2243
2306
  create(config) {
2244
2307
  return new SignalRBridgeConnection(config);
@@ -2464,14 +2527,6 @@ function providerStatus(config, provider) {
2464
2527
  return Object.entries(config.providerStatuses)
2465
2528
  .find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
2466
2529
  }
2467
- function defaultSandboxProfiles(providers, platform = process.platform) {
2468
- if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
2469
- return ["none"];
2470
- }
2471
- return platform === "win32"
2472
- ? ["danger-full-access"]
2473
- : ["provider-workspace-write"];
2474
- }
2475
2530
  function configuredModelsFor(provider) {
2476
2531
  const envName = `FORGE_${provider.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase()}_MODELS`;
2477
2532
  return splitCsv(process.env[envName] ?? "");
@@ -2620,10 +2675,7 @@ function errorMessage(error) {
2620
2675
  return error instanceof Error ? error.message : String(error);
2621
2676
  }
2622
2677
  function formatDelay(ms) {
2623
- if (ms >= 1000 && ms % 1000 === 0) {
2624
- return `${ms / 1000}s`;
2625
- }
2626
- return `${ms}ms`;
2678
+ return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
2627
2679
  }
2628
2680
  async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
2629
2681
  let timeout = null;
@@ -2692,35 +2744,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2692
2744
  const maxChatEventContentChars = 4000;
2693
2745
  const maxChatTerminalTextChars = 120_000;
2694
2746
  const maxChatExactSecretChars = 8 * 1024;
2695
- async function materializeChatTurnMetadata(packet, workspacePath) {
2696
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2697
- return;
2698
- }
2699
- await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
2700
- schemaVersion: 1,
2701
- attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
2702
- turnId: handoff.turnId,
2703
- attachmentId: handoff.attachmentId,
2704
- tempFileToken: handoff.tempFileToken,
2705
- mimeType: handoff.mimeType,
2706
- sizeBytes: handoff.sizeBytes,
2707
- sha256: handoff.sha256,
2708
- fileNameDisplay: handoff.fileNameDisplay,
2709
- expiresAt: handoff.expiresAt,
2710
- status: handoff.status,
2711
- })),
2712
- actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
2713
- grantId: grant.grantId,
2714
- turnId: grant.turnId,
2715
- leaseId: grant.leaseId,
2716
- fencingToken: grant.fencingToken,
2717
- allowedScopes: grant.allowedScopes,
2718
- expiresAt: grant.expiresAt,
2719
- redactionStatus: grant.redactionStatus,
2720
- nonceHeldByBridge: true,
2721
- })),
2722
- }, null, 2)}\n`, "utf8");
2723
- }
2724
2747
  function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
2725
2748
  const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
2726
2749
  const metadataExpiresAtMs = [
@@ -2843,21 +2866,6 @@ function containsIgnoreCase(values, value) {
2843
2866
  export function canReapManagedSandboxes(preflight) {
2844
2867
  return canRunDockerMaintenance(preflight);
2845
2868
  }
2846
- function sandboxNetworkPolicyFailure(dispatch, config) {
2847
- const sandbox = dispatch.sandbox;
2848
- if (!sandbox)
2849
- return "Protocol-v2 sandbox context is missing.";
2850
- if (sandbox.networkPolicy.mode === "open_public"
2851
- && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
2852
- return "open_public sandbox networking is not permitted by this runner policy.";
2853
- }
2854
- if (sandbox.networkPolicy.mode === "public_allowlist"
2855
- && sandbox.networkPolicy.allowedHosts.length > 0
2856
- && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
2857
- return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
2858
- }
2859
- return null;
2860
- }
2861
2869
  export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
2862
2870
  if (!requiredCapabilities.includes("docker_engine"))
2863
2871
  return null;
@@ -2894,34 +2902,6 @@ function parseReadinessProbe(value) {
2894
2902
  }
2895
2903
  return request;
2896
2904
  }
2897
- function deferredReadinessResult(request, runnerInstanceId) {
2898
- return {
2899
- schemaVersion: 1,
2900
- requestId: request.requestId,
2901
- fencingToken: request.fencingToken,
2902
- runnerInstanceId,
2903
- status: "failed",
2904
- reasonCode: "host_runtime_probe_deferred",
2905
- reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
2906
- checkedAt: new Date().toISOString(),
2907
- };
2908
- }
2909
- function readinessDeferralReason(signal) {
2910
- if (!signal.aborted)
2911
- return null;
2912
- const reason = errorMessage(signal.reason);
2913
- return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
2914
- }
2915
- function sandboxProviderNetworkFailure(dispatch, config) {
2916
- const sandbox = dispatch.sandbox;
2917
- if (!sandbox || sandbox.networkPolicy.mode !== "offline")
2918
- return null;
2919
- const provider = dispatch.execution.provider.trim().toLowerCase();
2920
- const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
2921
- if (!isNetworkProvider)
2922
- return null;
2923
- return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
2924
- }
2925
2905
  function sandboxAuthFailure(dispatch, config) {
2926
2906
  const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2927
2907
  if (unsupported) {
@@ -2950,151 +2930,6 @@ function rejectedOfferReservation(code, message) {
2950
2930
  resources: null,
2951
2931
  };
2952
2932
  }
2953
- export function canReserveSandboxResources(used, requested, capacity) {
2954
- return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
2955
- && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
2956
- && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
2957
- && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
2958
- && used.pids + requested.pids <= capacity.pids
2959
- && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
2960
- }
2961
- export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
2962
- const ambientCapacity = preflight.availableMemoryBytes
2963
- - preflight.hostReserveBytes
2964
- + activeMemoryBytes;
2965
- const commitmentCapacity = preflight.totalMemoryBytes
2966
- - preflight.hostReserveBytes;
2967
- return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
2968
- }
2969
- export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
2970
- const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
2971
- if (requested.sandboxSlots > availableSlots) {
2972
- return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
2973
- }
2974
- const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
2975
- if (requested.memoryBytes > availableMemoryBytes) {
2976
- return [
2977
- `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
2978
- `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
2979
- `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
2980
- `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
2981
- `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
2982
- ].join(" ");
2983
- }
2984
- const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
2985
- if (requested.cpuMillis > availableCpuMillis) {
2986
- return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
2987
- }
2988
- const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
2989
- if (requested.workspaceBytes > availableWorkspaceBytes) {
2990
- return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
2991
- }
2992
- const availablePids = Math.max(0, capacity.pids - used.pids);
2993
- if (requested.pids > availablePids) {
2994
- return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
2995
- }
2996
- const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
2997
- return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
2998
- }
2999
- function sumSandboxResources(resources) {
3000
- return resources.reduce((total, resource) => ({
3001
- sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
3002
- cpuMillis: total.cpuMillis + resource.cpuMillis,
3003
- workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
3004
- serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
3005
- runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
3006
- memoryBytes: total.memoryBytes + resource.memoryBytes,
3007
- workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
3008
- pids: total.pids + resource.pids,
3009
- buildSlots: total.buildSlots + resource.buildSlots
3010
- }), zeroSandboxResources());
3011
- }
3012
- function zeroSandboxResources() {
3013
- return {
3014
- sandboxSlots: 0,
3015
- cpuMillis: 0,
3016
- workerMemoryLimitBytes: 0,
3017
- serviceMemoryLimitBytes: 0,
3018
- runtimeOverheadBytes: 0,
3019
- memoryBytes: 0,
3020
- workspaceBytes: 0,
3021
- pids: 0,
3022
- buildSlots: 0,
3023
- };
3024
- }
3025
- function defaultSandboxResources() {
3026
- return {
3027
- sandboxSlots: 1,
3028
- cpuMillis: 2000,
3029
- workerMemoryLimitBytes: 2 * 1024 ** 3,
3030
- serviceMemoryLimitBytes: 0,
3031
- runtimeOverheadBytes: 128 * 1024 ** 2,
3032
- memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
3033
- workspaceBytes: 10 * 1024 ** 3,
3034
- pids: 512,
3035
- buildSlots: 0
3036
- };
3037
- }
3038
- export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
3039
- const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
3040
- const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
3041
- + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
3042
- return {
3043
- ...requested,
3044
- serviceMemoryLimitBytes,
3045
- runtimeOverheadBytes,
3046
- memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
3047
- };
3048
- }
3049
- export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
3050
- const repoPath = dispatch.repo.serverLocalPath;
3051
- const sandbox = dispatch.sandbox;
3052
- if (!repoPath || !sandbox) {
3053
- throw new Error("Sandbox admission needs a mapped repository.");
3054
- }
3055
- const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
3056
- const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
3057
- if (!configCommitSha) {
3058
- throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
3059
- }
3060
- const contractResult = await runSandboxProcess({
3061
- command: "git",
3062
- args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
3063
- timeoutMs: 30_000,
3064
- maxOutputBytes: 1024 * 1024,
3065
- });
3066
- if (contractResult.exitCode !== 0) {
3067
- throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
3068
- }
3069
- const contract = validateSandboxContract(contractResult.stdout);
3070
- const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
3071
- role: dispatch.execution.role,
3072
- serviceCount: contract.contract.services.length,
3073
- browser: contract.contract.browser,
3074
- });
3075
- return {
3076
- resources: resolveDynamicSandboxResources({
3077
- ...sandbox.requestedResources,
3078
- workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
3079
- }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
3080
- sandboxConfigCommitSha: configCommitSha,
3081
- };
3082
- }
3083
- async function resolveFirstGitCommit(repoPath, refs) {
3084
- for (const ref of refs) {
3085
- const result = await runSandboxProcess({
3086
- command: "git",
3087
- args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
3088
- timeoutMs: 30_000,
3089
- maxOutputBytes: 1024 * 1024,
3090
- });
3091
- const commitSha = result.stdout.trim().toLowerCase();
3092
- if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
3093
- return commitSha;
3094
- }
3095
- }
3096
- return null;
3097
- }
3098
2933
  function parseOfferEnvelope(value) {
3099
2934
  return parseDispatchEnvelope(value);
3100
2935
  }