@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.e1b4f55fb18d
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.
- package/README.md +2 -2
- package/dist/bridge/bridge.service.d.ts +2 -0
- package/dist/bridge/bridge.service.js +30 -5
- package/dist/bridge/bridge.types.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +57 -100
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.service.js +10 -2
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +172 -0
- package/dist/runtime/host-load-governor.js +519 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-sampler.d.ts +43 -0
- package/dist/runtime/host-load-sampler.js +74 -6
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +17 -3
- package/dist/runtime/host-runtime-lease.js +83 -4
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +94 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +21 -55
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
- package/dist/session/provider-cli/provider-cli.process.js +122 -30
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
- package/dist/session/provider-cli/provider-cli.service.js +80 -23
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +10 -1
- package/dist/session/publishable-worktree-changes.js +21 -5
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +21 -4
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +11 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { hostLoadStepCostForClass } from "../runtime/host-load-step-class.js";
|
|
2
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
3
|
+
// Host side of Docker-sandbox admission (decision 0013). The validator inside a
|
|
4
|
+
// container cannot reach the host ledger, so it asks the bridge over the
|
|
5
|
+
// channels the sandbox already has: a request line on the worker's stdout
|
|
6
|
+
// (which the bridge parses anyway) and a response file the bridge writes with
|
|
7
|
+
// `docker exec`. The bridge's own governor holds the token, renews it, and
|
|
8
|
+
// returns it when the sandbox releases it or exits, so Docker steps share the
|
|
9
|
+
// host budget.
|
|
10
|
+
//
|
|
11
|
+
// Replies are unforgeable from inside the sandbox. They live on their own tmpfs
|
|
12
|
+
// owned by root with mode 0755, mounted only for brokered workers, and are
|
|
13
|
+
// written by `docker exec --user 0`. The workload runs as uid 10001 with every
|
|
14
|
+
// capability dropped and no-new-privileges, so it can neither write there nor
|
|
15
|
+
// create any root-owned file anywhere, and a mount point cannot be renamed
|
|
16
|
+
// away. The validator accepts only a regular, root-owned, single-link reply
|
|
17
|
+
// that no one else can write (sandbox-host-capacity-gate.ts).
|
|
18
|
+
export const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
|
|
19
|
+
export const sandboxHostCapacityBrokerProtocol = "stdout-v1";
|
|
20
|
+
export const sandboxHostCapacityLineType = "forge_host_capacity";
|
|
21
|
+
export const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
|
|
22
|
+
/** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
|
|
23
|
+
export const sandboxHostCapacityResponseOwnerUid = 0;
|
|
24
|
+
export const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
|
|
25
|
+
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;
|
|
26
|
+
const stepClassPattern = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
|
|
27
|
+
/** A sandbox validates one step at a time; a small bound stops a runaway from hoarding tokens. */
|
|
28
|
+
const defaultMaximumOutstanding = 2;
|
|
29
|
+
/** A validation run sends two lines per step; this leaves room for reruns and caps docker exec churn. */
|
|
30
|
+
const defaultBurst = 40;
|
|
31
|
+
const defaultRefillPerSecond = 2;
|
|
32
|
+
function codeOf(error) {
|
|
33
|
+
const code = error?.code;
|
|
34
|
+
return typeof code === "string" ? code : null;
|
|
35
|
+
}
|
|
36
|
+
function hasCode(error, code) {
|
|
37
|
+
return codeOf(error) === code;
|
|
38
|
+
}
|
|
39
|
+
/** Parses one stdout line; null when it is not a well-formed broker request. */
|
|
40
|
+
export function parseSandboxHostCapacityRequest(line) {
|
|
41
|
+
const trimmed = line.trim();
|
|
42
|
+
if (!trimmed.startsWith("{") || !trimmed.includes(sandboxHostCapacityLineType) || trimmed.length > 4096)
|
|
43
|
+
return null;
|
|
44
|
+
let value;
|
|
45
|
+
try {
|
|
46
|
+
value = JSON.parse(trimmed);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (!value || value.type !== sandboxHostCapacityLineType || value.version !== 1)
|
|
52
|
+
return null;
|
|
53
|
+
if (value.action !== "acquire" && value.action !== "release")
|
|
54
|
+
return null;
|
|
55
|
+
if (typeof value.requestId !== "string" || !requestIdPattern.test(value.requestId))
|
|
56
|
+
return null;
|
|
57
|
+
const stepClass = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
|
|
58
|
+
// Diagnostics only, but never control characters or markup from the sandbox.
|
|
59
|
+
const label = typeof value.label === "string" ? value.label.replace(/[^\w .:/@+-]/gu, "_").slice(0, 128) : "";
|
|
60
|
+
return { action: value.action, requestId: value.requestId, stepClass, label };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* One sandbox's brokered tokens. The sandbox never chooses the cost or the
|
|
64
|
+
* attempt. Replies for one request go out one at a time, newest state only,
|
|
65
|
+
* each with a rising sequence the container-side writer uses to refuse an
|
|
66
|
+
* older reply; a failed delivery is retried until a newer state replaces it
|
|
67
|
+
* or the broker closes. A sandbox that floods requests or exceeds its
|
|
68
|
+
* outstanding limit stops the broker and fails its attempt.
|
|
69
|
+
*/
|
|
70
|
+
export class SandboxHostCapacityBroker {
|
|
71
|
+
gate;
|
|
72
|
+
dispatchAttemptId;
|
|
73
|
+
priority;
|
|
74
|
+
deliver;
|
|
75
|
+
options;
|
|
76
|
+
tokens = new Map();
|
|
77
|
+
deliveries = new Map();
|
|
78
|
+
work = new Set();
|
|
79
|
+
maximumOutstanding;
|
|
80
|
+
burst;
|
|
81
|
+
refillPerSecond;
|
|
82
|
+
retryMs;
|
|
83
|
+
now;
|
|
84
|
+
sequence = 0;
|
|
85
|
+
allowance;
|
|
86
|
+
allowanceAtMs;
|
|
87
|
+
closed = false;
|
|
88
|
+
abuse = null;
|
|
89
|
+
constructor(gate, dispatchAttemptId, priority, deliver, options = {}) {
|
|
90
|
+
this.gate = gate;
|
|
91
|
+
this.dispatchAttemptId = dispatchAttemptId;
|
|
92
|
+
this.priority = priority;
|
|
93
|
+
this.deliver = deliver;
|
|
94
|
+
this.options = options;
|
|
95
|
+
this.maximumOutstanding = options.maximumOutstanding ?? defaultMaximumOutstanding;
|
|
96
|
+
this.burst = options.burst ?? defaultBurst;
|
|
97
|
+
this.refillPerSecond = options.refillPerSecond ?? defaultRefillPerSecond;
|
|
98
|
+
this.retryMs = options.retryMs ?? 250;
|
|
99
|
+
this.now = options.now ?? Date.now;
|
|
100
|
+
this.allowance = this.burst;
|
|
101
|
+
this.allowanceAtMs = this.now();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* True when the line was a broker request; such a line is never a runner
|
|
105
|
+
* event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
|
|
106
|
+
* limits: its tokens are returned and the attempt fails with that reason.
|
|
107
|
+
*/
|
|
108
|
+
handleLine(line) {
|
|
109
|
+
if (this.abuse)
|
|
110
|
+
throw this.abuse;
|
|
111
|
+
const request = parseSandboxHostCapacityRequest(line);
|
|
112
|
+
if (!request)
|
|
113
|
+
return false;
|
|
114
|
+
if (!this.takeAllowance()) {
|
|
115
|
+
this.stop(`more than ${this.burst} host capacity requests in a burst (sustained limit ${this.refillPerSecond}/s)`);
|
|
116
|
+
}
|
|
117
|
+
if (request.action === "acquire" && !this.tokens.has(request.requestId) && this.tokens.size >= this.maximumOutstanding) {
|
|
118
|
+
this.stop(`more than ${this.maximumOutstanding} host capacity requests outstanding at once`);
|
|
119
|
+
}
|
|
120
|
+
this.track(request.action === "acquire" ? this.acquire(request) : this.release(request.requestId));
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
/** The sandbox exited: cancel its waits and return every token it holds. */
|
|
124
|
+
async close() {
|
|
125
|
+
this.closed = true;
|
|
126
|
+
await Promise.allSettled([...this.tokens.keys()].map(requestId => this.release(requestId)));
|
|
127
|
+
await Promise.allSettled([...this.work]);
|
|
128
|
+
}
|
|
129
|
+
/** Requests waiting or admitted, for diagnostics and tests. */
|
|
130
|
+
outstanding() {
|
|
131
|
+
return this.tokens.size;
|
|
132
|
+
}
|
|
133
|
+
stop(reason) {
|
|
134
|
+
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");
|
|
135
|
+
void this.close();
|
|
136
|
+
throw this.abuse;
|
|
137
|
+
}
|
|
138
|
+
takeAllowance() {
|
|
139
|
+
const nowMs = this.now();
|
|
140
|
+
this.allowance = Math.min(this.burst, this.allowance + ((nowMs - this.allowanceAtMs) / 1000) * this.refillPerSecond);
|
|
141
|
+
this.allowanceAtMs = nowMs;
|
|
142
|
+
if (this.allowance < 1)
|
|
143
|
+
return false;
|
|
144
|
+
this.allowance -= 1;
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
track(task) {
|
|
148
|
+
const tracked = task.catch(() => undefined);
|
|
149
|
+
this.work.add(tracked);
|
|
150
|
+
void tracked.finally(() => this.work.delete(tracked));
|
|
151
|
+
}
|
|
152
|
+
async acquire(request) {
|
|
153
|
+
if (this.closed || this.tokens.has(request.requestId))
|
|
154
|
+
return;
|
|
155
|
+
const entry = { controller: new AbortController(), admission: null, released: false };
|
|
156
|
+
this.tokens.set(request.requestId, entry);
|
|
157
|
+
let admission;
|
|
158
|
+
try {
|
|
159
|
+
admission = await this.gate.acquire({
|
|
160
|
+
stepClass: request.stepClass,
|
|
161
|
+
label: `sandbox ${request.label || request.stepClass}`,
|
|
162
|
+
// The host decides the cost from the class; the sandbox cannot claim a cheaper one.
|
|
163
|
+
cost: hostLoadStepCostForClass(request.stepClass),
|
|
164
|
+
dispatchAttemptId: this.dispatchAttemptId,
|
|
165
|
+
priority: this.priority,
|
|
166
|
+
}, {
|
|
167
|
+
signal: entry.controller.signal,
|
|
168
|
+
// Sequenced when called, so it can never overtake the admission that follows.
|
|
169
|
+
onWaiting: decision => this.respond({
|
|
170
|
+
requestId: request.requestId, status: "waiting", reason: decision.reason, detail: decision.detail,
|
|
171
|
+
}),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
this.tokens.delete(request.requestId);
|
|
176
|
+
if (entry.released)
|
|
177
|
+
return;
|
|
178
|
+
const failure = error;
|
|
179
|
+
void this.respond({
|
|
180
|
+
requestId: request.requestId,
|
|
181
|
+
status: "failed",
|
|
182
|
+
code: typeof failure.code === "string" ? failure.code : "host_capacity_broker_failed",
|
|
183
|
+
message: typeof failure.message === "string" ? failure.message : String(error),
|
|
184
|
+
...(typeof failure.waitMs === "number" ? { waitMs: Math.round(failure.waitMs) } : {}),
|
|
185
|
+
});
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (entry.released) {
|
|
189
|
+
await admission.release().catch(() => undefined);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
entry.admission = admission;
|
|
193
|
+
// A reclaim after a bridge crash then stops the sandbox before reusing its capacity.
|
|
194
|
+
// Without a known process (lookup failed) the token has no tree and, on a crash,
|
|
195
|
+
// stays degraded with its cost; a failed recording is terminal, not ignored.
|
|
196
|
+
let attachFailure = null;
|
|
197
|
+
if (!admission.fenced.aborted) {
|
|
198
|
+
const stepProcess = await this.options.stepProcess?.().catch(() => null);
|
|
199
|
+
if (stepProcess)
|
|
200
|
+
attachFailure = await admission.attachProcess(stepProcess).then(() => null, (error) => error);
|
|
201
|
+
}
|
|
202
|
+
if (entry.released)
|
|
203
|
+
return;
|
|
204
|
+
if (admission.fenced.aborted || attachFailure !== null) {
|
|
205
|
+
// Lost before the sandbox was told it may start: it never runs this step, so
|
|
206
|
+
// it gets a terminal answer instead of "admitted", and the token goes back now.
|
|
207
|
+
const reason = admission.fenced.aborted ? admission.fenced.reason : attachFailure;
|
|
208
|
+
const fenced = admission.fenced.aborted || hasCode(reason, "host_capacity_token_fenced");
|
|
209
|
+
entry.released = true;
|
|
210
|
+
this.tokens.delete(request.requestId);
|
|
211
|
+
void this.respond({
|
|
212
|
+
requestId: request.requestId,
|
|
213
|
+
status: fenced ? "fenced" : "failed",
|
|
214
|
+
code: fenced ? "host_capacity_token_fenced" : codeOf(reason) ?? "host_capacity_broker_failed",
|
|
215
|
+
message: reason instanceof Error ? reason.message : String(reason),
|
|
216
|
+
});
|
|
217
|
+
await admission.release().catch(() => undefined);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
// Registered synchronously after the check above, so no fence can slip between them.
|
|
221
|
+
admission.fenced.addEventListener("abort", () => {
|
|
222
|
+
void this.respond({
|
|
223
|
+
requestId: request.requestId,
|
|
224
|
+
status: "fenced",
|
|
225
|
+
code: "host_capacity_token_fenced",
|
|
226
|
+
message: admission.fenced.reason instanceof Error ? admission.fenced.reason.message : "host_capacity_token_fenced",
|
|
227
|
+
});
|
|
228
|
+
}, { once: true });
|
|
229
|
+
void this.respond({
|
|
230
|
+
requestId: request.requestId, status: "admitted", waitMs: Math.round(admission.waitMs), reason: admission.decision.reason,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
async release(requestId) {
|
|
234
|
+
const entry = this.tokens.get(requestId);
|
|
235
|
+
if (!entry || entry.released)
|
|
236
|
+
return;
|
|
237
|
+
entry.released = true;
|
|
238
|
+
this.tokens.delete(requestId);
|
|
239
|
+
this.deliveries.delete(requestId);
|
|
240
|
+
entry.controller.abort(new Error("The sandbox released its host capacity request."));
|
|
241
|
+
await entry.admission?.release().catch(() => undefined);
|
|
242
|
+
}
|
|
243
|
+
/** Queues the newest state for a request; at most one delivery per request is in flight. */
|
|
244
|
+
respond(response) {
|
|
245
|
+
// A container that already exited cannot read the answer; the token is released on close.
|
|
246
|
+
if (this.closed)
|
|
247
|
+
return Promise.resolve();
|
|
248
|
+
this.sequence += 1;
|
|
249
|
+
const state = this.deliveries.get(response.requestId) ?? { latest: null, delivering: false };
|
|
250
|
+
this.deliveries.set(response.requestId, state);
|
|
251
|
+
state.latest = { ...response, sequence: this.sequence };
|
|
252
|
+
if (state.delivering)
|
|
253
|
+
return Promise.resolve();
|
|
254
|
+
state.delivering = true;
|
|
255
|
+
const pump = this.pump(response.requestId, state);
|
|
256
|
+
this.track(pump);
|
|
257
|
+
return pump;
|
|
258
|
+
}
|
|
259
|
+
async pump(requestId, state) {
|
|
260
|
+
// The reply chain for one request; ends when its newest state landed or the broker closed.
|
|
261
|
+
let delayMs = this.retryMs;
|
|
262
|
+
try {
|
|
263
|
+
while (state.latest && !this.closed) {
|
|
264
|
+
const next = state.latest;
|
|
265
|
+
try {
|
|
266
|
+
await this.deliver(next);
|
|
267
|
+
if (state.latest === next)
|
|
268
|
+
state.latest = null;
|
|
269
|
+
delayMs = this.retryMs;
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// Redeliver the newest state (this one, unless a newer one arrived meanwhile).
|
|
273
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
274
|
+
delayMs = Math.min(delayMs * 2, 4_000);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
state.delivering = false;
|
|
280
|
+
if (!this.tokens.has(requestId) && this.deliveries.get(requestId) === state)
|
|
281
|
+
this.deliveries.delete(requestId);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Adds the broker variables to a worker `docker create` command, just before
|
|
287
|
+
* its image: the protocol, and the host's maximum queue wait so the
|
|
288
|
+
* container's own fail-safe never fires before the host answers.
|
|
289
|
+
*/
|
|
290
|
+
export function withSandboxHostCapacityBroker(createArgs, image, maxWaitMs) {
|
|
291
|
+
const imageIndex = createArgs.lastIndexOf(image);
|
|
292
|
+
if (imageIndex < 0)
|
|
293
|
+
throw new Error("sandbox_host_capacity_broker_invalid: the worker image is missing from its create command.");
|
|
294
|
+
const args = [...createArgs];
|
|
295
|
+
args.splice(imageIndex, 0,
|
|
296
|
+
// Root-owned and not writable by the sandbox user: only the bridge's replies land here.
|
|
297
|
+
"--tmpfs", `${sandboxHostCapacityResponseRoot}:rw,nosuid,nodev,noexec,size=4m,uid=0,gid=0,mode=0755`, "--env", `${sandboxHostCapacityBrokerEnvironment}=${sandboxHostCapacityBrokerProtocol}`, "--env", `${sandboxHostCapacityMaxWaitEnvironment}=${Math.round(maxWaitMs)}`);
|
|
298
|
+
return args;
|
|
299
|
+
}
|
|
300
|
+
/** `docker exec` arguments that write one reply into the container as root. */
|
|
301
|
+
export function sandboxHostCapacityDeliveryExecArgs(container) {
|
|
302
|
+
return ["exec", "--interactive", "--user", "0", container, "node", "-e", sandboxHostCapacityResponseScript];
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The `node -e` script that writes one response file inside the container, run
|
|
306
|
+
* as root. It keeps the newest reply: one with a lower or equal sequence than
|
|
307
|
+
* the file already holds is dropped, so a late delivery can never replace a
|
|
308
|
+
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
309
|
+
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
310
|
+
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
311
|
+
* created here, where it could turn out to be the sandbox's own directory.
|
|
312
|
+
*/
|
|
313
|
+
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='"
|
|
314
|
+
+ sandboxHostCapacityResponseRoot
|
|
315
|
+
+ "';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
|
-
|
|
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;
|
package/dist/sandbox/runtime.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
+
}
|
|
@@ -25,6 +25,8 @@ export declare function installOwnerShutdownHandlers(target?: OwnerShutdownSigna
|
|
|
25
25
|
*/
|
|
26
26
|
export declare function runWithOwnerShutdown<T>(body: () => Promise<T>, target?: OwnerShutdownSignalTarget, exit?: (code: number) => void): Promise<T>;
|
|
27
27
|
export declare function isManagedAttemptTool(name: string): boolean;
|
|
28
|
+
/** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
|
|
29
|
+
export declare function managedAttemptToolInputSchema(name: string): unknown;
|
|
28
30
|
export declare function managedAttemptToolDefinition(name: string): unknown;
|
|
29
31
|
export interface ManagedAttemptToolResult {
|
|
30
32
|
readonly content: readonly {
|