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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -2,29 +2,43 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { failureResult } from "../session/session.types.js";
5
+ import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
8
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
9
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
10
  import { SandboxEventBudget } from "./event-budget.js";
11
+ import { SandboxHostCapacityBroker, sandboxHostCapacityDeliveryExecArgs, withSandboxHostCapacityBroker, } from "./host-capacity-broker.js";
12
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
13
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
14
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
15
+ import { trackSandboxCgroups } from "./sandbox-cgroups.js";
16
+ import { runtimeAdmissionPriority } from "../runtime/host-runtime-lease.js";
11
17
  import { RepositoryCoordinatorLock } from "./repository-lock.js";
12
18
  import { redactText } from "../shared/redaction/redaction.js";
13
19
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
14
20
  import { sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "./provider-auth/codex.js";
21
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
15
22
  const managedLabel = "dev.forge.managed=true";
16
23
  const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
17
24
  export class DockerSandboxRuntime {
18
25
  config;
19
26
  publicationGrantRedeemer;
27
+ hostLoadGate;
20
28
  active = new Map();
21
29
  degraded = new Set();
22
30
  builds = new Map();
23
31
  verifiedCatalogImages = new Set();
24
32
  buildTail = Promise.resolve();
25
- constructor(config, publicationGrantRedeemer) {
33
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
34
+ forgeCgroups;
35
+ constructor(config, publicationGrantRedeemer,
36
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
37
+ hostLoadGate) {
26
38
  this.config = config;
27
39
  this.publicationGrantRedeemer = publicationGrantRedeemer;
40
+ this.hostLoadGate = hostLoadGate;
41
+ this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
28
42
  }
29
43
  async runOnce(dispatch, sink, signal) {
30
44
  if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
@@ -85,7 +99,7 @@ export class DockerSandboxRuntime {
85
99
  await fs.mkdir(path.join(attemptRoot, "output"), { recursive: true, mode: 0o700 });
86
100
  const repoPath = dispatch.repo.serverLocalPath ? path.resolve(dispatch.repo.serverLocalPath) : null;
87
101
  if (!repoPath)
88
- throw new Error("sandbox_input_failed: bridge repository mapping is required for bundle handoff.");
102
+ throw trustedSandboxFailure("sandbox_input_failed", "bridge repository mapping is required for bundle handoff.");
89
103
  await sink.emit(event("sandbox_preparing", `Preparing Docker sandbox attempt ${dispatch.sandbox.dispatchAttemptId}.`));
90
104
  const git = new HostGit(this.config, repoPath);
91
105
  const prepared = await git.prepare(dispatch, attemptRoot, runtimeSignal);
@@ -100,7 +114,7 @@ export class DockerSandboxRuntime {
100
114
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
101
115
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
102
116
  if (providerAuthUnavailable) {
103
- throw new Error(`sandbox_auth_unavailable: ${providerAuthUnavailable}`);
117
+ throw trustedSandboxFailure("sandbox_auth_unavailable", providerAuthUnavailable);
104
118
  }
105
119
  await sink.emit(event("sandbox_metadata", "Resolved immutable sandbox inputs.", {
106
120
  inputCommitSha: prepared.inputCommitSha,
@@ -125,6 +139,7 @@ export class DockerSandboxRuntime {
125
139
  await this.writeLedger(active.ledger);
126
140
  let teardownComplete = false;
127
141
  let memoryTelemetryEvent = null;
142
+ let trustedHostFailure = null;
128
143
  try {
129
144
  const internalNetworkId = dockerObjectId((await this.docker(["network", "create", ...networkArgs, ...labelArgs(labels), resources.network], 30_000, runtimeSignal)).stdout, "network");
130
145
  await this.docker(["volume", "create", ...labelArgs(labels), resources.workspaceVolume], 30_000, runtimeSignal);
@@ -151,7 +166,11 @@ export class DockerSandboxRuntime {
151
166
  await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
152
167
  const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
153
168
  const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
154
- const createArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
169
+ const brokered = this.hostLoadGate?.enabled === true;
170
+ const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
171
+ const createArgs = brokered
172
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
173
+ : workerArgs;
155
174
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
156
175
  const containerId = dockerObjectId(createdContainer.stdout, "container");
157
176
  await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
@@ -181,6 +200,16 @@ export class DockerSandboxRuntime {
181
200
  runtimeLease: active.runtimeLease,
182
201
  }));
183
202
  const eventBudget = new SandboxEventBudget();
203
+ const hostCapacity = brokered
204
+ ? new SandboxHostCapacityBroker(this.hostLoadGate, runtimeDispatch.sandbox.dispatchAttemptId, runtimeAdmissionPriority(runtimeDispatch), async (response) => void await requireSandboxProcess({
205
+ command: this.config.dockerExecutable,
206
+ // As root, into the root-owned reply mount the sandbox user cannot write.
207
+ args: this.dockerArgs(sandboxHostCapacityDeliveryExecArgs(containerId)),
208
+ input: `${JSON.stringify(response)}\n`,
209
+ timeoutMs: 10_000,
210
+ maxOutputBytes: 16 * 1024,
211
+ }), { stepProcess: async () => await this.containerInitProcess(containerId) })
212
+ : null;
184
213
  const startPromise = runSandboxProcess({
185
214
  command: this.config.dockerExecutable,
186
215
  args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
@@ -196,6 +225,8 @@ export class DockerSandboxRuntime {
196
225
  signal: runtimeSignal,
197
226
  onStdoutLine: async (line) => {
198
227
  eventBudget.accept(line);
228
+ if (hostCapacity?.handleLine(line))
229
+ return;
199
230
  const streamedEvent = parseSandboxEventLine(line);
200
231
  if (streamedEvent) {
201
232
  if (streamedEvent.eventType === "provider_cli_started")
@@ -205,7 +236,14 @@ export class DockerSandboxRuntime {
205
236
  }
206
237
  });
207
238
  const memorySampler = this.startPeakMemorySampler(runtimeContainers);
239
+ // The sandbox's CPU is Forge's own work, not external load, for the governor.
240
+ const untrackCgroups = brokered
241
+ ? trackSandboxCgroups(this.forgeCgroups, runtimeDispatch.sandbox.dispatchAttemptId, runtimeContainers.map(container => container.id), async (ids) => (await this.docker(["inspect", "--format", "{{.State.Pid}}", ...ids], 10_000)).stdout)
242
+ : null;
208
243
  const start = await startPromise.finally(async () => {
244
+ // The worker exited: its queued and admitted host load tokens go back to the budget.
245
+ untrackCgroups?.();
246
+ await hostCapacity?.close();
209
247
  const telemetry = await memorySampler.stop();
210
248
  if (!telemetry)
211
249
  return;
@@ -217,19 +255,18 @@ export class DockerSandboxRuntime {
217
255
  await sink.emit(memoryTelemetryEvent).catch(() => undefined);
218
256
  });
219
257
  if (start.truncated)
220
- throw new Error("sandbox_log_limit: sandbox output exceeded the 8 MiB supervisor capture budget.");
258
+ throw trustedSandboxFailure("sandbox_log_limit", "sandbox output exceeded the 8 MiB supervisor capture budget.");
221
259
  const containerState = await this.inspectContainerState(containerId);
222
260
  if (containerState.oomKilled) {
223
- throw new Error("sandbox_oom_killed: Docker terminated the agent after it exceeded the memory limit.");
261
+ trustedHostFailure = {
262
+ code: "sandbox_oom_killed",
263
+ message: "Docker terminated the agent after it exceeded the memory limit.",
264
+ };
224
265
  }
225
- if (start.exitCode !== 0) {
226
- const resourceFailure = classifySandboxResourceFailure([
227
- containerState.error,
228
- start.stderr,
229
- start.stdout
230
- ].filter(Boolean).join("\n"));
231
- if (resourceFailure)
232
- throw new Error(`${resourceFailure.code}: ${resourceFailure.message}`);
266
+ if (start.exitCode !== 0 && !trustedHostFailure) {
267
+ // Docker's inspect state is trusted host telemetry. Child stdout/stderr is
268
+ // evidence only and must not be able to choose a machine failure code.
269
+ trustedHostFailure = classifySandboxResourceFailure(containerState.error ?? "");
233
270
  }
234
271
  active.phase = "active";
235
272
  await sink.emit(event("sandbox_agent_exited", `Sandbox worker exited with code ${start.exitCode}.`, {
@@ -250,7 +287,7 @@ export class DockerSandboxRuntime {
250
287
  if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
251
288
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
252
289
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
253
- throw new Error("sandbox_output_publish_forbidden: bridge publication grant redemption is unavailable.");
290
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
254
291
  }
255
292
  const credential = await this.publicationGrantRedeemer({
256
293
  dispatchAttemptId: runtimeDispatch.sandbox.dispatchAttemptId,
@@ -269,29 +306,26 @@ export class DockerSandboxRuntime {
269
306
  resultCommitSha: output.manifest.resultCommitSha
270
307
  }));
271
308
  }
272
- const result = JSON.parse(await fs.readFile(output.resultPath, "utf8"));
273
- if (result.exitCode !== 0) {
274
- const resourceFailure = classifySandboxResourceFailure([
275
- result.summary,
276
- ...result.events.flatMap(resultEvent => [resultEvent.eventType, resultEvent.content, resultEvent.data ?? ""])
277
- ].join("\n"));
278
- if (resourceFailure) {
279
- return appendRunOnceEvent({
280
- ...result,
281
- summary: resourceFailure.message,
282
- events: [...result.events, event(resourceFailure.code, resourceFailure.message, { phase: "agent" })]
283
- }, memoryTelemetryEvent);
284
- }
285
- }
309
+ const rawResult = parseRunOnceResultPacket(JSON.parse(await fs.readFile(output.resultPath, "utf8")));
310
+ const result = {
311
+ ...rawResult,
312
+ resultCommitSha: output.manifest.resultCommitSha ?? rawResult.resultCommitSha ?? null,
313
+ publishedCommitSha: runtimeDispatch.sandbox.publicationMode === "bridge_push"
314
+ ? output.manifest.resultCommitSha
315
+ : rawResult.publishedCommitSha ?? null,
316
+ };
317
+ const canonicalResult = applyTrustedHostFailure(result, trustedHostFailure);
286
318
  await sink.emit(event("sandbox_output_imported", "Validated and imported sandbox output.", {
287
319
  resultCommitSha: output.manifest.resultCommitSha,
288
320
  }));
289
- return appendRunOnceEvent(result, memoryTelemetryEvent);
321
+ return appendRunOnceEvent(canonicalResult, memoryTelemetryEvent);
290
322
  }
291
323
  catch (error) {
292
- const message = error instanceof Error ? error.message : String(error);
293
- const classified = classifySandboxRuntimeFailure(message);
294
- return appendRunOnceEvent(failureResult(classified.message, [event(classified.code, classified.message, { phase: classified.phase })]), memoryTelemetryEvent);
324
+ const effectiveError = trustedHostFailure
325
+ ? new ForgeFailureError(trustedHostFailure.code, trustedHostFailure.message, "sandbox", { cause: error })
326
+ : error;
327
+ const classified = classifySandboxRuntimeFailure(effectiveError);
328
+ return appendRunOnceEvent(failureResult(classified.message, [event(classified.code, classified.message, { phase: classified.phase })], failureFactsForCode(classified.code, "sandbox")), memoryTelemetryEvent);
295
329
  }
296
330
  finally {
297
331
  try {
@@ -525,7 +559,7 @@ export class DockerSandboxRuntime {
525
559
  ledgerPath(dispatchAttemptId) {
526
560
  const attemptHex = dispatchAttemptId.replace(/-/g, "").toLowerCase();
527
561
  if (!/^[0-9a-f]{32}$/.test(attemptHex))
528
- throw new Error("sandbox_identity_invalid: dispatch attempt id must be a full UUID.");
562
+ throw trustedSandboxFailure("sandbox_identity_invalid", "dispatch attempt id must be a full UUID.");
529
563
  return path.join(this.config.sandboxStateRoot, "ledger", `${attemptHex}.json`);
530
564
  }
531
565
  async removeLedger(dispatchAttemptId) {
@@ -534,11 +568,11 @@ export class DockerSandboxRuntime {
534
568
  async buildImage(contextRoot, contextDigest, project, contract, upstreamImages, policy, sink, signal) {
535
569
  const toolingImage = process.env.FORGE_AGENT_TOOLING_IMAGE ?? "node:22.17.0-bookworm-slim";
536
570
  if (policy === "sandbox_required" && !/@sha256:[0-9a-f]{64}$/i.test(toolingImage)) {
537
- throw new Error("sandbox_build_failed: FORGE_AGENT_TOOLING_IMAGE must be digest-pinned for sandbox_required.");
571
+ throw trustedSandboxFailure("sandbox_build_failed", "FORGE_AGENT_TOOLING_IMAGE must be digest-pinned for sandbox_required.");
538
572
  }
539
573
  const codexVersion = process.env.FORGE_CODEX_PACKAGE_VERSION ?? "0.144.1";
540
574
  if (!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(codexVersion))
541
- throw new Error("sandbox_build_failed: invalid pinned Codex package version.");
575
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid pinned Codex package version.");
542
576
  const policyConfigurationDigest = await sandboxImagePolicyConfigurationDigest();
543
577
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
544
578
  const bridgeRuntimeDigest = await bridgeRuntimeContentDigest(packageRoot);
@@ -557,10 +591,10 @@ export class DockerSandboxRuntime {
557
591
  const existing = this.builds.get(key);
558
592
  if (existing) {
559
593
  await sink.emit(event("sandbox_image_cache_miss", `Sandbox image ${key.slice(0, 12)} is being built by another dispatch.`, { cacheKey: key, singleflight: true }));
560
- const waitStartedAt = Date.now();
594
+ const waitStartedAt = monotonicNowMs();
561
595
  const built = await existing;
562
596
  await sink.emit(event("sandbox_build_singleflight_wait", `Waited for the existing sandbox image build ${key.slice(0, 12)}.`, {
563
- durationMs: Date.now() - waitStartedAt,
597
+ durationMs: Math.round(monotonicNowMs() - waitStartedAt),
564
598
  imageDigest: built.imageDigest
565
599
  }));
566
600
  return built;
@@ -631,7 +665,7 @@ export class DockerSandboxRuntime {
631
665
  }
632
666
  await sink.emit(event("sandbox_image_cache_miss", `Sandbox image ${key.slice(0, 12)} requires a build.`, { cacheKey: key }));
633
667
  if (policy === "sandbox_required" && process.env.FORGE_SANDBOX_BUILD_EGRESS_ENFORCED !== "true") {
634
- throw new Error("sandbox_build_policy_failed: sandbox_required builds need an operator-enforced builder egress policy.");
668
+ throw trustedSandboxFailure("sandbox_build_policy_failed", "sandbox_required builds need an operator-enforced builder egress policy.");
635
669
  }
636
670
  const buildStartedAt = Date.now();
637
671
  await sink.emit(event("sandbox_build_started", `Building sandbox image ${key.slice(0, 12)}.`, { cacheKey: key }));
@@ -658,7 +692,7 @@ export class DockerSandboxRuntime {
658
692
  const installMode = await copyBridgePackageManifests(packageRoot, stagedBridgeRoot);
659
693
  const stagedBridgeRuntimeDigest = await bridgeRuntimeContentDigest(stagedBridgeRoot);
660
694
  if (stagedBridgeRuntimeDigest !== bridgeRuntimeDigest) {
661
- throw new Error("sandbox_build_failed: bridge runtime payload changed while preparing the sandbox image; retry the dispatch.");
695
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime payload changed while preparing the sandbox image; retry the dispatch.");
662
696
  }
663
697
  const dockerfile = agentOverlayDockerfile(toolingImage, projectContextName, installMode, codexVersion);
664
698
  await fs.writeFile(path.join(overlayRoot, "Dockerfile"), dockerfile);
@@ -666,7 +700,7 @@ export class DockerSandboxRuntime {
666
700
  await this.runBuildStage("tooling", key, buildxBuildArgs(builder, path.join(metadataRoot, "tooling.json"), ["--pull=false", "--target", "tooling", ...imageLabelArgs(project, key, "tooling", bridgeRuntimeDigest), "--tag", helperTag, overlayRoot]), sink, signal);
667
701
  const helperImageDigest = (await this.docker(["image", "inspect", helperTag, "--format", "{{.Id}}"], 15_000)).stdout.trim();
668
702
  if (!/^sha256:[0-9a-f]{64}$/i.test(helperImageDigest))
669
- throw new Error("sandbox_build_failed: helper image did not resolve to an immutable digest.");
703
+ throw trustedSandboxFailure("sandbox_build_failed", "helper image did not resolve to an immutable digest.");
670
704
  const projectContextRef = ociLayoutContextRef(path.relative(overlayRoot, projectOciRoot));
671
705
  await this.runBuildStage("agent", key, buildxBuildArgs(builder, path.join(metadataRoot, "agent.json"), [
672
706
  "--pull=false",
@@ -677,7 +711,7 @@ export class DockerSandboxRuntime {
677
711
  ]), sink, signal, { cwd: overlayRoot });
678
712
  const digest = (await this.docker(["image", "inspect", overlayTag, "--format", "{{.Id}}"], 15_000)).stdout.trim();
679
713
  if (!/^sha256:[0-9a-f]{64}$/i.test(digest))
680
- throw new Error("sandbox_build_failed: overlay image did not resolve to an immutable digest.");
714
+ throw trustedSandboxFailure("sandbox_build_failed", "overlay image did not resolve to an immutable digest.");
681
715
  const imagePolicy = await evaluateSandboxImagePolicy({
682
716
  key,
683
717
  project: dockerLabelValue(project),
@@ -752,7 +786,7 @@ export class DockerSandboxRuntime {
752
786
  byteCount: artifact.byteCount,
753
787
  truncated: artifact.truncated || result.truncated
754
788
  })).catch(() => undefined);
755
- throw new Error(`sandbox_build_failed: ${stage} image build failed; restricted log digest ${artifact.digest}.`);
789
+ throw trustedSandboxFailure("sandbox_build_failed", `${stage} image build failed; restricted log digest ${artifact.digest}.`);
756
790
  }
757
791
  async ensureBuildxBuilder(signal) {
758
792
  const name = dedicatedBuildxBuilderName(this.config.runnerId, this.config.dockerContext);
@@ -775,7 +809,7 @@ export class DockerSandboxRuntime {
775
809
  if (Number(hostConfig.PidsLimit) !== policy.builderPidsLimit
776
810
  || Number(hostConfig.Memory) !== policy.builderMemoryBytes
777
811
  || Number(hostConfig.MemorySwap) !== policy.builderMemoryBytes) {
778
- throw new Error("sandbox_build_policy_failed: dedicated BuildKit builder resource limits were not applied.");
812
+ throw trustedSandboxFailure("sandbox_build_policy_failed", "dedicated BuildKit builder resource limits were not applied.");
779
813
  }
780
814
  return name;
781
815
  }
@@ -848,10 +882,10 @@ export class DockerSandboxRuntime {
848
882
  return null;
849
883
  const image = process.env.FORGE_SANDBOX_EGRESS_PROXY_IMAGE?.trim();
850
884
  if (!image || !/@sha256:[0-9a-f]{64}$/iu.test(image)) {
851
- throw new Error("sandbox_egress_proxy_unavailable: public_allowlist needs a digest-pinned Squid-compatible proxy image.");
885
+ throw trustedSandboxFailure("sandbox_egress_proxy_unavailable", "public_allowlist needs a digest-pinned Squid-compatible proxy image.");
852
886
  }
853
887
  if (process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
854
- throw new Error("sandbox_egress_proxy_unavailable: runner egress enforcement is not enabled.");
888
+ throw trustedSandboxFailure("sandbox_egress_proxy_unavailable", "runner egress enforcement is not enabled.");
855
889
  }
856
890
  await this.verifyCatalogImage(image, dispatch.sandbox.executionPolicy, sink, signal);
857
891
  const name = `${resources.prefix}-egress`;
@@ -892,8 +926,8 @@ export class DockerSandboxRuntime {
892
926
  await sink.emit(event("sandbox_image_signature_warning", `Image signature enforcement is not configured for adoption-mode image ${image}.`));
893
927
  }
894
928
  async waitForServiceHealthy(name, signal) {
895
- const deadline = Date.now() + 60_000;
896
- while (Date.now() < deadline) {
929
+ const deadline = monotonicNowMs() + 60_000;
930
+ while (monotonicNowMs() < deadline) {
897
931
  if (signal?.aborted)
898
932
  throw new Error(String(signal.reason ?? "sandbox service startup cancelled"));
899
933
  const status = (await this.docker(["container", "inspect", name, "--format", "{{.State.Health.Status}}"], 10_000, signal)).stdout.trim();
@@ -1107,6 +1141,13 @@ export class DockerSandboxRuntime {
1107
1141
  docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
1108
1142
  return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
1109
1143
  }
1144
+ /** The container's init process: stopping it stops every process in the sandbox. */
1145
+ async containerInitProcess(containerId) {
1146
+ const pid = Number((await this.docker(["inspect", "--format", "{{.State.Pid}}", containerId], 10_000)).stdout.trim());
1147
+ return Number.isSafeInteger(pid) && pid > 1
1148
+ ? { rootPid: pid, rootIdentity: captureHostProcessIdentity(pid), processGroup: false }
1149
+ : null;
1150
+ }
1110
1151
  dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
1111
1152
  }
1112
1153
  class HostGit {
@@ -1162,7 +1203,7 @@ class HostGit {
1162
1203
  || !resultCommitSha
1163
1204
  || handle.branch !== dispatch.lease.worktreeKey
1164
1205
  || !/^[0-9a-f-]{32,36}$/iu.test(handle.grantId)) {
1165
- throw new Error("sandbox_output_publish_forbidden: remote publication grant is missing or outside its attempt scope.");
1206
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "remote publication grant is missing or outside its attempt scope.");
1166
1207
  }
1167
1208
  assertCurrent();
1168
1209
  const credentialEnvironment = publicationCredentialEnvironment(credential);
@@ -1202,15 +1243,15 @@ class HostGit {
1202
1243
  terminateOnOutputLimit: true
1203
1244
  });
1204
1245
  if (objectInventory.exitCode !== 0 || objectInventory.truncated) {
1205
- throw new Error("sandbox_output_invalid: Git bundle exceeds object validation limits.");
1246
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds object validation limits.");
1206
1247
  }
1207
1248
  validateGitObjectBudget(objectInventory.stdout);
1208
1249
  const imported = (await quarantineGit(quarantine, ["rev-parse", `${importRef}^{commit}`], 30_000)).stdout.trim();
1209
1250
  if (imported !== output.manifest.resultCommitSha)
1210
- throw new Error("sandbox_output_invalid: imported result SHA differs from manifest.");
1251
+ throw trustedSandboxFailure("sandbox_output_invalid", "imported result SHA differs from manifest.");
1211
1252
  const ancestry = await runSandboxProcess({ command: "git", args: ["-C", quarantine, "merge-base", "--is-ancestor", output.manifest.inputCommitSha, imported], timeoutMs: 30_000 });
1212
1253
  if (ancestry.exitCode !== 0)
1213
- throw new Error("sandbox_output_invalid: result commit is not descended from input commit.");
1254
+ throw trustedSandboxFailure("sandbox_output_invalid", "result commit is not descended from input commit.");
1214
1255
  const commitDepth = await quarantineGit(quarantine, ["rev-list", "--count", `${output.manifest.inputCommitSha}..${imported}`], 2 * 60_000);
1215
1256
  validateGitCommitDepth(commitDepth.stdout);
1216
1257
  await this.git(["fetch", "--no-write-fetch-head", quarantine, `${importRef}:${importRef}`], 5 * 60_000);
@@ -1238,7 +1279,7 @@ class HostGit {
1238
1279
  const head = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "rev-parse", "HEAD"], timeoutMs: 30_000 })).stdout.trim();
1239
1280
  const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
1240
1281
  if (head !== expected || status.trim())
1241
- throw new Error("sandbox_output_conflict: managed worktree changed after sandbox input was captured.");
1282
+ throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
1242
1283
  await this.git(["update-ref", branchRef, imported, expected], 30_000);
1243
1284
  await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
1244
1285
  }
@@ -1249,7 +1290,7 @@ class HostGit {
1249
1290
  if (result.exitCode === 0 && /^[0-9a-f]{40,64}$/i.test(sha))
1250
1291
  return sha;
1251
1292
  }
1252
- throw new Error("sandbox_input_failed: no approved input Git ref could be resolved.");
1293
+ throw trustedSandboxFailure("sandbox_input_failed", "no approved input Git ref could be resolved.");
1253
1294
  }
1254
1295
  git(args, timeoutMs, signal, env) { return requireSandboxProcess({ command: "git", args: ["-C", this.repoPath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024, signal, env }); }
1255
1296
  }
@@ -1259,19 +1300,19 @@ export function managedBranchUpdateExpectedValue(current, expectedInput, importe
1259
1300
  return "0".repeat(imported.length);
1260
1301
  }
1261
1302
  if (normalized !== expectedInput) {
1262
- throw new Error("sandbox_output_conflict: managed branch changed after sandbox input was captured.");
1303
+ throw trustedSandboxFailure("sandbox_output_conflict", "managed branch changed after sandbox input was captured.");
1263
1304
  }
1264
1305
  return normalized;
1265
1306
  }
1266
1307
  export function publicationPushArgs(branch, resultCommitSha, inputCommitSha, remoteCommitSha, remote = "origin") {
1267
1308
  const isCommit = (value) => /^[0-9a-f]{40,64}$/iu.test(value);
1268
1309
  if (!branch || branch.length > 240 || !isCommit(resultCommitSha) || !isCommit(inputCommitSha) || (remoteCommitSha && !isCommit(remoteCommitSha))) {
1269
- throw new Error("sandbox_output_publish_rejected: publication inputs contain an invalid branch or object id.");
1310
+ throw trustedSandboxFailure("sandbox_output_publish_rejected", "publication inputs contain an invalid branch or object id.");
1270
1311
  }
1271
1312
  if (remoteCommitSha === resultCommitSha)
1272
1313
  return null;
1273
1314
  if (remoteCommitSha && remoteCommitSha !== inputCommitSha) {
1274
- throw new Error("sandbox_output_publish_stale: remote branch changed after the sandbox input was captured.");
1315
+ throw trustedSandboxFailure("sandbox_output_publish_stale", "remote branch changed after the sandbox input was captured.");
1275
1316
  }
1276
1317
  const remoteRef = `refs/heads/${branch}`;
1277
1318
  return [
@@ -1303,7 +1344,7 @@ export function validatePublicationCredential(credential, nowMs = Date.now()) {
1303
1344
  || credential.secret.length > 16 * 1024
1304
1345
  || /[\r\n\0]/u.test(credential.secret)
1305
1346
  || Date.parse(credential.expiresAt) <= nowMs) {
1306
- throw new Error("sandbox_output_publish_forbidden: redeemed publication credential is invalid or expired.");
1347
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "redeemed publication credential is invalid or expired.");
1307
1348
  }
1308
1349
  }
1309
1350
  export function publicationCredentialEnvironment(credential, environment = process.env) {
@@ -1333,7 +1374,7 @@ export function restrictedBuildLog(source, exactSecrets = [], maximumBytes = 4 *
1333
1374
  export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000, maximumExpandedBytes = 2 * 1024 * 1024 * 1024) {
1334
1375
  const lines = inventory.split(/\r?\n/u).filter(Boolean);
1335
1376
  if (lines.length === 0 || lines.length > maximumObjectCount) {
1336
- throw new Error("sandbox_output_invalid: Git bundle exceeds the object-count budget.");
1377
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds the object-count budget.");
1337
1378
  }
1338
1379
  const maximum = BigInt(maximumExpandedBytes);
1339
1380
  let expanded = 0n;
@@ -1341,13 +1382,13 @@ export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000,
1341
1382
  for (const line of lines) {
1342
1383
  const match = /^([0-9a-f]{40}|[0-9a-f]{64}) (blob|tree|commit|tag) ([0-9]+)$/iu.exec(line);
1343
1384
  if (!match || objects.has(match[1].toLowerCase())) {
1344
- throw new Error("sandbox_output_invalid: Git object inventory is malformed or duplicated.");
1385
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git object inventory is malformed or duplicated.");
1345
1386
  }
1346
1387
  objects.add(match[1].toLowerCase());
1347
1388
  const size = BigInt(match[3]);
1348
1389
  expanded += size;
1349
1390
  if (size > maximum || expanded > maximum) {
1350
- throw new Error("sandbox_output_invalid: Git bundle exceeds the expanded-object byte budget.");
1391
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds the expanded-object byte budget.");
1351
1392
  }
1352
1393
  }
1353
1394
  return { objectCount: lines.length, expandedBytes: Number(expanded) };
@@ -1355,11 +1396,11 @@ export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000,
1355
1396
  export function validateGitCommitDepth(value, maximumCommitDepth = 50_000) {
1356
1397
  const normalized = value.trim();
1357
1398
  if (!/^[0-9]+$/u.test(normalized)) {
1358
- throw new Error("sandbox_output_invalid: Git commit-depth result is malformed.");
1399
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git commit-depth result is malformed.");
1359
1400
  }
1360
1401
  const depth = BigInt(normalized);
1361
1402
  if (depth > BigInt(maximumCommitDepth)) {
1362
- throw new Error("sandbox_output_invalid: Git result exceeds the commit-depth budget.");
1403
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git result exceeds the commit-depth budget.");
1363
1404
  }
1364
1405
  return Number(depth);
1365
1406
  }
@@ -1375,10 +1416,10 @@ export function selectAuditArtifactGcCandidates(records, retentionCount, retenti
1375
1416
  export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultBranch) {
1376
1417
  const approvedSha = configuredSha?.trim().toLowerCase() || null;
1377
1418
  if (executionPolicy === "sandbox_required" && !approvedSha) {
1378
- throw new Error("sandbox_config_commit_unapproved: sandbox_required dispatches need a server-approved config commit SHA.");
1419
+ throw trustedSandboxFailure("sandbox_config_commit_unapproved", "sandbox_required dispatches need a server-approved config commit SHA.");
1379
1420
  }
1380
1421
  if (approvedSha && !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(approvedSha)) {
1381
- throw new Error("sandbox_config_commit_invalid: approved sandbox config commit is not a full Git object id.");
1422
+ throw trustedSandboxFailure("sandbox_config_commit_invalid", "approved sandbox config commit is not a full Git object id.");
1382
1423
  }
1383
1424
  return approvedSha
1384
1425
  ? { refs: [approvedSha], approvedSha }
@@ -1423,12 +1464,12 @@ async function validateOutput(attemptRoot, dispatch) {
1423
1464
  const manifestPath = path.join(outputRoot, "manifest.json");
1424
1465
  const stat = await fs.lstat(manifestPath).catch(error => {
1425
1466
  if (isNodeErrorWithCode(error, "ENOENT")) {
1426
- throw new Error("sandbox_output_missing: sandbox worker did not produce manifest.json.");
1467
+ throw trustedSandboxFailure("sandbox_output_missing", "sandbox worker did not produce manifest.json.");
1427
1468
  }
1428
1469
  throw error;
1429
1470
  });
1430
1471
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
1431
- throw new Error("sandbox_output_invalid: manifest must be a bounded regular file.");
1472
+ throw trustedSandboxFailure("sandbox_output_invalid", "manifest must be a bounded regular file.");
1432
1473
  const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
1433
1474
  if (!dispatch.sandbox
1434
1475
  || manifest.dispatchAttemptId !== dispatch.sandbox.dispatchAttemptId
@@ -1439,10 +1480,10 @@ async function validateOutput(attemptRoot, dispatch) {
1439
1480
  || manifest.branch !== dispatch.lease.worktreeKey
1440
1481
  || manifest.contractDigest !== dispatch.sandbox.contractDigest
1441
1482
  || manifest.imageDigest !== dispatch.sandbox.imageDigest)
1442
- throw new Error("sandbox_output_invalid: manifest identity or fence mismatch.");
1483
+ throw trustedSandboxFailure("sandbox_output_invalid", "manifest identity or fence mismatch.");
1443
1484
  if ((manifest.resultCommitSha === null) !== (manifest.bundle === null)
1444
1485
  || (manifest.resultCommitSha !== null && !/^[0-9a-f]{40,64}$/i.test(manifest.resultCommitSha))) {
1445
- throw new Error("sandbox_output_invalid: result commit and bundle must be present together.");
1486
+ throw trustedSandboxFailure("sandbox_output_invalid", "result commit and bundle must be present together.");
1446
1487
  }
1447
1488
  const resultPath = await validateManifestFile(outputRoot, manifest.result, 16 * 1024 * 1024);
1448
1489
  const bundlePath = manifest.bundle ? await validateManifestFile(outputRoot, manifest.bundle, 512 * 1024 * 1024) : null;
@@ -1450,14 +1491,14 @@ async function validateOutput(attemptRoot, dispatch) {
1450
1491
  }
1451
1492
  async function validateManifestFile(root, file, max) {
1452
1493
  if (!/^[a-z0-9_.-]+$/i.test(file.path))
1453
- throw new Error("sandbox_output_invalid: output path is invalid.");
1494
+ throw trustedSandboxFailure("sandbox_output_invalid", "output path is invalid.");
1454
1495
  const target = path.join(root, file.path);
1455
1496
  const stat = await fs.lstat(target);
1456
1497
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== file.bytes || stat.size > max)
1457
- throw new Error("sandbox_output_invalid: output file bounds mismatch.");
1498
+ throw trustedSandboxFailure("sandbox_output_invalid", "output file bounds mismatch.");
1458
1499
  const digest = createHash("sha256").update(await fs.readFile(target)).digest("hex");
1459
1500
  if (digest !== file.sha256)
1460
- throw new Error("sandbox_output_invalid: output hash mismatch.");
1501
+ throw trustedSandboxFailure("sandbox_output_invalid", "output hash mismatch.");
1461
1502
  return target;
1462
1503
  }
1463
1504
  function isMissingSandboxManifest(error) {
@@ -1479,7 +1520,7 @@ export function sandboxWorkerFailureMessage(exitCode, stderr, containerError) {
1479
1520
  function identityFor(dispatch) {
1480
1521
  const value = dispatch.sandbox?.dispatchAttemptId.replace(/-/g, "").toLowerCase() ?? "";
1481
1522
  if (!/^[0-9a-f]{32}$/.test(value))
1482
- throw new Error("sandbox_identity_invalid: dispatch attempt id must be a full UUID.");
1523
+ throw trustedSandboxFailure("sandbox_identity_invalid", "dispatch attempt id must be a full UUID.");
1483
1524
  return { attemptHex: value };
1484
1525
  }
1485
1526
  class SandboxTeardownError extends Error {
@@ -1688,7 +1729,7 @@ export function assertSandboxImportCurrent(expected, current, signal, nowMs = Da
1688
1729
  || current.dispatchAttemptId !== expected.dispatchAttemptId
1689
1730
  || current.fencingToken !== expected.fencingToken
1690
1731
  || Date.parse(expected.expiresAt) <= nowMs) {
1691
- throw new Error("sandbox_output_stale: output cannot move the managed ref because its attempt, fence, or lease is no longer current.");
1732
+ throw trustedSandboxFailure("sandbox_output_stale", "output cannot move the managed ref because its attempt, fence, or lease is no longer current.");
1692
1733
  }
1693
1734
  }
1694
1735
  export function validSandboxLedger(value) {
@@ -1830,7 +1871,7 @@ export function sandboxResourceLabels(dispatch, image, contract) {
1830
1871
  ];
1831
1872
  const invalid = ownershipIds.find(([, value]) => !isFullUuid(value));
1832
1873
  if (invalid)
1833
- throw new Error(`sandbox_identity_invalid: ${invalid[0]} id must be a full UUID.`);
1874
+ throw trustedSandboxFailure("sandbox_identity_invalid", `${invalid[0]} id must be a full UUID.`);
1834
1875
  return {
1835
1876
  "dev.forge.managed": "true", "dev.forge.session-id": dispatch.session.id, "dev.forge.resource-lease-id": resourceLeaseId, "dev.forge.execution-lease-id": resourceLeaseId,
1836
1877
  "dev.forge.dispatch-attempt-id": dispatch.sandbox.dispatchAttemptId, "dev.forge.fencing-token": dispatch.lease.fencingToken,
@@ -1919,13 +1960,13 @@ export async function extractOciLayoutArchive(archivePath, destination, signal)
1919
1960
  signal
1920
1961
  });
1921
1962
  if (result.exitCode !== 0 || result.truncated) {
1922
- throw new Error(`sandbox_build_failed: project OCI layout extraction failed with exit code ${result.exitCode}; ${formatOciExtractionFailure(result)}. Archive retained at ${archivePath}.`);
1963
+ throw trustedSandboxFailure("sandbox_build_failed", `project OCI layout extraction failed with exit code ${result.exitCode}; ${formatOciExtractionFailure(result)}. Archive retained at ${archivePath}.`);
1923
1964
  }
1924
1965
  await fs.rm(archivePath, { force: true }).catch(() => undefined);
1925
1966
  }
1926
1967
  export function ociLayoutContextRef(layoutPath) {
1927
1968
  if (/^[A-Za-z]:[\\/]/u.test(layoutPath)) {
1928
- throw new Error("sandbox_build_failed: Windows absolute OCI layout paths are not BuildKit-safe; use a relative path from the build working directory.");
1969
+ throw trustedSandboxFailure("sandbox_build_failed", "Windows absolute OCI layout paths are not BuildKit-safe; use a relative path from the build working directory.");
1929
1970
  }
1930
1971
  const normalized = layoutPath.replace(/\\/gu, "/").replace(/^\.\//u, "");
1931
1972
  // BuildKit's oci-layout resolver expects a raw filesystem path here; it does not percent-decode
@@ -1945,7 +1986,7 @@ export async function readOciLayoutImageDigest(layoutRoot) {
1945
1986
  && /^sha256:[0-9a-f]{64}$/iu.test(entry.digest)
1946
1987
  && entry.annotations?.["vnd.docker.reference.type"] !== "attestation-manifest");
1947
1988
  if (!manifest || typeof manifest.digest !== "string") {
1948
- throw new Error("sandbox_build_failed: project OCI layout did not expose an immutable image digest.");
1989
+ throw trustedSandboxFailure("sandbox_build_failed", "project OCI layout did not expose an immutable image digest.");
1949
1990
  }
1950
1991
  return manifest.digest;
1951
1992
  }
@@ -1980,11 +2021,11 @@ export async function bridgeRuntimeContentDigest(packageRoot) {
1980
2021
  const distRoot = path.join(root, "dist");
1981
2022
  const distStat = await fs.lstat(distRoot).catch(() => null);
1982
2023
  if (!distStat?.isDirectory() || distStat.isSymbolicLink()) {
1983
- throw new Error("sandbox_build_failed: bridge runtime dist must be a real directory.");
2024
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime dist must be a real directory.");
1984
2025
  }
1985
2026
  const distFiles = await collectBridgeRuntimeFiles(root, "dist");
1986
2027
  if (distFiles.length === 0) {
1987
- throw new Error("sandbox_build_failed: bridge runtime dist is empty.");
2028
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime dist is empty.");
1988
2029
  }
1989
2030
  const files = [packageManifest, ...(lockManifest ? [lockManifest] : []), ...distFiles]
1990
2031
  .sort((left, right) => compareBridgeRuntimePaths(left.relativePath, right.relativePath));
@@ -2003,7 +2044,7 @@ export async function bridgeRuntimeContentDigest(packageRoot) {
2003
2044
  async function requireBridgeRuntimeFile(root, relativePath) {
2004
2045
  const file = await optionalBridgeRuntimeFile(root, relativePath);
2005
2046
  if (!file)
2006
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath} is missing.`);
2047
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath} is missing.`);
2007
2048
  return file;
2008
2049
  }
2009
2050
  async function optionalBridgeRuntimeFile(root, relativePath) {
@@ -2012,7 +2053,7 @@ async function optionalBridgeRuntimeFile(root, relativePath) {
2012
2053
  if (!stat)
2013
2054
  return null;
2014
2055
  if (!stat.isFile() || stat.isSymbolicLink()) {
2015
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath} must be a regular file.`);
2056
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath} must be a regular file.`);
2016
2057
  }
2017
2058
  return { absolutePath, relativePath: relativePath.replace(/\\/gu, "/") };
2018
2059
  }
@@ -2024,14 +2065,14 @@ async function collectBridgeRuntimeFiles(root, relativeDirectory) {
2024
2065
  for (const entry of entries) {
2025
2066
  const relativePath = path.join(relativeDirectory, entry.name);
2026
2067
  if (entry.isSymbolicLink()) {
2027
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath.replace(/\\/gu, "/")} cannot be a symbolic link.`);
2068
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath.replace(/\\/gu, "/")} cannot be a symbolic link.`);
2028
2069
  }
2029
2070
  if (entry.isDirectory()) {
2030
2071
  files.push(...await collectBridgeRuntimeFiles(root, relativePath));
2031
2072
  continue;
2032
2073
  }
2033
2074
  if (!entry.isFile()) {
2034
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath.replace(/\\/gu, "/")} must be a regular file.`);
2075
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath.replace(/\\/gu, "/")} must be a regular file.`);
2035
2076
  }
2036
2077
  files.push({
2037
2078
  absolutePath: path.join(root, relativePath),
@@ -2086,7 +2127,7 @@ async function copyOptionalBridgeManifest(packageRoot, bridgeRoot, fileName) {
2086
2127
  }
2087
2128
  export function buildxBuildArgs(builder, metadataFile, tail, environment = process.env, options = {}) {
2088
2129
  if (!/^forge-[0-9a-f]{20}$/u.test(builder))
2089
- throw new Error("sandbox_build_failed: invalid dedicated builder name.");
2130
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid dedicated builder name.");
2090
2131
  const resources = buildResourcePolicy(environment);
2091
2132
  const args = ["buildx", "build", "--builder", builder];
2092
2133
  if (options.load !== false)
@@ -2108,7 +2149,7 @@ export function dedicatedBuildxBuilderName(runnerId, dockerContext) {
2108
2149
  }
2109
2150
  export function dedicatedBuildxBuilderContainerName(builder) {
2110
2151
  if (!/^forge-[0-9a-f]{20}$/u.test(builder))
2111
- throw new Error("sandbox_build_failed: invalid dedicated builder name.");
2152
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid dedicated builder name.");
2112
2153
  return `buildx_buildkit_${builder}0`;
2113
2154
  }
2114
2155
  function boundedBuildCacheSize(value, fallback) {
@@ -2132,7 +2173,7 @@ export function selectImageGcCandidates(records, keepPerProject, ttlMs, nowMs) {
2132
2173
  async function sandboxProviderAuthForDispatch(dispatch) {
2133
2174
  const unavailable = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2134
2175
  if (unavailable) {
2135
- throw new Error(`sandbox_auth_unavailable: ${unavailable}`);
2176
+ throw trustedSandboxFailure("sandbox_auth_unavailable", unavailable);
2136
2177
  }
2137
2178
  const adapter = sandboxProviderAuthAdapterFor(dispatch.execution.provider, dispatch.execution.authKind);
2138
2179
  return adapter ? adapter.prepareAttemptAuth() : null;
@@ -2176,7 +2217,7 @@ export function proxyEnvironmentArgs(dispatch, contract, resources) {
2176
2217
  export function egressProxyConfig(allowedHosts) {
2177
2218
  const domains = allowedHosts.map(host => host.startsWith("*.") ? `.${host.slice(2)}` : host).join(" ");
2178
2219
  if (!domains)
2179
- throw new Error("sandbox_egress_policy_invalid: public_allowlist requires at least one approved host.");
2220
+ throw trustedSandboxFailure("sandbox_egress_policy_invalid", "public_allowlist requires at least one approved host.");
2180
2221
  return [
2181
2222
  "http_port 3128",
2182
2223
  "access_log none",
@@ -2208,7 +2249,7 @@ export function serviceContainerArgs(service, image, resources, labels, security
2208
2249
  else {
2209
2250
  const healthCommand = environment.FORGE_SERVICE_BROWSER_HEALTH_CMD?.trim();
2210
2251
  if (!healthCommand || /[\r\n\0]/u.test(healthCommand) || healthCommand.length > 1000) {
2211
- throw new Error("sandbox_service_health_policy_invalid: browser service needs an operator-configured bounded health command.");
2252
+ throw trustedSandboxFailure("sandbox_service_health_policy_invalid", "browser service needs an operator-configured bounded health command.");
2212
2253
  }
2213
2254
  args.push("--env", "FORGE_BROWSER_TOKEN_FILE=/run/secrets/browser-token", "--volume", `${resources.secretsVolume}:/run/secrets:ro`, "--health-cmd", healthCommand, "--health-interval", "1s", "--health-timeout", "5s", "--health-retries", "60");
2214
2255
  }
@@ -2221,13 +2262,13 @@ export function resolveSandboxSecurityOptions(executionPolicy, environment = pro
2221
2262
  const seccomp = environment.FORGE_SANDBOX_SECCOMP_PROFILE?.trim();
2222
2263
  const lsm = environment.FORGE_SANDBOX_LSM_SECURITY_OPT?.trim();
2223
2264
  if (seccomp && (!path.isAbsolute(seccomp) || /[\r\n\0]/u.test(seccomp))) {
2224
- throw new Error("sandbox_security_profile_invalid: seccomp profile must be an absolute host path.");
2265
+ throw trustedSandboxFailure("sandbox_security_profile_invalid", "seccomp profile must be an absolute host path.");
2225
2266
  }
2226
2267
  if (lsm && !/^(?:apparmor=[a-zA-Z0-9_.-]{1,128}|label=[a-zA-Z0-9_:,.-]{1,256})$/u.test(lsm)) {
2227
- throw new Error("sandbox_security_profile_invalid: LSM security option is invalid.");
2268
+ throw trustedSandboxFailure("sandbox_security_profile_invalid", "LSM security option is invalid.");
2228
2269
  }
2229
2270
  if (executionPolicy === "sandbox_required" && (!seccomp || !lsm)) {
2230
- throw new Error("sandbox_security_profile_unavailable: sandbox_required needs explicit seccomp and LSM profiles.");
2271
+ throw trustedSandboxFailure("sandbox_security_profile_unavailable", "sandbox_required needs explicit seccomp and LSM profiles.");
2231
2272
  }
2232
2273
  return [
2233
2274
  ...(seccomp ? ["--security-opt", `seccomp=${seccomp}`] : []),
@@ -2263,17 +2304,46 @@ function event(eventType, content, data) {
2263
2304
  };
2264
2305
  }
2265
2306
  export function classifySandboxRuntimeFailure(value) {
2266
- const message = value.replace(/[\r\n\t]+/gu, " ").trim().slice(0, 2000) || "Sandbox execution failed.";
2267
- const explicit = /^([a-z][a-z0-9_.-]{2,79}):/u.exec(message)?.[1] ?? null;
2268
- let code = explicit ?? "sandbox_runtime_failed";
2269
- if (/no space left|disk quota exceeded|enospc/iu.test(message))
2270
- code = "sandbox_storage_exhausted";
2271
- const phase = code.startsWith("sandbox_build") || code.startsWith("image_") ? "build"
2272
- : code.startsWith("sandbox_output") || code.startsWith("sandbox_import") ? "import"
2273
- : code.startsWith("teardown") ? "teardown"
2274
- : code.startsWith("sandbox_config") || code.startsWith("sandbox_auth") || code.startsWith("contract_") || code.startsWith("sandbox_input") || code.startsWith("sandbox_create") ? "prepare"
2275
- : "agent";
2276
- return { code, phase, message };
2307
+ const message = (value instanceof Error ? value.message : String(value))
2308
+ .replace(/[\r\n\t]+/gu, " ")
2309
+ .trim()
2310
+ .slice(0, 2000) || "Sandbox execution failed.";
2311
+ const code = value instanceof ForgeFailureError
2312
+ ? value.failureCode
2313
+ : "sandbox_runtime_failed";
2314
+ return { code, phase: failurePolicyForCode(code).phase, message };
2315
+ }
2316
+ export function applyTrustedHostFailure(result, trustedFailure) {
2317
+ if (!trustedFailure)
2318
+ return result;
2319
+ const originalFailure = result.failure
2320
+ ? [{
2321
+ code: result.failure.code,
2322
+ message: result.failure.message,
2323
+ source: result.failure.source,
2324
+ }, ...result.failure.causalChain]
2325
+ : result.exitCode === 0
2326
+ ? []
2327
+ : [{
2328
+ code: "sandbox_child_result_unknown",
2329
+ message: result.summary,
2330
+ source: "sandbox",
2331
+ }];
2332
+ const facts = {
2333
+ ...failureFactsForCode(trustedFailure.code, "sandbox"),
2334
+ causalChain: originalFailure,
2335
+ };
2336
+ return {
2337
+ ...result,
2338
+ schemaVersion: 2,
2339
+ exitCode: result.exitCode === 0 ? 1 : result.exitCode,
2340
+ summary: trustedFailure.message,
2341
+ failure: createFailureEnvelope(trustedFailure.message, facts),
2342
+ events: [
2343
+ ...result.events,
2344
+ event(trustedFailure.code, trustedFailure.message, { phase: facts.phase }),
2345
+ ],
2346
+ };
2277
2347
  }
2278
2348
  export function classifySandboxResourceFailure(value) {
2279
2349
  const diagnostic = value.replace(/[\r\n\t]+/gu, " ").trim().slice(0, 2000);
@@ -2293,6 +2363,9 @@ export function classifySandboxResourceFailure(value) {
2293
2363
  }
2294
2364
  return null;
2295
2365
  }
2366
+ function trustedSandboxFailure(code, detail, options) {
2367
+ return new ForgeFailureError(code, `${code}: ${detail}`, "sandbox", options);
2368
+ }
2296
2369
  function parseSandboxEventLine(line) {
2297
2370
  if (!line.trim().startsWith("{"))
2298
2371
  return null;
@@ -2307,25 +2380,25 @@ function parseSandboxEventLine(line) {
2307
2380
  return null;
2308
2381
  const candidate = value.event;
2309
2382
  if (!candidate || typeof candidate !== "object")
2310
- throw new Error("sandbox_event_invalid: runner event envelope is missing event data.");
2383
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event envelope is missing event data.");
2311
2384
  const eventValue = candidate;
2312
2385
  for (const field of ["role", "kind", "content", "eventType"]) {
2313
2386
  if (typeof eventValue[field] !== "string")
2314
- throw new Error(`sandbox_event_invalid: ${field} must be a string.`);
2387
+ throw trustedSandboxFailure("sandbox_event_invalid", `${field} must be a string.`);
2315
2388
  }
2316
2389
  if (eventValue.role.length > 64
2317
2390
  || eventValue.kind.length > 128
2318
2391
  || eventValue.eventType.length > 128
2319
2392
  || Buffer.byteLength(eventValue.content, "utf8") > 256 * 1024) {
2320
- throw new Error("sandbox_event_invalid: runner event exceeds field bounds.");
2393
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event exceeds field bounds.");
2321
2394
  }
2322
2395
  if (eventValue.data !== undefined && eventValue.data !== null
2323
2396
  && (typeof eventValue.data !== "string" || Buffer.byteLength(eventValue.data, "utf8") > 256 * 1024)) {
2324
- throw new Error("sandbox_event_invalid: runner event data exceeds field bounds.");
2397
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event data exceeds field bounds.");
2325
2398
  }
2326
2399
  if (eventValue.occurredAt !== undefined && eventValue.occurredAt !== null
2327
2400
  && (typeof eventValue.occurredAt !== "string" || !Number.isFinite(Date.parse(eventValue.occurredAt)))) {
2328
- throw new Error("sandbox_event_invalid: runner event occurredAt is invalid.");
2401
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event occurredAt is invalid.");
2329
2402
  }
2330
2403
  return {
2331
2404
  role: eventValue.role,