@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.deb7f72e7930
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 +144 -3
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +92 -15
- package/dist/bridge/bridge.service.js +432 -342
- package/dist/bridge/bridge.types.d.ts +27 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +17 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +152 -187
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +36 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -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 +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +186 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +156 -0
- package/dist/runtime/host-load-sampler.js +298 -0
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -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-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +16 -0
- package/dist/runtime/host-runtime-contract.js +35 -2
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +285 -55
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +48 -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/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +47 -8
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -7
- package/dist/session/managed-attempt-tools.js +202 -116
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -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 +100 -26
- 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 +12 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +5 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -11
- package/dist/session/phase-completion.runtime.js +91 -215
- 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 +208 -231
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +49 -93
- 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-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +33 -20
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +37 -21
- package/dist/session/pre-publication-validation.js +224 -166
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- 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 +41 -31
- package/dist/session/provider-cli/provider-cli.process.js +139 -438
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
- package/dist/session/provider-cli/provider-cli.service.js +200 -189
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
- package/dist/session/provider-cli/provider-output-state.js +15 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +11 -2
- package/dist/session/session.service.js +182 -61
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +15 -3
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- 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/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +14 -7
- 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/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +49 -0
- package/dist/worktree/worktree-wip.js +182 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +36 -5
- package/dist/worktree/worktree.service.js +120 -155
- package/dist/worktree/worktree.types.d.ts +38 -0
- package/package.json +2 -2
|
@@ -0,0 +1,336 @@
|
|
|
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. A
|
|
331
|
+
* runtime without POSIX user ids (Windows) cannot prove that, so the script
|
|
332
|
+
* writes nothing there (exit 3), as for any directory it cannot trust.
|
|
333
|
+
*/
|
|
334
|
+
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='"
|
|
335
|
+
+ sandboxHostCapacityResponseRoot
|
|
336
|
+
+ "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);if(typeof process.getuid!=='function')process.exit(3);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)})";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SandboxProcessRequest, type SandboxProcessResult } from "./process.js";
|
|
2
|
+
export type ManagedBranchProcess = (request: SandboxProcessRequest) => Promise<SandboxProcessResult>;
|
|
3
|
+
export interface CheckedOutBranchUpdate {
|
|
4
|
+
readonly repoPath: string;
|
|
5
|
+
readonly worktreePath: string;
|
|
6
|
+
readonly branchRef: string;
|
|
7
|
+
/** The commit the sandbox started from; the branch and worktree must still be exactly there. */
|
|
8
|
+
readonly expected: string;
|
|
9
|
+
readonly imported: string;
|
|
10
|
+
/** Runs git; tests inject one. */
|
|
11
|
+
readonly run?: ManagedBranchProcess;
|
|
12
|
+
}
|
|
13
|
+
export declare function advanceCheckedOutBranch(update: CheckedOutBranchUpdate): Promise<void>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
|
+
import { requireSandboxProcess } from "./process.js";
|
|
3
|
+
export async function advanceCheckedOutBranch(update) {
|
|
4
|
+
const run = update.run ?? requireSandboxProcess;
|
|
5
|
+
const inWorktree = (args, timeoutMs) => run({ command: "git", args: ["-C", update.worktreePath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024 });
|
|
6
|
+
const head = (await inWorktree(["rev-parse", "HEAD"], 30_000)).stdout.trim();
|
|
7
|
+
const status = (await inWorktree(["status", "--porcelain=v1", "--untracked-files=no"], 30_000)).stdout;
|
|
8
|
+
if (head !== update.expected || status.trim()) {
|
|
9
|
+
throw conflict("managed worktree changed after sandbox input was captured.");
|
|
10
|
+
}
|
|
11
|
+
await inWorktree(["read-tree", "-m", "-u", update.expected, update.imported], 2 * 60_000);
|
|
12
|
+
try {
|
|
13
|
+
await run({
|
|
14
|
+
command: "git",
|
|
15
|
+
args: ["-C", update.repoPath, "update-ref", update.branchRef, update.imported, update.expected],
|
|
16
|
+
timeoutMs: 30_000,
|
|
17
|
+
maxOutputBytes: 4 * 1024 * 1024,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
try {
|
|
22
|
+
await inWorktree(["read-tree", "-m", "-u", update.imported, update.expected], 2 * 60_000);
|
|
23
|
+
}
|
|
24
|
+
catch (rollbackError) {
|
|
25
|
+
throw conflict(`managed branch changed while the sandbox result was applied, and its worktree could not be put back to ${update.expected} `
|
|
26
|
+
+ `(${messageOf(rollbackError)}); it holds the imported files.`, { cause: rollbackError });
|
|
27
|
+
}
|
|
28
|
+
throw conflict(`managed branch changed while the sandbox result was applied (${messageOf(error)}); its worktree was put back.`, { cause: error });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function conflict(detail, options) {
|
|
32
|
+
return new ForgeFailureError("sandbox_output_conflict", `sandbox_output_conflict: ${detail}`, "sandbox", options);
|
|
33
|
+
}
|
|
34
|
+
function messageOf(error) {
|
|
35
|
+
return error instanceof Error ? error.message : String(error);
|
|
36
|
+
}
|
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import fsp from "node:fs/promises";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { fileIdentityChanged } from "../../shared/fs/file-identity.js";
|
|
5
6
|
const maxCredentialFileBytes = 1024 * 1024;
|
|
6
7
|
// Capability and heartbeat paths call doctor() synchronously; keep validation
|
|
7
8
|
// fresh enough for auth changes without rereading auth.json for every offer.
|
|
@@ -87,7 +88,7 @@ function codexAuthDoctor(environment) {
|
|
|
87
88
|
async function readValidatedCodexAuthFile(authPath) {
|
|
88
89
|
let pathStat;
|
|
89
90
|
try {
|
|
90
|
-
pathStat = await fsp.lstat(authPath);
|
|
91
|
+
pathStat = await fsp.lstat(authPath, { bigint: true });
|
|
91
92
|
}
|
|
92
93
|
catch {
|
|
93
94
|
throw new Error("Codex Local CLI auth is not available on the bridge host.");
|
|
@@ -101,11 +102,11 @@ async function readValidatedCodexAuthFile(authPath) {
|
|
|
101
102
|
throw codexAuthOpenError(error);
|
|
102
103
|
}
|
|
103
104
|
try {
|
|
104
|
-
const openedStat = await handle.stat();
|
|
105
|
+
const openedStat = await handle.stat({ bigint: true });
|
|
105
106
|
validateSameCodexAuthFile(pathStat, openedStat);
|
|
106
107
|
validateCodexAuthStat(openedStat);
|
|
107
108
|
const content = await handle.readFile();
|
|
108
|
-
const afterStat = await handle.stat();
|
|
109
|
+
const afterStat = await handle.stat({ bigint: true });
|
|
109
110
|
validateSameCodexAuthFile(openedStat, afterStat);
|
|
110
111
|
validateCodexAuthStat(afterStat);
|
|
111
112
|
validateCodexAuthReadSize(content, openedStat, afterStat);
|
|
@@ -119,7 +120,7 @@ async function readValidatedCodexAuthFile(authPath) {
|
|
|
119
120
|
function readValidatedCodexAuthFileSync(authPath) {
|
|
120
121
|
let pathStat;
|
|
121
122
|
try {
|
|
122
|
-
pathStat = fs.lstatSync(authPath);
|
|
123
|
+
pathStat = fs.lstatSync(authPath, { bigint: true });
|
|
123
124
|
}
|
|
124
125
|
catch {
|
|
125
126
|
throw new Error("Codex Local CLI auth is not available on the bridge host.");
|
|
@@ -133,11 +134,11 @@ function readValidatedCodexAuthFileSync(authPath) {
|
|
|
133
134
|
throw codexAuthOpenError(error);
|
|
134
135
|
}
|
|
135
136
|
try {
|
|
136
|
-
const openedStat = fs.fstatSync(fd);
|
|
137
|
+
const openedStat = fs.fstatSync(fd, { bigint: true });
|
|
137
138
|
validateSameCodexAuthFile(pathStat, openedStat);
|
|
138
139
|
validateCodexAuthStat(openedStat);
|
|
139
140
|
const content = fs.readFileSync(fd);
|
|
140
|
-
const afterStat = fs.fstatSync(fd);
|
|
141
|
+
const afterStat = fs.fstatSync(fd, { bigint: true });
|
|
141
142
|
validateSameCodexAuthFile(openedStat, afterStat);
|
|
142
143
|
validateCodexAuthStat(afterStat);
|
|
143
144
|
validateCodexAuthReadSize(content, openedStat, afterStat);
|
|
@@ -158,21 +159,20 @@ function validateCodexAuthStat(stat) {
|
|
|
158
159
|
if (!stat.isFile()) {
|
|
159
160
|
throw new Error("Codex Local CLI auth.json is not a regular file.");
|
|
160
161
|
}
|
|
161
|
-
if (stat.size <=
|
|
162
|
+
if (stat.size <= 0n) {
|
|
162
163
|
throw new Error("Codex Local CLI auth.json is empty.");
|
|
163
164
|
}
|
|
164
|
-
if (stat.size > maxCredentialFileBytes) {
|
|
165
|
+
if (stat.size > BigInt(maxCredentialFileBytes)) {
|
|
165
166
|
throw new Error("Codex Local CLI auth.json exceeds the 1 MiB sandbox auth limit.");
|
|
166
167
|
}
|
|
167
168
|
}
|
|
168
169
|
function validateSameCodexAuthFile(before, after) {
|
|
169
|
-
if (before
|
|
170
|
-
&& (before.dev !== after.dev || before.ino !== after.ino)) {
|
|
170
|
+
if (fileIdentityChanged(before, after)) {
|
|
171
171
|
throw new Error("Codex Local CLI auth.json changed while being copied.");
|
|
172
172
|
}
|
|
173
173
|
}
|
|
174
174
|
function validateCodexAuthReadSize(content, openedStat, afterStat) {
|
|
175
|
-
if (openedStat.size !== afterStat.size || content.length !== afterStat.size) {
|
|
175
|
+
if (openedStat.size !== afterStat.size || BigInt(content.length) !== afterStat.size) {
|
|
176
176
|
throw new Error("Codex Local CLI auth.json changed while being copied.");
|
|
177
177
|
}
|
|
178
178
|
}
|
|
@@ -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
|
@@ -5,9 +5,16 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
|
|
6
6
|
import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
|
|
7
7
|
import { requireSandboxProcess, runSandboxProcess } from "./process.js";
|
|
8
|
+
import { advanceCheckedOutBranch } from "./managed-branch.js";
|
|
8
9
|
import { createLeaseUpdate } from "./lease-watchdog.js";
|
|
9
10
|
import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
|
|
10
11
|
import { SandboxEventBudget } from "./event-budget.js";
|
|
12
|
+
import { SandboxHostCapacityBroker, sandboxHostCapacityDeliveryExecArgs, withSandboxHostCapacityBroker, } from "./host-capacity-broker.js";
|
|
13
|
+
import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
|
|
14
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
15
|
+
import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
|
|
16
|
+
import { trackSandboxCgroups } from "./sandbox-cgroups.js";
|
|
17
|
+
import { runtimeAdmissionPriority } from "../runtime/host-runtime-lease.js";
|
|
11
18
|
import { RepositoryCoordinatorLock } from "./repository-lock.js";
|
|
12
19
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
13
20
|
import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
|
|
@@ -18,14 +25,21 @@ const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
|
|
|
18
25
|
export class DockerSandboxRuntime {
|
|
19
26
|
config;
|
|
20
27
|
publicationGrantRedeemer;
|
|
28
|
+
hostLoadGate;
|
|
21
29
|
active = new Map();
|
|
22
30
|
degraded = new Set();
|
|
23
31
|
builds = new Map();
|
|
24
32
|
verifiedCatalogImages = new Set();
|
|
25
33
|
buildTail = Promise.resolve();
|
|
26
|
-
|
|
34
|
+
/** Shared with every sampler on the state root, so sandbox CPU is never external load. */
|
|
35
|
+
forgeCgroups;
|
|
36
|
+
constructor(config, publicationGrantRedeemer,
|
|
37
|
+
/** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
|
|
38
|
+
hostLoadGate) {
|
|
27
39
|
this.config = config;
|
|
28
40
|
this.publicationGrantRedeemer = publicationGrantRedeemer;
|
|
41
|
+
this.hostLoadGate = hostLoadGate;
|
|
42
|
+
this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
|
|
29
43
|
}
|
|
30
44
|
async runOnce(dispatch, sink, signal) {
|
|
31
45
|
if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
|
|
@@ -153,7 +167,11 @@ export class DockerSandboxRuntime {
|
|
|
153
167
|
await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
|
|
154
168
|
const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
|
|
155
169
|
const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
|
|
156
|
-
const
|
|
170
|
+
const brokered = this.hostLoadGate?.enabled === true;
|
|
171
|
+
const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
|
|
172
|
+
const createArgs = brokered
|
|
173
|
+
? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
|
|
174
|
+
: workerArgs;
|
|
157
175
|
const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
|
|
158
176
|
const containerId = dockerObjectId(createdContainer.stdout, "container");
|
|
159
177
|
await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
|
|
@@ -183,6 +201,16 @@ export class DockerSandboxRuntime {
|
|
|
183
201
|
runtimeLease: active.runtimeLease,
|
|
184
202
|
}));
|
|
185
203
|
const eventBudget = new SandboxEventBudget();
|
|
204
|
+
const hostCapacity = brokered
|
|
205
|
+
? new SandboxHostCapacityBroker(this.hostLoadGate, runtimeDispatch.sandbox.dispatchAttemptId, runtimeAdmissionPriority(runtimeDispatch), async (response) => void await requireSandboxProcess({
|
|
206
|
+
command: this.config.dockerExecutable,
|
|
207
|
+
// As root, into the root-owned reply mount the sandbox user cannot write.
|
|
208
|
+
args: this.dockerArgs(sandboxHostCapacityDeliveryExecArgs(containerId)),
|
|
209
|
+
input: `${JSON.stringify(response)}\n`,
|
|
210
|
+
timeoutMs: 10_000,
|
|
211
|
+
maxOutputBytes: 16 * 1024,
|
|
212
|
+
}), { stepProcess: async () => await this.containerInitProcess(containerId) })
|
|
213
|
+
: null;
|
|
186
214
|
const startPromise = runSandboxProcess({
|
|
187
215
|
command: this.config.dockerExecutable,
|
|
188
216
|
args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
|
|
@@ -198,6 +226,8 @@ export class DockerSandboxRuntime {
|
|
|
198
226
|
signal: runtimeSignal,
|
|
199
227
|
onStdoutLine: async (line) => {
|
|
200
228
|
eventBudget.accept(line);
|
|
229
|
+
if (hostCapacity?.handleLine(line))
|
|
230
|
+
return;
|
|
201
231
|
const streamedEvent = parseSandboxEventLine(line);
|
|
202
232
|
if (streamedEvent) {
|
|
203
233
|
if (streamedEvent.eventType === "provider_cli_started")
|
|
@@ -207,7 +237,14 @@ export class DockerSandboxRuntime {
|
|
|
207
237
|
}
|
|
208
238
|
});
|
|
209
239
|
const memorySampler = this.startPeakMemorySampler(runtimeContainers);
|
|
240
|
+
// The sandbox's CPU is Forge's own work, not external load, for the governor.
|
|
241
|
+
const untrackCgroups = brokered
|
|
242
|
+
? trackSandboxCgroups(this.forgeCgroups, runtimeDispatch.sandbox.dispatchAttemptId, runtimeContainers.map(container => container.id), async (ids) => (await this.docker(["inspect", "--format", "{{.State.Pid}}", ...ids], 10_000)).stdout)
|
|
243
|
+
: null;
|
|
210
244
|
const start = await startPromise.finally(async () => {
|
|
245
|
+
// The worker exited: its queued and admitted host load tokens go back to the budget.
|
|
246
|
+
untrackCgroups?.();
|
|
247
|
+
await hostCapacity?.close();
|
|
211
248
|
const telemetry = await memorySampler.stop();
|
|
212
249
|
if (!telemetry)
|
|
213
250
|
return;
|
|
@@ -1105,6 +1142,13 @@ export class DockerSandboxRuntime {
|
|
|
1105
1142
|
docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
|
|
1106
1143
|
return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
|
|
1107
1144
|
}
|
|
1145
|
+
/** The container's init process: stopping it stops every process in the sandbox. */
|
|
1146
|
+
async containerInitProcess(containerId) {
|
|
1147
|
+
const pid = Number((await this.docker(["inspect", "--format", "{{.State.Pid}}", containerId], 10_000)).stdout.trim());
|
|
1148
|
+
return Number.isSafeInteger(pid) && pid > 1
|
|
1149
|
+
? { rootPid: pid, rootIdentity: captureHostProcessIdentity(pid), processGroup: false }
|
|
1150
|
+
: null;
|
|
1151
|
+
}
|
|
1108
1152
|
dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
|
|
1109
1153
|
}
|
|
1110
1154
|
class HostGit {
|
|
@@ -1233,12 +1277,7 @@ class HostGit {
|
|
|
1233
1277
|
await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
|
|
1234
1278
|
return;
|
|
1235
1279
|
}
|
|
1236
|
-
|
|
1237
|
-
const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
|
|
1238
|
-
if (head !== expected || status.trim())
|
|
1239
|
-
throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
|
|
1240
|
-
await this.git(["update-ref", branchRef, imported, expected], 30_000);
|
|
1241
|
-
await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
|
|
1280
|
+
await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
|
|
1242
1281
|
}
|
|
1243
1282
|
async resolveFirst(refs) {
|
|
1244
1283
|
for (const ref of refs) {
|
|
@@ -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;
|