@loucompanion/forge-bridge 0.1.4-dev.494233aa2e50 → 0.1.4-dev.4e7855579f82

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 (217) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +89 -14
  16. package/dist/bridge/bridge.service.js +423 -342
  17. package/dist/bridge/bridge.types.d.ts +21 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  25. package/dist/bridge/runner-host-capabilities.js +17 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  29. package/dist/bridge/test-postgres-capability.js +120 -0
  30. package/dist/cleanup/cleanup.service.d.ts +9 -0
  31. package/dist/cleanup/cleanup.service.js +72 -109
  32. package/dist/cleanup/cleanup.types.d.ts +4 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  36. package/dist/cleanup/host-runtime-ledger.js +109 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +152 -187
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +138 -6
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  55. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  56. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  57. package/dist/runtime/host-facts.d.ts +2 -1
  58. package/dist/runtime/host-load-admission.d.ts +67 -0
  59. package/dist/runtime/host-load-admission.js +99 -0
  60. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  61. package/dist/runtime/host-load-child-environment.js +76 -0
  62. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  63. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  64. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  65. package/dist/runtime/host-load-governor-config.js +83 -0
  66. package/dist/runtime/host-load-governor.d.ts +184 -0
  67. package/dist/runtime/host-load-governor.js +632 -0
  68. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  69. package/dist/runtime/host-load-ledger-lock.js +185 -0
  70. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  71. package/dist/runtime/host-load-runtime-settings.js +78 -0
  72. package/dist/runtime/host-load-sampler.d.ts +75 -2
  73. package/dist/runtime/host-load-sampler.js +142 -8
  74. package/dist/runtime/host-load-step-class.d.ts +70 -0
  75. package/dist/runtime/host-load-step-class.js +161 -0
  76. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  77. package/dist/runtime/host-load-step-reaper.js +95 -0
  78. package/dist/runtime/host-load-step-run.d.ts +73 -0
  79. package/dist/runtime/host-load-step-run.js +102 -0
  80. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  81. package/dist/runtime/host-load-test-slot.js +81 -0
  82. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  83. package/dist/runtime/host-load-token-ledger.js +453 -0
  84. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  85. package/dist/runtime/host-load-windows-cpu.js +85 -0
  86. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  87. package/dist/runtime/host-pressure-stall.js +48 -1
  88. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  89. package/dist/runtime/host-runtime-contract.js +33 -2
  90. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  91. package/dist/runtime/host-runtime-lease.js +285 -55
  92. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  93. package/dist/runtime/host-runtime-promotion.js +48 -0
  94. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  95. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  96. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  97. package/dist/runtime/host-runtime-requirements.js +117 -0
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  101. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  102. package/dist/runtime/runner-settings.d.ts +104 -0
  103. package/dist/runtime/runner-settings.js +236 -0
  104. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  105. package/dist/sandbox/host-capacity-broker.js +334 -0
  106. package/dist/sandbox/runtime.d.ts +10 -1
  107. package/dist/sandbox/runtime.js +45 -2
  108. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  109. package/dist/sandbox/sandbox-cgroups.js +42 -0
  110. package/dist/session/architect-waits.d.ts +2 -0
  111. package/dist/session/architect-waits.js +138 -0
  112. package/dist/session/managed-attempt-tools.d.ts +2 -7
  113. package/dist/session/managed-attempt-tools.js +200 -92
  114. package/dist/session/managed-command-host-load.d.ts +47 -0
  115. package/dist/session/managed-command-host-load.js +83 -0
  116. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  117. package/dist/session/mcp-argument-coercion.js +121 -0
  118. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  119. package/dist/session/phase-completion.artifacts.js +96 -26
  120. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  121. package/dist/session/phase-completion.command-validation.js +77 -0
  122. package/dist/session/phase-completion.d.ts +12 -0
  123. package/dist/session/phase-completion.helpers.js +13 -12
  124. package/dist/session/phase-completion.js +5 -0
  125. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  126. package/dist/session/phase-completion.mcp-args.js +156 -0
  127. package/dist/session/phase-completion.prompts.js +6 -1
  128. package/dist/session/phase-completion.runtime.d.ts +5 -11
  129. package/dist/session/phase-completion.runtime.js +91 -215
  130. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  131. package/dist/session/phase-completion.schema-parts.js +188 -0
  132. package/dist/session/phase-completion.schemas.d.ts +3 -3
  133. package/dist/session/phase-completion.schemas.js +208 -231
  134. package/dist/session/phase-completion.validation.d.ts +2 -3
  135. package/dist/session/phase-completion.validation.js +49 -93
  136. package/dist/session/pre-publication-host-load.d.ts +27 -0
  137. package/dist/session/pre-publication-host-load.js +111 -0
  138. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  139. package/dist/session/pre-publication-native-postgres.js +111 -0
  140. package/dist/session/pre-publication-pass.d.ts +61 -0
  141. package/dist/session/pre-publication-pass.js +148 -0
  142. package/dist/session/pre-publication-process.d.ts +3 -0
  143. package/dist/session/pre-publication-process.js +23 -11
  144. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  145. package/dist/session/pre-publication-step-execution.js +50 -0
  146. package/dist/session/pre-publication-validation.d.ts +37 -21
  147. package/dist/session/pre-publication-validation.js +221 -182
  148. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  149. package/dist/session/provider-cli/claude-background-work.js +181 -0
  150. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  151. package/dist/session/provider-cli/host-build-lock.js +30 -0
  152. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  153. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  154. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  155. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  156. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  157. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  158. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  159. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  160. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  161. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  162. package/dist/session/provider-cli/provider-cli.process.d.ts +41 -31
  163. package/dist/session/provider-cli/provider-cli.process.js +139 -438
  164. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  165. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  166. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  167. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  168. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  169. package/dist/session/provider-cli/provider-cli.service.js +146 -182
  170. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  171. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  172. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  173. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  174. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  175. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  176. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  177. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  178. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  179. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  180. package/dist/session/provider-cli/provider-output-state.js +15 -0
  181. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  182. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  183. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  184. package/dist/session/publishable-worktree-changes.js +21 -5
  185. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  186. package/dist/session/qa-sidecar-validation.js +28 -0
  187. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  188. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  189. package/dist/session/session-redaction.js +31 -181
  190. package/dist/session/session.base.d.ts +9 -1
  191. package/dist/session/session.service.d.ts +9 -2
  192. package/dist/session/session.service.js +120 -5
  193. package/dist/session/session.types.d.ts +3 -0
  194. package/dist/session/session.types.js +13 -4
  195. package/dist/session/sidecar-json-shape.d.ts +31 -0
  196. package/dist/session/sidecar-json-shape.js +217 -0
  197. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  198. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  199. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  200. package/dist/shared/process/host-process-supervisor.js +1 -1
  201. package/dist/shared/process/process-tree.d.ts +52 -0
  202. package/dist/shared/process/process-tree.js +144 -0
  203. package/dist/shared/process/process.d.ts +67 -0
  204. package/dist/shared/process/process.js +213 -11
  205. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  206. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  207. package/dist/shared/process/windows-launch.d.ts +18 -0
  208. package/dist/shared/process/windows-launch.js +68 -0
  209. package/dist/shared/provider-capabilities.js +14 -7
  210. package/dist/version.d.ts +1 -1
  211. package/dist/version.js +1 -1
  212. package/dist/worktree/dependency-warmer.d.ts +25 -0
  213. package/dist/worktree/dependency-warmer.js +46 -10
  214. package/dist/worktree/worktree.service.d.ts +10 -1
  215. package/dist/worktree/worktree.service.js +42 -2
  216. package/dist/worktree/worktree.types.d.ts +7 -0
  217. package/package.json +2 -2
@@ -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)})";
@@ -2,6 +2,7 @@ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
2
2
  import type { SessionEventSink } from "../session/session.base.js";
3
3
  import { type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
4
4
  import type { SandboxService, ValidatedSandboxContract } from "./sandbox.types.js";
5
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
5
6
  import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
6
7
  export interface SandboxRuntime {
7
8
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
@@ -87,12 +88,18 @@ export type SandboxPublicationGrantRedeemer = (request: SandboxPublicationGrantR
87
88
  export declare class DockerSandboxRuntime implements SandboxRuntime {
88
89
  private readonly config;
89
90
  private readonly publicationGrantRedeemer?;
91
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
92
+ private readonly hostLoadGate?;
90
93
  private readonly active;
91
94
  private readonly degraded;
92
95
  private readonly builds;
93
96
  private readonly verifiedCatalogImages;
94
97
  private buildTail;
95
- constructor(config: BridgeServiceConfig, publicationGrantRedeemer?: SandboxPublicationGrantRedeemer | undefined);
98
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
99
+ private readonly forgeCgroups;
100
+ constructor(config: BridgeServiceConfig, publicationGrantRedeemer?: SandboxPublicationGrantRedeemer | undefined,
101
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
102
+ hostLoadGate?: HostLoadStepGate | undefined);
96
103
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
97
104
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
98
105
  private pushLeaseUpdate;
@@ -133,6 +140,8 @@ export declare class DockerSandboxRuntime implements SandboxRuntime {
133
140
  private inspectImageMetadata;
134
141
  private startPeakMemorySampler;
135
142
  private docker;
143
+ /** The container's init process: stopping it stops every process in the sandbox. */
144
+ private containerInitProcess;
136
145
  private dockerArgs;
137
146
  }
138
147
  export declare function managedBranchUpdateExpectedValue(current: string, expectedInput: string, imported: string): string;
@@ -8,6 +8,12 @@ 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";
@@ -18,14 +24,21 @@ const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
18
24
  export class DockerSandboxRuntime {
19
25
  config;
20
26
  publicationGrantRedeemer;
27
+ hostLoadGate;
21
28
  active = new Map();
22
29
  degraded = new Set();
23
30
  builds = new Map();
24
31
  verifiedCatalogImages = new Set();
25
32
  buildTail = Promise.resolve();
26
- 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) {
27
38
  this.config = config;
28
39
  this.publicationGrantRedeemer = publicationGrantRedeemer;
40
+ this.hostLoadGate = hostLoadGate;
41
+ this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
29
42
  }
30
43
  async runOnce(dispatch, sink, signal) {
31
44
  if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
@@ -153,7 +166,11 @@ export class DockerSandboxRuntime {
153
166
  await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
154
167
  const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
155
168
  const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
156
- 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;
157
174
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
158
175
  const containerId = dockerObjectId(createdContainer.stdout, "container");
159
176
  await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
@@ -183,6 +200,16 @@ export class DockerSandboxRuntime {
183
200
  runtimeLease: active.runtimeLease,
184
201
  }));
185
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;
186
213
  const startPromise = runSandboxProcess({
187
214
  command: this.config.dockerExecutable,
188
215
  args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
@@ -198,6 +225,8 @@ export class DockerSandboxRuntime {
198
225
  signal: runtimeSignal,
199
226
  onStdoutLine: async (line) => {
200
227
  eventBudget.accept(line);
228
+ if (hostCapacity?.handleLine(line))
229
+ return;
201
230
  const streamedEvent = parseSandboxEventLine(line);
202
231
  if (streamedEvent) {
203
232
  if (streamedEvent.eventType === "provider_cli_started")
@@ -207,7 +236,14 @@ export class DockerSandboxRuntime {
207
236
  }
208
237
  });
209
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;
210
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();
211
247
  const telemetry = await memorySampler.stop();
212
248
  if (!telemetry)
213
249
  return;
@@ -1105,6 +1141,13 @@ export class DockerSandboxRuntime {
1105
1141
  docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
1106
1142
  return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
1107
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
+ }
1108
1151
  dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
1109
1152
  }
1110
1153
  class HostGit {
@@ -0,0 +1,14 @@
1
+ import type { ForgeCgroupWriter } from "../runtime/host-load-forge-cgroups.js";
2
+ export type DockerInspectPids = (containerIds: readonly string[]) => Promise<string>;
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export declare function sandboxContainerCgroupPaths(inspectPids: DockerInspectPids, containerIds: readonly string[], procRoot?: string): Promise<readonly string[]>;
5
+ /**
6
+ * Registers a sandbox's container cgroups once its containers are running,
7
+ * retrying briefly while the agent container starts. Returns a function that
8
+ * stops the retries and removes the registration.
9
+ */
10
+ export declare function trackSandboxCgroups(registry: ForgeCgroupWriter, owner: string, containerIds: readonly string[], inspectPids: DockerInspectPids, options?: {
11
+ readonly attempts?: number;
12
+ readonly intervalMs?: number;
13
+ readonly procRoot?: string;
14
+ }): () => void;
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs/promises";
2
+ import { parseUnifiedCgroupPath } from "../runtime/host-pressure-stall.js";
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export async function sandboxContainerCgroupPaths(inspectPids, containerIds, procRoot = "/proc") {
5
+ const output = await inspectPids(containerIds);
6
+ const paths = [];
7
+ for (const line of output.split(/\r?\n/u)) {
8
+ const pid = Number(line.trim());
9
+ if (!Number.isSafeInteger(pid) || pid <= 1)
10
+ continue;
11
+ const membership = await fs.readFile(`${procRoot}/${pid}/cgroup`, "utf8").catch(() => null);
12
+ const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
13
+ if (cgroupPath)
14
+ paths.push(cgroupPath);
15
+ }
16
+ return paths;
17
+ }
18
+ /**
19
+ * Registers a sandbox's container cgroups once its containers are running,
20
+ * retrying briefly while the agent container starts. Returns a function that
21
+ * stops the retries and removes the registration.
22
+ */
23
+ export function trackSandboxCgroups(registry, owner, containerIds, inspectPids, options = {}) {
24
+ let stopped = false;
25
+ void (async () => {
26
+ for (let attempt = 0; attempt < (options.attempts ?? 10) && !stopped; attempt += 1) {
27
+ await new Promise(resolve => setTimeout(resolve, options.intervalMs ?? 1_000));
28
+ if (stopped)
29
+ return;
30
+ const paths = await sandboxContainerCgroupPaths(inspectPids, containerIds, options.procRoot).catch(() => []);
31
+ if (stopped)
32
+ return;
33
+ registry.set(owner, paths);
34
+ if (paths.length >= containerIds.length)
35
+ return;
36
+ }
37
+ })();
38
+ return () => {
39
+ stopped = true;
40
+ registry.delete(owner);
41
+ };
42
+ }
@@ -0,0 +1,2 @@
1
+ export declare function architectNonPassProperties(): Record<string, unknown>;
2
+ export declare function validateArchitectWaits(payload: Record<string, unknown>, status: string): void;