@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
@@ -0,0 +1,334 @@
1
+ import { hostLoadStepCostForClass } from "../runtime/host-load-step-class.js";
2
+ import { takesHostTestSlot } from "../runtime/host-load-test-slot.js";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ // Host side of Docker-sandbox admission (decision 0013). The validator inside a
5
+ // container cannot reach the host ledger, so it asks the bridge over the
6
+ // channels the sandbox already has: a request line on the worker's stdout
7
+ // (which the bridge parses anyway) and a response file the bridge writes with
8
+ // `docker exec`. The bridge's own governor holds the token, renews it, and
9
+ // returns it when the sandbox releases it or exits, so Docker steps share the
10
+ // host budget.
11
+ //
12
+ // Replies are unforgeable from inside the sandbox. They live on their own tmpfs
13
+ // owned by root with mode 0755, mounted only for brokered workers, and are
14
+ // written by `docker exec --user 0`. The workload runs as uid 10001 with every
15
+ // capability dropped and no-new-privileges, so it can neither write there nor
16
+ // create any root-owned file anywhere, and a mount point cannot be renamed
17
+ // away. The validator accepts only a regular, root-owned, single-link reply
18
+ // that no one else can write (sandbox-host-capacity-gate.ts).
19
+ export const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
20
+ export const sandboxHostCapacityBrokerProtocol = "stdout-v1";
21
+ export const sandboxHostCapacityLineType = "forge_host_capacity";
22
+ export const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
23
+ /** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
24
+ export const sandboxHostCapacityResponseOwnerUid = 0;
25
+ export const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
26
+ const requestIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
27
+ const stepClassPattern = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
28
+ /** A sandbox validates one step at a time; a small bound stops a runaway from hoarding tokens. */
29
+ const defaultMaximumOutstanding = 2;
30
+ /** A validation run sends two lines per step; this leaves room for reruns and caps docker exec churn. */
31
+ const defaultBurst = 40;
32
+ const defaultRefillPerSecond = 2;
33
+ function codeOf(error) {
34
+ const code = error?.code;
35
+ return typeof code === "string" ? code : null;
36
+ }
37
+ function hasCode(error, code) {
38
+ return codeOf(error) === code;
39
+ }
40
+ /** Parses one stdout line; null when it is not a well-formed broker request. */
41
+ export function parseSandboxHostCapacityRequest(line) {
42
+ const trimmed = line.trim();
43
+ if (!trimmed.startsWith("{") || !trimmed.includes(sandboxHostCapacityLineType) || trimmed.length > 4096)
44
+ return null;
45
+ let value;
46
+ try {
47
+ value = JSON.parse(trimmed);
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ if (!value || value.type !== sandboxHostCapacityLineType || value.version !== 1)
53
+ return null;
54
+ if (value.action !== "acquire" && value.action !== "release" && value.action !== "retain")
55
+ return null;
56
+ if (typeof value.requestId !== "string" || !requestIdPattern.test(value.requestId))
57
+ return null;
58
+ const claimed = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
59
+ // A sandbox brokers only validation steps; it cannot claim a class that skips the host test slot.
60
+ const stepClass = takesHostTestSlot(claimed) ? claimed : "generic";
61
+ // Diagnostics only, but never control characters or markup from the sandbox.
62
+ const label = typeof value.label === "string" ? value.label.replace(/[^\w .:/@+-]/gu, "_").slice(0, 128) : "";
63
+ return { action: value.action, requestId: value.requestId, stepClass, label };
64
+ }
65
+ /**
66
+ * One sandbox's brokered tokens. The sandbox never chooses the cost or the
67
+ * attempt. Replies for one request go out one at a time, newest state only,
68
+ * each with a rising sequence the container-side writer uses to refuse an
69
+ * older reply; a failed delivery is retried until a newer state replaces it
70
+ * or the broker closes. A sandbox that floods requests or exceeds its
71
+ * outstanding limit stops the broker and fails its attempt.
72
+ */
73
+ export class SandboxHostCapacityBroker {
74
+ gate;
75
+ dispatchAttemptId;
76
+ priority;
77
+ deliver;
78
+ options;
79
+ tokens = new Map();
80
+ deliveries = new Map();
81
+ work = new Set();
82
+ maximumOutstanding;
83
+ burst;
84
+ refillPerSecond;
85
+ retryMs;
86
+ now;
87
+ sequence = 0;
88
+ allowance;
89
+ allowanceAtMs;
90
+ closed = false;
91
+ abuse = null;
92
+ constructor(gate, dispatchAttemptId, priority, deliver, options = {}) {
93
+ this.gate = gate;
94
+ this.dispatchAttemptId = dispatchAttemptId;
95
+ this.priority = priority;
96
+ this.deliver = deliver;
97
+ this.options = options;
98
+ this.maximumOutstanding = options.maximumOutstanding ?? defaultMaximumOutstanding;
99
+ this.burst = options.burst ?? defaultBurst;
100
+ this.refillPerSecond = options.refillPerSecond ?? defaultRefillPerSecond;
101
+ this.retryMs = options.retryMs ?? 250;
102
+ this.now = options.now ?? Date.now;
103
+ this.allowance = this.burst;
104
+ this.allowanceAtMs = this.now();
105
+ }
106
+ /**
107
+ * True when the line was a broker request; such a line is never a runner
108
+ * event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
109
+ * limits: its tokens are returned and the attempt fails with that reason.
110
+ */
111
+ handleLine(line) {
112
+ if (this.abuse)
113
+ throw this.abuse;
114
+ const request = parseSandboxHostCapacityRequest(line);
115
+ if (!request)
116
+ return false;
117
+ if (!this.takeAllowance()) {
118
+ this.stop(`more than ${this.burst} host capacity requests in a burst (sustained limit ${this.refillPerSecond}/s)`);
119
+ }
120
+ if (request.action === "acquire" && !this.tokens.has(request.requestId) && this.tokens.size >= this.maximumOutstanding) {
121
+ this.stop(`more than ${this.maximumOutstanding} host capacity requests outstanding at once`);
122
+ }
123
+ this.track(request.action === "acquire" ? this.acquire(request)
124
+ : request.action === "retain" ? Promise.resolve(this.retain(request.requestId)) : this.release(request.requestId));
125
+ return true;
126
+ }
127
+ /** The sandbox exited: cancel its waits and return every token it holds. */
128
+ async close() {
129
+ this.closed = true;
130
+ await Promise.allSettled([...this.tokens.keys()].map(requestId => this.release(requestId)));
131
+ await Promise.allSettled([...this.work]);
132
+ }
133
+ /** Requests waiting or admitted, for diagnostics and tests. */
134
+ outstanding() {
135
+ return this.tokens.size;
136
+ }
137
+ stop(reason) {
138
+ this.abuse = new ForgeFailureError("sandbox_host_capacity_abuse", `sandbox_host_capacity_abuse: the sandbox sent ${reason}; Forge returned its host capacity and stopped the attempt.`, "sandbox");
139
+ void this.close();
140
+ throw this.abuse;
141
+ }
142
+ takeAllowance() {
143
+ const nowMs = this.now();
144
+ this.allowance = Math.min(this.burst, this.allowance + ((nowMs - this.allowanceAtMs) / 1000) * this.refillPerSecond);
145
+ this.allowanceAtMs = nowMs;
146
+ if (this.allowance < 1)
147
+ return false;
148
+ this.allowance -= 1;
149
+ return true;
150
+ }
151
+ track(task) {
152
+ const tracked = task.catch(() => undefined);
153
+ this.work.add(tracked);
154
+ void tracked.finally(() => this.work.delete(tracked));
155
+ }
156
+ async acquire(request) {
157
+ if (this.closed || this.tokens.has(request.requestId))
158
+ return;
159
+ const entry = { controller: new AbortController(), admission: null, released: false, retained: false };
160
+ this.tokens.set(request.requestId, entry);
161
+ let admission;
162
+ try {
163
+ admission = await this.gate.acquire({
164
+ stepClass: request.stepClass,
165
+ label: `sandbox ${request.label || request.stepClass}`,
166
+ // The host decides the cost from the class; the sandbox cannot claim a cheaper one.
167
+ cost: hostLoadStepCostForClass(request.stepClass),
168
+ dispatchAttemptId: this.dispatchAttemptId,
169
+ priority: this.priority,
170
+ }, {
171
+ signal: entry.controller.signal,
172
+ // Sequenced when called, so it can never overtake the admission that follows.
173
+ onWaiting: decision => this.respond({
174
+ requestId: request.requestId, status: "waiting", reason: decision.reason, detail: decision.detail,
175
+ }),
176
+ });
177
+ }
178
+ catch (error) {
179
+ this.tokens.delete(request.requestId);
180
+ if (entry.released)
181
+ return;
182
+ const failure = error;
183
+ void this.respond({
184
+ requestId: request.requestId,
185
+ status: "failed",
186
+ code: typeof failure.code === "string" ? failure.code : "host_capacity_broker_failed",
187
+ message: typeof failure.message === "string" ? failure.message : String(error),
188
+ ...(typeof failure.waitMs === "number" ? { waitMs: Math.round(failure.waitMs) } : {}),
189
+ });
190
+ return;
191
+ }
192
+ if (entry.released) {
193
+ await admission.release().catch(() => undefined);
194
+ return;
195
+ }
196
+ entry.admission = admission;
197
+ // A reclaim after a bridge crash then stops the sandbox before reusing its capacity.
198
+ // Without a known process (lookup failed) the token has no tree and, on a crash,
199
+ // stays degraded with its cost; a failed recording is terminal, not ignored.
200
+ let attachFailure = null;
201
+ if (!admission.fenced.aborted) {
202
+ const stepProcess = await this.options.stepProcess?.().catch(() => null);
203
+ if (stepProcess)
204
+ attachFailure = await admission.attachProcess(stepProcess).then(() => null, (error) => error);
205
+ }
206
+ if (entry.released)
207
+ return;
208
+ if (admission.fenced.aborted || attachFailure !== null) {
209
+ // Lost before the sandbox was told it may start: it never runs this step, so
210
+ // it gets a terminal answer instead of "admitted", and the token goes back now.
211
+ const reason = admission.fenced.aborted ? admission.fenced.reason : attachFailure;
212
+ const fenced = admission.fenced.aborted || hasCode(reason, "host_capacity_token_fenced");
213
+ entry.released = true;
214
+ this.tokens.delete(request.requestId);
215
+ void this.respond({
216
+ requestId: request.requestId,
217
+ status: fenced ? "fenced" : "failed",
218
+ code: fenced ? "host_capacity_token_fenced" : codeOf(reason) ?? "host_capacity_broker_failed",
219
+ message: reason instanceof Error ? reason.message : String(reason),
220
+ });
221
+ await admission.release().catch(() => undefined);
222
+ return;
223
+ }
224
+ // Registered synchronously after the check above, so no fence can slip between them.
225
+ admission.fenced.addEventListener("abort", () => {
226
+ // Retention stops the step's reservation on purpose; the sandbox already knows.
227
+ if (entry.retained)
228
+ return;
229
+ void this.respond({
230
+ requestId: request.requestId,
231
+ status: "fenced",
232
+ code: "host_capacity_token_fenced",
233
+ message: admission.fenced.reason instanceof Error ? admission.fenced.reason.message : "host_capacity_token_fenced",
234
+ });
235
+ }, { once: true });
236
+ void this.respond({
237
+ requestId: request.requestId, status: "admitted", waitMs: Math.round(admission.waitMs), reason: admission.decision.reason,
238
+ });
239
+ }
240
+ /**
241
+ * The sandbox's step ended but part of its tree may still run: the host token is
242
+ * kept, marked retained (so the attempt's own next step does not wait for it),
243
+ * until the sandbox releases the request or exits.
244
+ */
245
+ retain(requestId) {
246
+ const entry = this.tokens.get(requestId);
247
+ if (!entry?.admission || entry.released || entry.retained)
248
+ return;
249
+ entry.retained = true;
250
+ entry.admission.retainUntilStopped(async () => entry.released, new Error("The sandbox step's processes could not be proven stopped; its host capacity is kept until the sandbox releases it."));
251
+ }
252
+ async release(requestId) {
253
+ const entry = this.tokens.get(requestId);
254
+ if (!entry || entry.released)
255
+ return;
256
+ entry.released = true;
257
+ this.tokens.delete(requestId);
258
+ this.deliveries.delete(requestId);
259
+ entry.controller.abort(new Error("The sandbox released its host capacity request."));
260
+ await entry.admission?.release().catch(() => undefined);
261
+ }
262
+ /** Queues the newest state for a request; at most one delivery per request is in flight. */
263
+ respond(response) {
264
+ // A container that already exited cannot read the answer; the token is released on close.
265
+ if (this.closed)
266
+ return Promise.resolve();
267
+ this.sequence += 1;
268
+ const state = this.deliveries.get(response.requestId) ?? { latest: null, delivering: false };
269
+ this.deliveries.set(response.requestId, state);
270
+ state.latest = { ...response, sequence: this.sequence };
271
+ if (state.delivering)
272
+ return Promise.resolve();
273
+ state.delivering = true;
274
+ const pump = this.pump(response.requestId, state);
275
+ this.track(pump);
276
+ return pump;
277
+ }
278
+ async pump(requestId, state) {
279
+ // The reply chain for one request; ends when its newest state landed or the broker closed.
280
+ let delayMs = this.retryMs;
281
+ try {
282
+ while (state.latest && !this.closed) {
283
+ const next = state.latest;
284
+ try {
285
+ await this.deliver(next);
286
+ if (state.latest === next)
287
+ state.latest = null;
288
+ delayMs = this.retryMs;
289
+ }
290
+ catch {
291
+ // Redeliver the newest state (this one, unless a newer one arrived meanwhile).
292
+ await new Promise(resolve => setTimeout(resolve, delayMs));
293
+ delayMs = Math.min(delayMs * 2, 4_000);
294
+ }
295
+ }
296
+ }
297
+ finally {
298
+ state.delivering = false;
299
+ if (!this.tokens.has(requestId) && this.deliveries.get(requestId) === state)
300
+ this.deliveries.delete(requestId);
301
+ }
302
+ }
303
+ }
304
+ /**
305
+ * Adds the broker variables to a worker `docker create` command, just before
306
+ * its image: the protocol, and the host's maximum queue wait so the
307
+ * container's own fail-safe never fires before the host answers.
308
+ */
309
+ export function withSandboxHostCapacityBroker(createArgs, image, maxWaitMs) {
310
+ const imageIndex = createArgs.lastIndexOf(image);
311
+ if (imageIndex < 0)
312
+ throw new Error("sandbox_host_capacity_broker_invalid: the worker image is missing from its create command.");
313
+ const args = [...createArgs];
314
+ args.splice(imageIndex, 0,
315
+ // Root-owned and not writable by the sandbox user: only the bridge's replies land here.
316
+ "--tmpfs", `${sandboxHostCapacityResponseRoot}:rw,nosuid,nodev,noexec,size=4m,uid=0,gid=0,mode=0755`, "--env", `${sandboxHostCapacityBrokerEnvironment}=${sandboxHostCapacityBrokerProtocol}`, "--env", `${sandboxHostCapacityMaxWaitEnvironment}=${Math.round(maxWaitMs)}`);
317
+ return args;
318
+ }
319
+ /** `docker exec` arguments that write one reply into the container as root. */
320
+ export function sandboxHostCapacityDeliveryExecArgs(container) {
321
+ return ["exec", "--interactive", "--user", "0", container, "node", "-e", sandboxHostCapacityResponseScript];
322
+ }
323
+ /**
324
+ * The `node -e` script that writes one response file inside the container, run
325
+ * as root. It keeps the newest reply: one with a lower or equal sequence than
326
+ * the file already holds is dropped, so a late delivery can never replace a
327
+ * newer state. Replies are world-readable but owned by the writer (root, via
328
+ * `docker exec --user 0`). The directory must already be owned by that same uid
329
+ * and writable by no one else, i.e. the root-owned reply mount; it is never
330
+ * created here, where it could turn out to be the sandbox's own directory.
331
+ */
332
+ export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
333
+ + sandboxHostCapacityResponseRoot
334
+ + "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
@@ -19,23 +19,53 @@ export declare class DockerPreflight {
19
19
  private readonly cacheMs;
20
20
  private generation;
21
21
  private cached;
22
- private cacheAt;
22
+ private fullPreflightAt;
23
+ private staticPreflight;
24
+ private inspectionInFlight;
25
+ private lastCapacitySample;
23
26
  private readonly options;
24
27
  private readonly docker;
25
28
  private readonly ownership;
26
29
  private diskPressureLatched;
30
+ private readonly memoryAvailability;
27
31
  constructor(options?: DockerPreflightOptions | string, commands?: CommandRunner, cacheMs?: number);
32
+ private unavailable;
33
+ private memoryReserveBytes;
34
+ private defaultAdmissionMemoryBytes;
28
35
  current(): SandboxPreflightResult | null;
29
36
  refresh(): Promise<SandboxPreflightResult>;
30
37
  release(): Promise<void>;
31
38
  run(force?: boolean): Promise<SandboxPreflightResult>;
39
+ /**
40
+ * Refreshes only the admission inputs that change while the daemon's static
41
+ * capability snapshot remains valid. Heartbeats use this path so periodic
42
+ * liveness reporting does not wake Docker/WSL to rerun feature probes.
43
+ */
44
+ refreshCapacity(): Promise<SandboxPreflightResult>;
45
+ /**
46
+ * When the cached static preflight remains usable, produces a capacity sample
47
+ * that began after this admission request. An older inspection is awaited,
48
+ * not preempted or reused. Later admission callers may share the next sample
49
+ * only when it began after they entered this method. Without a usable static
50
+ * snapshot, the existing fail-closed result is returned without probing.
51
+ */
52
+ refreshCapacityForAdmission(): Promise<SandboxPreflightResult>;
53
+ private startInspection;
32
54
  private inspect;
55
+ private inspectCapacity;
33
56
  }
57
+ /**
58
+ * Uses the same reviewed reserve vector as host-runtime admission. The input
59
+ * is always the physical host total; Docker Desktop's VM total is tracked as
60
+ * a separate daemon commitment domain.
61
+ */
62
+ export declare function resolveSandboxHostMemoryReserveBytes(totalMemoryBytes: number, explicitBytes?: number, environment?: NodeJS.ProcessEnv): number;
34
63
  export declare function canRunDockerMaintenance(preflight: {
35
64
  readonly healthy: boolean;
36
65
  readonly unavailableCode?: string | null;
37
66
  }): boolean;
38
67
  export declare function evaluateDiskPressure(availableBytes: number, totalBytes: number, minimumAvailableBytes: number, highWatermarkPercent: number, lowWatermarkPercent: number, pressureLatched: boolean): boolean;
68
+ export declare function requiredAvailableBytesToClearDiskPressure(totalBytes: number, minimumAvailableBytes: number, lowWatermarkPercent: number): number;
39
69
  export declare function storagePolicyAvailable(storageQuota: boolean, environment?: NodeJS.ProcessEnv): boolean;
40
70
  export declare class DockerContextOwnershipLock {
41
71
  private lockPath;