@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.028808a841c8
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 +165 -1
- package/dist/bridge/bridge-chat.types.d.ts +111 -0
- package/dist/bridge/bridge-chat.types.js +401 -0
- package/dist/bridge/bridge.base.d.ts +9 -1
- package/dist/bridge/bridge.service.d.ts +140 -3
- package/dist/bridge/bridge.service.js +2471 -68
- package/dist/bridge/bridge.types.d.ts +224 -2
- package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
- package/dist/bridge/dispatch-result-outbox.js +87 -0
- package/dist/bridge/dispatch-result-worker.d.ts +2 -0
- package/dist/bridge/dispatch-result-worker.js +122 -0
- package/dist/bridge/internals.d.ts +2 -0
- package/dist/bridge/internals.js +1 -0
- package/dist/bridge/readiness-result-outbox.d.ts +21 -0
- package/dist/bridge/readiness-result-outbox.js +54 -0
- package/dist/bridge/readiness-result-worker.d.ts +2 -0
- package/dist/bridge/readiness-result-worker.js +121 -0
- package/dist/bridge/runner-host-capabilities.d.ts +15 -0
- package/dist/bridge/runner-host-capabilities.js +93 -0
- 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.d.ts +2 -0
- package/dist/cli/cli.help.js +217 -0
- package/dist/cli/cli.service.d.ts +55 -7
- package/dist/cli/cli.service.js +429 -219
- package/dist/cli/local-config.d.ts +7 -0
- package/dist/cli/local-config.js +51 -3
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
- package/dist/runtime/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
- package/dist/runtime/attempt-path-operation.d.ts +21 -0
- package/dist/runtime/attempt-path-operation.js +94 -0
- package/dist/runtime/attempt-private-directory.d.ts +6 -0
- package/dist/runtime/attempt-private-directory.js +54 -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 +121 -0
- package/dist/runtime/attempt-process-supervisor.js +471 -0
- package/dist/runtime/canonical-source-file.d.ts +3 -0
- package/dist/runtime/canonical-source-file.js +54 -0
- package/dist/runtime/docker-engine-probe.d.ts +90 -0
- package/dist/runtime/docker-engine-probe.js +333 -0
- package/dist/runtime/generated-output-reset.d.ts +20 -0
- package/dist/runtime/generated-output-reset.js +157 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
- package/dist/runtime/host-database-capability-boundary.js +63 -0
- package/dist/runtime/host-diagnostics.d.ts +11 -0
- package/dist/runtime/host-diagnostics.js +192 -0
- package/dist/runtime/host-execution-root.d.ts +4 -0
- package/dist/runtime/host-execution-root.js +39 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-listener-inspector.d.ts +51 -0
- package/dist/runtime/host-listener-inspector.js +385 -0
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-port-broker.d.ts +76 -0
- package/dist/runtime/host-port-broker.js +333 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +59 -0
- package/dist/runtime/host-runtime-contract.js +815 -0
- package/dist/runtime/host-runtime-lease.d.ts +217 -0
- package/dist/runtime/host-runtime-lease.js +2533 -0
- package/dist/runtime/host-runtime-promotion.d.ts +32 -0
- package/dist/runtime/host-runtime-promotion.js +206 -0
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/memory-capacity.d.ts +70 -0
- package/dist/runtime/memory-capacity.js +123 -0
- package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
- package/dist/runtime/native-test-postgres-fallback.js +91 -0
- package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
- package/dist/runtime/node-host-runtime-adapter.js +286 -0
- package/dist/runtime/pinned-directory-process.d.ts +9 -0
- package/dist/runtime/pinned-directory-process.js +61 -0
- package/dist/runtime/pinned-source-directory.d.ts +17 -0
- package/dist/runtime/pinned-source-directory.js +94 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +32 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +262 -0
- package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
- package/dist/runtime/prepared-runtime-identity.js +218 -0
- package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
- package/dist/runtime/prepared-runtime-readiness.js +285 -0
- package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
- package/dist/runtime/runtime-isolation-lease.js +161 -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 +6 -0
- package/dist/sandbox/repository-lock.js +129 -0
- package/dist/sandbox/runtime.d.ts +302 -0
- package/dist/sandbox/runtime.js +2368 -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 +74 -0
- package/dist/session/managed-attempt-tools.d.ts +53 -0
- package/dist/session/managed-attempt-tools.js +1213 -0
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +109 -0
- package/dist/session/managed-build-receipt.d.ts +21 -0
- package/dist/session/managed-build-receipt.js +337 -0
- package/dist/session/managed-verification-timeouts.d.ts +8 -0
- package/dist/session/managed-verification-timeouts.js +17 -0
- package/dist/session/phase-completion.artifacts.d.ts +27 -0
- package/dist/session/phase-completion.artifacts.js +833 -0
- package/dist/session/phase-completion.d.ts +53 -42
- package/dist/session/phase-completion.helpers.d.ts +117 -0
- package/dist/session/phase-completion.helpers.js +707 -0
- package/dist/session/phase-completion.js +125 -3007
- package/dist/session/phase-completion.prompts.d.ts +14 -0
- package/dist/session/phase-completion.prompts.js +233 -0
- package/dist/session/phase-completion.runtime.d.ts +49 -0
- package/dist/session/phase-completion.runtime.js +845 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -0
- package/dist/session/phase-completion.schemas.js +859 -0
- package/dist/session/phase-completion.validation.d.ts +38 -0
- package/dist/session/phase-completion.validation.js +918 -0
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -0
- 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-validation.d.ts +75 -0
- package/dist/session/pre-publication-validation.js +631 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
- package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
- package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +407 -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 +128 -0
- package/dist/session/provider-cli/provider-cli.process.js +1140 -0
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +57 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +730 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +92 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +47 -53
- package/dist/session/provider-cli/provider-cli.service.js +1344 -2506
- package/dist/session/provider-cli/provider-cli.types.d.ts +8 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +38 -0
- package/dist/session/provider-cli/provider-output-state.js +826 -0
- package/dist/session/provider-cli/provider-usage.d.ts +9 -1
- package/dist/session/provider-cli/provider-usage.js +28 -5
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session-redaction.d.ts +3 -0
- package/dist/session/session-redaction.js +448 -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 +586 -59
- package/dist/session/session.types.d.ts +324 -3
- package/dist/session/session.types.js +951 -10
- package/dist/session/unreferenced-exports.d.ts +12 -0
- package/dist/session/unreferenced-exports.js +59 -0
- package/dist/shared/format/format-bytes.d.ts +1 -0
- package/dist/shared/format/format-bytes.js +9 -0
- package/dist/shared/git/git.js +2 -1
- package/dist/shared/path/path.d.ts +1 -0
- package/dist/shared/path/path.js +21 -1
- package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
- package/dist/shared/process/dotnet-toolchain.js +307 -0
- package/dist/shared/process/host-process-recovery.d.ts +12 -0
- package/dist/shared/process/host-process-recovery.js +79 -0
- package/dist/shared/process/host-process-supervisor.d.ts +59 -0
- package/dist/shared/process/host-process-supervisor.js +331 -0
- package/dist/shared/process/process.d.ts +3 -0
- package/dist/shared/process/process.js +13 -7
- package/dist/shared/process/windows-launch.d.ts +8 -0
- package/dist/shared/process/windows-launch.js +41 -0
- package/dist/shared/provider-capabilities.d.ts +4 -0
- package/dist/shared/provider-capabilities.js +88 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +47 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- 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 +82 -10
- package/dist/worktree/dependency-warmer.d.ts +53 -1
- package/dist/worktree/dependency-warmer.js +693 -11
- 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/story-qa-reference-hydrator.d.ts +4 -0
- package/dist/worktree/story-qa-reference-hydrator.js +253 -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 +16 -3
- package/dist/worktree/worktree.service.js +334 -54
- package/dist/worktree/worktree.types.d.ts +9 -1
- package/package.json +12 -7
- package/runtime/windows-job-supervisor.ps1 +722 -0
- package/runtime/windows-listener-owner.ps1 +33 -0
|
@@ -1,47 +1,277 @@
|
|
|
1
|
-
import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
|
|
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 { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
8
|
+
import { redactText } from "../shared/redaction/redaction.js";
|
|
6
9
|
import { BridgeSessionService } from "../session/session.service.js";
|
|
7
|
-
import {
|
|
10
|
+
import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
11
|
+
import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } from "../session/provider-cli/provider-cli.prompts.js";
|
|
12
|
+
import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
|
|
13
|
+
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
14
|
+
import { PrePublicationValidator } from "../session/pre-publication-validation.js";
|
|
15
|
+
import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
|
|
16
|
+
import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
|
|
17
|
+
import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
|
|
18
|
+
import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
19
|
+
import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
|
|
20
|
+
import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
|
|
21
|
+
import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
|
|
22
|
+
import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
|
|
23
|
+
import { GitWorktreeService } from "../worktree/worktree.service.js";
|
|
24
|
+
import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
|
|
25
|
+
import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
|
|
26
|
+
import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
8
27
|
import { forgeBridgeVersion } from "../version.js";
|
|
28
|
+
import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
|
|
29
|
+
import { validateSandboxContract } from "../sandbox/contract.js";
|
|
30
|
+
import { runSandboxProcess } from "../sandbox/process.js";
|
|
31
|
+
import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
|
|
32
|
+
import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
|
|
33
|
+
import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
|
|
34
|
+
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
35
|
+
import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
|
|
36
|
+
import { HostLoadSampler } from "../runtime/host-load-sampler.js";
|
|
37
|
+
import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
|
|
38
|
+
import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
39
|
+
/**
|
|
40
|
+
* Protocol-v2 events are acknowledged one at a time before runOnce returns.
|
|
41
|
+
* Sending the complete transcript again in DispatchResult made long QA and CI
|
|
42
|
+
* sessions exceed SignalR's receive limit, disconnecting the bridge after the
|
|
43
|
+
* provider had already completed. The API combines its acknowledged streamed
|
|
44
|
+
* events with the terminal result, so the callback only needs the outcome and
|
|
45
|
+
* artifacts. Protocol v1 retains the transcript for legacy servers.
|
|
46
|
+
*/
|
|
47
|
+
export function compactTerminalResult(dispatch, result) {
|
|
48
|
+
return dispatch.schemaVersion >= 2 && result.events.length > 0
|
|
49
|
+
? { ...result, events: [] }
|
|
50
|
+
: result;
|
|
51
|
+
}
|
|
9
52
|
export class ForgeBridgeService {
|
|
10
53
|
config;
|
|
11
|
-
sessions;
|
|
12
54
|
connections;
|
|
55
|
+
hostCapabilityProbe;
|
|
56
|
+
chatProcessRunner;
|
|
57
|
+
hostLoad;
|
|
13
58
|
connection = null;
|
|
14
59
|
heartbeatTimer = null;
|
|
60
|
+
heartbeatInFlight = false;
|
|
61
|
+
consecutiveHeartbeatFailures = 0;
|
|
62
|
+
reconnectingFromHeartbeatFailure = false;
|
|
63
|
+
leaseWatchdogTimer = null;
|
|
64
|
+
sandboxMaintenanceTimer = null;
|
|
65
|
+
sandboxMaintenanceRunning = false;
|
|
15
66
|
closed = null;
|
|
67
|
+
transportRecovery = null;
|
|
68
|
+
transportRecoveryGeneration = 0;
|
|
16
69
|
stopped = false;
|
|
17
70
|
activeSessions = new Map();
|
|
18
|
-
|
|
71
|
+
reservations = new Map();
|
|
72
|
+
activeReadinessProbes = new Map();
|
|
73
|
+
readinessResultOutbox;
|
|
74
|
+
readinessResultFlush = null;
|
|
75
|
+
dispatchResultOutbox;
|
|
76
|
+
dispatchResultFlush = null;
|
|
77
|
+
dispatchResultGeneration = 0;
|
|
78
|
+
dispatchResultFlushedGeneration = -1;
|
|
79
|
+
dispatchResultHandoffs = new Map();
|
|
80
|
+
preflight;
|
|
81
|
+
dockerEngineProbe;
|
|
82
|
+
sandboxRuntime;
|
|
83
|
+
sandboxResourceResolver;
|
|
84
|
+
sessions;
|
|
85
|
+
enforceHostDatabaseCapabilityBoundary;
|
|
86
|
+
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
87
|
+
// Reaping deletes the stale ledger, so its stopped-process proof is held here
|
|
88
|
+
// until a Hello carrying it is accepted. A bridge restart forgets it, which
|
|
89
|
+
// leaves those attempts on Forge's conservative unknown-outcome path.
|
|
90
|
+
recoveredHostAttempts = new Map();
|
|
91
|
+
hostCapabilitiesDetected = false;
|
|
92
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
|
|
19
93
|
this.config = config;
|
|
20
|
-
this.sessions = sessions;
|
|
21
94
|
this.connections = connections;
|
|
95
|
+
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
96
|
+
this.chatProcessRunner = chatProcessRunner;
|
|
97
|
+
this.hostLoad = hostLoad;
|
|
98
|
+
this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
|
|
99
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
100
|
+
establishHostDatabaseCapabilityBoundary();
|
|
101
|
+
}
|
|
102
|
+
this.preflight = preflight ?? new DockerPreflight({
|
|
103
|
+
dockerExecutable: config.dockerExecutable,
|
|
104
|
+
dockerContext: config.dockerContext,
|
|
105
|
+
stateRoot: config.sandboxStateRoot,
|
|
106
|
+
runnerInstanceId: config.runnerInstanceId,
|
|
107
|
+
maxConcurrentSandboxes: config.maxConcurrentSandboxes,
|
|
108
|
+
diskHighWatermarkPercent: config.diskHighWatermarkPercent,
|
|
109
|
+
diskLowWatermarkPercent: config.diskLowWatermarkPercent,
|
|
110
|
+
minimumWorkspaceBytes: config.minimumWorkspaceBytes,
|
|
111
|
+
hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
|
|
112
|
+
defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
|
|
113
|
+
defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
|
|
114
|
+
runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
|
|
115
|
+
requireRootless: config.requireRootlessDocker
|
|
116
|
+
});
|
|
117
|
+
this.dockerEngineProbe = dockerEngineProbe ?? new DockerEngineProbe({
|
|
118
|
+
dockerExecutable: config.dockerExecutable,
|
|
119
|
+
dockerContext: config.dockerContext,
|
|
120
|
+
recovery: {
|
|
121
|
+
enabled: config.dockerDesktopRecoveryEnabled,
|
|
122
|
+
failureThreshold: config.dockerRecoveryFailureThreshold,
|
|
123
|
+
cooldownMs: config.dockerRecoveryCooldownMs,
|
|
124
|
+
startupTimeoutMs: config.dockerRecoveryStartupTimeoutMs,
|
|
125
|
+
canRecover: () => this.activeSessions.size === 0 && this.reservations.size === 0,
|
|
126
|
+
},
|
|
127
|
+
onStatus: logBridgeStatus,
|
|
128
|
+
});
|
|
129
|
+
this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
|
|
130
|
+
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
|
|
131
|
+
this.sandboxResourceResolver = sandboxResourceResolver
|
|
132
|
+
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
133
|
+
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
134
|
+
this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
|
|
22
135
|
}
|
|
23
136
|
async connectOnce() {
|
|
24
137
|
await this.stopConnection();
|
|
25
138
|
this.stopped = false;
|
|
139
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
140
|
+
assertHostDatabaseCapabilityBoundary();
|
|
141
|
+
}
|
|
142
|
+
const hostReap = await this.sessions.reapHostRuntime?.({
|
|
143
|
+
runnerId: this.config.runnerId,
|
|
144
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
145
|
+
});
|
|
146
|
+
this.rememberRecoveredHostAttempts(hostReap);
|
|
147
|
+
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
148
|
+
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.`);
|
|
149
|
+
}
|
|
150
|
+
if (this.config.dockerEnabled) {
|
|
151
|
+
const preflight = await this.preflight.refresh();
|
|
152
|
+
if (canReapManagedSandboxes(preflight)) {
|
|
153
|
+
await this.sandboxRuntime.reap({ diskLow: preflight.diskLow });
|
|
154
|
+
await this.preflight.refresh();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
await this.dockerEngineProbe.refresh(true);
|
|
158
|
+
if (!this.hostCapabilitiesDetected) {
|
|
159
|
+
this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
|
|
160
|
+
this.hostCapabilitiesDetected = true;
|
|
161
|
+
}
|
|
162
|
+
// Static host facts and the first load sample ride on Hello; the sampler
|
|
163
|
+
// keeps refreshing its cached snapshot for later heartbeats.
|
|
164
|
+
await this.hostLoad.start().catch(() => undefined);
|
|
26
165
|
const connection = this.connections.create(this.config);
|
|
27
166
|
this.connection = connection;
|
|
167
|
+
this.transportRecovery = null;
|
|
28
168
|
this.closed = new Promise((resolve) => {
|
|
29
|
-
connection.onClose(() => {
|
|
169
|
+
connection.onClose((error) => {
|
|
30
170
|
this.stopHeartbeat();
|
|
171
|
+
this.completeTransportRecovery(error ?? new Error("bridge connection closed"));
|
|
31
172
|
this.abortActiveSessions("bridge connection closed");
|
|
173
|
+
this.abortActiveReadinessProbes("bridge connection closed");
|
|
32
174
|
resolve();
|
|
33
175
|
});
|
|
34
176
|
});
|
|
177
|
+
connection.onReconnecting?.((error) => {
|
|
178
|
+
if (connection !== this.connection || this.stopped)
|
|
179
|
+
return;
|
|
180
|
+
this.stopHeartbeat();
|
|
181
|
+
this.beginTransportRecovery();
|
|
182
|
+
logBridgeStatus(`Forge connection interrupted${error ? `: ${errorMessage(error)}` : ""}. Reconnecting in place; active dispatches remain supervised...`);
|
|
183
|
+
});
|
|
184
|
+
connection.onReconnected?.(async () => {
|
|
185
|
+
if (connection !== this.connection || this.stopped)
|
|
186
|
+
return;
|
|
187
|
+
try {
|
|
188
|
+
await this.registerConnection(connection);
|
|
189
|
+
this.completeTransportRecovery();
|
|
190
|
+
this.startHeartbeat();
|
|
191
|
+
await this.flushDispatchResults(true).catch(error => {
|
|
192
|
+
logBridgeStatus(`Dispatch result replay deferred after reconnect: ${errorMessage(error)}`);
|
|
193
|
+
});
|
|
194
|
+
await this.flushReadinessResults().catch(error => {
|
|
195
|
+
logBridgeStatus(`Readiness result replay deferred after reconnect: ${errorMessage(error)}`);
|
|
196
|
+
});
|
|
197
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
198
|
+
logBridgeStatus("Forge connection restored; active dispatches remain attached to this runner process.");
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
this.completeTransportRecovery(error);
|
|
202
|
+
logBridgeStatus(`Forge reconnect registration failed: ${errorMessage(error)}. Closing the connection for a clean retry...`);
|
|
203
|
+
await connection.stop().catch(() => undefined);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
35
206
|
connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
|
|
207
|
+
connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
|
|
208
|
+
connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
|
|
209
|
+
connection.onStart?.((dispatch) => this.handleStart(dispatch));
|
|
210
|
+
connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
|
|
36
211
|
connection.onCancel((request) => this.handleCancel(request));
|
|
212
|
+
connection.onReap?.((request) => this.handleReap(request));
|
|
213
|
+
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
37
214
|
await connection.start();
|
|
38
|
-
await this.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
215
|
+
await this.registerConnection(connection);
|
|
216
|
+
await this.flushDispatchResults(true).catch(error => {
|
|
217
|
+
logBridgeStatus(`Dispatch result replay deferred: ${errorMessage(error)}`);
|
|
218
|
+
});
|
|
219
|
+
await this.flushReadinessResults().catch(error => {
|
|
220
|
+
logBridgeStatus(`Readiness result replay deferred: ${errorMessage(error)}`);
|
|
43
221
|
});
|
|
222
|
+
await this.flushCleanupReports();
|
|
44
223
|
this.startHeartbeat();
|
|
224
|
+
this.startLeaseWatchdog();
|
|
225
|
+
this.startSandboxMaintenance();
|
|
226
|
+
}
|
|
227
|
+
rememberRecoveredHostAttempts(report) {
|
|
228
|
+
for (const attempt of report?.recoveredAttempts ?? []) {
|
|
229
|
+
if (this.recoveredHostAttempts.size >= maxRecoveredHostAttempts)
|
|
230
|
+
break;
|
|
231
|
+
this.recoveredHostAttempts.set(attempt.dispatchAttemptId, attempt);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async recoveredHostAttemptsForHello() {
|
|
235
|
+
if (this.recoveredHostAttempts.size === 0)
|
|
236
|
+
return [];
|
|
237
|
+
// A durable terminal result outranks the stopped-process proof: it replays
|
|
238
|
+
// after Hello and Forge accepts the provider's real outcome instead.
|
|
239
|
+
const pendingResults = new Set((await this.dispatchResultOutbox.pending())
|
|
240
|
+
.map(entry => entry.payload.dispatchAttemptId)
|
|
241
|
+
.filter((id) => typeof id === "string"));
|
|
242
|
+
return [...this.recoveredHostAttempts.values()]
|
|
243
|
+
.filter(attempt => !pendingResults.has(attempt.dispatchAttemptId));
|
|
244
|
+
}
|
|
245
|
+
async registerConnection(connection) {
|
|
246
|
+
let storageRecoveryAttempt = 0;
|
|
247
|
+
while (true) {
|
|
248
|
+
try {
|
|
249
|
+
const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
|
|
250
|
+
const ack = await connection.invoke("Hello", {
|
|
251
|
+
version: this.config.version,
|
|
252
|
+
protocolVersion: this.config.protocolVersion,
|
|
253
|
+
minServerVersion: this.config.minServerVersion ?? null,
|
|
254
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
255
|
+
capabilities: this.capabilities(),
|
|
256
|
+
recoveredHostAttempts,
|
|
257
|
+
});
|
|
258
|
+
if (!ack.accepted) {
|
|
259
|
+
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
|
|
260
|
+
}
|
|
261
|
+
this.recoveredHostAttempts.clear();
|
|
262
|
+
logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (!isProviderStorageUnavailable(error) || storageRecoveryAttempt >= this.config.reconnectBackoffMs.length) {
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
const backoff = this.config.reconnectBackoffMs[storageRecoveryAttempt] ?? 5000;
|
|
270
|
+
storageRecoveryAttempt += 1;
|
|
271
|
+
logBridgeStatus(`Hello reached Forge while storage was recovering. Retrying registration ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
|
|
272
|
+
await delay(backoff);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
45
275
|
}
|
|
46
276
|
async run(signal) {
|
|
47
277
|
let attempt = 0;
|
|
@@ -72,6 +302,7 @@ export class ForgeBridgeService {
|
|
|
72
302
|
finally {
|
|
73
303
|
if (signal?.aborted) {
|
|
74
304
|
this.abortActiveSessions(String(signal.reason ?? "bridge stopping"));
|
|
305
|
+
this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
|
|
75
306
|
}
|
|
76
307
|
await this.stopConnection();
|
|
77
308
|
}
|
|
@@ -79,31 +310,408 @@ export class ForgeBridgeService {
|
|
|
79
310
|
async stop() {
|
|
80
311
|
this.stopped = true;
|
|
81
312
|
this.abortActiveSessions("bridge stopping");
|
|
313
|
+
this.abortActiveReadinessProbes("bridge stopping");
|
|
82
314
|
await this.stopConnection();
|
|
315
|
+
this.hostLoad.stop();
|
|
316
|
+
await this.preflight.release();
|
|
83
317
|
}
|
|
84
|
-
async
|
|
85
|
-
const
|
|
318
|
+
async handleChatTurn(rawDispatch) {
|
|
319
|
+
const packet = this.parseChatTurnOrReport(rawDispatch);
|
|
320
|
+
if (!packet) {
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (packet.runnerInstanceId !== this.config.runnerInstanceId) {
|
|
324
|
+
logBridgeStatus(`Rejected Bridge Chat turn ${packet.turnId}: stale runner instance.`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const capabilityFailure = this.requiredChatCapabilityFailure(packet);
|
|
328
|
+
if (capabilityFailure) {
|
|
329
|
+
await this.sendStandaloneChatTerminal(packet, "failed", {
|
|
330
|
+
code: "bridge_chat.runner_unavailable",
|
|
331
|
+
message: capabilityFailure,
|
|
332
|
+
}).catch(() => undefined);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const existing = this.activeSessions.get(packet.leaseId);
|
|
336
|
+
if (existing) {
|
|
337
|
+
if (existing.kind === "chat"
|
|
338
|
+
&& existing.fencingToken === packet.fencingToken
|
|
339
|
+
&& existing.chatRunId === packet.chatRunId
|
|
340
|
+
&& existing.conversationId === packet.conversationId
|
|
341
|
+
&& existing.turnId === packet.turnId) {
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
await this.sendStandaloneChatTerminal(packet, "failed", {
|
|
345
|
+
code: "bridge_chat.stale_fencing_token",
|
|
346
|
+
message: "Bridge Chat turn fence conflicts with an active bridge session.",
|
|
347
|
+
}).catch(() => undefined);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const controller = new AbortController();
|
|
351
|
+
const active = {
|
|
352
|
+
leaseId: packet.leaseId,
|
|
353
|
+
kind: "chat",
|
|
354
|
+
fencingToken: packet.fencingToken,
|
|
355
|
+
dispatchAttemptId: null,
|
|
356
|
+
runnerInstanceId: packet.runnerInstanceId,
|
|
357
|
+
leaseExpiresAt: chatTurnLeaseExpiresAt(packet),
|
|
358
|
+
sandboxed: false,
|
|
359
|
+
resources: zeroSandboxResources(),
|
|
360
|
+
controller,
|
|
361
|
+
chatRunId: packet.chatRunId,
|
|
362
|
+
conversationId: packet.conversationId,
|
|
363
|
+
turnId: packet.turnId,
|
|
364
|
+
providerThreadId: packet.providerThreadId ?? null,
|
|
365
|
+
chatSequence: 0,
|
|
366
|
+
terminalCallbackAttempted: false,
|
|
367
|
+
};
|
|
368
|
+
this.activeSessions.set(packet.leaseId, active);
|
|
369
|
+
let workspacePath = null;
|
|
370
|
+
let cleanupAttempted = false;
|
|
371
|
+
let cleanupOutcome = null;
|
|
372
|
+
let cleanupReported = false;
|
|
373
|
+
const cleanup = async () => {
|
|
374
|
+
if (!workspacePath || cleanupAttempted)
|
|
375
|
+
return null;
|
|
376
|
+
cleanupAttempted = true;
|
|
377
|
+
cleanupOutcome = await cleanupChatTurnWorkspace(workspacePath, chatRedactionSecrets(packet));
|
|
378
|
+
return cleanupOutcome;
|
|
379
|
+
};
|
|
380
|
+
const reportCleanup = async (outcome) => {
|
|
381
|
+
if (!outcome || cleanupReported)
|
|
382
|
+
return;
|
|
383
|
+
cleanupReported = true;
|
|
384
|
+
await this.sendChatCallback(active, "output_delta", outcome).catch(() => undefined);
|
|
385
|
+
};
|
|
386
|
+
try {
|
|
387
|
+
workspacePath = await this.createChatTurnWorkspace(packet);
|
|
388
|
+
await materializeChatTurnMetadata(packet, workspacePath);
|
|
389
|
+
const run = await this.runChatProviderProcess(packet, active, workspacePath);
|
|
390
|
+
cleanupOutcome = await cleanup();
|
|
391
|
+
await reportCleanup(cleanupOutcome);
|
|
392
|
+
if (controller.signal.aborted) {
|
|
393
|
+
await this.sendChatAbortTerminal(packet, active, cleanupOutcome);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (cleanupOutcome?.status === "failed") {
|
|
397
|
+
throw new Error(`chat_turn_cleanup_failed: ${cleanupOutcome.message}`);
|
|
398
|
+
}
|
|
399
|
+
if (run.result.exitCode !== 0) {
|
|
400
|
+
throw chatProviderExitFailure(run.command, run.result, chatRedactionSecrets(packet));
|
|
401
|
+
}
|
|
402
|
+
await this.sendChatCallback(active, "output_completed", {
|
|
403
|
+
code: "output_completed",
|
|
404
|
+
text: clip(redactText(run.output.finalMessage ?? "", chatRedactionSecrets(packet)), maxChatTerminalTextChars),
|
|
405
|
+
provider: packet.providerKind,
|
|
406
|
+
model: packet.model,
|
|
407
|
+
cleanup: cleanupOutcome,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
cleanupOutcome = cleanupOutcome ?? await cleanup();
|
|
412
|
+
if (active.terminalCallbackAttempted) {
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
await reportCleanup(cleanupOutcome);
|
|
416
|
+
const payload = controller.signal.aborted
|
|
417
|
+
? chatAbortPayload(controller.signal.reason, cleanupOutcome, packet)
|
|
418
|
+
: {
|
|
419
|
+
code: "provider_failed",
|
|
420
|
+
message: clip(redactText(errorMessage(error), chatRedactionSecrets(packet)), 2000),
|
|
421
|
+
cleanup: cleanupOutcome,
|
|
422
|
+
};
|
|
423
|
+
const kind = controller.signal.aborted ? chatAbortKind(controller.signal.reason) : "failed";
|
|
424
|
+
await this.sendChatCallback(active, kind, payload).catch(callbackError => {
|
|
425
|
+
logBridgeStatus(`Bridge Chat terminal callback for turn ${packet.turnId} was not accepted: ${errorMessage(callbackError)}`);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
await this.releaseActiveSessionAndRefreshCapacity(packet.leaseId);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async createChatTurnWorkspace(packet) {
|
|
433
|
+
const root = path.join(this.config.sandboxStateRoot, "chat-turns");
|
|
434
|
+
await fs.promises.mkdir(root, { recursive: true });
|
|
435
|
+
return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
|
|
436
|
+
}
|
|
437
|
+
async runChatProviderProcess(packet, active, cwd) {
|
|
438
|
+
const output = createProviderOutputState(packet.providerKind);
|
|
439
|
+
const plan = buildChatProviderCommand(packet, cwd);
|
|
440
|
+
const redactionSecrets = chatRedactionSecrets(packet);
|
|
441
|
+
let started = false;
|
|
442
|
+
const result = await this.chatProcessRunner.run({
|
|
443
|
+
command: plan.command.command,
|
|
444
|
+
args: plan.command.args,
|
|
445
|
+
cwd,
|
|
446
|
+
env: {
|
|
447
|
+
FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
|
|
448
|
+
FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
|
|
449
|
+
},
|
|
450
|
+
stdin: plan.stdin,
|
|
451
|
+
}, {
|
|
452
|
+
onStarted: async () => {
|
|
453
|
+
started = true;
|
|
454
|
+
await this.sendChatCallback(active, "turn_started", {
|
|
455
|
+
status: "running",
|
|
456
|
+
provider: packet.providerKind,
|
|
457
|
+
model: packet.model,
|
|
458
|
+
command: redactText(formatProviderCliCommandForCheckpoint(plan.command), redactionSecrets),
|
|
459
|
+
});
|
|
460
|
+
},
|
|
461
|
+
onStdoutLine: async (line) => {
|
|
462
|
+
for (const event of output.consume(line)) {
|
|
463
|
+
await this.sendChatProviderEvent(packet, active, event, output.providerThreadId);
|
|
464
|
+
}
|
|
465
|
+
},
|
|
466
|
+
}, active.controller.signal);
|
|
467
|
+
if (started && !active.controller.signal.aborted) {
|
|
468
|
+
await this.sendChatCallback(active, "output_delta", {
|
|
469
|
+
eventType: "provider_cli_completed",
|
|
470
|
+
role: "runner",
|
|
471
|
+
kind: "checkpoint",
|
|
472
|
+
content: "Bridge Chat provider process exited.",
|
|
473
|
+
}).catch(() => undefined);
|
|
474
|
+
}
|
|
475
|
+
return { command: plan.command, output, result };
|
|
476
|
+
}
|
|
477
|
+
async sendChatProviderEvent(packet, active, event, providerThreadId) {
|
|
478
|
+
if (providerThreadId) {
|
|
479
|
+
active.providerThreadId = providerThreadId;
|
|
480
|
+
}
|
|
481
|
+
else if (event.eventType === "provider_thread_started") {
|
|
482
|
+
active.providerThreadId = providerThreadIdFromEvent(event) ?? active.providerThreadId;
|
|
483
|
+
}
|
|
484
|
+
if (event.eventType === "provider_tool_heartbeat") {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
const redactionSecrets = chatRedactionSecrets(packet);
|
|
488
|
+
const payload = {
|
|
489
|
+
role: event.role,
|
|
490
|
+
kind: event.kind,
|
|
491
|
+
eventType: event.eventType ?? "provider_event",
|
|
492
|
+
content: clip(redactText(event.content, redactionSecrets), maxChatEventContentChars),
|
|
493
|
+
data: event.data ? clip(redactText(event.data, redactionSecrets), maxChatEventContentChars) : undefined,
|
|
494
|
+
};
|
|
495
|
+
await this.sendChatCallback(active, "output_delta", payload);
|
|
496
|
+
}
|
|
497
|
+
async sendChatAbortTerminal(packet, active, cleanupOutcome) {
|
|
498
|
+
await this.sendChatCallback(active, chatAbortKind(active.controller.signal.reason), chatAbortPayload(active.controller.signal.reason, cleanupOutcome, packet));
|
|
499
|
+
}
|
|
500
|
+
async sendStandaloneChatTerminal(packet, kind, payload) {
|
|
501
|
+
const active = {
|
|
502
|
+
leaseId: packet.leaseId,
|
|
503
|
+
kind: "chat",
|
|
504
|
+
fencingToken: packet.fencingToken,
|
|
505
|
+
dispatchAttemptId: null,
|
|
506
|
+
runnerInstanceId: packet.runnerInstanceId,
|
|
507
|
+
leaseExpiresAt: new Date(Date.now() + defaultChatTurnLeaseMs).toISOString(),
|
|
508
|
+
sandboxed: false,
|
|
509
|
+
resources: zeroSandboxResources(),
|
|
510
|
+
controller: new AbortController(),
|
|
511
|
+
chatRunId: packet.chatRunId,
|
|
512
|
+
conversationId: packet.conversationId,
|
|
513
|
+
turnId: packet.turnId,
|
|
514
|
+
providerThreadId: packet.providerThreadId ?? null,
|
|
515
|
+
chatSequence: 0,
|
|
516
|
+
terminalCallbackAttempted: false,
|
|
517
|
+
};
|
|
518
|
+
await this.sendChatCallback(active, kind, payload);
|
|
519
|
+
}
|
|
520
|
+
async sendChatCallback(active, kind, payload = null) {
|
|
521
|
+
if (active.kind !== "chat" || !active.chatRunId || !active.conversationId || !active.turnId) {
|
|
522
|
+
throw new Error("Bridge Chat callback requires an active chat turn.");
|
|
523
|
+
}
|
|
524
|
+
const terminal = isTerminalChatTurnCallbackKind(kind);
|
|
525
|
+
if (terminal && active.terminalCallbackAttempted) {
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
assertBridgeChatCallbackPayload(payload);
|
|
529
|
+
const sequence = (active.chatSequence ?? 0) + 1;
|
|
530
|
+
const envelope = {
|
|
531
|
+
callbackId: randomUUID(),
|
|
532
|
+
chatRunId: active.chatRunId,
|
|
533
|
+
conversationId: active.conversationId,
|
|
534
|
+
turnId: active.turnId,
|
|
535
|
+
leaseId: active.leaseId,
|
|
536
|
+
fencingToken: active.fencingToken,
|
|
537
|
+
runnerId: this.config.runnerId,
|
|
538
|
+
runnerInstanceId: active.runnerInstanceId ?? this.config.runnerInstanceId,
|
|
539
|
+
sequence,
|
|
540
|
+
eventType: kind,
|
|
541
|
+
redactionStatus: "redacted",
|
|
542
|
+
providerThreadId: active.providerThreadId ?? null,
|
|
543
|
+
payload,
|
|
544
|
+
occurredAt: new Date().toISOString(),
|
|
545
|
+
protocolVersion: bridgeChatProtocolVersion,
|
|
546
|
+
};
|
|
547
|
+
if (terminal) {
|
|
548
|
+
active.terminalCallbackAttempted = true;
|
|
549
|
+
}
|
|
550
|
+
await this.invokeChatCallbackWithRetry(envelope);
|
|
551
|
+
active.chatSequence = sequence;
|
|
552
|
+
}
|
|
553
|
+
async invokeChatCallbackWithRetry(envelope) {
|
|
554
|
+
const maxAttempts = 3;
|
|
555
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
556
|
+
try {
|
|
557
|
+
await this.invokeAck("ChatTurnCallback", envelope);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
if (error instanceof BridgeCallbackRejectedError || attempt === maxAttempts - 1) {
|
|
562
|
+
throw error;
|
|
563
|
+
}
|
|
564
|
+
await delay(200 * (attempt + 1));
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
requiredChatCapabilityFailure(packet) {
|
|
569
|
+
const capability = this.bridgeChatCapability();
|
|
570
|
+
if (capability.availability === "unavailable" || !capability.supportsTextStreaming) {
|
|
571
|
+
return capability.unavailableReason ?? "Bridge Chat text capability is unavailable.";
|
|
572
|
+
}
|
|
573
|
+
if (capability.supportedProviders.length > 0
|
|
574
|
+
&& !containsIgnoreCase(capability.supportedProviders, packet.providerKind)) {
|
|
575
|
+
return `Bridge Chat provider '${packet.providerKind}' is not advertised by this bridge.`;
|
|
576
|
+
}
|
|
577
|
+
if (capability.supportedModels.length > 0
|
|
578
|
+
&& !containsIgnoreCase(capability.supportedModels, packet.model)) {
|
|
579
|
+
return `Bridge Chat model '${packet.model}' is not advertised by this bridge.`;
|
|
580
|
+
}
|
|
581
|
+
if (packet.requestedCapabilities.includes("cancel") && !capability.supportsCancel) {
|
|
582
|
+
return "Bridge Chat cancellation is not advertised by this bridge.";
|
|
583
|
+
}
|
|
584
|
+
if (packet.requestedCapabilities.includes("resume") && !capability.supportsResume) {
|
|
585
|
+
return "Bridge Chat resume is not advertised by this bridge.";
|
|
586
|
+
}
|
|
587
|
+
if (packet.requestedCapabilities.includes("thread_continuity")
|
|
588
|
+
&& !capability.supportsProviderThreadContinuity) {
|
|
589
|
+
return "Bridge Chat provider thread continuity is not advertised by this bridge.";
|
|
590
|
+
}
|
|
591
|
+
if (packet.requestedCapabilities.includes("attachment_handoffs") && !capability.supportsAttachments) {
|
|
592
|
+
return "Bridge Chat attachment handoffs are not advertised by this bridge.";
|
|
593
|
+
}
|
|
594
|
+
if (packet.requestedCapabilities.includes("action_broker_grants") && !capability.supportsActionBrokerGrants) {
|
|
595
|
+
return "Bridge Chat action-broker grants are not advertised by this bridge.";
|
|
596
|
+
}
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
bridgeChatCapability() {
|
|
600
|
+
return bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat);
|
|
601
|
+
}
|
|
602
|
+
async handleDispatch(rawDispatch, reservationHandoff) {
|
|
603
|
+
const dispatch = await this.parseDispatchOrReport(rawDispatch);
|
|
86
604
|
if (!dispatch) {
|
|
605
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
609
|
+
try {
|
|
610
|
+
assertHostDatabaseCapabilityBoundary();
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
const message = errorMessage(error);
|
|
614
|
+
await this.sendResult(dispatch, failureResult(message, [{
|
|
615
|
+
role: "runner",
|
|
616
|
+
kind: "error",
|
|
617
|
+
content: message,
|
|
618
|
+
eventType: "host_database_capability_forbidden",
|
|
619
|
+
}], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
|
|
620
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
let capabilityFailure;
|
|
625
|
+
try {
|
|
626
|
+
capabilityFailure = await this.requiredCapabilityFailure(dispatch);
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
if (capabilityFailure) {
|
|
633
|
+
await this.sendResult(dispatch, failureResult(capabilityFailure, [{
|
|
634
|
+
role: "runner",
|
|
635
|
+
kind: "error",
|
|
636
|
+
content: capabilityFailure,
|
|
637
|
+
eventType: "docker_engine_unavailable",
|
|
638
|
+
}], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
|
|
639
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
87
640
|
return;
|
|
88
641
|
}
|
|
89
642
|
const leaseId = dispatch.lease.id;
|
|
90
643
|
const fencingToken = dispatch.lease.fencingToken;
|
|
91
644
|
const redactionSecrets = exactSecrets(dispatch, this.config);
|
|
92
|
-
if (this.
|
|
93
|
-
await this.sendResult(
|
|
645
|
+
if (reservationHandoff && !this.reservedDispatchHandoffIsCurrent(reservationHandoff, dispatch)) {
|
|
646
|
+
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
|
|
94
647
|
return;
|
|
95
648
|
}
|
|
96
|
-
const
|
|
97
|
-
|
|
649
|
+
const existing = this.activeSessions.get(leaseId);
|
|
650
|
+
if (existing) {
|
|
651
|
+
if (existing.fencingToken === fencingToken) {
|
|
652
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
await this.sendResult(dispatch, failureResult("Dispatch fence conflicts with an active bridge session.", [], failureFactsForCode("bridge.dispatch_fence_conflict"))).catch(() => undefined);
|
|
656
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
const controller = reservationHandoff?.controller ?? new AbortController();
|
|
660
|
+
this.activeSessions.set(leaseId, {
|
|
661
|
+
leaseId,
|
|
662
|
+
kind: "dispatch",
|
|
663
|
+
fencingToken,
|
|
664
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
665
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
666
|
+
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
667
|
+
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
668
|
+
resources: dispatch.sandbox?.executionMode === "docker"
|
|
669
|
+
? dispatch.sandbox.requestedResources
|
|
670
|
+
: zeroSandboxResources(),
|
|
671
|
+
controller
|
|
672
|
+
});
|
|
673
|
+
if (reservationHandoff) {
|
|
674
|
+
// Promotion is synchronous with active-session registration. A qualified
|
|
675
|
+
// pre-start Cancel therefore sees either the cancellable reservation or
|
|
676
|
+
// the fully active owner; there is no cancellation-blind handoff gap.
|
|
677
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
678
|
+
}
|
|
679
|
+
// Server-requested runtime readiness is background maintenance. A probe may
|
|
680
|
+
// have passed admission during the narrow handoff between prepared-runtime
|
|
681
|
+
// verification and the foreground attempt's final admission. Preempt it as
|
|
682
|
+
// soon as real agent work arrives so the probe cannot consume the memory
|
|
683
|
+
// headroom that the foreground attempt is waiting to acquire.
|
|
684
|
+
this.deferActiveReadinessProbes();
|
|
98
685
|
try {
|
|
99
686
|
const normalized = this.normalizeDispatch(dispatch);
|
|
100
|
-
|
|
687
|
+
if (normalized.sandbox) {
|
|
688
|
+
const started = {
|
|
689
|
+
dispatchAttemptId: normalized.sandbox.dispatchAttemptId,
|
|
690
|
+
leaseId,
|
|
691
|
+
fencingToken,
|
|
692
|
+
runnerInstanceId: normalized.sandbox.runnerInstanceId
|
|
693
|
+
};
|
|
694
|
+
await this.invokeAck("DispatchStarted", started);
|
|
695
|
+
}
|
|
696
|
+
const sink = {
|
|
101
697
|
emit: async (event) => {
|
|
698
|
+
if (event.eventType === "provider_cli_started") {
|
|
699
|
+
const active = this.activeSessions.get(leaseId);
|
|
700
|
+
if (active)
|
|
701
|
+
active.resources = { ...active.resources, buildSlots: 0 };
|
|
702
|
+
}
|
|
102
703
|
try {
|
|
103
704
|
await this.invokeAck("DispatchEvent", {
|
|
104
705
|
leaseId,
|
|
105
706
|
fencingToken,
|
|
106
|
-
|
|
707
|
+
...(dispatch.sandbox ? {
|
|
708
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
709
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
710
|
+
} : {}),
|
|
711
|
+
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
712
|
+
}, {
|
|
713
|
+
replayCallbackTimeout: true,
|
|
714
|
+
signal: controller.signal,
|
|
107
715
|
});
|
|
108
716
|
}
|
|
109
717
|
catch (error) {
|
|
@@ -114,20 +722,386 @@ export class ForgeBridgeService {
|
|
|
114
722
|
throw error;
|
|
115
723
|
}
|
|
116
724
|
}
|
|
117
|
-
}
|
|
118
|
-
|
|
725
|
+
};
|
|
726
|
+
const result = normalized.sandbox?.executionMode === "docker"
|
|
727
|
+
? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
|
|
728
|
+
: await this.sessions.runOnce(normalized, sink, controller.signal);
|
|
729
|
+
if (normalized.sandbox?.executionMode === "docker") {
|
|
730
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
731
|
+
}
|
|
732
|
+
const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
|
|
733
|
+
await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
|
|
119
734
|
}
|
|
120
735
|
catch (error) {
|
|
121
736
|
const summary = controller.signal.aborted
|
|
122
737
|
? `Dispatch cancelled: ${String(controller.signal.reason ?? "cancelled")}`
|
|
123
738
|
: redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
|
|
124
|
-
|
|
739
|
+
const failureFacts = failureFactsFromError(error, {
|
|
740
|
+
cancelled: controller.signal.aborted,
|
|
741
|
+
source: "bridge",
|
|
742
|
+
});
|
|
743
|
+
const failureEventType = failureFacts.category === "unknown" ? null : failureFacts.code;
|
|
744
|
+
const failureEvents = failureEventType ? [{
|
|
745
|
+
role: "runner",
|
|
746
|
+
kind: "error",
|
|
747
|
+
content: summary,
|
|
748
|
+
eventType: failureEventType,
|
|
749
|
+
}] : [];
|
|
750
|
+
await this.sendResult(dispatch, failureResult(summary, failureEvents, failureFacts)).catch(() => undefined);
|
|
751
|
+
}
|
|
752
|
+
finally {
|
|
753
|
+
await this.releaseActiveSessionAndRefreshCapacity(leaseId);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
reservedDispatchHandoffIsCurrent(handoff, dispatch) {
|
|
757
|
+
const sandbox = dispatch.sandbox;
|
|
758
|
+
const reservation = handoff.reservation;
|
|
759
|
+
return sandbox !== null
|
|
760
|
+
&& sandbox !== undefined
|
|
761
|
+
&& sandbox.dispatchAttemptId === handoff.dispatchAttemptId
|
|
762
|
+
&& this.reservations.get(handoff.dispatchAttemptId) === reservation
|
|
763
|
+
&& reservation.startClaim === handoff
|
|
764
|
+
&& !handoff.controller.signal.aborted
|
|
765
|
+
&& reservation.leaseId === dispatch.lease.id
|
|
766
|
+
&& reservation.fencingToken === dispatch.lease.fencingToken
|
|
767
|
+
&& reservation.runnerInstanceId === sandbox.runnerInstanceId
|
|
768
|
+
&& Date.parse(reservation.reservedUntil) > Date.now();
|
|
769
|
+
}
|
|
770
|
+
releaseReservedDispatchHandoff(handoff) {
|
|
771
|
+
if (!handoff
|
|
772
|
+
|| this.reservations.get(handoff.dispatchAttemptId) !== handoff.reservation
|
|
773
|
+
|| handoff.reservation.startClaim !== handoff)
|
|
774
|
+
return;
|
|
775
|
+
this.reservations.delete(handoff.dispatchAttemptId);
|
|
776
|
+
}
|
|
777
|
+
async releaseActiveSessionAndRefreshCapacity(leaseId, expectedDispatch) {
|
|
778
|
+
if (expectedDispatch) {
|
|
779
|
+
const active = this.activeSessions.get(leaseId);
|
|
780
|
+
// Admission failures may arrive after a newer attempt starts on the same
|
|
781
|
+
// lease. A terminal callback can release only the dispatch it identifies.
|
|
782
|
+
if (!active || active.kind !== "dispatch"
|
|
783
|
+
|| active.fencingToken !== expectedDispatch.lease.fencingToken
|
|
784
|
+
|| active.dispatchAttemptId !== (expectedDispatch.sandbox?.dispatchAttemptId ?? null)
|
|
785
|
+
|| active.runnerInstanceId !== (expectedDispatch.sandbox?.runnerInstanceId ?? null))
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
if (!this.activeSessions.delete(leaseId))
|
|
789
|
+
return;
|
|
790
|
+
// Publish released host/runtime capacity before the terminal result can
|
|
791
|
+
// enqueue the next pipeline phase. Otherwise the server may reject that
|
|
792
|
+
// handoff from the previous periodic heartbeat's active reservation.
|
|
793
|
+
// Publish the updated reservation counts from cached samples only. Probes
|
|
794
|
+
// belong to periodic/admission heartbeats and must not outlive this bounded
|
|
795
|
+
// terminal handoff. Storage recovery must not block durable result delivery.
|
|
796
|
+
const controller = new AbortController();
|
|
797
|
+
let timer;
|
|
798
|
+
try {
|
|
799
|
+
await Promise.race([
|
|
800
|
+
this.sendHeartbeatSnapshot(controller.signal).catch(() => undefined),
|
|
801
|
+
new Promise(resolve => {
|
|
802
|
+
timer = setTimeout(() => {
|
|
803
|
+
controller.abort("terminal capacity refresh deadline");
|
|
804
|
+
resolve();
|
|
805
|
+
}, Math.min(5000, positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000)));
|
|
806
|
+
}),
|
|
807
|
+
]);
|
|
125
808
|
}
|
|
126
809
|
finally {
|
|
127
|
-
|
|
810
|
+
if (timer)
|
|
811
|
+
clearTimeout(timer);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async handleOffer(rawDispatch) {
|
|
815
|
+
const envelope = parseOfferEnvelope(rawDispatch);
|
|
816
|
+
if (!envelope) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
const dispatch = await this.parseDispatchOrReport(envelope.dispatch);
|
|
820
|
+
if (!dispatch?.sandbox
|
|
821
|
+
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
822
|
+
|| dispatch.lease.id !== envelope.leaseId
|
|
823
|
+
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
824
|
+
return;
|
|
825
|
+
const sandbox = dispatch.sandbox;
|
|
826
|
+
this.expireReservations(Date.now());
|
|
827
|
+
const existing = this.reservations.get(sandbox.dispatchAttemptId);
|
|
828
|
+
if (existing) {
|
|
829
|
+
const sameFence = existing.leaseId === dispatch.lease.id
|
|
830
|
+
&& existing.fencingToken === dispatch.lease.fencingToken
|
|
831
|
+
&& existing.runnerInstanceId === sandbox.runnerInstanceId;
|
|
832
|
+
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);
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
if (sandbox.runnerInstanceId !== this.config.runnerInstanceId) {
|
|
836
|
+
await this.sendOfferDecision(dispatch, false, "stale_runner_instance", "Offer targets a different runner process instance.");
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
if (Date.parse(envelope.expiresAt) <= Date.now()) {
|
|
840
|
+
await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
|
|
844
|
+
? await this.preflight.run()
|
|
845
|
+
: this.preflight.current();
|
|
846
|
+
if (sandbox.executionMode === "docker") {
|
|
847
|
+
if (!this.config.dockerEnabled || !preflight?.healthy) {
|
|
848
|
+
await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
|
|
852
|
+
if (networkFailure) {
|
|
853
|
+
await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
|
|
857
|
+
if (providerNetworkFailure) {
|
|
858
|
+
await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const authFailure = sandboxAuthFailure(dispatch, this.config);
|
|
862
|
+
if (authFailure) {
|
|
863
|
+
await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
let requestedResources = sandbox.requestedResources;
|
|
868
|
+
let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
|
|
869
|
+
const normalizedDispatch = this.normalizeDispatch(dispatch);
|
|
870
|
+
if (sandbox.executionMode === "docker") {
|
|
871
|
+
try {
|
|
872
|
+
const profile = await this.sandboxResourceResolver(normalizedDispatch);
|
|
873
|
+
requestedResources = profile.resources;
|
|
874
|
+
sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
|
|
875
|
+
}
|
|
876
|
+
catch (error) {
|
|
877
|
+
await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
128
880
|
}
|
|
881
|
+
else if (normalizedDispatch.repo.serverLocalPath) {
|
|
882
|
+
// Host execution uses the same project-derived disk reservation as Docker.
|
|
883
|
+
// The API supplies a placement-time estimate; the runner can safely raise it
|
|
884
|
+
// from its authoritative checkout before admitting the attempt.
|
|
885
|
+
const measuredWorkspaceBytes = await estimateWorkspaceBytesFromRepo(normalizedDispatch.repo.serverLocalPath, { role: normalizedDispatch.execution.role }).catch(() => null);
|
|
886
|
+
if (measuredWorkspaceBytes !== null) {
|
|
887
|
+
requestedResources = {
|
|
888
|
+
...requestedResources,
|
|
889
|
+
workspaceBytes: Math.max(requestedResources.workspaceBytes, measuredWorkspaceBytes),
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
// Resource profiling can await filesystem and Docker work. Admission needs
|
|
894
|
+
// a dynamic host/daemon sample that began after profiling completed, so an
|
|
895
|
+
// older in-flight heartbeat inspection cannot supply the commit decision.
|
|
896
|
+
const admissionPreflight = sandbox.executionMode === "docker"
|
|
897
|
+
? await this.preflight.refreshCapacityForAdmission()
|
|
898
|
+
: preflight;
|
|
899
|
+
// Resource profiling and preflight may await slow filesystem or Docker I/O.
|
|
900
|
+
// Re-read every mutable capacity input only after that work, then decide and
|
|
901
|
+
// commit synchronously. JavaScript cannot interleave another Offer handler
|
|
902
|
+
// inside this non-async method, so the ledger check and insertion are one
|
|
903
|
+
// atomic event-loop turn without holding a lock across external I/O.
|
|
904
|
+
const decision = this.commitOfferReservation(dispatch, requestedResources, admissionPreflight);
|
|
905
|
+
await this.sendOfferDecision(dispatch, decision.accepted, decision.code, decision.message, decision.reservedUntil, decision.resources, sandboxConfigCommitSha);
|
|
129
906
|
}
|
|
130
|
-
|
|
907
|
+
commitOfferReservation(dispatch, requestedResources, preparedPreflight) {
|
|
908
|
+
const sandbox = dispatch.sandbox;
|
|
909
|
+
const now = Date.now();
|
|
910
|
+
this.expireReservations(now);
|
|
911
|
+
const existing = this.reservations.get(sandbox.dispatchAttemptId);
|
|
912
|
+
if (existing) {
|
|
913
|
+
const sameFence = existing.leaseId === dispatch.lease.id
|
|
914
|
+
&& existing.fencingToken === dispatch.lease.fencingToken
|
|
915
|
+
&& existing.runnerInstanceId === sandbox.runnerInstanceId;
|
|
916
|
+
return {
|
|
917
|
+
accepted: sameFence,
|
|
918
|
+
code: sameFence ? null : "stale_fence",
|
|
919
|
+
message: sameFence ? null : "Offer fence conflicts with the existing reservation.",
|
|
920
|
+
reservedUntil: sameFence ? existing.reservedUntil : null,
|
|
921
|
+
resources: sameFence ? existing.resources : null,
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
if (Date.parse(dispatch.lease.expiresAt) <= now) {
|
|
925
|
+
return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
|
|
926
|
+
}
|
|
927
|
+
if (sandbox.executionMode === "docker") {
|
|
928
|
+
// A concurrent heartbeat/preflight refresh may have produced a newer
|
|
929
|
+
// conservative dual-domain sample while this offer was being profiled.
|
|
930
|
+
const admissionPreflight = this.preflight.current() ?? preparedPreflight;
|
|
931
|
+
if (!this.config.dockerEnabled || !admissionPreflight?.healthy) {
|
|
932
|
+
return rejectedOfferReservation(admissionPreflight?.unavailableCode ?? "docker_unavailable", admissionPreflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
|
|
933
|
+
}
|
|
934
|
+
const runtimeState = this.sandboxRuntime.snapshot();
|
|
935
|
+
const usedResources = this.usedSandboxResources(runtimeState.degraded);
|
|
936
|
+
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
937
|
+
const capacity = this.sandboxResourceCapacity(admissionPreflight, activeResources);
|
|
938
|
+
if (!canReserveSandboxResources(usedResources, requestedResources, capacity)) {
|
|
939
|
+
return rejectedOfferReservation("capacity_unavailable", sandboxCapacityFailureMessage(usedResources, requestedResources, capacity, admissionPreflight, this.config));
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt), now + 30_000)).toISOString();
|
|
943
|
+
const reservation = {
|
|
944
|
+
leaseId: dispatch.lease.id,
|
|
945
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
946
|
+
runnerInstanceId: sandbox.runnerInstanceId,
|
|
947
|
+
expiresAt: dispatch.lease.expiresAt,
|
|
948
|
+
reservedUntil,
|
|
949
|
+
sandboxed: sandbox.executionMode === "docker",
|
|
950
|
+
resources: requestedResources,
|
|
951
|
+
};
|
|
952
|
+
this.reservations.set(sandbox.dispatchAttemptId, reservation);
|
|
953
|
+
return {
|
|
954
|
+
accepted: true,
|
|
955
|
+
code: null,
|
|
956
|
+
message: null,
|
|
957
|
+
reservedUntil,
|
|
958
|
+
resources: requestedResources,
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
async handleStart(rawDispatch) {
|
|
962
|
+
const envelope = parseStartEnvelope(rawDispatch);
|
|
963
|
+
if (!envelope) {
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
let dispatch = await this.parseDispatchOrReport(envelope.dispatch);
|
|
967
|
+
if (!dispatch?.sandbox
|
|
968
|
+
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
969
|
+
|| dispatch.lease.id !== envelope.leaseId
|
|
970
|
+
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
971
|
+
return;
|
|
972
|
+
const active = this.activeSessions.get(dispatch.lease.id);
|
|
973
|
+
if (active?.kind === "dispatch"
|
|
974
|
+
&& active.fencingToken === dispatch.lease.fencingToken
|
|
975
|
+
&& active.dispatchAttemptId === dispatch.sandbox.dispatchAttemptId
|
|
976
|
+
&& active.runnerInstanceId === dispatch.sandbox.runnerInstanceId) {
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const reservation = this.reservations.get(dispatch.sandbox.dispatchAttemptId);
|
|
980
|
+
if (!reservation
|
|
981
|
+
|| reservation.leaseId !== dispatch.lease.id
|
|
982
|
+
|| reservation.fencingToken !== dispatch.lease.fencingToken
|
|
983
|
+
|| reservation.runnerInstanceId !== dispatch.sandbox.runnerInstanceId
|
|
984
|
+
|| Date.parse(reservation.reservedUntil) <= Date.now()) {
|
|
985
|
+
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
// Claim the exact reservation before redemption or any other post-validation
|
|
989
|
+
// await. A duplicate Start for the same reservation is an idempotent replay:
|
|
990
|
+
// it must neither redeem a one-time grant nor disturb the original owner.
|
|
991
|
+
if (reservation.startClaim)
|
|
992
|
+
return;
|
|
993
|
+
const startClaim = {
|
|
994
|
+
dispatchAttemptId: envelope.dispatchAttemptId,
|
|
995
|
+
reservation,
|
|
996
|
+
controller: new AbortController(),
|
|
997
|
+
};
|
|
998
|
+
reservation.startClaim = startClaim;
|
|
999
|
+
if (dispatch.apiKeySecretGrant) {
|
|
1000
|
+
this.releaseReservedDispatchHandoff(startClaim);
|
|
1001
|
+
await this.sendResult(dispatch, failureResult("Start rejected because protocol-v2 packets may not contain a plaintext provider grant.", [], failureFactsForCode("contract_plaintext_secret_rejected"))).catch(() => undefined);
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
if (dispatch.apiKeySecretGrantHandle) {
|
|
1005
|
+
let response;
|
|
1006
|
+
try {
|
|
1007
|
+
response = await this.redeemSecretGrant(dispatch);
|
|
1008
|
+
}
|
|
1009
|
+
catch (error) {
|
|
1010
|
+
this.releaseReservedDispatchHandoff(startClaim);
|
|
1011
|
+
throw error;
|
|
1012
|
+
}
|
|
1013
|
+
// Redemption may yield while a qualified Cancel releases this reservation.
|
|
1014
|
+
// Never launch from it or remove a successor reservation after that wait.
|
|
1015
|
+
if (!this.reservedDispatchHandoffIsCurrent(startClaim, dispatch)) {
|
|
1016
|
+
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
const grant = response.grant;
|
|
1020
|
+
if (!response.accepted
|
|
1021
|
+
|| !grant
|
|
1022
|
+
|| grant.grantId !== dispatch.apiKeySecretGrantHandle.grantId
|
|
1023
|
+
|| grant.provider !== dispatch.apiKeySecretGrantHandle.provider
|
|
1024
|
+
|| Date.parse(grant.expiresAt) <= Date.now()) {
|
|
1025
|
+
this.releaseReservedDispatchHandoff(startClaim);
|
|
1026
|
+
await this.sendResult(dispatch, failureResult(response.message ?? "Secret grant redemption was rejected.", [], failureFactsForCode("bridge.api_key_secret_grant_denied"))).catch(() => undefined);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
dispatch = { ...dispatch, apiKeySecretGrant: grant, apiKeySecretGrantHandle: null };
|
|
1030
|
+
}
|
|
1031
|
+
else if (dispatch.execution.requiresApiKeySecretGrant) {
|
|
1032
|
+
this.releaseReservedDispatchHandoff(startClaim);
|
|
1033
|
+
await this.sendResult(dispatch, failureResult("Start rejected because the provider secret grant handle is missing.", [], failureFactsForCode("bridge.api_key_secret_grant_missing"))).catch(() => undefined);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
dispatch = {
|
|
1037
|
+
...dispatch,
|
|
1038
|
+
sandbox: { ...dispatch.sandbox, requestedResources: reservation.resources },
|
|
1039
|
+
};
|
|
1040
|
+
await this.handleDispatch(dispatch, startClaim);
|
|
1041
|
+
}
|
|
1042
|
+
async redeemSecretGrant(dispatch) {
|
|
1043
|
+
const sandbox = dispatch.sandbox;
|
|
1044
|
+
const handle = dispatch.apiKeySecretGrantHandle;
|
|
1045
|
+
const connection = this.connection;
|
|
1046
|
+
if (!connection)
|
|
1047
|
+
return { accepted: false, code: "bridge.disconnected", message: "Bridge is disconnected.", grant: null };
|
|
1048
|
+
return await connection.invoke("RedeemSecretGrant", {
|
|
1049
|
+
dispatchAttemptId: sandbox.dispatchAttemptId,
|
|
1050
|
+
leaseId: dispatch.lease.id,
|
|
1051
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1052
|
+
runnerInstanceId: sandbox.runnerInstanceId,
|
|
1053
|
+
grantId: handle.grantId
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
async redeemPublishGrant(request, signal) {
|
|
1057
|
+
if (signal?.aborted)
|
|
1058
|
+
throw new Error(String(signal.reason ?? "publication cancelled"));
|
|
1059
|
+
const connection = this.connection;
|
|
1060
|
+
if (!connection)
|
|
1061
|
+
throw new Error("sandbox_output_publish_forbidden: bridge is disconnected.");
|
|
1062
|
+
const response = await connection.invoke("RedeemPublishGrant", request);
|
|
1063
|
+
if (!response.accepted || !response.credential) {
|
|
1064
|
+
throw new Error(`sandbox_output_publish_forbidden: ${response.message ?? response.code ?? "publication grant redemption was rejected"}`);
|
|
1065
|
+
}
|
|
1066
|
+
return response.credential;
|
|
1067
|
+
}
|
|
1068
|
+
async handleLeaseUpdate(request) {
|
|
1069
|
+
if (request.runnerInstanceId !== this.config.runnerInstanceId) {
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
const reservation = this.reservations.get(request.dispatchAttemptId);
|
|
1073
|
+
if (reservation && reservation.leaseId === request.leaseId && reservation.fencingToken === request.fencingToken) {
|
|
1074
|
+
reservation.expiresAt = request.expiresAt;
|
|
1075
|
+
}
|
|
1076
|
+
const active = this.activeSessions.get(request.leaseId);
|
|
1077
|
+
if (active && active.fencingToken === request.fencingToken && active.dispatchAttemptId === request.dispatchAttemptId) {
|
|
1078
|
+
active.leaseExpiresAt = request.expiresAt;
|
|
1079
|
+
if (active.sandboxed) {
|
|
1080
|
+
await this.sandboxRuntime.updateLease(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
|
|
1081
|
+
}
|
|
1082
|
+
else {
|
|
1083
|
+
await this.sessions.updateLease?.(request.dispatchAttemptId, request.fencingToken, request.expiresAt);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
async sendOfferDecision(dispatch, accepted, code = null, message = null, reservedUntil = null, reservedResources = null, sandboxConfigCommitSha = null) {
|
|
1088
|
+
if (!dispatch.sandbox)
|
|
1089
|
+
return;
|
|
1090
|
+
const payload = {
|
|
1091
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
1092
|
+
leaseId: dispatch.lease.id,
|
|
1093
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1094
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId,
|
|
1095
|
+
accepted,
|
|
1096
|
+
code,
|
|
1097
|
+
message,
|
|
1098
|
+
reservedUntil: accepted ? reservedUntil ?? dispatch.lease.expiresAt : null,
|
|
1099
|
+
reservedResources: accepted ? reservedResources : null,
|
|
1100
|
+
sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
|
|
1101
|
+
};
|
|
1102
|
+
await this.invokeAck("OfferDecision", payload);
|
|
1103
|
+
}
|
|
1104
|
+
async parseDispatchOrReport(rawDispatch) {
|
|
131
1105
|
try {
|
|
132
1106
|
return parseRunOnceDispatchPacket(rawDispatch);
|
|
133
1107
|
}
|
|
@@ -137,32 +1111,253 @@ export class ForgeBridgeService {
|
|
|
137
1111
|
return null;
|
|
138
1112
|
}
|
|
139
1113
|
const summary = invalidDispatchSummary(error);
|
|
140
|
-
|
|
1114
|
+
await this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
|
|
141
1115
|
{
|
|
142
1116
|
role: "runner",
|
|
143
1117
|
kind: "error",
|
|
144
1118
|
content: summary,
|
|
145
1119
|
eventType: "invalid_dispatch"
|
|
146
1120
|
}
|
|
147
|
-
])).catch(() => undefined);
|
|
1121
|
+
], failureFactsForCode("invalid_dispatch"))).catch(() => undefined);
|
|
1122
|
+
return null;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
parseChatTurnOrReport(rawDispatch) {
|
|
1126
|
+
try {
|
|
1127
|
+
return parseChatTurnDispatchPacket(rawDispatch, this.bridgeChatCapability());
|
|
1128
|
+
}
|
|
1129
|
+
catch (error) {
|
|
1130
|
+
logBridgeStatus(invalidChatTurnSummary(error));
|
|
148
1131
|
return null;
|
|
149
1132
|
}
|
|
150
1133
|
}
|
|
151
1134
|
async handleCancel(request) {
|
|
1135
|
+
if (request.dispatchAttemptId !== undefined && request.dispatchAttemptId !== null) {
|
|
1136
|
+
// Qualified cancellation is reservation-only. In particular, a delayed
|
|
1137
|
+
// pre-start Cancel must not abort an active session if Start won the race.
|
|
1138
|
+
const reservation = this.reservations.get(request.dispatchAttemptId);
|
|
1139
|
+
if (reservation
|
|
1140
|
+
&& request.runnerId === this.config.runnerId
|
|
1141
|
+
&& request.runnerInstanceId === this.config.runnerInstanceId
|
|
1142
|
+
&& reservation.runnerInstanceId === request.runnerInstanceId
|
|
1143
|
+
&& reservation.leaseId === request.leaseId
|
|
1144
|
+
&& reservation.fencingToken === request.fencingToken) {
|
|
1145
|
+
reservation.startClaim?.controller.abort(request.reason ?? "cancelled by server");
|
|
1146
|
+
this.reservations.delete(request.dispatchAttemptId);
|
|
1147
|
+
}
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
152
1150
|
const active = this.activeSessions.get(request.leaseId);
|
|
153
1151
|
if (!active || active.fencingToken !== request.fencingToken) {
|
|
154
1152
|
return;
|
|
155
1153
|
}
|
|
1154
|
+
if (request.runnerId && request.runnerId !== this.config.runnerId) {
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
if (request.runnerInstanceId && request.runnerInstanceId !== (active.runnerInstanceId ?? this.config.runnerInstanceId)) {
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
if (active.kind === "chat" && !this.chatCancelMatchesActiveTurn(active, request)) {
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
156
1163
|
active.controller.abort(request.reason ?? "cancelled by server");
|
|
157
1164
|
}
|
|
1165
|
+
chatCancelMatchesActiveTurn(active, request) {
|
|
1166
|
+
if (request.protocolVersion && request.protocolVersion !== bridgeChatProtocolVersion) {
|
|
1167
|
+
return false;
|
|
1168
|
+
}
|
|
1169
|
+
try {
|
|
1170
|
+
assertBridgeChatCallbackPayload(request.payload, "cancel payload");
|
|
1171
|
+
}
|
|
1172
|
+
catch {
|
|
1173
|
+
return false;
|
|
1174
|
+
}
|
|
1175
|
+
if (request.chatRunId && request.chatRunId !== active.chatRunId)
|
|
1176
|
+
return false;
|
|
1177
|
+
if (request.conversationId && request.conversationId !== active.conversationId)
|
|
1178
|
+
return false;
|
|
1179
|
+
if (request.turnId && request.turnId !== active.turnId)
|
|
1180
|
+
return false;
|
|
1181
|
+
if (request.providerThreadId && active.providerThreadId && request.providerThreadId !== active.providerThreadId) {
|
|
1182
|
+
return false;
|
|
1183
|
+
}
|
|
1184
|
+
return true;
|
|
1185
|
+
}
|
|
1186
|
+
async handleReap(request) {
|
|
1187
|
+
if (request.runnerId !== this.config.runnerId
|
|
1188
|
+
|| request.runnerInstanceId !== this.config.runnerInstanceId)
|
|
1189
|
+
return;
|
|
1190
|
+
await this.runSandboxMaintenance();
|
|
1191
|
+
await this.sendHeartbeat();
|
|
1192
|
+
}
|
|
1193
|
+
async handleReadinessProbe(rawRequest) {
|
|
1194
|
+
const request = parseReadinessProbe(rawRequest);
|
|
1195
|
+
if (!request || request.runnerInstanceId !== this.config.runnerInstanceId)
|
|
1196
|
+
return;
|
|
1197
|
+
const existing = this.activeReadinessProbes.get(request.requestId);
|
|
1198
|
+
if (existing)
|
|
1199
|
+
return;
|
|
1200
|
+
const controller = new AbortController();
|
|
1201
|
+
this.activeReadinessProbes.set(request.requestId, controller);
|
|
1202
|
+
const deadlineMs = Date.parse(request.expiresAt) - Date.now();
|
|
1203
|
+
const timer = setTimeout(() => controller.abort("readiness probe expired"), Math.max(0, deadlineMs));
|
|
1204
|
+
timer.unref?.();
|
|
1205
|
+
let result;
|
|
1206
|
+
try {
|
|
1207
|
+
const accepted = {
|
|
1208
|
+
schemaVersion: 1,
|
|
1209
|
+
requestId: request.requestId,
|
|
1210
|
+
fencingToken: request.fencingToken,
|
|
1211
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1212
|
+
acceptedAt: new Date().toISOString(),
|
|
1213
|
+
};
|
|
1214
|
+
await this.invokeAck("ReadinessAccepted", accepted);
|
|
1215
|
+
if (this.activeSessions.size > 0) {
|
|
1216
|
+
result = deferredReadinessResult(request, this.config.runnerInstanceId);
|
|
1217
|
+
}
|
|
1218
|
+
else if (!this.sessions.probeHostRuntime) {
|
|
1219
|
+
throw new Error("host_runtime_probe_unavailable: this bridge does not implement runtime readiness probes.");
|
|
1220
|
+
}
|
|
1221
|
+
else {
|
|
1222
|
+
const probe = await this.sessions.probeHostRuntime(this.normalizeReadinessProbe(request), controller.signal);
|
|
1223
|
+
result = readinessDeferralReason(controller.signal)
|
|
1224
|
+
? deferredReadinessResult(request, this.config.runnerInstanceId)
|
|
1225
|
+
: {
|
|
1226
|
+
schemaVersion: 1,
|
|
1227
|
+
requestId: request.requestId,
|
|
1228
|
+
fencingToken: request.fencingToken,
|
|
1229
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1230
|
+
...probe,
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
catch (error) {
|
|
1235
|
+
const deferredReason = readinessDeferralReason(controller.signal);
|
|
1236
|
+
result = {
|
|
1237
|
+
schemaVersion: 1,
|
|
1238
|
+
requestId: request.requestId,
|
|
1239
|
+
fencingToken: request.fencingToken,
|
|
1240
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1241
|
+
status: "failed",
|
|
1242
|
+
reasonCode: deferredReason ? "host_runtime_probe_deferred" : "host_runtime_probe_failed",
|
|
1243
|
+
reasonMessage: (deferredReason ?? errorMessage(error)).slice(0, 1000),
|
|
1244
|
+
checkedAt: new Date().toISOString(),
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
finally {
|
|
1248
|
+
clearTimeout(timer);
|
|
1249
|
+
this.activeReadinessProbes.delete(request.requestId);
|
|
1250
|
+
}
|
|
1251
|
+
try {
|
|
1252
|
+
await this.readinessResultOutbox.persist(result, request.expiresAt);
|
|
1253
|
+
}
|
|
1254
|
+
catch (error) {
|
|
1255
|
+
if (errorMessage(error).includes("runtime_readiness_result_conflict:")) {
|
|
1256
|
+
logBridgeStatus(`Readiness result ${request.requestId} rejected conflicting reuse of a durable request identity.`);
|
|
1257
|
+
await this.sendHeartbeat().catch(() => undefined);
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
logBridgeStatus(`Readiness result ${request.requestId} could not be persisted; attempting direct delivery: ${errorMessage(error)}`);
|
|
1261
|
+
await this.invokeAck("ReadinessResult", result).catch(deliveryError => {
|
|
1262
|
+
logBridgeStatus(`Readiness result ${request.requestId} could not be persisted or delivered: ${errorMessage(deliveryError)}`);
|
|
1263
|
+
});
|
|
1264
|
+
await this.sendHeartbeat().catch(() => undefined);
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
try {
|
|
1268
|
+
await this.flushReadinessResults();
|
|
1269
|
+
}
|
|
1270
|
+
catch (error) {
|
|
1271
|
+
logBridgeStatus(`Readiness result ${request.requestId} remains queued for replay: ${errorMessage(error)}`);
|
|
1272
|
+
}
|
|
1273
|
+
await this.sendHeartbeat().catch(() => undefined);
|
|
1274
|
+
}
|
|
1275
|
+
deferActiveReadinessProbes() {
|
|
1276
|
+
for (const controller of this.activeReadinessProbes.values()) {
|
|
1277
|
+
if (!controller.signal.aborted) {
|
|
1278
|
+
controller.abort("host_runtime_probe_deferred: foreground agent work took priority over background runtime readiness.");
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
async flushReadinessResults() {
|
|
1283
|
+
if (this.readinessResultFlush)
|
|
1284
|
+
return await this.readinessResultFlush;
|
|
1285
|
+
const flush = this.flushReadinessResultsCore();
|
|
1286
|
+
this.readinessResultFlush = flush;
|
|
1287
|
+
try {
|
|
1288
|
+
await flush;
|
|
1289
|
+
}
|
|
1290
|
+
finally {
|
|
1291
|
+
if (this.readinessResultFlush === flush)
|
|
1292
|
+
this.readinessResultFlush = null;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
async flushReadinessResultsCore() {
|
|
1296
|
+
for (const pending of await this.readinessResultOutbox.pending()) {
|
|
1297
|
+
if (Date.parse(pending.expiresAt) <= Date.now()) {
|
|
1298
|
+
await this.readinessResultOutbox.acknowledge(pending.result.requestId);
|
|
1299
|
+
continue;
|
|
1300
|
+
}
|
|
1301
|
+
try {
|
|
1302
|
+
await this.invokeAck("ReadinessResult", pending.result);
|
|
1303
|
+
await this.readinessResultOutbox.acknowledge(pending.result.requestId);
|
|
1304
|
+
}
|
|
1305
|
+
catch (error) {
|
|
1306
|
+
if (isReadinessNoLongerPending(error)) {
|
|
1307
|
+
await this.readinessResultOutbox.acknowledge(pending.result.requestId);
|
|
1308
|
+
continue;
|
|
1309
|
+
}
|
|
1310
|
+
throw error;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
158
1314
|
abortActiveSessions(reason) {
|
|
159
1315
|
for (const active of this.activeSessions.values()) {
|
|
160
1316
|
active.controller.abort(reason);
|
|
161
1317
|
}
|
|
162
1318
|
this.activeSessions.clear();
|
|
163
1319
|
}
|
|
1320
|
+
abortActiveReadinessProbes(reason) {
|
|
1321
|
+
for (const controller of this.activeReadinessProbes.values())
|
|
1322
|
+
controller.abort(reason);
|
|
1323
|
+
this.activeReadinessProbes.clear();
|
|
1324
|
+
}
|
|
1325
|
+
normalizeReadinessProbe(request) {
|
|
1326
|
+
const mapping = findRepoMapping({
|
|
1327
|
+
id: request.repoId,
|
|
1328
|
+
name: request.repoName,
|
|
1329
|
+
remoteUrl: request.remoteUrl,
|
|
1330
|
+
}, repoMappingsFor(this.config));
|
|
1331
|
+
const configuredPath = mapping?.localPath?.trim();
|
|
1332
|
+
if (!configuredPath) {
|
|
1333
|
+
throw new Error("bridge_repo_mapping_missing: readiness requires a matching local repository mapping.");
|
|
1334
|
+
}
|
|
1335
|
+
// Local configuration, not a path supplied by the server, grants checkout
|
|
1336
|
+
// authority. Equality also excludes a different child/sibling of this repo.
|
|
1337
|
+
const suppliedPath = request.runnerRepoLocalPath.trim();
|
|
1338
|
+
if (!path.isAbsolute(suppliedPath)
|
|
1339
|
+
|| (process.platform === "win32" && path.parse(suppliedPath).root.length === 1)) {
|
|
1340
|
+
throw new Error("bridge_repo_mapping_mismatch: readiness requires a fully qualified checkout path.");
|
|
1341
|
+
}
|
|
1342
|
+
const localPath = path.resolve(configuredPath);
|
|
1343
|
+
const requestedPath = path.resolve(suppliedPath);
|
|
1344
|
+
const pathsMatch = process.platform === "win32"
|
|
1345
|
+
? localPath.toLowerCase() === requestedPath.toLowerCase()
|
|
1346
|
+
: localPath === requestedPath;
|
|
1347
|
+
if (!pathsMatch) {
|
|
1348
|
+
throw new Error("bridge_repo_mapping_mismatch: readiness checkout differs from the locally configured repository.");
|
|
1349
|
+
}
|
|
1350
|
+
return {
|
|
1351
|
+
...request,
|
|
1352
|
+
runnerId: this.config.runnerId,
|
|
1353
|
+
runnerRepoLocalPath: localPath,
|
|
1354
|
+
cloneOnDemand: false,
|
|
1355
|
+
repoRoot: path.dirname(localPath),
|
|
1356
|
+
cleanupWorktrees: this.config.cleanupWorktrees,
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
164
1359
|
normalizeDispatch(dispatch) {
|
|
165
|
-
const mapping = findRepoMapping(dispatch, repoMappingsFor(this.config));
|
|
1360
|
+
const mapping = findRepoMapping(dispatch.repo, repoMappingsFor(this.config));
|
|
166
1361
|
const localPath = mapping?.localPath?.trim();
|
|
167
1362
|
const repoRoot = localPath ? path.dirname(path.resolve(localPath)) : this.config.defaultRepoRoot;
|
|
168
1363
|
const qaLaunchTarget = normalizeQaAppLaunchTarget(mapping?.qaAppLaunchTarget) ?? dispatch.qaBrowser?.launchTarget ?? null;
|
|
@@ -185,47 +1380,320 @@ export class ForgeBridgeService {
|
|
|
185
1380
|
: dispatch.qaBrowser
|
|
186
1381
|
};
|
|
187
1382
|
}
|
|
188
|
-
async sendResult(
|
|
1383
|
+
async sendResult(dispatch, result) {
|
|
189
1384
|
const payload = {
|
|
190
|
-
leaseId,
|
|
191
|
-
fencingToken,
|
|
192
|
-
|
|
1385
|
+
leaseId: dispatch.lease.id,
|
|
1386
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1387
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
1388
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
1389
|
+
// Every terminal writer, including early admission failures and exception
|
|
1390
|
+
// paths, crosses the same redaction boundary before outbox persistence.
|
|
1391
|
+
result: redactRunOnceResultPacket(result, exactSecrets(dispatch, this.config))
|
|
193
1392
|
};
|
|
1393
|
+
await this.sendResultPayload(payload, () => this.releaseActiveSessionAndRefreshCapacity(dispatch.lease.id, dispatch));
|
|
1394
|
+
}
|
|
1395
|
+
async sendLegacyResult(leaseId, fencingToken, result) {
|
|
1396
|
+
await this.sendResultPayload({ leaseId, fencingToken, result });
|
|
1397
|
+
}
|
|
1398
|
+
async sendResultPayload(payload, beforeDelivery) {
|
|
1399
|
+
// Register before persistence: replay can observe a record as soon as the
|
|
1400
|
+
// durable write becomes visible, even before persist() has returned.
|
|
1401
|
+
let releaseHandoff;
|
|
1402
|
+
const priorHandoff = this.dispatchResultHandoffs.get(payload.leaseId);
|
|
1403
|
+
const handoff = new Promise(resolve => { releaseHandoff = resolve; });
|
|
1404
|
+
this.dispatchResultHandoffs.set(payload.leaseId, handoff);
|
|
1405
|
+
let persisted = false;
|
|
1406
|
+
try {
|
|
1407
|
+
try {
|
|
1408
|
+
await this.dispatchResultOutbox.persist(payload);
|
|
1409
|
+
persisted = true;
|
|
1410
|
+
this.dispatchResultGeneration += 1;
|
|
1411
|
+
}
|
|
1412
|
+
catch (error) {
|
|
1413
|
+
logBridgeStatus(`Dispatch result ${payload.leaseId} could not be persisted; attempting direct delivery: ${errorMessage(error)}`);
|
|
1414
|
+
}
|
|
1415
|
+
await priorHandoff;
|
|
1416
|
+
await beforeDelivery?.();
|
|
1417
|
+
}
|
|
1418
|
+
finally {
|
|
1419
|
+
releaseHandoff();
|
|
1420
|
+
if (this.dispatchResultHandoffs.get(payload.leaseId) === handoff)
|
|
1421
|
+
this.dispatchResultHandoffs.delete(payload.leaseId);
|
|
1422
|
+
}
|
|
1423
|
+
if (!persisted) {
|
|
1424
|
+
await this.sendResultPayloadDirect(payload);
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
await this.flushDispatchResults().catch(error => {
|
|
1428
|
+
logBridgeStatus(`Dispatch result ${payload.leaseId} remains queued for replay: ${errorMessage(error)}`);
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
async sendResultPayloadDirect(payload) {
|
|
194
1432
|
try {
|
|
195
1433
|
await this.invokeAck("DispatchResult", payload);
|
|
196
1434
|
}
|
|
197
1435
|
catch (error) {
|
|
198
|
-
if (isDispatchNoLongerPending(error))
|
|
1436
|
+
if (isDispatchNoLongerPending(error))
|
|
1437
|
+
return;
|
|
1438
|
+
throw error;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
async flushDispatchResults(force = false) {
|
|
1442
|
+
if (!force && this.dispatchResultGeneration === this.dispatchResultFlushedGeneration)
|
|
1443
|
+
return;
|
|
1444
|
+
if (this.dispatchResultFlush) {
|
|
1445
|
+
await this.dispatchResultFlush;
|
|
1446
|
+
if (!force && this.dispatchResultGeneration === this.dispatchResultFlushedGeneration)
|
|
199
1447
|
return;
|
|
1448
|
+
}
|
|
1449
|
+
const flush = this.flushDispatchResultsCore();
|
|
1450
|
+
this.dispatchResultFlush = flush;
|
|
1451
|
+
try {
|
|
1452
|
+
await flush;
|
|
1453
|
+
}
|
|
1454
|
+
finally {
|
|
1455
|
+
if (this.dispatchResultFlush === flush)
|
|
1456
|
+
this.dispatchResultFlush = null;
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
async flushDispatchResultsCore() {
|
|
1460
|
+
const startedGeneration = this.dispatchResultGeneration;
|
|
1461
|
+
while (true) {
|
|
1462
|
+
const records = await this.dispatchResultOutbox.pending();
|
|
1463
|
+
for (const pending of records) {
|
|
1464
|
+
// Periodic heartbeats and reconnect replay share the same release
|
|
1465
|
+
// barrier as the terminal writer. Restart replay has no live handoff.
|
|
1466
|
+
while (this.dispatchResultHandoffs.has(pending.payload.leaseId)) {
|
|
1467
|
+
await this.dispatchResultHandoffs.get(pending.payload.leaseId);
|
|
1468
|
+
}
|
|
1469
|
+
try {
|
|
1470
|
+
await this.sendResultPayloadDirect(pending.payload);
|
|
1471
|
+
await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
|
|
1472
|
+
}
|
|
1473
|
+
catch (error) {
|
|
1474
|
+
if (isDispatchNoLongerPending(error)) {
|
|
1475
|
+
await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (this.isReplacedRunnerInstanceResult(pending.payload, error)) {
|
|
1479
|
+
try {
|
|
1480
|
+
await this.dispatchResultOutbox.quarantine(pending);
|
|
1481
|
+
}
|
|
1482
|
+
catch (quarantineError) {
|
|
1483
|
+
// Keep the record and surface Forge's rejection: replay stays
|
|
1484
|
+
// deferred and a heartbeat tick does not count it as a failure.
|
|
1485
|
+
logBridgeStatus(`Dispatch result ${pending.payload.leaseId} from replaced runner instance ${pending.payload.runnerInstanceId} could not be quarantined: ${errorMessage(quarantineError)}`);
|
|
1486
|
+
throw error;
|
|
1487
|
+
}
|
|
1488
|
+
logBridgeStatus(`Quarantined dispatch result ${pending.payload.leaseId}: Forge rejected it because it belongs to replaced runner instance ${pending.payload.runnerInstanceId}. Forge's own recovery handles that instance's attempt; the redacted result is kept in ${dispatchResultQuarantineDirectory} for reconciliation.`);
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
throw error;
|
|
1492
|
+
}
|
|
200
1493
|
}
|
|
201
|
-
|
|
1494
|
+
if (records.length < 3)
|
|
1495
|
+
break;
|
|
202
1496
|
}
|
|
1497
|
+
if (this.dispatchResultGeneration === startedGeneration) {
|
|
1498
|
+
this.dispatchResultFlushedGeneration = startedGeneration;
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Forge binds each result to the runner instance that ran the attempt. On an
|
|
1503
|
+
* authoritative connection it rejects another instance's result with
|
|
1504
|
+
* bridge.stale_result_instance; Forge's own recovery handles that attempt,
|
|
1505
|
+
* so the record can never be delivered and must not block the replay queue.
|
|
1506
|
+
* bridge.stale_runner_instance means this connection is not authoritative
|
|
1507
|
+
* and says nothing about the record, so it never quarantines.
|
|
1508
|
+
*/
|
|
1509
|
+
isReplacedRunnerInstanceResult(payload, error) {
|
|
1510
|
+
return error instanceof BridgeCallbackRejectedError
|
|
1511
|
+
&& error.code === "bridge.stale_result_instance"
|
|
1512
|
+
&& typeof payload.runnerInstanceId === "string"
|
|
1513
|
+
&& payload.runnerInstanceId.toLowerCase() !== this.config.runnerInstanceId.toLowerCase();
|
|
203
1514
|
}
|
|
204
1515
|
startHeartbeat() {
|
|
205
1516
|
this.stopHeartbeat();
|
|
1517
|
+
this.consecutiveHeartbeatFailures = 0;
|
|
1518
|
+
this.reconnectingFromHeartbeatFailure = false;
|
|
206
1519
|
const intervalMs = positiveFiniteNumber(this.config.heartbeatIntervalMs, 30_000);
|
|
207
1520
|
this.heartbeatTimer = setInterval(() => {
|
|
208
|
-
this.
|
|
1521
|
+
void this.heartbeatTick();
|
|
209
1522
|
}, intervalMs);
|
|
210
1523
|
this.heartbeatTimer.unref?.();
|
|
211
1524
|
}
|
|
1525
|
+
async heartbeatTick() {
|
|
1526
|
+
if (this.heartbeatInFlight || this.reconnectingFromHeartbeatFailure)
|
|
1527
|
+
return;
|
|
1528
|
+
const connection = this.connection;
|
|
1529
|
+
if (!connection)
|
|
1530
|
+
return;
|
|
1531
|
+
this.heartbeatInFlight = true;
|
|
1532
|
+
try {
|
|
1533
|
+
// A rejected replay is an answer from Forge, so the connection is alive:
|
|
1534
|
+
// an undeliverable record must not count as a heartbeat failure and
|
|
1535
|
+
// force reconnects. Transport failures still do.
|
|
1536
|
+
await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
|
|
1537
|
+
await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
|
|
1538
|
+
await this.sendHeartbeat();
|
|
1539
|
+
this.consecutiveHeartbeatFailures = 0;
|
|
1540
|
+
}
|
|
1541
|
+
catch (error) {
|
|
1542
|
+
if (connection !== this.connection || this.stopped)
|
|
1543
|
+
return;
|
|
1544
|
+
this.consecutiveHeartbeatFailures += 1;
|
|
1545
|
+
logBridgeStatus(`Heartbeat ${this.consecutiveHeartbeatFailures} failed: ${errorMessage(error)}.`);
|
|
1546
|
+
if (this.consecutiveHeartbeatFailures < 2)
|
|
1547
|
+
return;
|
|
1548
|
+
this.reconnectingFromHeartbeatFailure = true;
|
|
1549
|
+
this.stopHeartbeat();
|
|
1550
|
+
logBridgeStatus("Heartbeat failed twice. Closing the stale connection so the Bridge can reconnect...");
|
|
1551
|
+
await connection.stop().catch(() => undefined);
|
|
1552
|
+
}
|
|
1553
|
+
finally {
|
|
1554
|
+
this.heartbeatInFlight = false;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
startLeaseWatchdog() {
|
|
1558
|
+
this.stopLeaseWatchdog();
|
|
1559
|
+
this.leaseWatchdogTimer = setInterval(() => this.expireLeases(), 1000);
|
|
1560
|
+
this.leaseWatchdogTimer.unref?.();
|
|
1561
|
+
}
|
|
1562
|
+
stopLeaseWatchdog() {
|
|
1563
|
+
if (this.leaseWatchdogTimer) {
|
|
1564
|
+
clearInterval(this.leaseWatchdogTimer);
|
|
1565
|
+
this.leaseWatchdogTimer = null;
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
expireLeases() {
|
|
1569
|
+
const now = Date.now();
|
|
1570
|
+
this.expireReservations(now);
|
|
1571
|
+
for (const active of this.activeSessions.values()) {
|
|
1572
|
+
if (Date.parse(active.leaseExpiresAt) <= now && !active.controller.signal.aborted) {
|
|
1573
|
+
active.controller.abort("dispatch lease expired");
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
expireReservations(now) {
|
|
1578
|
+
for (const [attemptId, reservation] of this.reservations) {
|
|
1579
|
+
if (Date.parse(reservation.expiresAt) <= now || Date.parse(reservation.reservedUntil) <= now) {
|
|
1580
|
+
this.reservations.delete(attemptId);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
212
1584
|
stopHeartbeat() {
|
|
213
1585
|
if (this.heartbeatTimer) {
|
|
214
1586
|
clearInterval(this.heartbeatTimer);
|
|
215
1587
|
this.heartbeatTimer = null;
|
|
216
1588
|
}
|
|
217
1589
|
}
|
|
1590
|
+
startSandboxMaintenance() {
|
|
1591
|
+
this.stopSandboxMaintenance();
|
|
1592
|
+
this.sandboxMaintenanceTimer = setInterval(() => {
|
|
1593
|
+
this.runSandboxMaintenance().catch(() => undefined);
|
|
1594
|
+
}, 60_000);
|
|
1595
|
+
this.sandboxMaintenanceTimer.unref?.();
|
|
1596
|
+
}
|
|
1597
|
+
stopSandboxMaintenance() {
|
|
1598
|
+
if (this.sandboxMaintenanceTimer) {
|
|
1599
|
+
clearInterval(this.sandboxMaintenanceTimer);
|
|
1600
|
+
this.sandboxMaintenanceTimer = null;
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
async runSandboxMaintenance() {
|
|
1604
|
+
if (this.sandboxMaintenanceRunning)
|
|
1605
|
+
return;
|
|
1606
|
+
this.sandboxMaintenanceRunning = true;
|
|
1607
|
+
try {
|
|
1608
|
+
const hostReap = await this.sessions.reapHostRuntime?.({
|
|
1609
|
+
runnerId: this.config.runnerId,
|
|
1610
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1611
|
+
});
|
|
1612
|
+
this.rememberRecoveredHostAttempts(hostReap);
|
|
1613
|
+
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
1614
|
+
logBridgeStatus(`Managed-host maintenance reaped ${hostReap.reaped} stale attempt(s) and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
|
|
1615
|
+
}
|
|
1616
|
+
if (this.config.dockerEnabled) {
|
|
1617
|
+
const preflight = await this.preflight.refresh();
|
|
1618
|
+
if (canReapManagedSandboxes(preflight)) {
|
|
1619
|
+
const attemptSnapshot = await this.readAttemptSnapshot();
|
|
1620
|
+
await this.sandboxRuntime.reap({ diskLow: preflight.diskLow, attemptSnapshot });
|
|
1621
|
+
await this.flushCleanupReports();
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
finally {
|
|
1626
|
+
this.sandboxMaintenanceRunning = false;
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
async readAttemptSnapshot() {
|
|
1630
|
+
const connection = this.connection;
|
|
1631
|
+
if (!connection)
|
|
1632
|
+
throw new Error("Bridge is not connected.");
|
|
1633
|
+
const response = await connection.invoke("AttemptSnapshot", {
|
|
1634
|
+
runnerInstanceId: this.config.runnerInstanceId
|
|
1635
|
+
});
|
|
1636
|
+
if (!response.accepted) {
|
|
1637
|
+
throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
|
|
1638
|
+
}
|
|
1639
|
+
return response.attempts ?? [];
|
|
1640
|
+
}
|
|
1641
|
+
async flushCleanupReports() {
|
|
1642
|
+
if (!this.sandboxRuntime.pendingCleanupReports || !this.sandboxRuntime.acknowledgeCleanupReport)
|
|
1643
|
+
return;
|
|
1644
|
+
for (const report of await this.sandboxRuntime.pendingCleanupReports()) {
|
|
1645
|
+
await this.invokeAck("CleanupReport", {
|
|
1646
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1647
|
+
report
|
|
1648
|
+
});
|
|
1649
|
+
await this.sandboxRuntime.acknowledgeCleanupReport(report.reportId);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
218
1652
|
async sendHeartbeat() {
|
|
1653
|
+
// Heartbeats are the recovery path for capacity-blocked work. Refresh the
|
|
1654
|
+
// dynamic sample before advertising it, while reusing the static Docker
|
|
1655
|
+
// capability snapshot established at startup or by an offer.
|
|
1656
|
+
if (this.config.dockerEnabled)
|
|
1657
|
+
await this.preflight.refreshCapacity();
|
|
1658
|
+
// A due probe can start a Docker Desktop recovery that runs for minutes.
|
|
1659
|
+
// Wait only as long as a normal probe takes, then advertise the last
|
|
1660
|
+
// snapshot so the server doesn't mark the runner offline meanwhile.
|
|
1661
|
+
const probeWait = new AbortController();
|
|
1662
|
+
await Promise.race([
|
|
1663
|
+
this.dockerEngineProbe.refresh().catch(() => undefined),
|
|
1664
|
+
delay(positiveFiniteNumber(this.config.heartbeatDockerProbeWaitMs ?? 15_000, 15_000), probeWait.signal),
|
|
1665
|
+
]);
|
|
1666
|
+
probeWait.abort();
|
|
1667
|
+
await this.sendHeartbeatSnapshot();
|
|
1668
|
+
}
|
|
1669
|
+
async sendHeartbeatSnapshot(signal) {
|
|
219
1670
|
await this.invokeAck("Heartbeat", {
|
|
220
1671
|
status: "online",
|
|
221
1672
|
capabilities: this.capabilities(),
|
|
222
1673
|
version: this.config.version,
|
|
223
1674
|
protocolVersion: this.config.protocolVersion
|
|
224
|
-
});
|
|
1675
|
+
}, { signal });
|
|
225
1676
|
}
|
|
226
1677
|
capabilities() {
|
|
1678
|
+
const preflight = this.preflight.current();
|
|
1679
|
+
const dockerEngine = this.dockerEngineProbe.current();
|
|
1680
|
+
const runtimeState = this.sandboxRuntime.snapshot();
|
|
1681
|
+
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
1682
|
+
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
1683
|
+
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
1684
|
+
const capacity = this.sandboxResourceCapacity(preflight, activeResources);
|
|
1685
|
+
const memoryAdmission = preflight ? buildMemoryAdmissionDiagnostics({
|
|
1686
|
+
sampledAt: preflight.sampledAt,
|
|
1687
|
+
totalMemoryBytes: preflight.totalMemoryBytes,
|
|
1688
|
+
rawAvailableMemoryBytes: preflight.rawAvailableMemoryBytes,
|
|
1689
|
+
stabilizedAvailableMemoryBytes: preflight.availableMemoryBytes,
|
|
1690
|
+
controlPlaneMemoryBytes: process.memoryUsage().rss,
|
|
1691
|
+
reserveMemoryBytes: preflight.hostReserveBytes,
|
|
1692
|
+
committedMemoryBytes: used.memoryBytes,
|
|
1693
|
+
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
1694
|
+
}) : null;
|
|
227
1695
|
return {
|
|
228
|
-
schemaVersion:
|
|
1696
|
+
schemaVersion: 7,
|
|
229
1697
|
activeSessionCount: this.activeSessions.size,
|
|
230
1698
|
cliProviders: this.config.cliProviders,
|
|
231
1699
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -233,32 +1701,210 @@ export class ForgeBridgeService {
|
|
|
233
1701
|
repoMappings: repoMappingsFor(this.config),
|
|
234
1702
|
os: this.config.os,
|
|
235
1703
|
sandboxProfiles: this.config.sandboxProfiles,
|
|
1704
|
+
runnerInstanceId: this.config.runnerInstanceId,
|
|
1705
|
+
trustDomainId: this.config.trustDomainId,
|
|
1706
|
+
executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
|
|
1707
|
+
dockerEngine,
|
|
1708
|
+
toolchains: {
|
|
1709
|
+
...this.hostCapabilities.toolchains,
|
|
1710
|
+
docker: {
|
|
1711
|
+
available: dockerEngine?.available === true,
|
|
1712
|
+
executable: this.config.dockerExecutable,
|
|
1713
|
+
version: dockerEngine?.runtimeVersion ?? null,
|
|
1714
|
+
},
|
|
1715
|
+
},
|
|
1716
|
+
playwrightProjects: this.hostCapabilities.playwrightProjects,
|
|
1717
|
+
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
1718
|
+
providerConnectivity: this.hostCapabilities.providerConnectivity,
|
|
1719
|
+
host: this.hostLoad.facts(),
|
|
1720
|
+
load: this.hostLoad.current(),
|
|
1721
|
+
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
1722
|
+
reservedSandboxCount: reserved,
|
|
1723
|
+
activeSandboxCount: runtimeState.active,
|
|
1724
|
+
startingSandboxCount: runtimeState.starting,
|
|
1725
|
+
degradedReservationCount: runtimeState.degraded,
|
|
1726
|
+
sandboxRuntimes: preflight?.healthy ? ["docker"] : [],
|
|
1727
|
+
sandboxRuntimeVersion: preflight?.runtimeVersion ?? null,
|
|
1728
|
+
sandboxFeatures: preflight?.features ?? null,
|
|
1729
|
+
allowsOpenPublicSandbox: this.config.allowOpenPublicSandbox,
|
|
1730
|
+
sandboxPublicationModes: [this.config.sandboxPublicationMode ?? "shared_filesystem"],
|
|
1731
|
+
sandboxAuthModes: sandboxAuthModesFor(this.config),
|
|
1732
|
+
availableMemoryBytes: memoryAdmission?.availableForAdmissionBytes ?? null,
|
|
1733
|
+
availableCpuMillis: preflight ? Math.max(0, capacity.cpuMillis - used.cpuMillis) : null,
|
|
1734
|
+
availableWorkspaceBytes: preflight ? Math.max(0, capacity.workspaceBytes - used.workspaceBytes) : null,
|
|
1735
|
+
diskLow: preflight?.diskLow ?? null,
|
|
1736
|
+
preflightGeneration: preflight?.generation ?? 0,
|
|
1737
|
+
sandboxUnavailableCode: this.config.dockerEnabled ? preflight?.unavailableCode ?? null : "docker_disabled",
|
|
1738
|
+
sandboxUnavailableReason: this.config.dockerEnabled ? preflight?.unavailableReason ?? null : "Docker sandboxing is disabled by runner configuration.",
|
|
1739
|
+
sandboxMemoryCapacity: preflight ? {
|
|
1740
|
+
defaultWorkerMemoryLimitBytes: this.config.defaultSandboxWorkerMemoryLimitBytes,
|
|
1741
|
+
defaultServiceMemoryLimitBytes: this.config.defaultSandboxServiceMemoryLimitBytes,
|
|
1742
|
+
runtimeOverheadBytes: this.config.sandboxRuntimeOverheadBytes,
|
|
1743
|
+
hostReserveBytes: preflight.hostReserveBytes,
|
|
1744
|
+
activeReservationBytes: used.memoryBytes,
|
|
1745
|
+
daemonTotalBytes: preflight.totalMemoryBytes,
|
|
1746
|
+
daemonAvailableBytes: preflight.rawDaemonAvailableMemoryBytes ?? 0,
|
|
1747
|
+
hostAvailableBytes: preflight.rawHostAvailableMemoryBytes,
|
|
1748
|
+
conservativeAvailableBytes: preflight.rawAvailableMemoryBytes,
|
|
1749
|
+
availableForAdmissionBytes: memoryAdmission.availableForAdmissionBytes,
|
|
1750
|
+
memoryAdmission: memoryAdmission,
|
|
1751
|
+
} : null,
|
|
1752
|
+
hostRuntime: this.sessions.runtimeCapacity?.() ?? null,
|
|
236
1753
|
supportsApiSecretGrant: this.config.supportsApiSecretGrant,
|
|
237
1754
|
supportsManagedWorktrees: this.config.supportsManagedWorktrees,
|
|
238
1755
|
supportsManagedForgeArtifacts: this.config.supportsManagedForgeArtifacts,
|
|
239
1756
|
supportsRunnerAuthoredPhaseArtifacts: this.config.supportsRunnerAuthoredPhaseArtifacts,
|
|
240
|
-
supportsDraftRunOnce: this.config.supportsDraftRunOnce
|
|
1757
|
+
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
1758
|
+
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
1759
|
+
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
|
|
1760
|
+
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
|
|
241
1761
|
};
|
|
242
1762
|
}
|
|
243
|
-
async
|
|
244
|
-
const
|
|
245
|
-
if (!
|
|
246
|
-
|
|
1763
|
+
async requiredCapabilityFailure(dispatch) {
|
|
1764
|
+
const requiredCapabilities = dispatch.qaScope?.required_capabilities ?? [];
|
|
1765
|
+
if (!requiredCapabilities.includes("docker_engine"))
|
|
1766
|
+
return null;
|
|
1767
|
+
const executionMode = dispatch.sandbox?.executionMode;
|
|
1768
|
+
if (executionMode === "docker") {
|
|
1769
|
+
return dockerEngineRequirementFailure(requiredCapabilities, executionMode, null);
|
|
1770
|
+
}
|
|
1771
|
+
return dockerEngineRequirementFailure(requiredCapabilities, executionMode, await this.dockerEngineProbe.refresh(true));
|
|
1772
|
+
}
|
|
1773
|
+
usedSandboxResources(degradedReservations) {
|
|
1774
|
+
const resources = [
|
|
1775
|
+
...[...this.reservations.values()]
|
|
1776
|
+
.filter(reservation => reservation.sandboxed)
|
|
1777
|
+
.map(reservation => reservation.resources),
|
|
1778
|
+
...[...this.activeSessions.values()]
|
|
1779
|
+
.filter(session => session.sandboxed)
|
|
1780
|
+
.map(session => session.resources),
|
|
1781
|
+
...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
|
|
1782
|
+
];
|
|
1783
|
+
return sumSandboxResources(resources);
|
|
1784
|
+
}
|
|
1785
|
+
activeSandboxResources(degradedReservations) {
|
|
1786
|
+
return sumSandboxResources([
|
|
1787
|
+
...[...this.activeSessions.values()]
|
|
1788
|
+
.filter(session => session.sandboxed)
|
|
1789
|
+
.map(session => session.resources),
|
|
1790
|
+
...Array.from({ length: degradedReservations }, () => defaultSandboxResources())
|
|
1791
|
+
]);
|
|
1792
|
+
}
|
|
1793
|
+
sandboxResourceCapacity(preflight, activeResources) {
|
|
1794
|
+
if (!preflight)
|
|
1795
|
+
return zeroSandboxResources();
|
|
1796
|
+
return {
|
|
1797
|
+
// Host free memory and disk already reflect active containers. Add their
|
|
1798
|
+
// commitments back to form a stable total capacity, then subtract them
|
|
1799
|
+
// exactly once in usedSandboxResources.
|
|
1800
|
+
sandboxSlots: Math.min(this.config.maxConcurrentSandboxes, preflight.maxConcurrentSandboxes + activeResources.sandboxSlots),
|
|
1801
|
+
cpuMillis: preflight.availableCpuMillis,
|
|
1802
|
+
workerMemoryLimitBytes: 0,
|
|
1803
|
+
serviceMemoryLimitBytes: 0,
|
|
1804
|
+
runtimeOverheadBytes: 0,
|
|
1805
|
+
memoryBytes: sandboxMemoryCommitmentCapacity(preflight, activeResources.memoryBytes),
|
|
1806
|
+
workspaceBytes: Math.max(0, preflight.availableWorkspaceBytes
|
|
1807
|
+
- this.config.minimumWorkspaceBytes
|
|
1808
|
+
+ activeResources.workspaceBytes),
|
|
1809
|
+
pids: this.config.sandboxPidCapacity,
|
|
1810
|
+
buildSlots: this.config.maxConcurrentSandboxBuilds
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
async invokeAck(methodName, payload, options = {}) {
|
|
1814
|
+
let storageRecoveryAttempt = 0;
|
|
1815
|
+
let callbackTimeoutAttempt = 0;
|
|
1816
|
+
while (true) {
|
|
1817
|
+
if (options.signal?.aborted) {
|
|
1818
|
+
throw new Error(String(options.signal.reason ?? `${methodName} callback was cancelled.`));
|
|
1819
|
+
}
|
|
1820
|
+
const connection = this.connection;
|
|
1821
|
+
if (!connection) {
|
|
1822
|
+
throw new Error("Bridge is not connected.");
|
|
1823
|
+
}
|
|
1824
|
+
await this.waitForTransportRecovery(connection, this.transportRecovery, options.signal);
|
|
1825
|
+
const recoveryGeneration = this.transportRecoveryGeneration;
|
|
1826
|
+
try {
|
|
1827
|
+
const ack = await waitForCallbackAck(connection.invoke(methodName, payload), methodName, positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000), options.signal);
|
|
1828
|
+
if (!ack.accepted) {
|
|
1829
|
+
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? `${methodName} callback was rejected.`);
|
|
1830
|
+
}
|
|
1831
|
+
return ack;
|
|
1832
|
+
}
|
|
1833
|
+
catch (error) {
|
|
1834
|
+
if (options.signal?.aborted)
|
|
1835
|
+
throw error;
|
|
1836
|
+
if (connection !== this.connection || this.stopped)
|
|
1837
|
+
throw error;
|
|
1838
|
+
const recovery = this.transportRecovery;
|
|
1839
|
+
if (recovery && recovery.generation > recoveryGeneration) {
|
|
1840
|
+
await this.waitForTransportRecovery(connection, recovery, options.signal);
|
|
1841
|
+
continue;
|
|
1842
|
+
}
|
|
1843
|
+
if (isProviderStorageUnavailable(error)) {
|
|
1844
|
+
const backoff = this.config.reconnectBackoffMs[Math.min(storageRecoveryAttempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
|
|
1845
|
+
storageRecoveryAttempt += 1;
|
|
1846
|
+
logBridgeStatus(`${methodName} reached Forge while storage was recovering. Retrying callback ${storageRecoveryAttempt} in ${formatDelay(backoff)}...`);
|
|
1847
|
+
await delay(backoff, options.signal);
|
|
1848
|
+
continue;
|
|
1849
|
+
}
|
|
1850
|
+
if (options.replayCallbackTimeout && isBridgeCallbackTimeout(error)) {
|
|
1851
|
+
const backoff = this.config.reconnectBackoffMs[Math.min(callbackTimeoutAttempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
|
|
1852
|
+
callbackTimeoutAttempt += 1;
|
|
1853
|
+
logBridgeStatus(`${methodName} acknowledgement timed out. Replaying the idempotent callback ${callbackTimeoutAttempt} in ${formatDelay(backoff)}...`);
|
|
1854
|
+
await delay(backoff, options.signal);
|
|
1855
|
+
continue;
|
|
1856
|
+
}
|
|
1857
|
+
throw error;
|
|
1858
|
+
}
|
|
247
1859
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
1860
|
+
}
|
|
1861
|
+
beginTransportRecovery() {
|
|
1862
|
+
if (this.transportRecovery && !this.transportRecovery.completed)
|
|
1863
|
+
return;
|
|
1864
|
+
let resolve = () => undefined;
|
|
1865
|
+
const promise = new Promise((complete) => { resolve = complete; });
|
|
1866
|
+
this.transportRecoveryGeneration += 1;
|
|
1867
|
+
this.transportRecovery = {
|
|
1868
|
+
generation: this.transportRecoveryGeneration,
|
|
1869
|
+
promise,
|
|
1870
|
+
resolve,
|
|
1871
|
+
completed: false,
|
|
1872
|
+
error: null,
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
completeTransportRecovery(error = null) {
|
|
1876
|
+
const recovery = this.transportRecovery;
|
|
1877
|
+
if (!recovery || recovery.completed)
|
|
1878
|
+
return;
|
|
1879
|
+
recovery.completed = true;
|
|
1880
|
+
recovery.error = error;
|
|
1881
|
+
recovery.resolve();
|
|
1882
|
+
}
|
|
1883
|
+
async waitForTransportRecovery(connection, recovery, signal) {
|
|
1884
|
+
if (!recovery)
|
|
1885
|
+
return;
|
|
1886
|
+
if (recovery.completed) {
|
|
1887
|
+
if (recovery.error)
|
|
1888
|
+
throw recovery.error;
|
|
1889
|
+
return;
|
|
251
1890
|
}
|
|
252
|
-
|
|
1891
|
+
await waitForPromiseOrAbort(recovery.promise, signal);
|
|
1892
|
+
signal?.throwIfAborted();
|
|
1893
|
+
if (connection !== this.connection)
|
|
1894
|
+
throw new Error("Bridge connection changed while recovering.");
|
|
1895
|
+
if (recovery.error)
|
|
1896
|
+
throw recovery.error;
|
|
253
1897
|
}
|
|
254
1898
|
async waitForClose(signal) {
|
|
255
1899
|
if (!this.closed) {
|
|
256
1900
|
return;
|
|
257
1901
|
}
|
|
258
|
-
await
|
|
1902
|
+
await waitForPromiseOrAbort(this.closed, signal);
|
|
259
1903
|
}
|
|
260
1904
|
async stopConnection() {
|
|
261
1905
|
this.stopHeartbeat();
|
|
1906
|
+
this.stopLeaseWatchdog();
|
|
1907
|
+
this.stopSandboxMaintenance();
|
|
262
1908
|
if (this.connection) {
|
|
263
1909
|
await this.connection.stop().catch(() => undefined);
|
|
264
1910
|
this.connection = null;
|
|
@@ -273,12 +1919,37 @@ class BridgeCallbackRejectedError extends Error {
|
|
|
273
1919
|
this.name = "BridgeCallbackRejectedError";
|
|
274
1920
|
}
|
|
275
1921
|
}
|
|
1922
|
+
function deferRejectedReplay(kind) {
|
|
1923
|
+
return error => {
|
|
1924
|
+
if (!(error instanceof BridgeCallbackRejectedError))
|
|
1925
|
+
throw error;
|
|
1926
|
+
logBridgeStatus(`${kind} result replay deferred: ${errorMessage(error)}`);
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
276
1929
|
function isDispatchNoLongerPending(error) {
|
|
277
1930
|
if (error instanceof BridgeCallbackRejectedError) {
|
|
278
1931
|
return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
|
|
279
1932
|
}
|
|
280
1933
|
return error instanceof Error && error.message === "Dispatch is no longer pending.";
|
|
281
1934
|
}
|
|
1935
|
+
function isReadinessNoLongerPending(error) {
|
|
1936
|
+
return error instanceof BridgeCallbackRejectedError
|
|
1937
|
+
&& (error.code === "bridge.stale_readiness_probe" || error.code === "bridge.stale_runner_instance");
|
|
1938
|
+
}
|
|
1939
|
+
function isProviderStorageUnavailable(error) {
|
|
1940
|
+
const message = errorMessage(error).toLowerCase();
|
|
1941
|
+
return message.includes("provider_storage_unavailable")
|
|
1942
|
+
|| (message.includes("storage is recovering") && message.includes("503"));
|
|
1943
|
+
}
|
|
1944
|
+
function isBridgeCallbackTimeout(error) {
|
|
1945
|
+
return errorMessage(error).startsWith("bridge_callback_timeout:");
|
|
1946
|
+
}
|
|
1947
|
+
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
|
|
1948
|
+
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1949
|
+
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1950
|
+
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1951
|
+
return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback))), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot)));
|
|
1952
|
+
}
|
|
282
1953
|
export class SignalRBridgeConnectionFactory {
|
|
283
1954
|
create(config) {
|
|
284
1955
|
return new SignalRBridgeConnection(config);
|
|
@@ -293,10 +1964,20 @@ export class SignalRBridgeConnection {
|
|
|
293
1964
|
url.searchParams.set("runnerId", config.runnerId);
|
|
294
1965
|
this.connection = new HubConnectionBuilder()
|
|
295
1966
|
.withUrl(url.toString(), {
|
|
296
|
-
|
|
1967
|
+
// Query-string access tokens are intentionally rejected by the API. The bridge is
|
|
1968
|
+
// a Node CLI, so use long polling where Authorization headers are carried on each
|
|
1969
|
+
// HTTP request instead of relying on browser/WebSocket token fallbacks.
|
|
1970
|
+
transport: HttpTransportType.LongPolling,
|
|
1971
|
+
headers: {
|
|
1972
|
+
Authorization: `Bearer ${config.deviceToken}`
|
|
1973
|
+
}
|
|
297
1974
|
})
|
|
1975
|
+
.withAutomaticReconnect([...config.reconnectBackoffMs])
|
|
298
1976
|
.configureLogging(LogLevel.Warning)
|
|
299
1977
|
.build();
|
|
1978
|
+
this.connection.on("Superseded", () => {
|
|
1979
|
+
void this.connection.stop().catch(() => undefined);
|
|
1980
|
+
});
|
|
300
1981
|
}
|
|
301
1982
|
start() {
|
|
302
1983
|
return this.connection.start();
|
|
@@ -307,16 +1988,54 @@ export class SignalRBridgeConnection {
|
|
|
307
1988
|
onClose(handler) {
|
|
308
1989
|
this.connection.onclose(handler);
|
|
309
1990
|
}
|
|
1991
|
+
onReconnecting(handler) {
|
|
1992
|
+
this.connection.onreconnecting(handler);
|
|
1993
|
+
}
|
|
1994
|
+
onReconnected(handler) {
|
|
1995
|
+
this.connection.onreconnected((connectionId) => {
|
|
1996
|
+
void Promise.resolve(handler(connectionId)).catch(() => undefined);
|
|
1997
|
+
});
|
|
1998
|
+
}
|
|
310
1999
|
onDispatch(handler) {
|
|
311
2000
|
this.connection.on("Dispatch", (raw) => {
|
|
312
2001
|
void handler(raw).catch(() => undefined);
|
|
313
2002
|
});
|
|
314
2003
|
}
|
|
2004
|
+
onChatTurn(handler) {
|
|
2005
|
+
this.connection.on("ChatTurn", (raw) => {
|
|
2006
|
+
void handler(raw).catch(() => undefined);
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
2009
|
+
onOffer(handler) {
|
|
2010
|
+
this.connection.on("Offer", (raw) => {
|
|
2011
|
+
void handler(raw).catch(() => undefined);
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
onStart(handler) {
|
|
2015
|
+
this.connection.on("Start", (raw) => {
|
|
2016
|
+
void handler(raw).catch(() => undefined);
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
onLeaseUpdate(handler) {
|
|
2020
|
+
this.connection.on("LeaseUpdate", (request) => {
|
|
2021
|
+
void handler(request).catch(() => undefined);
|
|
2022
|
+
});
|
|
2023
|
+
}
|
|
315
2024
|
onCancel(handler) {
|
|
316
2025
|
this.connection.on("Cancel", (request) => {
|
|
317
2026
|
void handler(request).catch(() => undefined);
|
|
318
2027
|
});
|
|
319
2028
|
}
|
|
2029
|
+
onReap(handler) {
|
|
2030
|
+
this.connection.on("Reap", (request) => {
|
|
2031
|
+
void handler(request).catch(() => undefined);
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
onReadinessProbe(handler) {
|
|
2035
|
+
this.connection.on("ReadinessProbe", (request) => {
|
|
2036
|
+
void handler(request).catch(() => undefined);
|
|
2037
|
+
});
|
|
2038
|
+
}
|
|
320
2039
|
invoke(methodName, payload) {
|
|
321
2040
|
return this.connection.invoke(methodName, payload);
|
|
322
2041
|
}
|
|
@@ -324,9 +2043,42 @@ export class SignalRBridgeConnection {
|
|
|
324
2043
|
export function defaultBridgeServiceConfig(overrides = {}) {
|
|
325
2044
|
const defaults = defaultForgeBridgeConfig();
|
|
326
2045
|
const cliProviders = splitCsv(process.env.FORGE_CLI_PROVIDERS ?? "codex");
|
|
2046
|
+
const configuredSandboxHostMemoryReserveBytes = optionalPositiveFiniteNumber(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES);
|
|
2047
|
+
const sandboxPublicationMode = process.env.FORGE_SANDBOX_PUBLICATION_MODE === "bridge_push" ? "bridge_push" : "shared_filesystem";
|
|
327
2048
|
const config = {
|
|
328
2049
|
serverUrl: process.env.FORGE_URL ?? "http://localhost:5208",
|
|
329
2050
|
runnerId: process.env.FORGE_RUNNER_ID ?? "",
|
|
2051
|
+
runnerInstanceId: process.env.FORGE_RUNNER_INSTANCE_ID ?? randomUUID(),
|
|
2052
|
+
trustDomainId: process.env.FORGE_TRUST_DOMAIN_ID ?? "default",
|
|
2053
|
+
maxConcurrentSandboxes: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOXES ?? 3), 3),
|
|
2054
|
+
maxConcurrentSandboxBuilds: positiveFiniteNumber(Number(process.env.FORGE_MAX_CONCURRENT_SANDBOX_BUILDS ?? 1), 1),
|
|
2055
|
+
sandboxPidCapacity: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_PID_CAPACITY ?? 2048), 2048),
|
|
2056
|
+
dockerEnabled: process.env.FORGE_DOCKER_SANDBOX !== "false",
|
|
2057
|
+
allowOpenPublicSandbox: process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX === "true",
|
|
2058
|
+
sandboxPublicationMode,
|
|
2059
|
+
dockerExecutable: process.env.FORGE_DOCKER_EXECUTABLE ?? "docker",
|
|
2060
|
+
dockerContext: process.env.FORGE_DOCKER_CONTEXT ?? "",
|
|
2061
|
+
dockerDesktopRecoveryEnabled: process.env.FORGE_DOCKER_DESKTOP_AUTO_RECOVERY === "true",
|
|
2062
|
+
dockerRecoveryFailureThreshold: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_FAILURE_THRESHOLD ?? 3), 3),
|
|
2063
|
+
dockerRecoveryCooldownMs: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_COOLDOWN_MS ?? 10 * 60_000), 10 * 60_000),
|
|
2064
|
+
dockerRecoveryStartupTimeoutMs: positiveFiniteNumber(Number(process.env.FORGE_DOCKER_RECOVERY_STARTUP_TIMEOUT_MS ?? 2 * 60_000), 2 * 60_000),
|
|
2065
|
+
sandboxStateRoot: process.env.FORGE_SANDBOX_STATE_ROOT ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes"),
|
|
2066
|
+
sandboxExecutionRoot: defaultHostExecutionRoot(),
|
|
2067
|
+
requireRootlessDocker: process.env.FORGE_REQUIRE_ROOTLESS_DOCKER === "true" || process.platform === "linux",
|
|
2068
|
+
diskHighWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_HIGH_WATERMARK_PERCENT ?? 85), 85),
|
|
2069
|
+
diskLowWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_LOW_WATERMARK_PERCENT ?? 75), 75),
|
|
2070
|
+
minimumWorkspaceBytes: positiveFiniteNumber(Number(process.env.FORGE_MINIMUM_WORKSPACE_BYTES ?? 10 * 1024 ** 3), 10 * 1024 ** 3),
|
|
2071
|
+
// Undefined means preflight derives the bounded reserve from the actual
|
|
2072
|
+
// Docker/host capacity domain after sampling it.
|
|
2073
|
+
sandboxHostMemoryReserveBytes: configuredSandboxHostMemoryReserveBytes,
|
|
2074
|
+
defaultSandboxWorkerMemoryLimitBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_WORKER_MEMORY_LIMIT_BYTES ?? 2 * 1024 ** 3), 2 * 1024 ** 3),
|
|
2075
|
+
defaultSandboxServiceMemoryLimitBytes: nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_SERVICE_MEMORY_LIMIT_BYTES ?? 0), 0),
|
|
2076
|
+
sandboxRuntimeOverheadBytes: Math.max(128 * 1024 ** 2, nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_RUNTIME_OVERHEAD_BYTES ?? 128 * 1024 ** 2), 128 * 1024 ** 2)),
|
|
2077
|
+
sandboxMemorySampleIntervalMs: Math.min(30_000, Math.max(250, positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_MEMORY_SAMPLE_INTERVAL_MS ?? 1000), 1000))),
|
|
2078
|
+
imageRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_COUNT ?? 3), 3),
|
|
2079
|
+
imageRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_IMAGE_RETENTION_TTL_MS ?? 7 * 24 * 60 * 60 * 1000), 7 * 24 * 60 * 60 * 1000),
|
|
2080
|
+
auditRetentionCount: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_COUNT ?? 200), 200),
|
|
2081
|
+
auditRetentionTtlMs: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_AUDIT_RETENTION_TTL_MS ?? 30 * 24 * 60 * 60 * 1000), 30 * 24 * 60 * 60 * 1000),
|
|
330
2082
|
deviceToken: process.env.FORGE_DEVICE_TOKEN ?? "",
|
|
331
2083
|
deviceName: process.env.FORGE_DEVICE_NAME ?? "",
|
|
332
2084
|
defaultRepoRoot: process.env.FORGE_REPO_ROOT ?? defaults.defaultRepoRoot,
|
|
@@ -342,17 +2094,25 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
342
2094
|
supportsManagedForgeArtifacts: true,
|
|
343
2095
|
supportsRunnerAuthoredPhaseArtifacts: true,
|
|
344
2096
|
supportsDraftRunOnce: true,
|
|
2097
|
+
supportsDraftAttachments: true,
|
|
2098
|
+
supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
|
|
2099
|
+
bridgeChat: bridgeChatCapabilityFor(cliProviders, providerStatusesFor(cliProviders)),
|
|
345
2100
|
version: process.env.FORGE_BRIDGE_VERSION ?? forgeBridgeVersion,
|
|
346
|
-
protocolVersion:
|
|
2101
|
+
protocolVersion: 4,
|
|
347
2102
|
minServerVersion: null,
|
|
348
2103
|
heartbeatIntervalMs: positiveFiniteNumber(Number(process.env.FORGE_HEARTBEAT_INTERVAL_MS ?? 30_000), 30_000),
|
|
2104
|
+
callbackAckTimeoutMs: positiveFiniteNumber(Number(process.env.FORGE_CALLBACK_ACK_TIMEOUT_MS ?? 30_000), 30_000),
|
|
349
2105
|
reconnectBackoffMs: [1000, 2000, 5000, 10000, 30000],
|
|
350
2106
|
...overrides
|
|
351
2107
|
};
|
|
352
2108
|
return {
|
|
353
2109
|
...config,
|
|
2110
|
+
providerStatuses: overrides.providerStatuses ?? providerStatusesFor(config.cliProviders),
|
|
354
2111
|
sandboxProfiles: config.sandboxProfiles ?? defaultSandboxProfiles(config.cliProviders),
|
|
355
|
-
|
|
2112
|
+
supportsDraftImageAttachments: (overrides.supportsDraftImageAttachments ?? true) && supportsDraftImageAttachmentsFor(config.cliProviders),
|
|
2113
|
+
bridgeChat: overrides.bridgeChat ?? bridgeChatCapabilityFor(config.cliProviders, overrides.providerStatuses ?? providerStatusesFor(config.cliProviders), config.bridgeChat),
|
|
2114
|
+
heartbeatIntervalMs: positiveFiniteNumber(config.heartbeatIntervalMs, 30_000),
|
|
2115
|
+
callbackAckTimeoutMs: positiveFiniteNumber(config.callbackAckTimeoutMs ?? 30_000, 30_000),
|
|
356
2116
|
};
|
|
357
2117
|
}
|
|
358
2118
|
export function resolveBridgeRunnerHubUrl(serverUrl) {
|
|
@@ -367,9 +2127,42 @@ function normalizeServerUrl(serverUrl) {
|
|
|
367
2127
|
function positiveFiniteNumber(value, fallback) {
|
|
368
2128
|
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
369
2129
|
}
|
|
2130
|
+
function optionalPositiveFiniteNumber(value) {
|
|
2131
|
+
if (value === undefined || value.trim().length === 0)
|
|
2132
|
+
return undefined;
|
|
2133
|
+
const parsed = Number(value);
|
|
2134
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
|
2135
|
+
}
|
|
2136
|
+
function nonNegativeFiniteNumber(value, fallback) {
|
|
2137
|
+
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
2138
|
+
}
|
|
370
2139
|
function providerStatusesFor(providers) {
|
|
371
2140
|
return Object.fromEntries(providers.map((provider) => [provider, { signedIn: true, version: "", models: configuredModelsFor(provider) }]));
|
|
372
2141
|
}
|
|
2142
|
+
function sandboxAuthModesFor(config) {
|
|
2143
|
+
return Object.fromEntries(config.cliProviders.map((provider) => {
|
|
2144
|
+
const modes = ["api_key"];
|
|
2145
|
+
if (sandboxBridgeCliAuthAvailable(config, provider)) {
|
|
2146
|
+
modes.push("bridge_cli");
|
|
2147
|
+
}
|
|
2148
|
+
return [provider, modes];
|
|
2149
|
+
}));
|
|
2150
|
+
}
|
|
2151
|
+
function sandboxBridgeCliAuthAvailable(config, provider) {
|
|
2152
|
+
if (provider.trim().toLowerCase() !== "codex") {
|
|
2153
|
+
return false;
|
|
2154
|
+
}
|
|
2155
|
+
const status = providerStatus(config, provider);
|
|
2156
|
+
if (status?.signedIn === false) {
|
|
2157
|
+
return false;
|
|
2158
|
+
}
|
|
2159
|
+
return codexSandboxProviderAuthAdapter.doctor().available;
|
|
2160
|
+
}
|
|
2161
|
+
function providerStatus(config, provider) {
|
|
2162
|
+
const normalized = provider.trim().toLowerCase();
|
|
2163
|
+
return Object.entries(config.providerStatuses)
|
|
2164
|
+
.find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
|
|
2165
|
+
}
|
|
373
2166
|
function defaultSandboxProfiles(providers, platform = process.platform) {
|
|
374
2167
|
if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
|
|
375
2168
|
return ["none"];
|
|
@@ -444,15 +2237,32 @@ function mappingKeys(mapping) {
|
|
|
444
2237
|
mapping.localPath ? `path:${path.resolve(mapping.localPath).toLowerCase()}` : null
|
|
445
2238
|
].filter((key) => Boolean(key));
|
|
446
2239
|
}
|
|
447
|
-
function findRepoMapping(
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
2240
|
+
function findRepoMapping(repo, mappings) {
|
|
2241
|
+
const usable = mappings.filter(mapping => Boolean(mapping.localPath?.trim()));
|
|
2242
|
+
const selectUnique = (candidates, identity) => {
|
|
2243
|
+
if (candidates.length > 1) {
|
|
2244
|
+
throw new Error(`bridge_repo_mapping_ambiguous: multiple local checkouts match ${identity}.`);
|
|
451
2245
|
}
|
|
452
|
-
return
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
2246
|
+
return candidates[0];
|
|
2247
|
+
};
|
|
2248
|
+
// Repository identity is authoritative. A same-name mapping for a different
|
|
2249
|
+
// repository must never win merely because it appears first in configuration.
|
|
2250
|
+
const byId = usable.filter(mapping => equalsIgnoreCase(mapping.repoId, repo.id));
|
|
2251
|
+
if (byId.length > 0)
|
|
2252
|
+
return selectUnique(byId, `repo id '${repo.id}'`);
|
|
2253
|
+
const byRemote = repo.remoteUrl?.trim()
|
|
2254
|
+
? usable.filter(mapping => !mapping.repoId?.trim()
|
|
2255
|
+
&& Boolean(mapping.remoteUrl?.trim())
|
|
2256
|
+
&& equalsIgnoreCase(mapping.remoteUrl, repo.remoteUrl))
|
|
2257
|
+
: [];
|
|
2258
|
+
if (byRemote.length > 0)
|
|
2259
|
+
return selectUnique(byRemote, `remote '${repo.remoteUrl}'`);
|
|
2260
|
+
const byName = usable.filter(mapping => !mapping.repoId?.trim()
|
|
2261
|
+
&& !mapping.remoteUrl?.trim()
|
|
2262
|
+
&& equalsIgnoreCase(mapping.name, repo.name));
|
|
2263
|
+
return byName.length > 0
|
|
2264
|
+
? selectUnique(byName, `repo name '${repo.name}'`)
|
|
2265
|
+
: undefined;
|
|
456
2266
|
}
|
|
457
2267
|
function normalizeQaAppLaunchTarget(target) {
|
|
458
2268
|
if (!target) {
|
|
@@ -464,10 +2274,11 @@ function normalizeQaAppLaunchTarget(target) {
|
|
|
464
2274
|
command: cleanString(target.command),
|
|
465
2275
|
working_directory: cleanString(target.working_directory),
|
|
466
2276
|
ready_url: cleanString(target.ready_url),
|
|
2277
|
+
managed_runtime_port: cleanString(target.managed_runtime_port),
|
|
467
2278
|
routes,
|
|
468
2279
|
notes: cleanString(target.notes)
|
|
469
2280
|
};
|
|
470
|
-
return normalized.url || normalized.command || normalized.ready_url ||
|
|
2281
|
+
return normalized.url || normalized.command || normalized.ready_url || normalized.managed_runtime_port
|
|
471
2282
|
? normalized
|
|
472
2283
|
: null;
|
|
473
2284
|
}
|
|
@@ -500,6 +2311,10 @@ function invalidDispatchSummary(error) {
|
|
|
500
2311
|
const detail = error instanceof Error ? error.message : String(error);
|
|
501
2312
|
return `Invalid bridge dispatch packet: ${detail}`;
|
|
502
2313
|
}
|
|
2314
|
+
function invalidChatTurnSummary(error) {
|
|
2315
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2316
|
+
return `Invalid Bridge Chat turn packet: ${detail}`;
|
|
2317
|
+
}
|
|
503
2318
|
function errorMessage(error) {
|
|
504
2319
|
return error instanceof Error ? error.message : String(error);
|
|
505
2320
|
}
|
|
@@ -509,33 +2324,621 @@ function formatDelay(ms) {
|
|
|
509
2324
|
}
|
|
510
2325
|
return `${ms}ms`;
|
|
511
2326
|
}
|
|
2327
|
+
async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
|
|
2328
|
+
let timeout = null;
|
|
2329
|
+
let rejectAbort = null;
|
|
2330
|
+
const expired = new Promise((_resolve, reject) => {
|
|
2331
|
+
timeout = setTimeout(() => {
|
|
2332
|
+
reject(new Error(`bridge_callback_timeout: ${methodName} callback was not acknowledged within ${formatDelay(timeoutMs)}.`));
|
|
2333
|
+
}, timeoutMs);
|
|
2334
|
+
});
|
|
2335
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
2336
|
+
rejectAbort = reject;
|
|
2337
|
+
});
|
|
2338
|
+
const onAbort = () => rejectAbort?.(new Error(String(signal?.reason ?? `${methodName} callback was cancelled.`)));
|
|
2339
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2340
|
+
if (signal?.aborted)
|
|
2341
|
+
onAbort();
|
|
2342
|
+
try {
|
|
2343
|
+
return await Promise.race(signal ? [callback, expired, aborted] : [callback, expired]);
|
|
2344
|
+
}
|
|
2345
|
+
finally {
|
|
2346
|
+
if (timeout)
|
|
2347
|
+
clearTimeout(timeout);
|
|
2348
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
512
2351
|
function logBridgeStatus(message) {
|
|
513
2352
|
process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
|
|
514
2353
|
}
|
|
515
|
-
function delay(ms, signal) {
|
|
2354
|
+
export function delay(ms, signal) {
|
|
516
2355
|
if (signal?.aborted) {
|
|
517
2356
|
return Promise.resolve();
|
|
518
2357
|
}
|
|
519
2358
|
return new Promise((resolve) => {
|
|
520
|
-
const
|
|
521
|
-
signal?.addEventListener("abort", () => {
|
|
2359
|
+
const complete = () => {
|
|
522
2360
|
clearTimeout(timeout);
|
|
2361
|
+
signal?.removeEventListener("abort", complete);
|
|
523
2362
|
resolve();
|
|
524
|
-
}
|
|
2363
|
+
};
|
|
2364
|
+
const timeout = setTimeout(complete, ms);
|
|
2365
|
+
signal?.addEventListener("abort", complete, { once: true });
|
|
2366
|
+
if (signal?.aborted)
|
|
2367
|
+
complete();
|
|
525
2368
|
});
|
|
526
2369
|
}
|
|
527
|
-
function
|
|
2370
|
+
export async function waitForPromiseOrAbort(promise, signal) {
|
|
528
2371
|
if (!signal) {
|
|
529
|
-
|
|
2372
|
+
await promise;
|
|
2373
|
+
return;
|
|
530
2374
|
}
|
|
531
2375
|
if (signal.aborted) {
|
|
532
|
-
return
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
let resolveAbort;
|
|
2379
|
+
const abort = new Promise(resolve => { resolveAbort = resolve; });
|
|
2380
|
+
signal.addEventListener("abort", resolveAbort, { once: true });
|
|
2381
|
+
try {
|
|
2382
|
+
await Promise.race([promise, abort]);
|
|
2383
|
+
}
|
|
2384
|
+
finally {
|
|
2385
|
+
signal.removeEventListener("abort", resolveAbort);
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
// Matches the API Hello bound on settled recovered host attempts.
|
|
2389
|
+
const maxRecoveredHostAttempts = 128;
|
|
2390
|
+
const defaultChatTurnLeaseMs = 60 * 60 * 1000;
|
|
2391
|
+
const maxChatEventContentChars = 4000;
|
|
2392
|
+
const maxChatTerminalTextChars = 120_000;
|
|
2393
|
+
const maxChatExactSecretChars = 8 * 1024;
|
|
2394
|
+
const chatTurnMetadataFileName = "forge-chat-metadata.json";
|
|
2395
|
+
async function materializeChatTurnMetadata(packet, workspacePath) {
|
|
2396
|
+
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2397
|
+
return;
|
|
2398
|
+
}
|
|
2399
|
+
await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
|
|
2400
|
+
schemaVersion: 1,
|
|
2401
|
+
attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
|
|
2402
|
+
turnId: handoff.turnId,
|
|
2403
|
+
attachmentId: handoff.attachmentId,
|
|
2404
|
+
tempFileToken: handoff.tempFileToken,
|
|
2405
|
+
mimeType: handoff.mimeType,
|
|
2406
|
+
sizeBytes: handoff.sizeBytes,
|
|
2407
|
+
sha256: handoff.sha256,
|
|
2408
|
+
fileNameDisplay: handoff.fileNameDisplay,
|
|
2409
|
+
expiresAt: handoff.expiresAt,
|
|
2410
|
+
status: handoff.status,
|
|
2411
|
+
})),
|
|
2412
|
+
actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
|
|
2413
|
+
grantId: grant.grantId,
|
|
2414
|
+
turnId: grant.turnId,
|
|
2415
|
+
leaseId: grant.leaseId,
|
|
2416
|
+
fencingToken: grant.fencingToken,
|
|
2417
|
+
allowedScopes: grant.allowedScopes,
|
|
2418
|
+
expiresAt: grant.expiresAt,
|
|
2419
|
+
redactionStatus: grant.redactionStatus,
|
|
2420
|
+
nonceHeldByBridge: true,
|
|
2421
|
+
})),
|
|
2422
|
+
}, null, 2)}\n`, "utf8");
|
|
2423
|
+
}
|
|
2424
|
+
function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
|
|
2425
|
+
const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
|
|
2426
|
+
const metadataExpiresAtMs = [
|
|
2427
|
+
...packet.attachmentHandoffs.map(handoff => Date.parse(handoff.expiresAt)),
|
|
2428
|
+
...packet.actionBrokerGrants.map(grant => Date.parse(grant.expiresAt)),
|
|
2429
|
+
].filter(Number.isFinite);
|
|
2430
|
+
return new Date(Math.min(defaultExpiresAtMs, ...metadataExpiresAtMs)).toISOString();
|
|
2431
|
+
}
|
|
2432
|
+
async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
|
|
2433
|
+
try {
|
|
2434
|
+
await fs.promises.rm(workspacePath, { recursive: true, force: true, maxRetries: 3 });
|
|
2435
|
+
return {
|
|
2436
|
+
status: "completed",
|
|
2437
|
+
eventType: "chat_turn_cleanup_completed",
|
|
2438
|
+
role: "runner",
|
|
2439
|
+
kind: "checkpoint",
|
|
2440
|
+
content: "Bridge Chat workspace cleanup completed.",
|
|
2441
|
+
};
|
|
2442
|
+
}
|
|
2443
|
+
catch (error) {
|
|
2444
|
+
return {
|
|
2445
|
+
status: "failed",
|
|
2446
|
+
eventType: "chat_turn_cleanup_failed",
|
|
2447
|
+
role: "runner",
|
|
2448
|
+
kind: "error",
|
|
2449
|
+
content: "Bridge Chat workspace cleanup failed.",
|
|
2450
|
+
message: clip(redactText(errorMessage(error), redactionSecrets), 1000),
|
|
2451
|
+
};
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
function buildChatProviderCommand(packet, cwd) {
|
|
2455
|
+
const provider = packet.providerKind.trim().toLowerCase();
|
|
2456
|
+
const model = packet.model.trim();
|
|
2457
|
+
const prompt = buildChatPrompt(packet);
|
|
2458
|
+
const resumeThreadId = packet.providerThreadId?.trim() || null;
|
|
2459
|
+
if (provider === "codex") {
|
|
2460
|
+
const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
|
|
2461
|
+
if (resumeThreadId) {
|
|
2462
|
+
args.push("--cd", cwd, "resume");
|
|
2463
|
+
}
|
|
2464
|
+
args.push("--model", model, "--json");
|
|
2465
|
+
if (!resumeThreadId) {
|
|
2466
|
+
args.push("--cd", cwd);
|
|
2467
|
+
}
|
|
2468
|
+
args.push("--skip-git-repo-check");
|
|
2469
|
+
if (resumeThreadId) {
|
|
2470
|
+
args.push(resumeThreadId);
|
|
2471
|
+
}
|
|
2472
|
+
args.push("-");
|
|
2473
|
+
return { command: { command: "codex", args }, stdin: prompt };
|
|
2474
|
+
}
|
|
2475
|
+
if (provider === "cursor") {
|
|
2476
|
+
const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
|
|
2477
|
+
if (resumeThreadId) {
|
|
2478
|
+
args.push("--resume", resumeThreadId);
|
|
2479
|
+
}
|
|
2480
|
+
args.push("--yolo", "--approve-mcps", "--trust", prompt);
|
|
2481
|
+
return { command: { command: "cursor-agent", args } };
|
|
2482
|
+
}
|
|
2483
|
+
if (provider === "claude") {
|
|
2484
|
+
const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
|
|
2485
|
+
if (resumeThreadId) {
|
|
2486
|
+
args.push("--resume", resumeThreadId);
|
|
2487
|
+
}
|
|
2488
|
+
return { command: { command: "claude", args }, stdin: prompt };
|
|
2489
|
+
}
|
|
2490
|
+
return {
|
|
2491
|
+
command: {
|
|
2492
|
+
command: provider,
|
|
2493
|
+
args: ["--model", model, prompt],
|
|
2494
|
+
},
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
function buildChatPrompt(packet) {
|
|
2498
|
+
const messages = packet.messages
|
|
2499
|
+
.map((message, index) => {
|
|
2500
|
+
const role = message.role.trim() || `message-${index + 1}`;
|
|
2501
|
+
return `[${role}]\n${message.content}`;
|
|
2502
|
+
})
|
|
2503
|
+
.join("\n\n");
|
|
2504
|
+
const contextRefs = packet.contextRefs.length === 0
|
|
2505
|
+
? ""
|
|
2506
|
+
: `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
|
|
2507
|
+
const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
|
|
2508
|
+
const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
|
|
2509
|
+
return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
|
|
2510
|
+
}).join("\n\n")}`;
|
|
2511
|
+
const continuation = packet.providerThreadId
|
|
2512
|
+
? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
|
|
2513
|
+
: "";
|
|
2514
|
+
const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
|
|
2515
|
+
return `You are handling a Forge Bridge Chat turn.
|
|
2516
|
+
|
|
2517
|
+
Conversation ID: ${packet.conversationId}
|
|
2518
|
+
Turn ID: ${packet.turnId}
|
|
2519
|
+
Provider: ${packet.providerKind}
|
|
2520
|
+
Model: ${packet.model}${continuation}${boundedMetadata}
|
|
2521
|
+
|
|
2522
|
+
# Conversation
|
|
2523
|
+
|
|
2524
|
+
${messages}${contextRefs}
|
|
2525
|
+
`;
|
|
2526
|
+
}
|
|
2527
|
+
function buildChatBoundedMetadataPrompt(packet) {
|
|
2528
|
+
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2529
|
+
return "";
|
|
2530
|
+
}
|
|
2531
|
+
const sections = [
|
|
2532
|
+
`\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
|
|
2533
|
+
];
|
|
2534
|
+
if (packet.attachmentHandoffs.length > 0) {
|
|
2535
|
+
sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
|
|
2536
|
+
`${index + 1}. turnId: ${handoff.turnId}`,
|
|
2537
|
+
` attachmentId: ${handoff.attachmentId}`,
|
|
2538
|
+
` tempFileToken: ${handoff.tempFileToken}`,
|
|
2539
|
+
` mimeType: ${handoff.mimeType}`,
|
|
2540
|
+
` sizeBytes: ${handoff.sizeBytes}`,
|
|
2541
|
+
` sha256: ${handoff.sha256}`,
|
|
2542
|
+
` fileNameDisplay: ${handoff.fileNameDisplay}`,
|
|
2543
|
+
` expiresAt: ${handoff.expiresAt}`,
|
|
2544
|
+
` status: ${handoff.status}`,
|
|
2545
|
+
].join("\n")).join("\n\n")}`);
|
|
2546
|
+
}
|
|
2547
|
+
if (packet.actionBrokerGrants.length > 0) {
|
|
2548
|
+
sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
|
|
2549
|
+
`${index + 1}. grantId: ${grant.grantId}`,
|
|
2550
|
+
` turnId: ${grant.turnId}`,
|
|
2551
|
+
` leaseId: ${grant.leaseId}`,
|
|
2552
|
+
` fencingToken: ${grant.fencingToken}`,
|
|
2553
|
+
` allowedScopes: ${grant.allowedScopes.join(", ")}`,
|
|
2554
|
+
` expiresAt: ${grant.expiresAt}`,
|
|
2555
|
+
` redactionStatus: ${grant.redactionStatus}`,
|
|
2556
|
+
" nonce: held by bridge",
|
|
2557
|
+
].join("\n")).join("\n\n")}`);
|
|
2558
|
+
}
|
|
2559
|
+
return sections.join("\n\n");
|
|
2560
|
+
}
|
|
2561
|
+
function chatProviderExitFailure(command, result, redactionSecrets) {
|
|
2562
|
+
const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
|
|
2563
|
+
const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
|
|
2564
|
+
const stdout = clip(redactText(result.stdout.trim(), redactionSecrets), 1000);
|
|
2565
|
+
const diagnostics = [
|
|
2566
|
+
stderr ? `stderr: ${stderr}` : null,
|
|
2567
|
+
stdout ? `stdout: ${stdout}` : null,
|
|
2568
|
+
].filter(Boolean).join(" ");
|
|
2569
|
+
return new Error(`provider_failed: ${commandText} exited with code ${result.exitCode}.${diagnostics ? ` ${diagnostics}` : ""}`);
|
|
2570
|
+
}
|
|
2571
|
+
function chatAbortKind(reason) {
|
|
2572
|
+
const message = typeof reason === "string" ? reason.toLowerCase() : "";
|
|
2573
|
+
return message.includes("expired") ? "expired" : "cancelled";
|
|
2574
|
+
}
|
|
2575
|
+
function chatAbortPayload(reason, cleanupOutcome, packet) {
|
|
2576
|
+
const kind = chatAbortKind(reason);
|
|
2577
|
+
const message = typeof reason === "string" && reason.trim()
|
|
2578
|
+
? reason.trim()
|
|
2579
|
+
: (kind === "expired" ? "Bridge Chat turn expired." : "Bridge Chat turn cancelled.");
|
|
2580
|
+
return {
|
|
2581
|
+
code: kind === "expired" ? "chat_turn_expired" : "chat_turn_cancelled",
|
|
2582
|
+
message: clip(redactText(message, packet ? chatRedactionSecrets(packet) : []), 1000),
|
|
2583
|
+
cleanup: cleanupOutcome,
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
function providerThreadIdFromEvent(event) {
|
|
2587
|
+
if (!event.data) {
|
|
2588
|
+
return null;
|
|
2589
|
+
}
|
|
2590
|
+
try {
|
|
2591
|
+
const data = JSON.parse(event.data);
|
|
2592
|
+
for (const key of ["threadId", "thread_id", "sessionId", "session_id", "providerThreadId"]) {
|
|
2593
|
+
const value = data[key];
|
|
2594
|
+
if (typeof value === "string") {
|
|
2595
|
+
const clean = value.trim();
|
|
2596
|
+
if (clean.length > 0 && clean.length <= bridgeChatMaxProviderThreadIdChars) {
|
|
2597
|
+
return clean;
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
catch {
|
|
2603
|
+
return null;
|
|
2604
|
+
}
|
|
2605
|
+
return null;
|
|
2606
|
+
}
|
|
2607
|
+
function chatRedactionSecrets(packet) {
|
|
2608
|
+
return [
|
|
2609
|
+
packet.chatRunId,
|
|
2610
|
+
packet.conversationId,
|
|
2611
|
+
packet.turnId,
|
|
2612
|
+
packet.leaseId,
|
|
2613
|
+
packet.fencingToken,
|
|
2614
|
+
packet.runnerInstanceId,
|
|
2615
|
+
packet.providerThreadId,
|
|
2616
|
+
...packet.attachmentHandoffs.flatMap((handoff) => [
|
|
2617
|
+
handoff.attachmentId,
|
|
2618
|
+
handoff.tempFileToken,
|
|
2619
|
+
]),
|
|
2620
|
+
...packet.actionBrokerGrants.flatMap((grant) => [
|
|
2621
|
+
grant.grantId,
|
|
2622
|
+
grant.nonce,
|
|
2623
|
+
]),
|
|
2624
|
+
...packet.messages.flatMap((message) => boundedChatSecretFragments(message.content)),
|
|
2625
|
+
...packet.contextRefs.flatMap((ref) => [
|
|
2626
|
+
...boundedChatSecretFragments(ref.title ?? ""),
|
|
2627
|
+
...boundedChatSecretFragments(ref.summary ?? ""),
|
|
2628
|
+
]),
|
|
2629
|
+
].filter((value) => typeof value === "string" && value.length > 0);
|
|
2630
|
+
}
|
|
2631
|
+
function boundedChatSecretFragments(value) {
|
|
2632
|
+
const clean = value.trim();
|
|
2633
|
+
if (!clean) {
|
|
2634
|
+
return [];
|
|
2635
|
+
}
|
|
2636
|
+
if (clean.length <= maxChatExactSecretChars) {
|
|
2637
|
+
return [clean];
|
|
2638
|
+
}
|
|
2639
|
+
const half = Math.floor(maxChatExactSecretChars / 2);
|
|
2640
|
+
return [clean.slice(0, half), clean.slice(clean.length - half)];
|
|
2641
|
+
}
|
|
2642
|
+
function safePathComponent(value) {
|
|
2643
|
+
const clean = value.trim().replace(/[^a-zA-Z0-9_.-]+/gu, "-").replace(/^-+|-+$/gu, "");
|
|
2644
|
+
return clean || "chat-turn";
|
|
2645
|
+
}
|
|
2646
|
+
function containsIgnoreCase(values, value) {
|
|
2647
|
+
const normalized = value.trim().toLowerCase();
|
|
2648
|
+
return values.some((candidate) => candidate.trim().toLowerCase() === normalized);
|
|
2649
|
+
}
|
|
2650
|
+
export function canReapManagedSandboxes(preflight) {
|
|
2651
|
+
return canRunDockerMaintenance(preflight);
|
|
2652
|
+
}
|
|
2653
|
+
function sandboxNetworkPolicyFailure(dispatch, config) {
|
|
2654
|
+
const sandbox = dispatch.sandbox;
|
|
2655
|
+
if (!sandbox)
|
|
2656
|
+
return "Protocol-v2 sandbox context is missing.";
|
|
2657
|
+
if (sandbox.networkPolicy.mode === "open_public"
|
|
2658
|
+
&& (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
|
|
2659
|
+
return "open_public sandbox networking is not permitted by this runner policy.";
|
|
2660
|
+
}
|
|
2661
|
+
if (sandbox.networkPolicy.mode === "public_allowlist"
|
|
2662
|
+
&& sandbox.networkPolicy.allowedHosts.length > 0
|
|
2663
|
+
&& process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
|
|
2664
|
+
return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
|
|
2665
|
+
}
|
|
2666
|
+
return null;
|
|
2667
|
+
}
|
|
2668
|
+
export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
|
|
2669
|
+
if (!requiredCapabilities.includes("docker_engine"))
|
|
2670
|
+
return null;
|
|
2671
|
+
if (executionMode === "docker") {
|
|
2672
|
+
return "docker_engine_unavailable: docker_engine is not exposed inside Forge agent sandboxes; use a managed host runner with Docker-daemon access.";
|
|
2673
|
+
}
|
|
2674
|
+
return capability?.available
|
|
2675
|
+
? null
|
|
2676
|
+
: `docker_engine_unavailable: ${capability?.unavailableReason ?? "Docker daemon is unreachable from the bridge process."}`;
|
|
2677
|
+
}
|
|
2678
|
+
function parseReadinessProbe(value) {
|
|
2679
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2680
|
+
return null;
|
|
2681
|
+
const request = value;
|
|
2682
|
+
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;
|
|
2683
|
+
const bounded = (candidate, maximum) => typeof candidate === "string" && candidate.trim().length > 0 && candidate.length <= maximum;
|
|
2684
|
+
if (request.schemaVersion !== 1
|
|
2685
|
+
|| !uuid.test(request.requestId ?? "")
|
|
2686
|
+
|| !uuid.test(request.fencingToken ?? "")
|
|
2687
|
+
|| !uuid.test(request.userId ?? "")
|
|
2688
|
+
|| !uuid.test(request.projectId ?? "")
|
|
2689
|
+
|| !uuid.test(request.repoId ?? "")
|
|
2690
|
+
|| !uuid.test(request.runnerInstanceId ?? "")
|
|
2691
|
+
|| !Number.isInteger(request.attempt) || (request.attempt ?? 0) < 1
|
|
2692
|
+
|| !bounded(request.repoName, 160)
|
|
2693
|
+
|| typeof request.remoteUrl !== "string" || request.remoteUrl.length > 2048
|
|
2694
|
+
|| !bounded(request.defaultBranch, 512)
|
|
2695
|
+
|| typeof request.cloneOnDemand !== "boolean"
|
|
2696
|
+
|| !bounded(request.runnerRepoLocalPath, 4096)
|
|
2697
|
+
|| !bounded(request.revision, 512)
|
|
2698
|
+
|| !Number.isFinite(Date.parse(request.expiresAt ?? ""))
|
|
2699
|
+
|| Date.parse(request.expiresAt ?? "") <= Date.now()) {
|
|
2700
|
+
return null;
|
|
2701
|
+
}
|
|
2702
|
+
return request;
|
|
2703
|
+
}
|
|
2704
|
+
function deferredReadinessResult(request, runnerInstanceId) {
|
|
2705
|
+
return {
|
|
2706
|
+
schemaVersion: 1,
|
|
2707
|
+
requestId: request.requestId,
|
|
2708
|
+
fencingToken: request.fencingToken,
|
|
2709
|
+
runnerInstanceId,
|
|
2710
|
+
status: "failed",
|
|
2711
|
+
reasonCode: "host_runtime_probe_deferred",
|
|
2712
|
+
reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
|
|
2713
|
+
checkedAt: new Date().toISOString(),
|
|
2714
|
+
};
|
|
2715
|
+
}
|
|
2716
|
+
function readinessDeferralReason(signal) {
|
|
2717
|
+
if (!signal.aborted)
|
|
2718
|
+
return null;
|
|
2719
|
+
const reason = errorMessage(signal.reason);
|
|
2720
|
+
return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
|
|
2721
|
+
}
|
|
2722
|
+
function sandboxProviderNetworkFailure(dispatch, config) {
|
|
2723
|
+
const sandbox = dispatch.sandbox;
|
|
2724
|
+
if (!sandbox || sandbox.networkPolicy.mode !== "offline")
|
|
2725
|
+
return null;
|
|
2726
|
+
const provider = dispatch.execution.provider.trim().toLowerCase();
|
|
2727
|
+
const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
|
|
2728
|
+
if (!isNetworkProvider)
|
|
2729
|
+
return null;
|
|
2730
|
+
return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
|
|
2731
|
+
}
|
|
2732
|
+
function sandboxAuthFailure(dispatch, config) {
|
|
2733
|
+
const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
|
|
2734
|
+
if (unsupported) {
|
|
2735
|
+
return unsupported;
|
|
2736
|
+
}
|
|
2737
|
+
if (dispatch.execution.authKind.trim().toLowerCase() !== "bridge_cli") {
|
|
2738
|
+
return null;
|
|
2739
|
+
}
|
|
2740
|
+
const status = providerStatus(config, dispatch.execution.provider);
|
|
2741
|
+
if (status?.signedIn === false) {
|
|
2742
|
+
return `${dispatch.execution.provider} Local CLI is not signed in on this runner.`;
|
|
2743
|
+
}
|
|
2744
|
+
const adapter = sandboxProviderAuthAdapterFor(dispatch.execution.provider, dispatch.execution.authKind);
|
|
2745
|
+
if (!adapter) {
|
|
2746
|
+
return `${dispatch.execution.provider} Local CLI auth is not portable into Docker yet.`;
|
|
2747
|
+
}
|
|
2748
|
+
const doctor = adapter.doctor();
|
|
2749
|
+
return doctor.available ? null : doctor.message;
|
|
2750
|
+
}
|
|
2751
|
+
function rejectedOfferReservation(code, message) {
|
|
2752
|
+
return {
|
|
2753
|
+
accepted: false,
|
|
2754
|
+
code,
|
|
2755
|
+
message,
|
|
2756
|
+
reservedUntil: null,
|
|
2757
|
+
resources: null,
|
|
2758
|
+
};
|
|
2759
|
+
}
|
|
2760
|
+
export function canReserveSandboxResources(used, requested, capacity) {
|
|
2761
|
+
return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
|
|
2762
|
+
&& used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
|
|
2763
|
+
&& used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
|
|
2764
|
+
&& used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
|
|
2765
|
+
&& used.pids + requested.pids <= capacity.pids
|
|
2766
|
+
&& used.buildSlots + requested.buildSlots <= capacity.buildSlots;
|
|
2767
|
+
}
|
|
2768
|
+
export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
|
|
2769
|
+
const ambientCapacity = preflight.availableMemoryBytes
|
|
2770
|
+
- preflight.hostReserveBytes
|
|
2771
|
+
+ activeMemoryBytes;
|
|
2772
|
+
const commitmentCapacity = preflight.totalMemoryBytes
|
|
2773
|
+
- preflight.hostReserveBytes;
|
|
2774
|
+
return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
|
|
2775
|
+
}
|
|
2776
|
+
export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
|
|
2777
|
+
const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
|
|
2778
|
+
if (requested.sandboxSlots > availableSlots) {
|
|
2779
|
+
return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
|
|
2780
|
+
}
|
|
2781
|
+
const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
|
|
2782
|
+
if (requested.memoryBytes > availableMemoryBytes) {
|
|
2783
|
+
return [
|
|
2784
|
+
`Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
|
|
2785
|
+
`(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
|
|
2786
|
+
`but ${formatBytes(availableMemoryBytes)} is available for admission.`,
|
|
2787
|
+
`Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
|
|
2788
|
+
`Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
|
|
2789
|
+
].join(" ");
|
|
2790
|
+
}
|
|
2791
|
+
const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
|
|
2792
|
+
if (requested.cpuMillis > availableCpuMillis) {
|
|
2793
|
+
return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
|
|
533
2794
|
}
|
|
534
|
-
|
|
2795
|
+
const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
|
|
2796
|
+
if (requested.workspaceBytes > availableWorkspaceBytes) {
|
|
2797
|
+
return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
|
|
2798
|
+
}
|
|
2799
|
+
const availablePids = Math.max(0, capacity.pids - used.pids);
|
|
2800
|
+
if (requested.pids > availablePids) {
|
|
2801
|
+
return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
|
|
2802
|
+
}
|
|
2803
|
+
const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
|
|
2804
|
+
return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
|
|
2805
|
+
}
|
|
2806
|
+
function sumSandboxResources(resources) {
|
|
2807
|
+
return resources.reduce((total, resource) => ({
|
|
2808
|
+
sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
|
|
2809
|
+
cpuMillis: total.cpuMillis + resource.cpuMillis,
|
|
2810
|
+
workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
|
|
2811
|
+
serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
|
|
2812
|
+
runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
|
|
2813
|
+
memoryBytes: total.memoryBytes + resource.memoryBytes,
|
|
2814
|
+
workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
|
|
2815
|
+
pids: total.pids + resource.pids,
|
|
2816
|
+
buildSlots: total.buildSlots + resource.buildSlots
|
|
2817
|
+
}), zeroSandboxResources());
|
|
2818
|
+
}
|
|
2819
|
+
function zeroSandboxResources() {
|
|
2820
|
+
return {
|
|
2821
|
+
sandboxSlots: 0,
|
|
2822
|
+
cpuMillis: 0,
|
|
2823
|
+
workerMemoryLimitBytes: 0,
|
|
2824
|
+
serviceMemoryLimitBytes: 0,
|
|
2825
|
+
runtimeOverheadBytes: 0,
|
|
2826
|
+
memoryBytes: 0,
|
|
2827
|
+
workspaceBytes: 0,
|
|
2828
|
+
pids: 0,
|
|
2829
|
+
buildSlots: 0,
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
function defaultSandboxResources() {
|
|
2833
|
+
return {
|
|
2834
|
+
sandboxSlots: 1,
|
|
2835
|
+
cpuMillis: 2000,
|
|
2836
|
+
workerMemoryLimitBytes: 2 * 1024 ** 3,
|
|
2837
|
+
serviceMemoryLimitBytes: 0,
|
|
2838
|
+
runtimeOverheadBytes: 128 * 1024 ** 2,
|
|
2839
|
+
memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
|
|
2840
|
+
workspaceBytes: 10 * 1024 ** 3,
|
|
2841
|
+
pids: 512,
|
|
2842
|
+
buildSlots: 0
|
|
2843
|
+
};
|
|
2844
|
+
}
|
|
2845
|
+
export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2846
|
+
const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
|
|
2847
|
+
const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
|
|
2848
|
+
+ (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
|
|
2849
|
+
return {
|
|
2850
|
+
...requested,
|
|
2851
|
+
serviceMemoryLimitBytes,
|
|
2852
|
+
runtimeOverheadBytes,
|
|
2853
|
+
memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
|
|
2854
|
+
};
|
|
2855
|
+
}
|
|
2856
|
+
export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2857
|
+
const repoPath = dispatch.repo.serverLocalPath;
|
|
2858
|
+
const sandbox = dispatch.sandbox;
|
|
2859
|
+
if (!repoPath || !sandbox) {
|
|
2860
|
+
throw new Error("Sandbox admission needs a mapped repository.");
|
|
2861
|
+
}
|
|
2862
|
+
const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
|
|
2863
|
+
const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
|
|
2864
|
+
if (!configCommitSha) {
|
|
2865
|
+
throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
|
|
2866
|
+
}
|
|
2867
|
+
const contractResult = await runSandboxProcess({
|
|
2868
|
+
command: "git",
|
|
2869
|
+
args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
|
|
2870
|
+
timeoutMs: 30_000,
|
|
2871
|
+
maxOutputBytes: 1024 * 1024,
|
|
2872
|
+
});
|
|
2873
|
+
if (contractResult.exitCode !== 0) {
|
|
2874
|
+
throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
|
|
2875
|
+
}
|
|
2876
|
+
const contract = validateSandboxContract(contractResult.stdout);
|
|
2877
|
+
const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
|
|
2878
|
+
role: dispatch.execution.role,
|
|
2879
|
+
serviceCount: contract.contract.services.length,
|
|
2880
|
+
browser: contract.contract.browser,
|
|
2881
|
+
});
|
|
2882
|
+
return {
|
|
2883
|
+
resources: resolveDynamicSandboxResources({
|
|
2884
|
+
...sandbox.requestedResources,
|
|
2885
|
+
workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
|
|
2886
|
+
}, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
|
|
2887
|
+
sandboxConfigCommitSha: configCommitSha,
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
async function resolveFirstGitCommit(repoPath, refs) {
|
|
2891
|
+
for (const ref of refs) {
|
|
2892
|
+
const result = await runSandboxProcess({
|
|
2893
|
+
command: "git",
|
|
2894
|
+
args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
|
|
2895
|
+
timeoutMs: 30_000,
|
|
2896
|
+
maxOutputBytes: 1024 * 1024,
|
|
2897
|
+
});
|
|
2898
|
+
const commitSha = result.stdout.trim().toLowerCase();
|
|
2899
|
+
if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
|
|
2900
|
+
return commitSha;
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
return null;
|
|
535
2904
|
}
|
|
2905
|
+
function parseOfferEnvelope(value) {
|
|
2906
|
+
return parseDispatchEnvelope(value);
|
|
2907
|
+
}
|
|
2908
|
+
function parseStartEnvelope(value) {
|
|
2909
|
+
return parseDispatchEnvelope(value);
|
|
2910
|
+
}
|
|
2911
|
+
function parseDispatchEnvelope(value) {
|
|
2912
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2913
|
+
return null;
|
|
2914
|
+
const envelope = value;
|
|
2915
|
+
if (envelope.schemaVersion !== 1
|
|
2916
|
+
|| typeof envelope.dispatchAttemptId !== "string"
|
|
2917
|
+
|| typeof envelope.leaseId !== "string"
|
|
2918
|
+
|| typeof envelope.fencingToken !== "string"
|
|
2919
|
+
|| typeof envelope.runnerInstanceId !== "string"
|
|
2920
|
+
|| typeof envelope.expiresAt !== "string"
|
|
2921
|
+
|| !envelope.dispatch)
|
|
2922
|
+
return null;
|
|
2923
|
+
return {
|
|
2924
|
+
dispatchAttemptId: envelope.dispatchAttemptId,
|
|
2925
|
+
leaseId: envelope.leaseId,
|
|
2926
|
+
fencingToken: envelope.fencingToken,
|
|
2927
|
+
runnerInstanceId: envelope.runnerInstanceId,
|
|
2928
|
+
expiresAt: envelope.expiresAt,
|
|
2929
|
+
dispatch: envelope.dispatch
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
const maxAttachmentExactSecretLength = 8 * 1024;
|
|
536
2933
|
function exactSecrets(dispatch, config) {
|
|
537
2934
|
return [
|
|
538
2935
|
dispatch.apiKeySecretGrant?.secret,
|
|
539
|
-
config.deviceToken
|
|
2936
|
+
config.deviceToken,
|
|
2937
|
+
...boundedAttachmentExactSecrets(dispatch)
|
|
540
2938
|
].filter((secret) => typeof secret === "string" && secret.length > 0);
|
|
541
2939
|
}
|
|
2940
|
+
function boundedAttachmentExactSecrets(dispatch) {
|
|
2941
|
+
return (dispatch.draft?.attachments ?? [])
|
|
2942
|
+
.flatMap((attachment) => [attachment.textContent, attachment.contentBase64])
|
|
2943
|
+
.filter((secret) => typeof secret === "string" && secret.length > 0 && secret.length <= maxAttachmentExactSecretLength);
|
|
2944
|
+
}
|