@loucompanion/forge-bridge 0.1.3-dev.62c25087ca89 → 0.1.3-dev.66e9a6e6a9f9
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 +95 -0
- package/dist/bridge/bridge.base.d.ts +8 -1
- package/dist/bridge/bridge.service.d.ts +84 -3
- package/dist/bridge/bridge.service.js +1252 -45
- package/dist/bridge/bridge.types.d.ts +176 -1
- package/dist/cleanup/cleanup.service.d.ts +14 -2
- package/dist/cleanup/cleanup.service.js +496 -3
- package/dist/cleanup/cleanup.types.d.ts +10 -0
- package/dist/cleanup/index.d.ts +1 -1
- package/dist/cleanup/index.js +1 -1
- package/dist/cleanup/internals.d.ts +2 -2
- package/dist/cleanup/internals.js +1 -1
- package/dist/cli/cli.help.js +47 -1
- package/dist/cli/cli.service.d.ts +42 -2
- package/dist/cli/cli.service.js +360 -26
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +47 -3
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
- package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
- package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +97 -0
- package/dist/runtime/attempt-process-supervisor.js +384 -0
- package/dist/runtime/generated-output-reset.d.ts +10 -0
- package/dist/runtime/generated-output-reset.js +103 -0
- package/dist/runtime/host-listener-inspector.d.ts +46 -0
- package/dist/runtime/host-listener-inspector.js +349 -0
- package/dist/runtime/host-port-broker.d.ts +76 -0
- package/dist/runtime/host-port-broker.js +333 -0
- package/dist/runtime/host-runtime-contract.d.ts +47 -0
- package/dist/runtime/host-runtime-contract.js +700 -0
- package/dist/runtime/host-runtime-lease.d.ts +194 -0
- package/dist/runtime/host-runtime-lease.js +2138 -0
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +159 -0
- package/dist/runtime/memory-capacity.d.ts +68 -0
- package/dist/runtime/memory-capacity.js +121 -0
- package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
- package/dist/runtime/node-host-runtime-adapter.js +284 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +21 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +225 -0
- package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
- package/dist/runtime/runtime-isolation-lease.js +158 -0
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/command-runner.d.ts +4 -0
- package/dist/sandbox/command-runner.js +47 -0
- package/dist/sandbox/contract.d.ts +5 -0
- package/dist/sandbox/contract.js +276 -0
- package/dist/sandbox/event-budget.d.ts +11 -0
- package/dist/sandbox/event-budget.js +27 -0
- package/dist/sandbox/image-policy.d.ts +35 -0
- package/dist/sandbox/image-policy.js +247 -0
- package/dist/sandbox/index.d.ts +5 -0
- package/dist/sandbox/index.js +5 -0
- package/dist/sandbox/lease-watchdog.d.ts +18 -0
- package/dist/sandbox/lease-watchdog.js +67 -0
- package/dist/sandbox/preflight.d.ts +84 -0
- package/dist/sandbox/preflight.js +521 -0
- package/dist/sandbox/process.d.ts +20 -0
- package/dist/sandbox/process.js +209 -0
- package/dist/sandbox/provider-auth/codex.d.ts +26 -0
- package/dist/sandbox/provider-auth/codex.js +212 -0
- package/dist/sandbox/repository-lock.d.ts +5 -0
- package/dist/sandbox/repository-lock.js +121 -0
- package/dist/sandbox/runtime.d.ts +297 -0
- package/dist/sandbox/runtime.js +2338 -0
- package/dist/sandbox/sandbox.types.d.ts +93 -0
- package/dist/sandbox/sandbox.types.js +1 -0
- package/dist/sandbox/smoke.d.ts +76 -0
- package/dist/sandbox/smoke.js +380 -0
- package/dist/sandbox/worker-supervisor.d.ts +13 -0
- package/dist/sandbox/worker-supervisor.js +36 -0
- package/dist/sandbox/worker.d.ts +1 -0
- package/dist/sandbox/worker.js +225 -0
- package/dist/sandbox/workspace.service.d.ts +13 -0
- package/dist/sandbox/workspace.service.js +72 -0
- package/dist/session/managed-attempt-tools.d.ts +18 -0
- package/dist/session/managed-attempt-tools.js +854 -0
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +105 -0
- package/dist/session/managed-build-receipt.d.ts +21 -0
- package/dist/session/managed-build-receipt.js +335 -0
- package/dist/session/phase-completion.artifacts.d.ts +17 -0
- package/dist/session/phase-completion.artifacts.js +256 -26
- package/dist/session/phase-completion.d.ts +11 -2
- package/dist/session/phase-completion.helpers.d.ts +5 -0
- package/dist/session/phase-completion.helpers.js +51 -10
- package/dist/session/phase-completion.js +12 -3
- package/dist/session/phase-completion.prompts.d.ts +3 -3
- package/dist/session/phase-completion.prompts.js +21 -6
- package/dist/session/phase-completion.runtime.d.ts +13 -1
- package/dist/session/phase-completion.runtime.js +189 -8
- package/dist/session/phase-completion.schemas.js +132 -5
- package/dist/session/phase-completion.validation.d.ts +4 -1
- package/dist/session/phase-completion.validation.js +151 -21
- package/dist/session/provider-cli/ci-repair-readiness.d.ts +14 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +105 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
- package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +2 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +66 -9
- package/dist/session/provider-cli/provider-cli.process.d.ts +24 -0
- package/dist/session/provider-cli/provider-cli.process.js +431 -21
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +17 -2
- package/dist/session/provider-cli/provider-cli.prompts.js +241 -20
- package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
- package/dist/session/provider-cli/provider-cli.runtime.js +6 -3
- package/dist/session/provider-cli/provider-cli.service.d.ts +24 -3
- package/dist/session/provider-cli/provider-cli.service.js +588 -108
- package/dist/session/provider-cli/provider-cli.types.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +91 -16
- package/dist/session/provider-cli/provider-usage.d.ts +7 -0
- package/dist/session/provider-cli/provider-usage.js +28 -5
- package/dist/session/session-redaction.d.ts +3 -0
- package/dist/session/session-redaction.js +38 -0
- package/dist/session/session.base.d.ts +6 -1
- package/dist/session/session.service.d.ts +8 -2
- package/dist/session/session.service.js +549 -58
- package/dist/session/session.types.d.ts +159 -1
- package/dist/session/session.types.js +282 -4
- package/dist/shared/format/format-bytes.d.ts +1 -0
- package/dist/shared/format/format-bytes.js +9 -0
- package/dist/shared/path/path.d.ts +1 -0
- package/dist/shared/path/path.js +21 -1
- package/dist/shared/process/host-process-recovery.d.ts +12 -0
- package/dist/shared/process/host-process-recovery.js +78 -0
- package/dist/shared/process/host-process-supervisor.d.ts +59 -0
- package/dist/shared/process/host-process-supervisor.js +330 -0
- package/dist/shared/process/process.d.ts +1 -0
- package/dist/shared/process/process.js +1 -0
- package/dist/shared/process/windows-launch.d.ts +1 -1
- package/dist/shared/process/windows-launch.js +6 -3
- package/dist/shared/provider-capabilities.d.ts +1 -0
- package/dist/shared/provider-capabilities.js +3 -0
- package/dist/shared/redaction/redaction.js +16 -4
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +3 -2
- package/dist/worktree/artifact-injector.js +43 -4
- package/dist/worktree/dependency-warmer.d.ts +39 -1
- package/dist/worktree/dependency-warmer.js +351 -8
- package/dist/worktree/index.d.ts +2 -1
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
- package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
- package/dist/worktree/worktree-paths.d.ts +4 -0
- package/dist/worktree/worktree-paths.js +30 -0
- package/dist/worktree/worktree.base.d.ts +3 -0
- package/dist/worktree/worktree.service.d.ts +9 -2
- package/dist/worktree/worktree.service.js +217 -48
- package/dist/worktree/worktree.types.d.ts +5 -1
- package/package.json +8 -4
- package/runtime/windows-job-supervisor.ps1 +444 -0
- package/runtime/windows-listener-owner.ps1 +33 -0
|
@@ -1,47 +1,179 @@
|
|
|
1
1
|
import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import os from "node:os";
|
|
4
6
|
import { defaultForgeBridgeConfig } from "../config.js";
|
|
5
|
-
import {
|
|
7
|
+
import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
8
|
+
import { redactText } from "../shared/redaction/redaction.js";
|
|
6
9
|
import { BridgeSessionService } from "../session/session.service.js";
|
|
10
|
+
import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
11
|
+
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
12
|
+
import { HostRuntimeLeaseManager } from "../runtime/host-runtime-lease.js";
|
|
13
|
+
import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
14
|
+
import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
|
|
15
|
+
import { GitWorktreeService } from "../worktree/worktree.service.js";
|
|
16
|
+
import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
|
|
17
|
+
import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
|
|
7
18
|
import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
8
19
|
import { forgeBridgeVersion } from "../version.js";
|
|
20
|
+
import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
|
|
21
|
+
import { validateSandboxContract } from "../sandbox/contract.js";
|
|
22
|
+
import { runSandboxProcess } from "../sandbox/process.js";
|
|
23
|
+
import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
|
|
24
|
+
import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
|
|
25
|
+
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
26
|
+
/**
|
|
27
|
+
* Protocol-v2 events are acknowledged one at a time before runOnce returns.
|
|
28
|
+
* Sending the complete transcript again in DispatchResult made long QA and CI
|
|
29
|
+
* sessions exceed SignalR's receive limit, disconnecting the bridge after the
|
|
30
|
+
* provider had already completed. The API combines its acknowledged streamed
|
|
31
|
+
* events with the terminal result, so the callback only needs the outcome and
|
|
32
|
+
* artifacts. Protocol v1 retains the transcript for legacy servers.
|
|
33
|
+
*/
|
|
34
|
+
export function compactTerminalResult(dispatch, result) {
|
|
35
|
+
return dispatch.schemaVersion >= 2 && result.events.length > 0
|
|
36
|
+
? { ...result, events: [] }
|
|
37
|
+
: result;
|
|
38
|
+
}
|
|
9
39
|
export class ForgeBridgeService {
|
|
10
40
|
config;
|
|
11
|
-
sessions;
|
|
12
41
|
connections;
|
|
13
42
|
connection = null;
|
|
14
43
|
heartbeatTimer = null;
|
|
44
|
+
heartbeatInFlight = false;
|
|
45
|
+
consecutiveHeartbeatFailures = 0;
|
|
46
|
+
reconnectingFromHeartbeatFailure = false;
|
|
47
|
+
leaseWatchdogTimer = null;
|
|
48
|
+
sandboxMaintenanceTimer = null;
|
|
49
|
+
sandboxMaintenanceRunning = false;
|
|
15
50
|
closed = null;
|
|
51
|
+
transportRecovery = null;
|
|
52
|
+
transportRecoveryGeneration = 0;
|
|
16
53
|
stopped = false;
|
|
17
54
|
activeSessions = new Map();
|
|
18
|
-
|
|
55
|
+
reservations = new Map();
|
|
56
|
+
activeReadinessProbes = new Map();
|
|
57
|
+
preflight;
|
|
58
|
+
sandboxRuntime;
|
|
59
|
+
sandboxResourceResolver;
|
|
60
|
+
sessions;
|
|
61
|
+
sandboxAmbientMemoryCommitmentBytes = null;
|
|
62
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver) {
|
|
19
63
|
this.config = config;
|
|
20
|
-
this.sessions = sessions;
|
|
21
64
|
this.connections = connections;
|
|
65
|
+
this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot);
|
|
66
|
+
this.preflight = preflight ?? new DockerPreflight({
|
|
67
|
+
dockerExecutable: config.dockerExecutable,
|
|
68
|
+
dockerContext: config.dockerContext,
|
|
69
|
+
stateRoot: config.sandboxStateRoot,
|
|
70
|
+
runnerInstanceId: config.runnerInstanceId,
|
|
71
|
+
maxConcurrentSandboxes: config.maxConcurrentSandboxes,
|
|
72
|
+
diskHighWatermarkPercent: config.diskHighWatermarkPercent,
|
|
73
|
+
diskLowWatermarkPercent: config.diskLowWatermarkPercent,
|
|
74
|
+
minimumWorkspaceBytes: config.minimumWorkspaceBytes,
|
|
75
|
+
hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
|
|
76
|
+
defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
|
|
77
|
+
defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
|
|
78
|
+
runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
|
|
79
|
+
requireRootless: config.requireRootlessDocker
|
|
80
|
+
});
|
|
81
|
+
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
|
|
82
|
+
this.sandboxResourceResolver = sandboxResourceResolver
|
|
83
|
+
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
22
84
|
}
|
|
23
85
|
async connectOnce() {
|
|
24
86
|
await this.stopConnection();
|
|
25
87
|
this.stopped = false;
|
|
88
|
+
const hostReap = await this.sessions.reapHostRuntime?.({
|
|
89
|
+
runnerId: this.config.runnerId,
|
|
90
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
91
|
+
});
|
|
92
|
+
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
93
|
+
logBridgeStatus(`Managed-host recovery reaped ${hostReap.reaped} stale attempt(s), protected ${hostReap.reusedPidsProtected} reused PID(s), and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
|
|
94
|
+
}
|
|
95
|
+
if (this.config.dockerEnabled) {
|
|
96
|
+
const preflight = await this.preflight.refresh();
|
|
97
|
+
if (canReapManagedSandboxes(preflight)) {
|
|
98
|
+
await this.sandboxRuntime.reap({ diskLow: preflight.diskLow });
|
|
99
|
+
await this.preflight.refresh();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
26
102
|
const connection = this.connections.create(this.config);
|
|
27
103
|
this.connection = connection;
|
|
104
|
+
this.transportRecovery = null;
|
|
28
105
|
this.closed = new Promise((resolve) => {
|
|
29
|
-
connection.onClose(() => {
|
|
106
|
+
connection.onClose((error) => {
|
|
30
107
|
this.stopHeartbeat();
|
|
108
|
+
this.completeTransportRecovery(error ?? new Error("bridge connection closed"));
|
|
31
109
|
this.abortActiveSessions("bridge connection closed");
|
|
110
|
+
this.abortActiveReadinessProbes("bridge connection closed");
|
|
32
111
|
resolve();
|
|
33
112
|
});
|
|
34
113
|
});
|
|
114
|
+
connection.onReconnecting?.((error) => {
|
|
115
|
+
if (connection !== this.connection || this.stopped)
|
|
116
|
+
return;
|
|
117
|
+
this.stopHeartbeat();
|
|
118
|
+
this.beginTransportRecovery();
|
|
119
|
+
logBridgeStatus(`Forge connection interrupted${error ? `: ${errorMessage(error)}` : ""}. Reconnecting in place; active dispatches remain supervised...`);
|
|
120
|
+
});
|
|
121
|
+
connection.onReconnected?.(async () => {
|
|
122
|
+
if (connection !== this.connection || this.stopped)
|
|
123
|
+
return;
|
|
124
|
+
try {
|
|
125
|
+
await this.registerConnection(connection);
|
|
126
|
+
this.completeTransportRecovery();
|
|
127
|
+
this.startHeartbeat();
|
|
128
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
129
|
+
logBridgeStatus("Forge connection restored; active dispatches remain attached to this runner process.");
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
this.completeTransportRecovery(error);
|
|
133
|
+
logBridgeStatus(`Forge reconnect registration failed: ${errorMessage(error)}. Closing the connection for a clean retry...`);
|
|
134
|
+
await connection.stop().catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
35
137
|
connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
|
|
138
|
+
connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
|
|
139
|
+
connection.onStart?.((dispatch) => this.handleStart(dispatch));
|
|
140
|
+
connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
|
|
36
141
|
connection.onCancel((request) => this.handleCancel(request));
|
|
142
|
+
connection.onReap?.((request) => this.handleReap(request));
|
|
143
|
+
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
37
144
|
await connection.start();
|
|
38
|
-
await this.
|
|
39
|
-
|
|
40
|
-
protocolVersion: this.config.protocolVersion,
|
|
41
|
-
minServerVersion: this.config.minServerVersion ?? null,
|
|
42
|
-
capabilities: this.capabilities()
|
|
43
|
-
});
|
|
145
|
+
await this.registerConnection(connection);
|
|
146
|
+
await this.flushCleanupReports();
|
|
44
147
|
this.startHeartbeat();
|
|
148
|
+
this.startLeaseWatchdog();
|
|
149
|
+
this.startSandboxMaintenance();
|
|
150
|
+
}
|
|
151
|
+
async registerConnection(connection) {
|
|
152
|
+
let storageRecoveryAttempt = 0;
|
|
153
|
+
while (true) {
|
|
154
|
+
try {
|
|
155
|
+
const ack = await connection.invoke("Hello", {
|
|
156
|
+
version: this.config.version,
|
|
157
|
+
protocolVersion: this.config.protocolVersion,
|
|
158
|
+
minServerVersion: this.config.minServerVersion ?? null,
|
|
159
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
160
|
+
capabilities: this.capabilities()
|
|
161
|
+
});
|
|
162
|
+
if (!ack.accepted) {
|
|
163
|
+
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
|
|
164
|
+
}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (!isProviderStorageUnavailable(error) || storageRecoveryAttempt >= this.config.reconnectBackoffMs.length) {
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
const backoff = this.config.reconnectBackoffMs[storageRecoveryAttempt] ?? 5000;
|
|
172
|
+
storageRecoveryAttempt += 1;
|
|
173
|
+
logBridgeStatus(`Hello reached Forge while storage was recovering. Retrying registration ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
|
|
174
|
+
await delay(backoff);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
45
177
|
}
|
|
46
178
|
async run(signal) {
|
|
47
179
|
let attempt = 0;
|
|
@@ -72,6 +204,7 @@ export class ForgeBridgeService {
|
|
|
72
204
|
finally {
|
|
73
205
|
if (signal?.aborted) {
|
|
74
206
|
this.abortActiveSessions(String(signal.reason ?? "bridge stopping"));
|
|
207
|
+
this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
|
|
75
208
|
}
|
|
76
209
|
await this.stopConnection();
|
|
77
210
|
}
|
|
@@ -79,7 +212,9 @@ export class ForgeBridgeService {
|
|
|
79
212
|
async stop() {
|
|
80
213
|
this.stopped = true;
|
|
81
214
|
this.abortActiveSessions("bridge stopping");
|
|
215
|
+
this.abortActiveReadinessProbes("bridge stopping");
|
|
82
216
|
await this.stopConnection();
|
|
217
|
+
await this.preflight.release();
|
|
83
218
|
}
|
|
84
219
|
async handleDispatch(rawDispatch) {
|
|
85
220
|
const dispatch = this.parseDispatchOrReport(rawDispatch);
|
|
@@ -89,21 +224,53 @@ export class ForgeBridgeService {
|
|
|
89
224
|
const leaseId = dispatch.lease.id;
|
|
90
225
|
const fencingToken = dispatch.lease.fencingToken;
|
|
91
226
|
const redactionSecrets = exactSecrets(dispatch, this.config);
|
|
92
|
-
|
|
93
|
-
|
|
227
|
+
const existing = this.activeSessions.get(leaseId);
|
|
228
|
+
if (existing) {
|
|
229
|
+
if (existing.fencingToken === fencingToken) {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
await this.sendResult(dispatch, failureResult("Dispatch fence conflicts with an active bridge session.")).catch(() => undefined);
|
|
94
233
|
return;
|
|
95
234
|
}
|
|
96
235
|
const controller = new AbortController();
|
|
97
|
-
this.activeSessions.set(leaseId, {
|
|
236
|
+
this.activeSessions.set(leaseId, {
|
|
237
|
+
fencingToken,
|
|
238
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
239
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
240
|
+
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
241
|
+
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
242
|
+
resources: dispatch.sandbox?.executionMode === "docker"
|
|
243
|
+
? dispatch.sandbox.requestedResources
|
|
244
|
+
: zeroSandboxResources(),
|
|
245
|
+
controller
|
|
246
|
+
});
|
|
98
247
|
try {
|
|
99
248
|
const normalized = this.normalizeDispatch(dispatch);
|
|
100
|
-
|
|
249
|
+
if (normalized.sandbox) {
|
|
250
|
+
const started = {
|
|
251
|
+
dispatchAttemptId: normalized.sandbox.dispatchAttemptId,
|
|
252
|
+
leaseId,
|
|
253
|
+
fencingToken,
|
|
254
|
+
runnerInstanceId: normalized.sandbox.runnerInstanceId
|
|
255
|
+
};
|
|
256
|
+
await this.invokeAck("DispatchStarted", started);
|
|
257
|
+
}
|
|
258
|
+
const sink = {
|
|
101
259
|
emit: async (event) => {
|
|
260
|
+
if (event.eventType === "provider_cli_started") {
|
|
261
|
+
const active = this.activeSessions.get(leaseId);
|
|
262
|
+
if (active)
|
|
263
|
+
active.resources = { ...active.resources, buildSlots: 0 };
|
|
264
|
+
}
|
|
102
265
|
try {
|
|
103
266
|
await this.invokeAck("DispatchEvent", {
|
|
104
267
|
leaseId,
|
|
105
268
|
fencingToken,
|
|
106
|
-
|
|
269
|
+
...(dispatch.sandbox ? {
|
|
270
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
271
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
272
|
+
} : {}),
|
|
273
|
+
event: redactRunnerDispatchEvent(event, redactionSecrets)
|
|
107
274
|
});
|
|
108
275
|
}
|
|
109
276
|
catch (error) {
|
|
@@ -114,19 +281,293 @@ export class ForgeBridgeService {
|
|
|
114
281
|
throw error;
|
|
115
282
|
}
|
|
116
283
|
}
|
|
117
|
-
}
|
|
118
|
-
|
|
284
|
+
};
|
|
285
|
+
const result = normalized.sandbox?.executionMode === "docker"
|
|
286
|
+
? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
|
|
287
|
+
: await this.sessions.runOnce(normalized, sink, controller.signal);
|
|
288
|
+
if (normalized.sandbox?.executionMode === "docker") {
|
|
289
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
290
|
+
}
|
|
291
|
+
const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
|
|
292
|
+
await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
|
|
119
293
|
}
|
|
120
294
|
catch (error) {
|
|
121
295
|
const summary = controller.signal.aborted
|
|
122
296
|
? `Dispatch cancelled: ${String(controller.signal.reason ?? "cancelled")}`
|
|
123
297
|
: redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
|
|
124
|
-
|
|
298
|
+
const failureEventType = infrastructureFailureEventType(summary);
|
|
299
|
+
const failureEvents = failureEventType ? [{
|
|
300
|
+
role: "runner",
|
|
301
|
+
kind: "error",
|
|
302
|
+
content: summary,
|
|
303
|
+
eventType: failureEventType,
|
|
304
|
+
}] : [];
|
|
305
|
+
await this.sendResult(dispatch, failureResult(summary, failureEvents)).catch(() => undefined);
|
|
125
306
|
}
|
|
126
307
|
finally {
|
|
127
308
|
this.activeSessions.delete(leaseId);
|
|
128
309
|
}
|
|
129
310
|
}
|
|
311
|
+
async handleOffer(rawDispatch) {
|
|
312
|
+
const envelope = parseOfferEnvelope(rawDispatch);
|
|
313
|
+
if (!envelope) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const dispatch = this.parseDispatchOrReport(envelope.dispatch);
|
|
317
|
+
if (!dispatch?.sandbox
|
|
318
|
+
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
319
|
+
|| dispatch.lease.id !== envelope.leaseId
|
|
320
|
+
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
321
|
+
return;
|
|
322
|
+
const sandbox = dispatch.sandbox;
|
|
323
|
+
this.expireReservations(Date.now());
|
|
324
|
+
const existing = this.reservations.get(sandbox.dispatchAttemptId);
|
|
325
|
+
if (existing) {
|
|
326
|
+
const sameFence = existing.leaseId === dispatch.lease.id
|
|
327
|
+
&& existing.fencingToken === dispatch.lease.fencingToken
|
|
328
|
+
&& existing.runnerInstanceId === sandbox.runnerInstanceId;
|
|
329
|
+
await this.sendOfferDecision(dispatch, sameFence, sameFence ? null : "stale_fence", sameFence ? null : "Offer fence conflicts with the existing reservation.", sameFence ? existing.reservedUntil : null, sameFence ? existing.resources : null);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (sandbox.runnerInstanceId !== this.config.runnerInstanceId) {
|
|
333
|
+
await this.sendOfferDecision(dispatch, false, "stale_runner_instance", "Offer targets a different runner process instance.");
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (Date.parse(envelope.expiresAt) <= Date.now()) {
|
|
337
|
+
await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
|
|
341
|
+
? await this.preflight.run()
|
|
342
|
+
: this.preflight.current();
|
|
343
|
+
if (sandbox.executionMode === "docker") {
|
|
344
|
+
if (!this.config.dockerEnabled || !preflight?.healthy) {
|
|
345
|
+
await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
|
|
349
|
+
if (networkFailure) {
|
|
350
|
+
await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
|
|
354
|
+
if (providerNetworkFailure) {
|
|
355
|
+
await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const authFailure = sandboxAuthFailure(dispatch, this.config);
|
|
359
|
+
if (authFailure) {
|
|
360
|
+
await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
let requestedResources = sandbox.requestedResources;
|
|
365
|
+
let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
|
|
366
|
+
const normalizedDispatch = this.normalizeDispatch(dispatch);
|
|
367
|
+
if (sandbox.executionMode === "docker") {
|
|
368
|
+
try {
|
|
369
|
+
const profile = await this.sandboxResourceResolver(normalizedDispatch);
|
|
370
|
+
requestedResources = profile.resources;
|
|
371
|
+
sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
else if (normalizedDispatch.repo.serverLocalPath) {
|
|
379
|
+
// Host execution uses the same project-derived disk reservation as Docker.
|
|
380
|
+
// The API supplies a placement-time estimate; the runner can safely raise it
|
|
381
|
+
// from its authoritative checkout before admitting the attempt.
|
|
382
|
+
const measuredWorkspaceBytes = await estimateWorkspaceBytesFromRepo(normalizedDispatch.repo.serverLocalPath, { role: normalizedDispatch.execution.role }).catch(() => null);
|
|
383
|
+
if (measuredWorkspaceBytes !== null) {
|
|
384
|
+
requestedResources = {
|
|
385
|
+
...requestedResources,
|
|
386
|
+
workspaceBytes: Math.max(requestedResources.workspaceBytes, measuredWorkspaceBytes),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
// Resource profiling can await filesystem and Docker work. Admission needs
|
|
391
|
+
// a dynamic host/daemon sample that began after profiling completed, so an
|
|
392
|
+
// older in-flight heartbeat inspection cannot supply the commit decision.
|
|
393
|
+
const admissionPreflight = sandbox.executionMode === "docker"
|
|
394
|
+
? await this.preflight.refreshCapacityForAdmission()
|
|
395
|
+
: preflight;
|
|
396
|
+
// Resource profiling and preflight may await slow filesystem or Docker I/O.
|
|
397
|
+
// Re-read every mutable capacity input only after that work, then decide and
|
|
398
|
+
// commit synchronously. JavaScript cannot interleave another Offer handler
|
|
399
|
+
// inside this non-async method, so the ledger check and insertion are one
|
|
400
|
+
// atomic event-loop turn without holding a lock across external I/O.
|
|
401
|
+
const decision = this.commitOfferReservation(dispatch, requestedResources, admissionPreflight);
|
|
402
|
+
await this.sendOfferDecision(dispatch, decision.accepted, decision.code, decision.message, decision.reservedUntil, decision.resources, sandboxConfigCommitSha);
|
|
403
|
+
}
|
|
404
|
+
commitOfferReservation(dispatch, requestedResources, preparedPreflight) {
|
|
405
|
+
const sandbox = dispatch.sandbox;
|
|
406
|
+
const now = Date.now();
|
|
407
|
+
this.expireReservations(now);
|
|
408
|
+
const existing = this.reservations.get(sandbox.dispatchAttemptId);
|
|
409
|
+
if (existing) {
|
|
410
|
+
const sameFence = existing.leaseId === dispatch.lease.id
|
|
411
|
+
&& existing.fencingToken === dispatch.lease.fencingToken
|
|
412
|
+
&& existing.runnerInstanceId === sandbox.runnerInstanceId;
|
|
413
|
+
return {
|
|
414
|
+
accepted: sameFence,
|
|
415
|
+
code: sameFence ? null : "stale_fence",
|
|
416
|
+
message: sameFence ? null : "Offer fence conflicts with the existing reservation.",
|
|
417
|
+
reservedUntil: sameFence ? existing.reservedUntil : null,
|
|
418
|
+
resources: sameFence ? existing.resources : null,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
if (Date.parse(dispatch.lease.expiresAt) <= now) {
|
|
422
|
+
return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
|
|
423
|
+
}
|
|
424
|
+
if (sandbox.executionMode === "docker") {
|
|
425
|
+
// A concurrent heartbeat/preflight refresh may have produced a newer
|
|
426
|
+
// conservative dual-domain sample while this offer was being profiled.
|
|
427
|
+
const admissionPreflight = this.preflight.current() ?? preparedPreflight;
|
|
428
|
+
if (!this.config.dockerEnabled || !admissionPreflight?.healthy) {
|
|
429
|
+
return rejectedOfferReservation(admissionPreflight?.unavailableCode ?? "docker_unavailable", admissionPreflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
|
|
430
|
+
}
|
|
431
|
+
const runtimeState = this.sandboxRuntime.snapshot();
|
|
432
|
+
const usedResources = this.usedSandboxResources(runtimeState.degraded);
|
|
433
|
+
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
434
|
+
const capacity = this.sandboxResourceCapacity(admissionPreflight, activeResources, usedResources);
|
|
435
|
+
if (!canReserveSandboxResources(usedResources, requestedResources, capacity)) {
|
|
436
|
+
return rejectedOfferReservation("capacity_unavailable", sandboxCapacityFailureMessage(usedResources, requestedResources, capacity, admissionPreflight, this.config));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt), now + 30_000)).toISOString();
|
|
440
|
+
const reservation = {
|
|
441
|
+
leaseId: dispatch.lease.id,
|
|
442
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
443
|
+
runnerInstanceId: sandbox.runnerInstanceId,
|
|
444
|
+
expiresAt: dispatch.lease.expiresAt,
|
|
445
|
+
reservedUntil,
|
|
446
|
+
sandboxed: sandbox.executionMode === "docker",
|
|
447
|
+
resources: requestedResources,
|
|
448
|
+
};
|
|
449
|
+
this.reservations.set(sandbox.dispatchAttemptId, reservation);
|
|
450
|
+
return {
|
|
451
|
+
accepted: true,
|
|
452
|
+
code: null,
|
|
453
|
+
message: null,
|
|
454
|
+
reservedUntil,
|
|
455
|
+
resources: requestedResources,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
async handleStart(rawDispatch) {
|
|
459
|
+
const envelope = parseStartEnvelope(rawDispatch);
|
|
460
|
+
if (!envelope) {
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
let dispatch = this.parseDispatchOrReport(envelope.dispatch);
|
|
464
|
+
if (!dispatch?.sandbox
|
|
465
|
+
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
466
|
+
|| dispatch.lease.id !== envelope.leaseId
|
|
467
|
+
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
468
|
+
return;
|
|
469
|
+
const reservation = this.reservations.get(dispatch.sandbox.dispatchAttemptId);
|
|
470
|
+
if (!reservation
|
|
471
|
+
|| reservation.leaseId !== dispatch.lease.id
|
|
472
|
+
|| reservation.fencingToken !== dispatch.lease.fencingToken
|
|
473
|
+
|| reservation.runnerInstanceId !== dispatch.sandbox.runnerInstanceId
|
|
474
|
+
|| Date.parse(reservation.reservedUntil) <= Date.now()) {
|
|
475
|
+
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.")).catch(() => undefined);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
if (dispatch.apiKeySecretGrant) {
|
|
479
|
+
this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
|
|
480
|
+
await this.sendResult(dispatch, failureResult("Start rejected because protocol-v2 packets may not contain a plaintext provider grant.")).catch(() => undefined);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (dispatch.apiKeySecretGrantHandle) {
|
|
484
|
+
const response = await this.redeemSecretGrant(dispatch);
|
|
485
|
+
const grant = response.grant;
|
|
486
|
+
if (!response.accepted
|
|
487
|
+
|| !grant
|
|
488
|
+
|| grant.grantId !== dispatch.apiKeySecretGrantHandle.grantId
|
|
489
|
+
|| grant.provider !== dispatch.apiKeySecretGrantHandle.provider
|
|
490
|
+
|| Date.parse(grant.expiresAt) <= Date.now()) {
|
|
491
|
+
this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
|
|
492
|
+
await this.sendResult(dispatch, failureResult(response.message ?? "Secret grant redemption was rejected.")).catch(() => undefined);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
dispatch = { ...dispatch, apiKeySecretGrant: grant, apiKeySecretGrantHandle: null };
|
|
496
|
+
}
|
|
497
|
+
else if (dispatch.execution.requiresApiKeySecretGrant) {
|
|
498
|
+
this.reservations.delete(dispatch.sandbox.dispatchAttemptId);
|
|
499
|
+
await this.sendResult(dispatch, failureResult("Start rejected because the provider secret grant handle is missing.")).catch(() => undefined);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
dispatch = {
|
|
503
|
+
...dispatch,
|
|
504
|
+
sandbox: { ...dispatch.sandbox, requestedResources: reservation.resources },
|
|
505
|
+
};
|
|
506
|
+
this.reservations.delete(envelope.dispatchAttemptId);
|
|
507
|
+
await this.handleDispatch(dispatch);
|
|
508
|
+
}
|
|
509
|
+
async redeemSecretGrant(dispatch) {
|
|
510
|
+
const sandbox = dispatch.sandbox;
|
|
511
|
+
const handle = dispatch.apiKeySecretGrantHandle;
|
|
512
|
+
const connection = this.connection;
|
|
513
|
+
if (!connection)
|
|
514
|
+
return { accepted: false, code: "bridge.disconnected", message: "Bridge is disconnected.", grant: null };
|
|
515
|
+
return await connection.invoke("RedeemSecretGrant", {
|
|
516
|
+
dispatchAttemptId: sandbox.dispatchAttemptId,
|
|
517
|
+
leaseId: dispatch.lease.id,
|
|
518
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
519
|
+
runnerInstanceId: sandbox.runnerInstanceId,
|
|
520
|
+
grantId: handle.grantId
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
async redeemPublishGrant(request, signal) {
|
|
524
|
+
if (signal?.aborted)
|
|
525
|
+
throw new Error(String(signal.reason ?? "publication cancelled"));
|
|
526
|
+
const connection = this.connection;
|
|
527
|
+
if (!connection)
|
|
528
|
+
throw new Error("sandbox_output_publish_forbidden: bridge is disconnected.");
|
|
529
|
+
const response = await connection.invoke("RedeemPublishGrant", request);
|
|
530
|
+
if (!response.accepted || !response.credential) {
|
|
531
|
+
throw new Error(`sandbox_output_publish_forbidden: ${response.message ?? response.code ?? "publication grant redemption was rejected"}`);
|
|
532
|
+
}
|
|
533
|
+
return response.credential;
|
|
534
|
+
}
|
|
535
|
+
async handleLeaseUpdate(request) {
|
|
536
|
+
if (request.runnerInstanceId !== this.config.runnerInstanceId) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const reservation = this.reservations.get(request.dispatchAttemptId);
|
|
540
|
+
if (reservation && reservation.leaseId === request.leaseId && reservation.fencingToken === request.fencingToken) {
|
|
541
|
+
reservation.expiresAt = request.expiresAt;
|
|
542
|
+
}
|
|
543
|
+
const active = this.activeSessions.get(request.leaseId);
|
|
544
|
+
if (active && active.fencingToken === request.fencingToken && active.dispatchAttemptId === request.dispatchAttemptId) {
|
|
545
|
+
active.leaseExpiresAt = request.expiresAt;
|
|
546
|
+
if (active.sandboxed) {
|
|
547
|
+
await this.sandboxRuntime.updateLease(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
|
|
548
|
+
}
|
|
549
|
+
else {
|
|
550
|
+
await this.sessions.updateLease?.(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async sendOfferDecision(dispatch, accepted, code = null, message = null, reservedUntil = null, reservedResources = null, sandboxConfigCommitSha = null) {
|
|
555
|
+
if (!dispatch.sandbox)
|
|
556
|
+
return;
|
|
557
|
+
const payload = {
|
|
558
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
559
|
+
leaseId: dispatch.lease.id,
|
|
560
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
561
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId,
|
|
562
|
+
accepted,
|
|
563
|
+
code,
|
|
564
|
+
message,
|
|
565
|
+
reservedUntil: accepted ? reservedUntil ?? dispatch.lease.expiresAt : null,
|
|
566
|
+
reservedResources: accepted ? reservedResources : null,
|
|
567
|
+
sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
|
|
568
|
+
};
|
|
569
|
+
await this.invokeAck("OfferDecision", payload);
|
|
570
|
+
}
|
|
130
571
|
parseDispatchOrReport(rawDispatch) {
|
|
131
572
|
try {
|
|
132
573
|
return parseRunOnceDispatchPacket(rawDispatch);
|
|
@@ -137,7 +578,7 @@ export class ForgeBridgeService {
|
|
|
137
578
|
return null;
|
|
138
579
|
}
|
|
139
580
|
const summary = invalidDispatchSummary(error);
|
|
140
|
-
void this.
|
|
581
|
+
void this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
|
|
141
582
|
{
|
|
142
583
|
role: "runner",
|
|
143
584
|
kind: "error",
|
|
@@ -155,12 +596,74 @@ export class ForgeBridgeService {
|
|
|
155
596
|
}
|
|
156
597
|
active.controller.abort(request.reason ?? "cancelled by server");
|
|
157
598
|
}
|
|
599
|
+
async handleReap(request) {
|
|
600
|
+
if (request.runnerId !== this.config.runnerId
|
|
601
|
+
|| request.runnerInstanceId !== this.config.runnerInstanceId)
|
|
602
|
+
return;
|
|
603
|
+
await this.runSandboxMaintenance();
|
|
604
|
+
await this.sendHeartbeat();
|
|
605
|
+
}
|
|
606
|
+
async handleReadinessProbe(rawRequest) {
|
|
607
|
+
const request = parseReadinessProbe(rawRequest);
|
|
608
|
+
if (!request || request.runnerInstanceId !== this.config.runnerInstanceId)
|
|
609
|
+
return;
|
|
610
|
+
const existing = this.activeReadinessProbes.get(request.requestId);
|
|
611
|
+
if (existing)
|
|
612
|
+
return;
|
|
613
|
+
const controller = new AbortController();
|
|
614
|
+
this.activeReadinessProbes.set(request.requestId, controller);
|
|
615
|
+
const deadlineMs = Date.parse(request.expiresAt) - Date.now();
|
|
616
|
+
const timer = setTimeout(() => controller.abort("readiness probe expired"), Math.max(0, deadlineMs));
|
|
617
|
+
timer.unref?.();
|
|
618
|
+
let result;
|
|
619
|
+
try {
|
|
620
|
+
if (!this.sessions.probeHostRuntime) {
|
|
621
|
+
throw new Error("host_runtime_probe_unavailable: this bridge does not implement runtime readiness probes.");
|
|
622
|
+
}
|
|
623
|
+
const probe = await this.sessions.probeHostRuntime({
|
|
624
|
+
...request,
|
|
625
|
+
runnerId: this.config.runnerId,
|
|
626
|
+
repoRoot: this.config.defaultRepoRoot,
|
|
627
|
+
cleanupWorktrees: this.config.cleanupWorktrees,
|
|
628
|
+
}, controller.signal);
|
|
629
|
+
result = {
|
|
630
|
+
schemaVersion: 1,
|
|
631
|
+
requestId: request.requestId,
|
|
632
|
+
fencingToken: request.fencingToken,
|
|
633
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
634
|
+
...probe,
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
result = {
|
|
639
|
+
schemaVersion: 1,
|
|
640
|
+
requestId: request.requestId,
|
|
641
|
+
fencingToken: request.fencingToken,
|
|
642
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
643
|
+
status: "failed",
|
|
644
|
+
reasonCode: "host_runtime_probe_failed",
|
|
645
|
+
reasonMessage: errorMessage(error).slice(0, 1000),
|
|
646
|
+
checkedAt: new Date().toISOString(),
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
finally {
|
|
650
|
+
clearTimeout(timer);
|
|
651
|
+
this.activeReadinessProbes.delete(request.requestId);
|
|
652
|
+
}
|
|
653
|
+
await this.invokeAck("ReadinessResult", result).catch(() => undefined);
|
|
654
|
+
await this.sendHeartbeat().catch(() => undefined);
|
|
655
|
+
}
|
|
158
656
|
abortActiveSessions(reason) {
|
|
159
657
|
for (const active of this.activeSessions.values()) {
|
|
160
658
|
active.controller.abort(reason);
|
|
161
659
|
}
|
|
162
660
|
this.activeSessions.clear();
|
|
163
661
|
}
|
|
662
|
+
abortActiveReadinessProbes(reason) {
|
|
663
|
+
for (const controller of this.activeReadinessProbes.values())
|
|
664
|
+
controller.abort(reason);
|
|
665
|
+
this.activeReadinessProbes.clear();
|
|
666
|
+
}
|
|
164
667
|
normalizeDispatch(dispatch) {
|
|
165
668
|
const mapping = findRepoMapping(dispatch, repoMappingsFor(this.config));
|
|
166
669
|
const localPath = mapping?.localPath?.trim();
|
|
@@ -185,12 +688,20 @@ export class ForgeBridgeService {
|
|
|
185
688
|
: dispatch.qaBrowser
|
|
186
689
|
};
|
|
187
690
|
}
|
|
188
|
-
async sendResult(
|
|
691
|
+
async sendResult(dispatch, result) {
|
|
189
692
|
const payload = {
|
|
190
|
-
leaseId,
|
|
191
|
-
fencingToken,
|
|
693
|
+
leaseId: dispatch.lease.id,
|
|
694
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
695
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
696
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
192
697
|
result
|
|
193
698
|
};
|
|
699
|
+
await this.sendResultPayload(payload);
|
|
700
|
+
}
|
|
701
|
+
async sendLegacyResult(leaseId, fencingToken, result) {
|
|
702
|
+
await this.sendResultPayload({ leaseId, fencingToken, result });
|
|
703
|
+
}
|
|
704
|
+
async sendResultPayload(payload) {
|
|
194
705
|
try {
|
|
195
706
|
await this.invokeAck("DispatchResult", payload);
|
|
196
707
|
}
|
|
@@ -203,19 +714,141 @@ export class ForgeBridgeService {
|
|
|
203
714
|
}
|
|
204
715
|
startHeartbeat() {
|
|
205
716
|
this.stopHeartbeat();
|
|
717
|
+
this.consecutiveHeartbeatFailures = 0;
|
|
718
|
+
this.reconnectingFromHeartbeatFailure = false;
|
|
206
719
|
const intervalMs = positiveFiniteNumber(this.config.heartbeatIntervalMs, 30_000);
|
|
207
720
|
this.heartbeatTimer = setInterval(() => {
|
|
208
|
-
this.
|
|
721
|
+
void this.heartbeatTick();
|
|
209
722
|
}, intervalMs);
|
|
210
723
|
this.heartbeatTimer.unref?.();
|
|
211
724
|
}
|
|
725
|
+
async heartbeatTick() {
|
|
726
|
+
if (this.heartbeatInFlight || this.reconnectingFromHeartbeatFailure)
|
|
727
|
+
return;
|
|
728
|
+
const connection = this.connection;
|
|
729
|
+
if (!connection)
|
|
730
|
+
return;
|
|
731
|
+
this.heartbeatInFlight = true;
|
|
732
|
+
try {
|
|
733
|
+
await this.sendHeartbeat();
|
|
734
|
+
this.consecutiveHeartbeatFailures = 0;
|
|
735
|
+
}
|
|
736
|
+
catch (error) {
|
|
737
|
+
if (connection !== this.connection || this.stopped)
|
|
738
|
+
return;
|
|
739
|
+
this.consecutiveHeartbeatFailures += 1;
|
|
740
|
+
logBridgeStatus(`Heartbeat ${this.consecutiveHeartbeatFailures} failed: ${errorMessage(error)}.`);
|
|
741
|
+
if (this.consecutiveHeartbeatFailures < 2)
|
|
742
|
+
return;
|
|
743
|
+
this.reconnectingFromHeartbeatFailure = true;
|
|
744
|
+
this.stopHeartbeat();
|
|
745
|
+
logBridgeStatus("Heartbeat failed twice. Closing the stale connection so the Bridge can reconnect...");
|
|
746
|
+
await connection.stop().catch(() => undefined);
|
|
747
|
+
}
|
|
748
|
+
finally {
|
|
749
|
+
this.heartbeatInFlight = false;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
startLeaseWatchdog() {
|
|
753
|
+
this.stopLeaseWatchdog();
|
|
754
|
+
this.leaseWatchdogTimer = setInterval(() => this.expireLeases(), 1000);
|
|
755
|
+
this.leaseWatchdogTimer.unref?.();
|
|
756
|
+
}
|
|
757
|
+
stopLeaseWatchdog() {
|
|
758
|
+
if (this.leaseWatchdogTimer) {
|
|
759
|
+
clearInterval(this.leaseWatchdogTimer);
|
|
760
|
+
this.leaseWatchdogTimer = null;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
expireLeases() {
|
|
764
|
+
const now = Date.now();
|
|
765
|
+
this.expireReservations(now);
|
|
766
|
+
for (const active of this.activeSessions.values()) {
|
|
767
|
+
if (Date.parse(active.leaseExpiresAt) <= now && !active.controller.signal.aborted) {
|
|
768
|
+
active.controller.abort("dispatch lease expired");
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
expireReservations(now) {
|
|
773
|
+
for (const [attemptId, reservation] of this.reservations) {
|
|
774
|
+
if (Date.parse(reservation.expiresAt) <= now || Date.parse(reservation.reservedUntil) <= now) {
|
|
775
|
+
this.reservations.delete(attemptId);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
212
779
|
stopHeartbeat() {
|
|
213
780
|
if (this.heartbeatTimer) {
|
|
214
781
|
clearInterval(this.heartbeatTimer);
|
|
215
782
|
this.heartbeatTimer = null;
|
|
216
783
|
}
|
|
217
784
|
}
|
|
785
|
+
startSandboxMaintenance() {
|
|
786
|
+
this.stopSandboxMaintenance();
|
|
787
|
+
this.sandboxMaintenanceTimer = setInterval(() => {
|
|
788
|
+
this.runSandboxMaintenance().catch(() => undefined);
|
|
789
|
+
}, 60_000);
|
|
790
|
+
this.sandboxMaintenanceTimer.unref?.();
|
|
791
|
+
}
|
|
792
|
+
stopSandboxMaintenance() {
|
|
793
|
+
if (this.sandboxMaintenanceTimer) {
|
|
794
|
+
clearInterval(this.sandboxMaintenanceTimer);
|
|
795
|
+
this.sandboxMaintenanceTimer = null;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
async runSandboxMaintenance() {
|
|
799
|
+
if (this.sandboxMaintenanceRunning)
|
|
800
|
+
return;
|
|
801
|
+
this.sandboxMaintenanceRunning = true;
|
|
802
|
+
try {
|
|
803
|
+
const hostReap = await this.sessions.reapHostRuntime?.({
|
|
804
|
+
runnerId: this.config.runnerId,
|
|
805
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
806
|
+
});
|
|
807
|
+
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
808
|
+
logBridgeStatus(`Managed-host maintenance reaped ${hostReap.reaped} stale attempt(s) and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
|
|
809
|
+
}
|
|
810
|
+
if (this.config.dockerEnabled) {
|
|
811
|
+
const preflight = await this.preflight.refresh();
|
|
812
|
+
if (canReapManagedSandboxes(preflight)) {
|
|
813
|
+
const attemptSnapshot = await this.readAttemptSnapshot();
|
|
814
|
+
await this.sandboxRuntime.reap({ diskLow: preflight.diskLow, attemptSnapshot });
|
|
815
|
+
await this.flushCleanupReports();
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
finally {
|
|
820
|
+
this.sandboxMaintenanceRunning = false;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
async readAttemptSnapshot() {
|
|
824
|
+
const connection = this.connection;
|
|
825
|
+
if (!connection)
|
|
826
|
+
throw new Error("Bridge is not connected.");
|
|
827
|
+
const response = await connection.invoke("AttemptSnapshot", {
|
|
828
|
+
runnerInstanceId: this.config.runnerInstanceId
|
|
829
|
+
});
|
|
830
|
+
if (!response.accepted) {
|
|
831
|
+
throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
|
|
832
|
+
}
|
|
833
|
+
return response.attempts ?? [];
|
|
834
|
+
}
|
|
835
|
+
async flushCleanupReports() {
|
|
836
|
+
if (!this.sandboxRuntime.pendingCleanupReports || !this.sandboxRuntime.acknowledgeCleanupReport)
|
|
837
|
+
return;
|
|
838
|
+
for (const report of await this.sandboxRuntime.pendingCleanupReports()) {
|
|
839
|
+
await this.invokeAck("CleanupReport", {
|
|
840
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
841
|
+
report
|
|
842
|
+
});
|
|
843
|
+
await this.sandboxRuntime.acknowledgeCleanupReport(report.reportId);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
218
846
|
async sendHeartbeat() {
|
|
847
|
+
// Heartbeats are the recovery path for capacity-blocked work. Refresh the
|
|
848
|
+
// dynamic sample before advertising it, while reusing the static Docker
|
|
849
|
+
// capability snapshot established at startup or by an offer.
|
|
850
|
+
if (this.config.dockerEnabled)
|
|
851
|
+
await this.preflight.refreshCapacity();
|
|
219
852
|
await this.invokeAck("Heartbeat", {
|
|
220
853
|
status: "online",
|
|
221
854
|
capabilities: this.capabilities(),
|
|
@@ -224,8 +857,25 @@ export class ForgeBridgeService {
|
|
|
224
857
|
});
|
|
225
858
|
}
|
|
226
859
|
capabilities() {
|
|
860
|
+
const preflight = this.preflight.current();
|
|
861
|
+
const runtimeState = this.sandboxRuntime.snapshot();
|
|
862
|
+
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
863
|
+
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
864
|
+
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
865
|
+
const capacity = this.sandboxResourceCapacity(preflight, activeResources, used);
|
|
866
|
+
const ambientMemoryCommitmentBytes = this.sandboxAmbientMemoryCommitmentBytes ?? 0;
|
|
867
|
+
const memoryAdmission = preflight ? buildMemoryAdmissionDiagnostics({
|
|
868
|
+
sampledAt: preflight.sampledAt,
|
|
869
|
+
totalMemoryBytes: preflight.totalMemoryBytes,
|
|
870
|
+
rawAvailableMemoryBytes: preflight.rawAvailableMemoryBytes,
|
|
871
|
+
stabilizedAvailableMemoryBytes: preflight.availableMemoryBytes,
|
|
872
|
+
controlPlaneMemoryBytes: process.memoryUsage().rss,
|
|
873
|
+
reserveMemoryBytes: preflight.hostReserveBytes,
|
|
874
|
+
committedMemoryBytes: ambientMemoryCommitmentBytes + used.memoryBytes,
|
|
875
|
+
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
876
|
+
}) : null;
|
|
227
877
|
return {
|
|
228
|
-
schemaVersion:
|
|
878
|
+
schemaVersion: 3,
|
|
229
879
|
activeSessionCount: this.activeSessions.size,
|
|
230
880
|
cliProviders: this.config.cliProviders,
|
|
231
881
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -233,32 +883,176 @@ export class ForgeBridgeService {
|
|
|
233
883
|
repoMappings: repoMappingsFor(this.config),
|
|
234
884
|
os: this.config.os,
|
|
235
885
|
sandboxProfiles: this.config.sandboxProfiles,
|
|
886
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
887
|
+
trustDomainId: this.config.trustDomainId,
|
|
888
|
+
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
889
|
+
reservedSandboxCount: reserved,
|
|
890
|
+
activeSandboxCount: runtimeState.active,
|
|
891
|
+
startingSandboxCount: runtimeState.starting,
|
|
892
|
+
degradedReservationCount: runtimeState.degraded,
|
|
893
|
+
sandboxRuntimes: preflight?.healthy ? ["docker"] : [],
|
|
894
|
+
sandboxRuntimeVersion: preflight?.runtimeVersion ?? null,
|
|
895
|
+
sandboxFeatures: preflight?.features ?? null,
|
|
896
|
+
allowsOpenPublicSandbox: this.config.allowOpenPublicSandbox,
|
|
897
|
+
sandboxPublicationModes: [this.config.sandboxPublicationMode ?? "shared_filesystem"],
|
|
898
|
+
sandboxAuthModes: sandboxAuthModesFor(this.config),
|
|
899
|
+
availableMemoryBytes: memoryAdmission?.availableForAdmissionBytes ?? null,
|
|
900
|
+
availableCpuMillis: preflight ? Math.max(0, capacity.cpuMillis - used.cpuMillis) : null,
|
|
901
|
+
availableWorkspaceBytes: preflight ? Math.max(0, capacity.workspaceBytes - used.workspaceBytes) : null,
|
|
902
|
+
diskLow: preflight?.diskLow ?? null,
|
|
903
|
+
preflightGeneration: preflight?.generation ?? 0,
|
|
904
|
+
sandboxUnavailableCode: this.config.dockerEnabled ? preflight?.unavailableCode ?? null : "docker_disabled",
|
|
905
|
+
sandboxUnavailableReason: this.config.dockerEnabled ? preflight?.unavailableReason ?? null : "Docker sandboxing is disabled by runner configuration.",
|
|
906
|
+
sandboxMemoryCapacity: preflight ? {
|
|
907
|
+
defaultWorkerMemoryLimitBytes: this.config.defaultSandboxWorkerMemoryLimitBytes,
|
|
908
|
+
defaultServiceMemoryLimitBytes: this.config.defaultSandboxServiceMemoryLimitBytes,
|
|
909
|
+
runtimeOverheadBytes: this.config.sandboxRuntimeOverheadBytes,
|
|
910
|
+
hostReserveBytes: preflight.hostReserveBytes,
|
|
911
|
+
activeReservationBytes: used.memoryBytes,
|
|
912
|
+
daemonTotalBytes: preflight.totalMemoryBytes,
|
|
913
|
+
daemonAvailableBytes: preflight.rawDaemonAvailableMemoryBytes ?? 0,
|
|
914
|
+
hostAvailableBytes: preflight.rawHostAvailableMemoryBytes,
|
|
915
|
+
conservativeAvailableBytes: preflight.rawAvailableMemoryBytes,
|
|
916
|
+
availableForAdmissionBytes: memoryAdmission.availableForAdmissionBytes,
|
|
917
|
+
memoryAdmission: memoryAdmission,
|
|
918
|
+
} : null,
|
|
919
|
+
hostRuntime: this.sessions.runtimeCapacity?.() ?? null,
|
|
236
920
|
supportsApiSecretGrant: this.config.supportsApiSecretGrant,
|
|
237
921
|
supportsManagedWorktrees: this.config.supportsManagedWorktrees,
|
|
238
922
|
supportsManagedForgeArtifacts: this.config.supportsManagedForgeArtifacts,
|
|
239
923
|
supportsRunnerAuthoredPhaseArtifacts: this.config.supportsRunnerAuthoredPhaseArtifacts,
|
|
240
|
-
supportsDraftRunOnce: this.config.supportsDraftRunOnce
|
|
924
|
+
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
925
|
+
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
926
|
+
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
usedSandboxResources(degradedReservations) {
|
|
930
|
+
const resources = [
|
|
931
|
+
...[...this.reservations.values()]
|
|
932
|
+
.filter(reservation => reservation.sandboxed)
|
|
933
|
+
.map(reservation => reservation.resources),
|
|
934
|
+
...[...this.activeSessions.values()]
|
|
935
|
+
.filter(session => session.sandboxed)
|
|
936
|
+
.map(session => session.resources),
|
|
937
|
+
...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
|
|
938
|
+
];
|
|
939
|
+
return sumSandboxResources(resources);
|
|
940
|
+
}
|
|
941
|
+
activeSandboxResources(degradedReservations) {
|
|
942
|
+
return sumSandboxResources([
|
|
943
|
+
...[...this.activeSessions.values()]
|
|
944
|
+
.filter(session => session.sandboxed)
|
|
945
|
+
.map(session => session.resources),
|
|
946
|
+
...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
|
|
947
|
+
]);
|
|
948
|
+
}
|
|
949
|
+
sandboxResourceCapacity(preflight, activeResources, usedResources) {
|
|
950
|
+
if (!preflight)
|
|
951
|
+
return zeroSandboxResources();
|
|
952
|
+
if (usedResources.memoryBytes === 0 || this.sandboxAmbientMemoryCommitmentBytes === null) {
|
|
953
|
+
// Freeze non-Forge daemon use while reservations exist. If the bridge
|
|
954
|
+
// reconnects with managed containers already present, the initial value
|
|
955
|
+
// is deliberately conservative until their ledger drains.
|
|
956
|
+
this.sandboxAmbientMemoryCommitmentBytes = Math.max(0, preflight.totalMemoryBytes - preflight.rawAvailableMemoryBytes);
|
|
957
|
+
}
|
|
958
|
+
return {
|
|
959
|
+
// Host free memory and disk already reflect active containers. Add their
|
|
960
|
+
// commitments back to form a stable total capacity, then subtract them
|
|
961
|
+
// exactly once in usedSandboxResources.
|
|
962
|
+
sandboxSlots: Math.min(this.config.maxConcurrentSandboxes, preflight.maxConcurrentSandboxes + activeResources.sandboxSlots),
|
|
963
|
+
cpuMillis: preflight.availableCpuMillis,
|
|
964
|
+
workerMemoryLimitBytes: 0,
|
|
965
|
+
serviceMemoryLimitBytes: 0,
|
|
966
|
+
runtimeOverheadBytes: 0,
|
|
967
|
+
memoryBytes: sandboxMemoryCommitmentCapacity(preflight, activeResources.memoryBytes, this.sandboxAmbientMemoryCommitmentBytes),
|
|
968
|
+
workspaceBytes: Math.max(0, preflight.availableWorkspaceBytes
|
|
969
|
+
- this.config.minimumWorkspaceBytes
|
|
970
|
+
+ activeResources.workspaceBytes),
|
|
971
|
+
pids: this.config.sandboxPidCapacity,
|
|
972
|
+
buildSlots: this.config.maxConcurrentSandboxBuilds
|
|
241
973
|
};
|
|
242
974
|
}
|
|
243
975
|
async invokeAck(methodName, payload) {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
976
|
+
let storageRecoveryAttempt = 0;
|
|
977
|
+
while (true) {
|
|
978
|
+
const connection = this.connection;
|
|
979
|
+
if (!connection) {
|
|
980
|
+
throw new Error("Bridge is not connected.");
|
|
981
|
+
}
|
|
982
|
+
await this.waitForTransportRecovery(connection, this.transportRecovery);
|
|
983
|
+
const recoveryGeneration = this.transportRecoveryGeneration;
|
|
984
|
+
try {
|
|
985
|
+
const ack = await connection.invoke(methodName, payload);
|
|
986
|
+
if (!ack.accepted) {
|
|
987
|
+
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? `${methodName} callback was rejected.`);
|
|
988
|
+
}
|
|
989
|
+
return ack;
|
|
990
|
+
}
|
|
991
|
+
catch (error) {
|
|
992
|
+
if (connection !== this.connection || this.stopped)
|
|
993
|
+
throw error;
|
|
994
|
+
const recovery = this.transportRecovery;
|
|
995
|
+
if (recovery && recovery.generation > recoveryGeneration) {
|
|
996
|
+
await this.waitForTransportRecovery(connection, recovery);
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (isProviderStorageUnavailable(error) && storageRecoveryAttempt < this.config.reconnectBackoffMs.length) {
|
|
1000
|
+
const backoff = this.config.reconnectBackoffMs[storageRecoveryAttempt] ?? 5000;
|
|
1001
|
+
storageRecoveryAttempt += 1;
|
|
1002
|
+
logBridgeStatus(`${methodName} reached Forge while storage was recovering. Retrying callback ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
|
|
1003
|
+
await delay(backoff);
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
throw error;
|
|
1007
|
+
}
|
|
247
1008
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
1009
|
+
}
|
|
1010
|
+
beginTransportRecovery() {
|
|
1011
|
+
if (this.transportRecovery && !this.transportRecovery.completed)
|
|
1012
|
+
return;
|
|
1013
|
+
let resolve = () => undefined;
|
|
1014
|
+
const promise = new Promise((complete) => { resolve = complete; });
|
|
1015
|
+
this.transportRecoveryGeneration += 1;
|
|
1016
|
+
this.transportRecovery = {
|
|
1017
|
+
generation: this.transportRecoveryGeneration,
|
|
1018
|
+
promise,
|
|
1019
|
+
resolve,
|
|
1020
|
+
completed: false,
|
|
1021
|
+
error: null,
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
completeTransportRecovery(error = null) {
|
|
1025
|
+
const recovery = this.transportRecovery;
|
|
1026
|
+
if (!recovery || recovery.completed)
|
|
1027
|
+
return;
|
|
1028
|
+
recovery.completed = true;
|
|
1029
|
+
recovery.error = error;
|
|
1030
|
+
recovery.resolve();
|
|
1031
|
+
}
|
|
1032
|
+
async waitForTransportRecovery(connection, recovery) {
|
|
1033
|
+
if (!recovery)
|
|
1034
|
+
return;
|
|
1035
|
+
if (recovery.completed) {
|
|
1036
|
+
if (recovery.error)
|
|
1037
|
+
throw recovery.error;
|
|
1038
|
+
return;
|
|
251
1039
|
}
|
|
252
|
-
|
|
1040
|
+
await recovery.promise;
|
|
1041
|
+
if (connection !== this.connection)
|
|
1042
|
+
throw new Error("Bridge connection changed while recovering.");
|
|
1043
|
+
if (recovery.error)
|
|
1044
|
+
throw recovery.error;
|
|
253
1045
|
}
|
|
254
1046
|
async waitForClose(signal) {
|
|
255
1047
|
if (!this.closed) {
|
|
256
1048
|
return;
|
|
257
1049
|
}
|
|
258
|
-
await
|
|
1050
|
+
await waitForPromiseOrAbort(this.closed, signal);
|
|
259
1051
|
}
|
|
260
1052
|
async stopConnection() {
|
|
261
1053
|
this.stopHeartbeat();
|
|
1054
|
+
this.stopLeaseWatchdog();
|
|
1055
|
+
this.stopSandboxMaintenance();
|
|
262
1056
|
if (this.connection) {
|
|
263
1057
|
await this.connection.stop().catch(() => undefined);
|
|
264
1058
|
this.connection = null;
|
|
@@ -279,6 +1073,17 @@ function isDispatchNoLongerPending(error) {
|
|
|
279
1073
|
}
|
|
280
1074
|
return error instanceof Error && error.message === "Dispatch is no longer pending.";
|
|
281
1075
|
}
|
|
1076
|
+
function isProviderStorageUnavailable(error) {
|
|
1077
|
+
const message = errorMessage(error).toLowerCase();
|
|
1078
|
+
return message.includes("provider_storage_unavailable")
|
|
1079
|
+
|| (message.includes("storage is recovering") && message.includes("503"));
|
|
1080
|
+
}
|
|
1081
|
+
function createDefaultSessionService(sandboxStateRoot) {
|
|
1082
|
+
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1083
|
+
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1084
|
+
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1085
|
+
return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner)), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner));
|
|
1086
|
+
}
|
|
282
1087
|
export class SignalRBridgeConnectionFactory {
|
|
283
1088
|
create(config) {
|
|
284
1089
|
return new SignalRBridgeConnection(config);
|
|
@@ -301,8 +1106,12 @@ export class SignalRBridgeConnection {
|
|
|
301
1106
|
Authorization: `Bearer ${config.deviceToken}`
|
|
302
1107
|
}
|
|
303
1108
|
})
|
|
1109
|
+
.withAutomaticReconnect([...config.reconnectBackoffMs])
|
|
304
1110
|
.configureLogging(LogLevel.Warning)
|
|
305
1111
|
.build();
|
|
1112
|
+
this.connection.on("Superseded", () => {
|
|
1113
|
+
void this.connection.stop().catch(() => undefined);
|
|
1114
|
+
});
|
|
306
1115
|
}
|
|
307
1116
|
start() {
|
|
308
1117
|
return this.connection.start();
|
|
@@ -313,16 +1122,49 @@ export class SignalRBridgeConnection {
|
|
|
313
1122
|
onClose(handler) {
|
|
314
1123
|
this.connection.onclose(handler);
|
|
315
1124
|
}
|
|
1125
|
+
onReconnecting(handler) {
|
|
1126
|
+
this.connection.onreconnecting(handler);
|
|
1127
|
+
}
|
|
1128
|
+
onReconnected(handler) {
|
|
1129
|
+
this.connection.onreconnected((connectionId) => {
|
|
1130
|
+
void Promise.resolve(handler(connectionId)).catch(() => undefined);
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
316
1133
|
onDispatch(handler) {
|
|
317
1134
|
this.connection.on("Dispatch", (raw) => {
|
|
318
1135
|
void handler(raw).catch(() => undefined);
|
|
319
1136
|
});
|
|
320
1137
|
}
|
|
1138
|
+
onOffer(handler) {
|
|
1139
|
+
this.connection.on("Offer", (raw) => {
|
|
1140
|
+
void handler(raw).catch(() => undefined);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
onStart(handler) {
|
|
1144
|
+
this.connection.on("Start", (raw) => {
|
|
1145
|
+
void handler(raw).catch(() => undefined);
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
onLeaseUpdate(handler) {
|
|
1149
|
+
this.connection.on("LeaseUpdate", (request) => {
|
|
1150
|
+
void handler(request).catch(() => undefined);
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
321
1153
|
onCancel(handler) {
|
|
322
1154
|
this.connection.on("Cancel", (request) => {
|
|
323
1155
|
void handler(request).catch(() => undefined);
|
|
324
1156
|
});
|
|
325
1157
|
}
|
|
1158
|
+
onReap(handler) {
|
|
1159
|
+
this.connection.on("Reap", (request) => {
|
|
1160
|
+
void handler(request).catch(() => undefined);
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
onReadinessProbe(handler) {
|
|
1164
|
+
this.connection.on("ReadinessProbe", (request) => {
|
|
1165
|
+
void handler(request).catch(() => undefined);
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
326
1168
|
invoke(methodName, payload) {
|
|
327
1169
|
return this.connection.invoke(methodName, payload);
|
|
328
1170
|
}
|
|
@@ -330,9 +1172,37 @@ export class SignalRBridgeConnection {
|
|
|
330
1172
|
export function defaultBridgeServiceConfig(overrides = {}) {
|
|
331
1173
|
const defaults = defaultForgeBridgeConfig();
|
|
332
1174
|
const cliProviders = splitCsv(process.env.FORGE_CLI_PROVIDERS ?? "codex");
|
|
1175
|
+
const configuredSandboxHostMemoryReserveBytes = optionalPositiveFiniteNumber(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES);
|
|
1176
|
+
const sandboxPublicationMode = process.env.FORGE_SANDBOX_PUBLICATION_MODE === "bridge_push" ? "bridge_push" : "shared_filesystem";
|
|
333
1177
|
const config = {
|
|
334
1178
|
serverUrl: process.env.FORGE_URL ?? "http://localhost:5208",
|
|
335
1179
|
runnerId: process.env.FORGE_RUNNER_ID ?? "",
|
|
1180
|
+
runnerInstanceId: process.env.FORGE_RUNNER_INSTANCE_ID ?? randomUUID(),
|
|
1181
|
+
trustDomainId: process.env.FORGE_TRUST_DOMAIN_ID ?? "default",
|
|
1182
|
+
maxConcurrentSandboxes: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOXES ?? 3), 3),
|
|
1183
|
+
maxConcurrentSandboxBuilds: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOX_BUILDS ?? 1), 1),
|
|
1184
|
+
sandboxPidCapacity: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_PID_CAPACITY ?? 2048), 2048),
|
|
1185
|
+
dockerEnabled: process.env.FORGE_DOCKER_SANDBOX !== "false",
|
|
1186
|
+
allowOpenPublicSandbox: process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX === "true",
|
|
1187
|
+
sandboxPublicationMode,
|
|
1188
|
+
dockerExecutable: process.env.FORGE_DOCKER_EXECUTABLE ?? "docker",
|
|
1189
|
+
dockerContext: process.env.FORGE_DOCKER_CONTEXT ?? "",
|
|
1190
|
+
sandboxStateRoot: process.env.FORGE_SANDBOX_STATE_ROOT ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes"),
|
|
1191
|
+
requireRootlessDocker: process.env.FORGE_REQUIRE_ROOTLESS_DOCKER === "true" || process.platform === "linux",
|
|
1192
|
+
diskHighWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_HIGH_WATERMARK_PERCENT ?? 85), 85),
|
|
1193
|
+
diskLowWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_LOW_WATERMARK_PERCENT ?? 75), 75),
|
|
1194
|
+
minimumWorkspaceBytes: positiveFiniteNumber(Number(process.env.FORGE_MINIMUM_WORKSPACE_BYTES ?? 10 * 1024 ** 3), 10 * 1024 ** 3),
|
|
1195
|
+
// Undefined means preflight derives the bounded reserve from the actual
|
|
1196
|
+
// Docker/host capacity domain after sampling it.
|
|
1197
|
+
sandboxHostMemoryReserveBytes: configuredSandboxHostMemoryReserveBytes,
|
|
1198
|
+
defaultSandboxWorkerMemoryLimitBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_WORKER_MEMORY_LIMIT_BYTES ?? 2 * 1024 ** 3), 2 * 1024 ** 3),
|
|
1199
|
+
defaultSandboxServiceMemoryLimitBytes: nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_SERVICE_MEMORY_LIMIT_BYTES ?? 0), 0),
|
|
1200
|
+
sandboxRuntimeOverheadBytes: Math.max(128 * 1024 ** 2, nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_RUNTIME_OVERHEAD_BYTES ?? 128 * 1024 ** 2), 128 * 1024 ** 2)),
|
|
1201
|
+
sandboxMemorySampleIntervalMs: Math.min(30_000, Math.max(250, positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_MEMORY_SAMPLE_INTERVAL_MS ?? 1000), 1000))),
|
|
1202
|
+
imageRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_COUNT ?? 3), 3),
|
|
1203
|
+
imageRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_TTL_MS ?? 7 * 24 * 60 * 60 * 1000), 7 * 24 * 60 * 60 * 1000),
|
|
1204
|
+
auditRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_COUNT ?? 200), 200),
|
|
1205
|
+
auditRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_TTL_MS ?? 30 * 24 * 60 * 60 * 1000), 30 * 24 * 60 * 60 * 1000),
|
|
336
1206
|
deviceToken: process.env.FORGE_DEVICE_TOKEN ?? "",
|
|
337
1207
|
deviceName: process.env.FORGE_DEVICE_NAME ?? "",
|
|
338
1208
|
defaultRepoRoot: process.env.FORGE_REPO_ROOT ?? defaults.defaultRepoRoot,
|
|
@@ -348,8 +1218,10 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
348
1218
|
supportsManagedForgeArtifacts: true,
|
|
349
1219
|
supportsRunnerAuthoredPhaseArtifacts: true,
|
|
350
1220
|
supportsDraftRunOnce: true,
|
|
1221
|
+
supportsDraftAttachments: true,
|
|
1222
|
+
supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
|
|
351
1223
|
version: process.env.FORGE_BRIDGE_VERSION ?? forgeBridgeVersion,
|
|
352
|
-
protocolVersion:
|
|
1224
|
+
protocolVersion: 2,
|
|
353
1225
|
minServerVersion: null,
|
|
354
1226
|
heartbeatIntervalMs: positiveFiniteNumber(Number(process.env.FORGE_HEARTBEAT_INTERVAL_MS ?? 30_000), 30_000),
|
|
355
1227
|
reconnectBackoffMs: [1000, 2000, 5000, 10000, 30000],
|
|
@@ -357,7 +1229,9 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
357
1229
|
};
|
|
358
1230
|
return {
|
|
359
1231
|
...config,
|
|
1232
|
+
providerStatuses: overrides.providerStatuses ?? providerStatusesFor(config.cliProviders),
|
|
360
1233
|
sandboxProfiles: config.sandboxProfiles ?? defaultSandboxProfiles(config.cliProviders),
|
|
1234
|
+
supportsDraftImageAttachments: (overrides.supportsDraftImageAttachments ?? true) && supportsDraftImageAttachmentsFor(config.cliProviders),
|
|
361
1235
|
heartbeatIntervalMs: positiveFiniteNumber(config.heartbeatIntervalMs, 30_000)
|
|
362
1236
|
};
|
|
363
1237
|
}
|
|
@@ -373,9 +1247,42 @@ function normalizeServerUrl(serverUrl) {
|
|
|
373
1247
|
function positiveFiniteNumber(value, fallback) {
|
|
374
1248
|
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
375
1249
|
}
|
|
1250
|
+
function optionalPositiveFiniteNumber(value) {
|
|
1251
|
+
if (value === undefined || value.trim().length === 0)
|
|
1252
|
+
return undefined;
|
|
1253
|
+
const parsed = Number(value);
|
|
1254
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
|
1255
|
+
}
|
|
1256
|
+
function nonNegativeFiniteNumber(value, fallback) {
|
|
1257
|
+
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
1258
|
+
}
|
|
376
1259
|
function providerStatusesFor(providers) {
|
|
377
1260
|
return Object.fromEntries(providers.map((provider) => [provider, { signedIn: true, version: "", models: configuredModelsFor(provider) }]));
|
|
378
1261
|
}
|
|
1262
|
+
function sandboxAuthModesFor(config) {
|
|
1263
|
+
return Object.fromEntries(config.cliProviders.map((provider) => {
|
|
1264
|
+
const modes = ["api_key"];
|
|
1265
|
+
if (sandboxBridgeCliAuthAvailable(config, provider)) {
|
|
1266
|
+
modes.push("bridge_cli");
|
|
1267
|
+
}
|
|
1268
|
+
return [provider, modes];
|
|
1269
|
+
}));
|
|
1270
|
+
}
|
|
1271
|
+
function sandboxBridgeCliAuthAvailable(config, provider) {
|
|
1272
|
+
if (provider.trim().toLowerCase() !== "codex") {
|
|
1273
|
+
return false;
|
|
1274
|
+
}
|
|
1275
|
+
const status = providerStatus(config, provider);
|
|
1276
|
+
if (status?.signedIn === false) {
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
return codexSandboxProviderAuthAdapter.doctor().available;
|
|
1280
|
+
}
|
|
1281
|
+
function providerStatus(config, provider) {
|
|
1282
|
+
const normalized = provider.trim().toLowerCase();
|
|
1283
|
+
return Object.entries(config.providerStatuses)
|
|
1284
|
+
.find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
|
|
1285
|
+
}
|
|
379
1286
|
function defaultSandboxProfiles(providers, platform = process.platform) {
|
|
380
1287
|
if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
|
|
381
1288
|
return ["none"];
|
|
@@ -470,10 +1377,11 @@ function normalizeQaAppLaunchTarget(target) {
|
|
|
470
1377
|
command: cleanString(target.command),
|
|
471
1378
|
working_directory: cleanString(target.working_directory),
|
|
472
1379
|
ready_url: cleanString(target.ready_url),
|
|
1380
|
+
managed_runtime_port: cleanString(target.managed_runtime_port),
|
|
473
1381
|
routes,
|
|
474
1382
|
notes: cleanString(target.notes)
|
|
475
1383
|
};
|
|
476
|
-
return normalized.url || normalized.command || normalized.ready_url ||
|
|
1384
|
+
return normalized.url || normalized.command || normalized.ready_url || normalized.managed_runtime_port
|
|
477
1385
|
? normalized
|
|
478
1386
|
: null;
|
|
479
1387
|
}
|
|
@@ -518,30 +1426,329 @@ function formatDelay(ms) {
|
|
|
518
1426
|
function logBridgeStatus(message) {
|
|
519
1427
|
process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
|
|
520
1428
|
}
|
|
521
|
-
function delay(ms, signal) {
|
|
1429
|
+
export function delay(ms, signal) {
|
|
522
1430
|
if (signal?.aborted) {
|
|
523
1431
|
return Promise.resolve();
|
|
524
1432
|
}
|
|
525
1433
|
return new Promise((resolve) => {
|
|
526
|
-
const
|
|
527
|
-
signal?.addEventListener("abort", () => {
|
|
1434
|
+
const complete = () => {
|
|
528
1435
|
clearTimeout(timeout);
|
|
1436
|
+
signal?.removeEventListener("abort", complete);
|
|
529
1437
|
resolve();
|
|
530
|
-
}
|
|
1438
|
+
};
|
|
1439
|
+
const timeout = setTimeout(complete, ms);
|
|
1440
|
+
signal?.addEventListener("abort", complete, { once: true });
|
|
1441
|
+
if (signal?.aborted)
|
|
1442
|
+
complete();
|
|
531
1443
|
});
|
|
532
1444
|
}
|
|
533
|
-
function
|
|
1445
|
+
export async function waitForPromiseOrAbort(promise, signal) {
|
|
534
1446
|
if (!signal) {
|
|
535
|
-
|
|
1447
|
+
await promise;
|
|
1448
|
+
return;
|
|
536
1449
|
}
|
|
537
1450
|
if (signal.aborted) {
|
|
538
|
-
return
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
let resolveAbort;
|
|
1454
|
+
const abort = new Promise(resolve => { resolveAbort = resolve; });
|
|
1455
|
+
signal.addEventListener("abort", resolveAbort, { once: true });
|
|
1456
|
+
try {
|
|
1457
|
+
await Promise.race([promise, abort]);
|
|
1458
|
+
}
|
|
1459
|
+
finally {
|
|
1460
|
+
signal.removeEventListener("abort", resolveAbort);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
export function canReapManagedSandboxes(preflight) {
|
|
1464
|
+
return canRunDockerMaintenance(preflight);
|
|
1465
|
+
}
|
|
1466
|
+
function sandboxNetworkPolicyFailure(dispatch, config) {
|
|
1467
|
+
const sandbox = dispatch.sandbox;
|
|
1468
|
+
if (!sandbox)
|
|
1469
|
+
return "Protocol-v2 sandbox context is missing.";
|
|
1470
|
+
if (sandbox.networkPolicy.mode === "open_public"
|
|
1471
|
+
&& (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
|
|
1472
|
+
return "open_public sandbox networking is not permitted by this runner policy.";
|
|
1473
|
+
}
|
|
1474
|
+
if (sandbox.networkPolicy.mode === "public_allowlist"
|
|
1475
|
+
&& sandbox.networkPolicy.allowedHosts.length > 0
|
|
1476
|
+
&& process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
|
|
1477
|
+
return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
|
|
1478
|
+
}
|
|
1479
|
+
return null;
|
|
1480
|
+
}
|
|
1481
|
+
export function infrastructureFailureEventType(summary) {
|
|
1482
|
+
const sandboxFailure = /^(sandbox_[a-z0-9_.-]+|image_[a-z0-9_.-]+|contract_[a-z0-9_.-]+|teardown_[a-z0-9_.-]+):/u.exec(summary)?.[1];
|
|
1483
|
+
if (sandboxFailure)
|
|
1484
|
+
return sandboxFailure;
|
|
1485
|
+
if (summary.startsWith("worktree_prepare_failed:"))
|
|
1486
|
+
return "worktree_prepare_failed";
|
|
1487
|
+
if (summary.startsWith("provider_network_unavailable:"))
|
|
1488
|
+
return "provider_network_unavailable";
|
|
1489
|
+
if (summary.startsWith("provider_start_unavailable:"))
|
|
1490
|
+
return "provider_start_unavailable";
|
|
1491
|
+
if (summary.startsWith("host_port_collision:"))
|
|
1492
|
+
return "host_port_collision";
|
|
1493
|
+
if (summary.startsWith("host_runtime_process_exited:"))
|
|
1494
|
+
return "host_runtime_process_exited";
|
|
1495
|
+
if (summary.startsWith("host_runtime_listener_timeout:"))
|
|
1496
|
+
return "host_runtime_listener_timeout";
|
|
1497
|
+
if (summary.startsWith("host_runtime_http_readiness_timeout:"))
|
|
1498
|
+
return "host_runtime_http_readiness_timeout";
|
|
1499
|
+
if (summary.startsWith("attempt_process_supervisor_start_failed:"))
|
|
1500
|
+
return "attempt_process_supervisor_start_failed";
|
|
1501
|
+
if (summary.startsWith("attempt_process_supervisor_start_timeout:"))
|
|
1502
|
+
return "attempt_process_supervisor_start_timeout";
|
|
1503
|
+
return null;
|
|
1504
|
+
}
|
|
1505
|
+
function parseReadinessProbe(value) {
|
|
1506
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1507
|
+
return null;
|
|
1508
|
+
const request = value;
|
|
1509
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
|
|
1510
|
+
const bounded = (candidate, maximum) => typeof candidate === "string" && candidate.trim().length > 0 && candidate.length <= maximum;
|
|
1511
|
+
if (request.schemaVersion !== 1
|
|
1512
|
+
|| !uuid.test(request.requestId ?? "")
|
|
1513
|
+
|| !uuid.test(request.fencingToken ?? "")
|
|
1514
|
+
|| !uuid.test(request.userId ?? "")
|
|
1515
|
+
|| !uuid.test(request.projectId ?? "")
|
|
1516
|
+
|| !uuid.test(request.repoId ?? "")
|
|
1517
|
+
|| !uuid.test(request.runnerInstanceId ?? "")
|
|
1518
|
+
|| !Number.isInteger(request.attempt) || (request.attempt ?? 0) < 1
|
|
1519
|
+
|| !bounded(request.repoName, 160)
|
|
1520
|
+
|| typeof request.remoteUrl !== "string" || request.remoteUrl.length > 2048
|
|
1521
|
+
|| !bounded(request.defaultBranch, 512)
|
|
1522
|
+
|| typeof request.cloneOnDemand !== "boolean"
|
|
1523
|
+
|| !bounded(request.runnerRepoLocalPath, 4096)
|
|
1524
|
+
|| !bounded(request.revision, 512)
|
|
1525
|
+
|| !Number.isFinite(Date.parse(request.expiresAt ?? ""))
|
|
1526
|
+
|| Date.parse(request.expiresAt ?? "") <= Date.now()) {
|
|
1527
|
+
return null;
|
|
1528
|
+
}
|
|
1529
|
+
return request;
|
|
1530
|
+
}
|
|
1531
|
+
function sandboxProviderNetworkFailure(dispatch, config) {
|
|
1532
|
+
const sandbox = dispatch.sandbox;
|
|
1533
|
+
if (!sandbox || sandbox.networkPolicy.mode !== "offline")
|
|
1534
|
+
return null;
|
|
1535
|
+
const provider = dispatch.execution.provider.trim().toLowerCase();
|
|
1536
|
+
const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
|
|
1537
|
+
if (!isNetworkProvider)
|
|
1538
|
+
return null;
|
|
1539
|
+
return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
|
|
1540
|
+
}
|
|
1541
|
+
function sandboxAuthFailure(dispatch, config) {
|
|
1542
|
+
const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
|
|
1543
|
+
if (unsupported) {
|
|
1544
|
+
return unsupported;
|
|
1545
|
+
}
|
|
1546
|
+
if (dispatch.execution.authKind.trim().toLowerCase() !== "bridge_cli") {
|
|
1547
|
+
return null;
|
|
1548
|
+
}
|
|
1549
|
+
const status = providerStatus(config, dispatch.execution.provider);
|
|
1550
|
+
if (status?.signedIn === false) {
|
|
1551
|
+
return `${dispatch.execution.provider} Local CLI is not signed in on this runner.`;
|
|
1552
|
+
}
|
|
1553
|
+
const adapter = sandboxProviderAuthAdapterFor(dispatch.execution.provider, dispatch.execution.authKind);
|
|
1554
|
+
if (!adapter) {
|
|
1555
|
+
return `${dispatch.execution.provider} Local CLI auth is not portable into Docker yet.`;
|
|
1556
|
+
}
|
|
1557
|
+
const doctor = adapter.doctor();
|
|
1558
|
+
return doctor.available ? null : doctor.message;
|
|
1559
|
+
}
|
|
1560
|
+
function rejectedOfferReservation(code, message) {
|
|
1561
|
+
return {
|
|
1562
|
+
accepted: false,
|
|
1563
|
+
code,
|
|
1564
|
+
message,
|
|
1565
|
+
reservedUntil: null,
|
|
1566
|
+
resources: null,
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
export function canReserveSandboxResources(used, requested, capacity) {
|
|
1570
|
+
return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
|
|
1571
|
+
&& used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
|
|
1572
|
+
&& used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
|
|
1573
|
+
&& used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
|
|
1574
|
+
&& used.pids + requested.pids <= capacity.pids
|
|
1575
|
+
&& used.buildSlots + requested.buildSlots <= capacity.buildSlots;
|
|
1576
|
+
}
|
|
1577
|
+
export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes, ambientMemoryCommitmentBytes = 0) {
|
|
1578
|
+
const ambientCapacity = preflight.availableMemoryBytes
|
|
1579
|
+
- preflight.hostReserveBytes
|
|
1580
|
+
+ activeMemoryBytes;
|
|
1581
|
+
const commitmentCapacity = preflight.totalMemoryBytes
|
|
1582
|
+
- preflight.hostReserveBytes
|
|
1583
|
+
- Math.max(0, ambientMemoryCommitmentBytes);
|
|
1584
|
+
return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
|
|
1585
|
+
}
|
|
1586
|
+
export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
|
|
1587
|
+
const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
|
|
1588
|
+
if (requested.sandboxSlots > availableSlots) {
|
|
1589
|
+
return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
|
|
1590
|
+
}
|
|
1591
|
+
const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
|
|
1592
|
+
if (requested.memoryBytes > availableMemoryBytes) {
|
|
1593
|
+
return [
|
|
1594
|
+
`Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
|
|
1595
|
+
`(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
|
|
1596
|
+
`but ${formatBytes(availableMemoryBytes)} is available for admission.`,
|
|
1597
|
+
`Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
|
|
1598
|
+
`Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
|
|
1599
|
+
].join(" ");
|
|
1600
|
+
}
|
|
1601
|
+
const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
|
|
1602
|
+
if (requested.cpuMillis > availableCpuMillis) {
|
|
1603
|
+
return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
|
|
1604
|
+
}
|
|
1605
|
+
const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
|
|
1606
|
+
if (requested.workspaceBytes > availableWorkspaceBytes) {
|
|
1607
|
+
return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
|
|
1608
|
+
}
|
|
1609
|
+
const availablePids = Math.max(0, capacity.pids - used.pids);
|
|
1610
|
+
if (requested.pids > availablePids) {
|
|
1611
|
+
return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
|
|
539
1612
|
}
|
|
540
|
-
|
|
1613
|
+
const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
|
|
1614
|
+
return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
|
|
1615
|
+
}
|
|
1616
|
+
function sumSandboxResources(resources) {
|
|
1617
|
+
return resources.reduce((total, resource) => ({
|
|
1618
|
+
sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
|
|
1619
|
+
cpuMillis: total.cpuMillis + resource.cpuMillis,
|
|
1620
|
+
workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
|
|
1621
|
+
serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
|
|
1622
|
+
runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
|
|
1623
|
+
memoryBytes: total.memoryBytes + resource.memoryBytes,
|
|
1624
|
+
workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
|
|
1625
|
+
pids: total.pids + resource.pids,
|
|
1626
|
+
buildSlots: total.buildSlots + resource.buildSlots
|
|
1627
|
+
}), zeroSandboxResources());
|
|
1628
|
+
}
|
|
1629
|
+
function zeroSandboxResources() {
|
|
1630
|
+
return {
|
|
1631
|
+
sandboxSlots: 0,
|
|
1632
|
+
cpuMillis: 0,
|
|
1633
|
+
workerMemoryLimitBytes: 0,
|
|
1634
|
+
serviceMemoryLimitBytes: 0,
|
|
1635
|
+
runtimeOverheadBytes: 0,
|
|
1636
|
+
memoryBytes: 0,
|
|
1637
|
+
workspaceBytes: 0,
|
|
1638
|
+
pids: 0,
|
|
1639
|
+
buildSlots: 0,
|
|
1640
|
+
};
|
|
541
1641
|
}
|
|
1642
|
+
function defaultSandboxResources() {
|
|
1643
|
+
return {
|
|
1644
|
+
sandboxSlots: 1,
|
|
1645
|
+
cpuMillis: 2000,
|
|
1646
|
+
workerMemoryLimitBytes: 2 * 1024 ** 3,
|
|
1647
|
+
serviceMemoryLimitBytes: 0,
|
|
1648
|
+
runtimeOverheadBytes: 128 * 1024 ** 2,
|
|
1649
|
+
memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
|
|
1650
|
+
workspaceBytes: 10 * 1024 ** 3,
|
|
1651
|
+
pids: 512,
|
|
1652
|
+
buildSlots: 0
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
1656
|
+
const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
|
|
1657
|
+
const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
|
|
1658
|
+
+ (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
|
|
1659
|
+
return {
|
|
1660
|
+
...requested,
|
|
1661
|
+
serviceMemoryLimitBytes,
|
|
1662
|
+
runtimeOverheadBytes,
|
|
1663
|
+
memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
1667
|
+
const repoPath = dispatch.repo.serverLocalPath;
|
|
1668
|
+
const sandbox = dispatch.sandbox;
|
|
1669
|
+
if (!repoPath || !sandbox) {
|
|
1670
|
+
throw new Error("Sandbox admission needs a mapped repository.");
|
|
1671
|
+
}
|
|
1672
|
+
const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
|
|
1673
|
+
const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
|
|
1674
|
+
if (!configCommitSha) {
|
|
1675
|
+
throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
|
|
1676
|
+
}
|
|
1677
|
+
const contractResult = await runSandboxProcess({
|
|
1678
|
+
command: "git",
|
|
1679
|
+
args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
|
|
1680
|
+
timeoutMs: 30_000,
|
|
1681
|
+
maxOutputBytes: 1024 * 1024,
|
|
1682
|
+
});
|
|
1683
|
+
if (contractResult.exitCode !== 0) {
|
|
1684
|
+
throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
|
|
1685
|
+
}
|
|
1686
|
+
const contract = validateSandboxContract(contractResult.stdout);
|
|
1687
|
+
const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
|
|
1688
|
+
role: dispatch.execution.role,
|
|
1689
|
+
serviceCount: contract.contract.services.length,
|
|
1690
|
+
browser: contract.contract.browser,
|
|
1691
|
+
});
|
|
1692
|
+
return {
|
|
1693
|
+
resources: resolveDynamicSandboxResources({
|
|
1694
|
+
...sandbox.requestedResources,
|
|
1695
|
+
workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
|
|
1696
|
+
}, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
|
|
1697
|
+
sandboxConfigCommitSha: configCommitSha,
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
async function resolveFirstGitCommit(repoPath, refs) {
|
|
1701
|
+
for (const ref of refs) {
|
|
1702
|
+
const result = await runSandboxProcess({
|
|
1703
|
+
command: "git",
|
|
1704
|
+
args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
|
|
1705
|
+
timeoutMs: 30_000,
|
|
1706
|
+
maxOutputBytes: 1024 * 1024,
|
|
1707
|
+
});
|
|
1708
|
+
const commitSha = result.stdout.trim().toLowerCase();
|
|
1709
|
+
if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
|
|
1710
|
+
return commitSha;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
return null;
|
|
1714
|
+
}
|
|
1715
|
+
function parseOfferEnvelope(value) {
|
|
1716
|
+
return parseDispatchEnvelope(value);
|
|
1717
|
+
}
|
|
1718
|
+
function parseStartEnvelope(value) {
|
|
1719
|
+
return parseDispatchEnvelope(value);
|
|
1720
|
+
}
|
|
1721
|
+
function parseDispatchEnvelope(value) {
|
|
1722
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1723
|
+
return null;
|
|
1724
|
+
const envelope = value;
|
|
1725
|
+
if (envelope.schemaVersion !== 1
|
|
1726
|
+
|| typeof envelope.dispatchAttemptId !== "string"
|
|
1727
|
+
|| typeof envelope.leaseId !== "string"
|
|
1728
|
+
|| typeof envelope.fencingToken !== "string"
|
|
1729
|
+
|| typeof envelope.runnerInstanceId !== "string"
|
|
1730
|
+
|| typeof envelope.expiresAt !== "string"
|
|
1731
|
+
|| !envelope.dispatch)
|
|
1732
|
+
return null;
|
|
1733
|
+
return {
|
|
1734
|
+
dispatchAttemptId: envelope.dispatchAttemptId,
|
|
1735
|
+
leaseId: envelope.leaseId,
|
|
1736
|
+
fencingToken: envelope.fencingToken,
|
|
1737
|
+
runnerInstanceId: envelope.runnerInstanceId,
|
|
1738
|
+
expiresAt: envelope.expiresAt,
|
|
1739
|
+
dispatch: envelope.dispatch
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
const maxAttachmentExactSecretLength = 8 * 1024;
|
|
542
1743
|
function exactSecrets(dispatch, config) {
|
|
543
1744
|
return [
|
|
544
1745
|
dispatch.apiKeySecretGrant?.secret,
|
|
545
|
-
config.deviceToken
|
|
1746
|
+
config.deviceToken,
|
|
1747
|
+
...boundedAttachmentExactSecrets(dispatch)
|
|
546
1748
|
].filter((secret) => typeof secret === "string" && secret.length > 0);
|
|
547
1749
|
}
|
|
1750
|
+
function boundedAttachmentExactSecrets(dispatch) {
|
|
1751
|
+
return (dispatch.draft?.attachments ?? [])
|
|
1752
|
+
.flatMap((attachment) => [attachment.textContent, attachment.contentBase64])
|
|
1753
|
+
.filter((secret) => typeof secret === "string" && secret.length > 0 && secret.length <= maxAttachmentExactSecretLength);
|
|
1754
|
+
}
|