@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 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 +89 -3
- 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 +4 -1
- package/dist/bridge/bridge.service.d.ts +83 -3
- package/dist/bridge/bridge.service.js +1609 -152
- package/dist/bridge/bridge.types.d.ts +52 -1
- 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 +1 -0
- package/dist/cleanup/cleanup.service.js +70 -9
- package/dist/cli/cli.help.js +4 -4
- package/dist/cli/cli.service.d.ts +14 -6
- package/dist/cli/cli.service.js +75 -16
- package/dist/cli/local-config.d.ts +1 -0
- package/dist/cli/local-config.js +4 -0
- 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 +2 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
- 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.d.ts +35 -0
- package/dist/runtime/attempt-process-supervisor.js +144 -23
- 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 +10 -0
- package/dist/runtime/generated-output-reset.js +62 -8
- 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 +8 -1
- package/dist/runtime/host-listener-inspector.js +121 -60
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -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 +13 -1
- package/dist/runtime/host-runtime-contract.js +170 -55
- package/dist/runtime/host-runtime-lease.d.ts +92 -8
- package/dist/runtime/host-runtime-lease.js +1193 -120
- package/dist/runtime/host-runtime-promotion.d.ts +12 -3
- package/dist/runtime/host-runtime-promotion.js +59 -12
- 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 +3 -0
- package/dist/runtime/node-host-runtime-adapter.js +29 -11
- 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 +12 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
- 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.js +4 -1
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/preflight.d.ts +31 -1
- package/dist/sandbox/preflight.js +237 -51
- package/dist/sandbox/repository-lock.d.ts +2 -1
- package/dist/sandbox/repository-lock.js +19 -9
- package/dist/sandbox/runtime.d.ts +6 -1
- package/dist/sandbox/runtime.js +137 -107
- package/dist/sandbox/sandbox.types.d.ts +7 -0
- package/dist/sandbox/workspace.service.js +2 -0
- package/dist/session/managed-attempt-tools.d.ts +42 -1
- package/dist/session/managed-attempt-tools.js +692 -40
- 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 +17 -0
- package/dist/session/phase-completion.artifacts.js +228 -22
- package/dist/session/phase-completion.d.ts +11 -1
- package/dist/session/phase-completion.helpers.d.ts +5 -0
- package/dist/session/phase-completion.helpers.js +30 -7
- package/dist/session/phase-completion.js +14 -3
- package/dist/session/phase-completion.prompts.js +17 -18
- package/dist/session/phase-completion.runtime.d.ts +3 -1
- package/dist/session/phase-completion.runtime.js +148 -34
- package/dist/session/phase-completion.schemas.js +49 -2
- package/dist/session/phase-completion.validation.d.ts +1 -0
- package/dist/session/phase-completion.validation.js +111 -21
- 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 +8 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
- package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
- 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 +80 -0
- package/dist/session/provider-cli/provider-cli.process.js +694 -28
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
- 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 +14 -1
- package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
- package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
- package/dist/session/provider-cli/provider-cli.service.js +858 -77
- package/dist/session/provider-cli/provider-cli.types.d.ts +2 -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 +16 -0
- package/dist/session/provider-cli/provider-output-state.js +370 -17
- 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.js +434 -9
- package/dist/session/session.service.js +145 -23
- package/dist/session/session.types.d.ts +147 -2
- package/dist/session/session.types.js +599 -7
- 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 +18 -0
- 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.js +3 -2
- package/dist/shared/process/host-process-supervisor.d.ts +2 -0
- package/dist/shared/process/host-process-supervisor.js +60 -11
- package/dist/shared/process/process.d.ts +2 -0
- package/dist/shared/process/process.js +12 -7
- package/dist/shared/provider-capabilities.d.ts +3 -0
- package/dist/shared/provider-capabilities.js +85 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +39 -3
- 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/dependency-warmer.d.ts +41 -9
- package/dist/worktree/dependency-warmer.js +571 -22
- package/dist/worktree/index.d.ts +1 -1
- 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.service.d.ts +7 -0
- package/dist/worktree/worktree.service.js +253 -21
- package/dist/worktree/worktree.types.d.ts +7 -1
- package/package.json +7 -5
- package/runtime/windows-job-supervisor.ps1 +380 -14
|
@@ -4,25 +4,57 @@ import path from "node:path";
|
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { defaultForgeBridgeConfig } from "../config.js";
|
|
7
|
-
import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
7
|
+
import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
8
8
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
9
9
|
import { BridgeSessionService } from "../session/session.service.js";
|
|
10
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";
|
|
11
13
|
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
12
|
-
import {
|
|
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";
|
|
13
23
|
import { GitWorktreeService } from "../worktree/worktree.service.js";
|
|
14
24
|
import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
|
|
15
25
|
import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
|
|
16
|
-
import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
26
|
+
import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
17
27
|
import { forgeBridgeVersion } from "../version.js";
|
|
18
28
|
import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
|
|
19
29
|
import { validateSandboxContract } from "../sandbox/contract.js";
|
|
20
30
|
import { runSandboxProcess } from "../sandbox/process.js";
|
|
21
31
|
import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
|
|
22
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
|
+
}
|
|
23
52
|
export class ForgeBridgeService {
|
|
24
53
|
config;
|
|
25
54
|
connections;
|
|
55
|
+
hostCapabilityProbe;
|
|
56
|
+
chatProcessRunner;
|
|
57
|
+
hostLoad;
|
|
26
58
|
connection = null;
|
|
27
59
|
heartbeatTimer = null;
|
|
28
60
|
heartbeatInFlight = false;
|
|
@@ -32,18 +64,41 @@ export class ForgeBridgeService {
|
|
|
32
64
|
sandboxMaintenanceTimer = null;
|
|
33
65
|
sandboxMaintenanceRunning = false;
|
|
34
66
|
closed = null;
|
|
67
|
+
transportRecovery = null;
|
|
68
|
+
transportRecoveryGeneration = 0;
|
|
35
69
|
stopped = false;
|
|
36
70
|
activeSessions = new Map();
|
|
37
71
|
reservations = new Map();
|
|
38
72
|
activeReadinessProbes = new Map();
|
|
73
|
+
readinessResultOutbox;
|
|
74
|
+
readinessResultFlush = null;
|
|
75
|
+
dispatchResultOutbox;
|
|
76
|
+
dispatchResultFlush = null;
|
|
77
|
+
dispatchResultGeneration = 0;
|
|
78
|
+
dispatchResultFlushedGeneration = -1;
|
|
79
|
+
dispatchResultHandoffs = new Map();
|
|
39
80
|
preflight;
|
|
81
|
+
dockerEngineProbe;
|
|
40
82
|
sandboxRuntime;
|
|
41
83
|
sandboxResourceResolver;
|
|
42
84
|
sessions;
|
|
43
|
-
|
|
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()) {
|
|
44
93
|
this.config = config;
|
|
45
94
|
this.connections = connections;
|
|
46
|
-
this.
|
|
95
|
+
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
96
|
+
this.chatProcessRunner = chatProcessRunner;
|
|
97
|
+
this.hostLoad = hostLoad;
|
|
98
|
+
this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
|
|
99
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
100
|
+
establishHostDatabaseCapabilityBoundary();
|
|
101
|
+
}
|
|
47
102
|
this.preflight = preflight ?? new DockerPreflight({
|
|
48
103
|
dockerExecutable: config.dockerExecutable,
|
|
49
104
|
dockerContext: config.dockerContext,
|
|
@@ -59,17 +114,36 @@ export class ForgeBridgeService {
|
|
|
59
114
|
runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
|
|
60
115
|
requireRootless: config.requireRootlessDocker
|
|
61
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);
|
|
62
130
|
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
|
|
63
131
|
this.sandboxResourceResolver = sandboxResourceResolver
|
|
64
132
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
133
|
+
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
134
|
+
this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
|
|
65
135
|
}
|
|
66
136
|
async connectOnce() {
|
|
67
137
|
await this.stopConnection();
|
|
68
138
|
this.stopped = false;
|
|
139
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
140
|
+
assertHostDatabaseCapabilityBoundary();
|
|
141
|
+
}
|
|
69
142
|
const hostReap = await this.sessions.reapHostRuntime?.({
|
|
70
143
|
runnerId: this.config.runnerId,
|
|
71
144
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
72
145
|
});
|
|
146
|
+
this.rememberRecoveredHostAttempts(hostReap);
|
|
73
147
|
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
74
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.`);
|
|
75
149
|
}
|
|
@@ -80,17 +154,57 @@ export class ForgeBridgeService {
|
|
|
80
154
|
await this.preflight.refresh();
|
|
81
155
|
}
|
|
82
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);
|
|
83
165
|
const connection = this.connections.create(this.config);
|
|
84
166
|
this.connection = connection;
|
|
167
|
+
this.transportRecovery = null;
|
|
85
168
|
this.closed = new Promise((resolve) => {
|
|
86
|
-
connection.onClose(() => {
|
|
169
|
+
connection.onClose((error) => {
|
|
87
170
|
this.stopHeartbeat();
|
|
171
|
+
this.completeTransportRecovery(error ?? new Error("bridge connection closed"));
|
|
88
172
|
this.abortActiveSessions("bridge connection closed");
|
|
89
173
|
this.abortActiveReadinessProbes("bridge connection closed");
|
|
90
174
|
resolve();
|
|
91
175
|
});
|
|
92
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
|
+
});
|
|
93
206
|
connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
|
|
207
|
+
connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
|
|
94
208
|
connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
|
|
95
209
|
connection.onStart?.((dispatch) => this.handleStart(dispatch));
|
|
96
210
|
connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
|
|
@@ -98,18 +212,67 @@ export class ForgeBridgeService {
|
|
|
98
212
|
connection.onReap?.((request) => this.handleReap(request));
|
|
99
213
|
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
100
214
|
await connection.start();
|
|
101
|
-
await this.
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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)}`);
|
|
107
221
|
});
|
|
108
222
|
await this.flushCleanupReports();
|
|
109
223
|
this.startHeartbeat();
|
|
110
224
|
this.startLeaseWatchdog();
|
|
111
225
|
this.startSandboxMaintenance();
|
|
112
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
|
+
}
|
|
275
|
+
}
|
|
113
276
|
async run(signal) {
|
|
114
277
|
let attempt = 0;
|
|
115
278
|
try {
|
|
@@ -149,26 +312,354 @@ export class ForgeBridgeService {
|
|
|
149
312
|
this.abortActiveSessions("bridge stopping");
|
|
150
313
|
this.abortActiveReadinessProbes("bridge stopping");
|
|
151
314
|
await this.stopConnection();
|
|
315
|
+
this.hostLoad.stop();
|
|
152
316
|
await this.preflight.release();
|
|
153
317
|
}
|
|
154
|
-
async
|
|
155
|
-
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);
|
|
156
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);
|
|
157
640
|
return;
|
|
158
641
|
}
|
|
159
642
|
const leaseId = dispatch.lease.id;
|
|
160
643
|
const fencingToken = dispatch.lease.fencingToken;
|
|
161
644
|
const redactionSecrets = exactSecrets(dispatch, this.config);
|
|
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);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
162
649
|
const existing = this.activeSessions.get(leaseId);
|
|
163
650
|
if (existing) {
|
|
164
651
|
if (existing.fencingToken === fencingToken) {
|
|
652
|
+
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
165
653
|
return;
|
|
166
654
|
}
|
|
167
|
-
await this.sendResult(dispatch, failureResult("Dispatch fence conflicts with an active bridge session.")).catch(() => undefined);
|
|
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);
|
|
168
657
|
return;
|
|
169
658
|
}
|
|
170
|
-
const controller = new AbortController();
|
|
659
|
+
const controller = reservationHandoff?.controller ?? new AbortController();
|
|
171
660
|
this.activeSessions.set(leaseId, {
|
|
661
|
+
leaseId,
|
|
662
|
+
kind: "dispatch",
|
|
172
663
|
fencingToken,
|
|
173
664
|
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
174
665
|
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
@@ -179,6 +670,18 @@ export class ForgeBridgeService {
|
|
|
179
670
|
: zeroSandboxResources(),
|
|
180
671
|
controller
|
|
181
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();
|
|
182
685
|
try {
|
|
183
686
|
const normalized = this.normalizeDispatch(dispatch);
|
|
184
687
|
if (normalized.sandbox) {
|
|
@@ -205,7 +708,10 @@ export class ForgeBridgeService {
|
|
|
205
708
|
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
206
709
|
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
207
710
|
} : {}),
|
|
208
|
-
event: redactRunnerDispatchEvent(event, redactionSecrets)
|
|
711
|
+
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
712
|
+
}, {
|
|
713
|
+
replayCallbackTimeout: true,
|
|
714
|
+
signal: controller.signal,
|
|
209
715
|
});
|
|
210
716
|
}
|
|
211
717
|
catch (error) {
|
|
@@ -223,23 +729,86 @@ export class ForgeBridgeService {
|
|
|
223
729
|
if (normalized.sandbox?.executionMode === "docker") {
|
|
224
730
|
await this.flushCleanupReports().catch(() => undefined);
|
|
225
731
|
}
|
|
226
|
-
|
|
732
|
+
const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
|
|
733
|
+
await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
|
|
227
734
|
}
|
|
228
735
|
catch (error) {
|
|
229
736
|
const summary = controller.signal.aborted
|
|
230
737
|
? `Dispatch cancelled: ${String(controller.signal.reason ?? "cancelled")}`
|
|
231
738
|
: redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
|
|
232
|
-
const
|
|
739
|
+
const failureFacts = failureFactsFromError(error, {
|
|
740
|
+
cancelled: controller.signal.aborted,
|
|
741
|
+
source: "bridge",
|
|
742
|
+
});
|
|
743
|
+
const failureEventType = failureFacts.category === "unknown" ? null : failureFacts.code;
|
|
233
744
|
const failureEvents = failureEventType ? [{
|
|
234
745
|
role: "runner",
|
|
235
746
|
kind: "error",
|
|
236
747
|
content: summary,
|
|
237
748
|
eventType: failureEventType,
|
|
238
749
|
}] : [];
|
|
239
|
-
await this.sendResult(dispatch, failureResult(summary, failureEvents)).catch(() => undefined);
|
|
750
|
+
await this.sendResult(dispatch, failureResult(summary, failureEvents, failureFacts)).catch(() => undefined);
|
|
240
751
|
}
|
|
241
752
|
finally {
|
|
242
|
-
this.
|
|
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
|
+
]);
|
|
808
|
+
}
|
|
809
|
+
finally {
|
|
810
|
+
if (timer)
|
|
811
|
+
clearTimeout(timer);
|
|
243
812
|
}
|
|
244
813
|
}
|
|
245
814
|
async handleOffer(rawDispatch) {
|
|
@@ -247,20 +816,19 @@ export class ForgeBridgeService {
|
|
|
247
816
|
if (!envelope) {
|
|
248
817
|
return;
|
|
249
818
|
}
|
|
250
|
-
const dispatch = this.parseDispatchOrReport(envelope.dispatch);
|
|
819
|
+
const dispatch = await this.parseDispatchOrReport(envelope.dispatch);
|
|
251
820
|
if (!dispatch?.sandbox
|
|
252
821
|
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
253
822
|
|| dispatch.lease.id !== envelope.leaseId
|
|
254
823
|
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
255
824
|
return;
|
|
256
825
|
const sandbox = dispatch.sandbox;
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
this.reservations.delete(sandbox.dispatchAttemptId);
|
|
260
|
-
existing = undefined;
|
|
261
|
-
}
|
|
826
|
+
this.expireReservations(Date.now());
|
|
827
|
+
const existing = this.reservations.get(sandbox.dispatchAttemptId);
|
|
262
828
|
if (existing) {
|
|
263
|
-
const sameFence = existing.
|
|
829
|
+
const sameFence = existing.leaseId === dispatch.lease.id
|
|
830
|
+
&& existing.fencingToken === dispatch.lease.fencingToken
|
|
831
|
+
&& existing.runnerInstanceId === sandbox.runnerInstanceId;
|
|
264
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);
|
|
265
833
|
return;
|
|
266
834
|
}
|
|
@@ -287,7 +855,7 @@ export class ForgeBridgeService {
|
|
|
287
855
|
}
|
|
288
856
|
const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
|
|
289
857
|
if (providerNetworkFailure) {
|
|
290
|
-
await this.sendOfferDecision(dispatch, false, "
|
|
858
|
+
await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
|
|
291
859
|
return;
|
|
292
860
|
}
|
|
293
861
|
const authFailure = sandboxAuthFailure(dispatch, this.config);
|
|
@@ -296,15 +864,12 @@ export class ForgeBridgeService {
|
|
|
296
864
|
return;
|
|
297
865
|
}
|
|
298
866
|
}
|
|
299
|
-
const runtimeState = this.sandboxRuntime.snapshot();
|
|
300
|
-
const usedResources = this.usedSandboxResources(runtimeState.degraded);
|
|
301
|
-
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
302
|
-
const capacity = this.sandboxResourceCapacity(preflight, activeResources);
|
|
303
867
|
let requestedResources = sandbox.requestedResources;
|
|
304
868
|
let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
|
|
869
|
+
const normalizedDispatch = this.normalizeDispatch(dispatch);
|
|
305
870
|
if (sandbox.executionMode === "docker") {
|
|
306
871
|
try {
|
|
307
|
-
const profile = await this.sandboxResourceResolver(
|
|
872
|
+
const profile = await this.sandboxResourceResolver(normalizedDispatch);
|
|
308
873
|
requestedResources = profile.resources;
|
|
309
874
|
sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
|
|
310
875
|
}
|
|
@@ -313,73 +878,166 @@ export class ForgeBridgeService {
|
|
|
313
878
|
return;
|
|
314
879
|
}
|
|
315
880
|
}
|
|
316
|
-
if (
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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);
|
|
906
|
+
}
|
|
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
|
+
}
|
|
320
941
|
}
|
|
321
|
-
const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt),
|
|
322
|
-
|
|
942
|
+
const reservedUntil = new Date(Math.min(Date.parse(dispatch.lease.expiresAt), now + 30_000)).toISOString();
|
|
943
|
+
const reservation = {
|
|
323
944
|
leaseId: dispatch.lease.id,
|
|
324
945
|
fencingToken: dispatch.lease.fencingToken,
|
|
325
946
|
runnerInstanceId: sandbox.runnerInstanceId,
|
|
326
947
|
expiresAt: dispatch.lease.expiresAt,
|
|
327
948
|
reservedUntil,
|
|
328
949
|
sandboxed: sandbox.executionMode === "docker",
|
|
329
|
-
resources: requestedResources
|
|
330
|
-
}
|
|
331
|
-
|
|
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
|
+
};
|
|
332
960
|
}
|
|
333
961
|
async handleStart(rawDispatch) {
|
|
334
962
|
const envelope = parseStartEnvelope(rawDispatch);
|
|
335
963
|
if (!envelope) {
|
|
336
964
|
return;
|
|
337
965
|
}
|
|
338
|
-
let dispatch = this.parseDispatchOrReport(envelope.dispatch);
|
|
966
|
+
let dispatch = await this.parseDispatchOrReport(envelope.dispatch);
|
|
339
967
|
if (!dispatch?.sandbox
|
|
340
968
|
|| dispatch.sandbox.dispatchAttemptId !== envelope.dispatchAttemptId
|
|
341
969
|
|| dispatch.lease.id !== envelope.leaseId
|
|
342
970
|
|| dispatch.lease.fencingToken !== envelope.fencingToken)
|
|
343
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
|
+
}
|
|
344
979
|
const reservation = this.reservations.get(dispatch.sandbox.dispatchAttemptId);
|
|
345
980
|
if (!reservation
|
|
346
981
|
|| reservation.leaseId !== dispatch.lease.id
|
|
347
982
|
|| reservation.fencingToken !== dispatch.lease.fencingToken
|
|
348
983
|
|| reservation.runnerInstanceId !== dispatch.sandbox.runnerInstanceId
|
|
349
984
|
|| Date.parse(reservation.reservedUntil) <= Date.now()) {
|
|
350
|
-
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.")).catch(() => undefined);
|
|
985
|
+
await this.sendResult(dispatch, failureResult("Start rejected because its reservation is missing or stale.", [], failureFactsForCode("bridge.reservation_stale"))).catch(() => undefined);
|
|
351
986
|
return;
|
|
352
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;
|
|
353
999
|
if (dispatch.apiKeySecretGrant) {
|
|
354
|
-
this.
|
|
355
|
-
await this.sendResult(dispatch, failureResult("Start rejected because protocol-v2 packets may not contain a plaintext provider grant.")).catch(() => undefined);
|
|
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);
|
|
356
1002
|
return;
|
|
357
1003
|
}
|
|
358
1004
|
if (dispatch.apiKeySecretGrantHandle) {
|
|
359
|
-
|
|
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
|
+
}
|
|
360
1019
|
const grant = response.grant;
|
|
361
1020
|
if (!response.accepted
|
|
362
1021
|
|| !grant
|
|
363
1022
|
|| grant.grantId !== dispatch.apiKeySecretGrantHandle.grantId
|
|
364
1023
|
|| grant.provider !== dispatch.apiKeySecretGrantHandle.provider
|
|
365
1024
|
|| Date.parse(grant.expiresAt) <= Date.now()) {
|
|
366
|
-
this.
|
|
367
|
-
await this.sendResult(dispatch, failureResult(response.message ?? "Secret grant redemption was rejected.")).catch(() => undefined);
|
|
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);
|
|
368
1027
|
return;
|
|
369
1028
|
}
|
|
370
1029
|
dispatch = { ...dispatch, apiKeySecretGrant: grant, apiKeySecretGrantHandle: null };
|
|
371
1030
|
}
|
|
372
1031
|
else if (dispatch.execution.requiresApiKeySecretGrant) {
|
|
373
|
-
this.
|
|
374
|
-
await this.sendResult(dispatch, failureResult("Start rejected because the provider secret grant handle is missing.")).catch(() => undefined);
|
|
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);
|
|
375
1034
|
return;
|
|
376
1035
|
}
|
|
377
1036
|
dispatch = {
|
|
378
1037
|
...dispatch,
|
|
379
1038
|
sandbox: { ...dispatch.sandbox, requestedResources: reservation.resources },
|
|
380
1039
|
};
|
|
381
|
-
this.
|
|
382
|
-
await this.handleDispatch(dispatch);
|
|
1040
|
+
await this.handleDispatch(dispatch, startClaim);
|
|
383
1041
|
}
|
|
384
1042
|
async redeemSecretGrant(dispatch) {
|
|
385
1043
|
const sandbox = dispatch.sandbox;
|
|
@@ -443,7 +1101,7 @@ export class ForgeBridgeService {
|
|
|
443
1101
|
};
|
|
444
1102
|
await this.invokeAck("OfferDecision", payload);
|
|
445
1103
|
}
|
|
446
|
-
parseDispatchOrReport(rawDispatch) {
|
|
1104
|
+
async parseDispatchOrReport(rawDispatch) {
|
|
447
1105
|
try {
|
|
448
1106
|
return parseRunOnceDispatchPacket(rawDispatch);
|
|
449
1107
|
}
|
|
@@ -453,24 +1111,78 @@ export class ForgeBridgeService {
|
|
|
453
1111
|
return null;
|
|
454
1112
|
}
|
|
455
1113
|
const summary = invalidDispatchSummary(error);
|
|
456
|
-
|
|
1114
|
+
await this.sendLegacyResult(identifiers.leaseId, identifiers.fencingToken, failureResult(summary, [
|
|
457
1115
|
{
|
|
458
1116
|
role: "runner",
|
|
459
1117
|
kind: "error",
|
|
460
1118
|
content: summary,
|
|
461
1119
|
eventType: "invalid_dispatch"
|
|
462
1120
|
}
|
|
463
|
-
])).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));
|
|
464
1131
|
return null;
|
|
465
1132
|
}
|
|
466
1133
|
}
|
|
467
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
|
+
}
|
|
468
1150
|
const active = this.activeSessions.get(request.leaseId);
|
|
469
1151
|
if (!active || active.fencingToken !== request.fencingToken) {
|
|
470
1152
|
return;
|
|
471
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
|
+
}
|
|
472
1163
|
active.controller.abort(request.reason ?? "cancelled by server");
|
|
473
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
|
+
}
|
|
474
1186
|
async handleReap(request) {
|
|
475
1187
|
if (request.runnerId !== this.config.runnerId
|
|
476
1188
|
|| request.runnerInstanceId !== this.config.runnerInstanceId)
|
|
@@ -492,32 +1204,43 @@ export class ForgeBridgeService {
|
|
|
492
1204
|
timer.unref?.();
|
|
493
1205
|
let result;
|
|
494
1206
|
try {
|
|
495
|
-
|
|
496
|
-
throw new Error("host_runtime_probe_unavailable: this bridge does not implement runtime readiness probes.");
|
|
497
|
-
}
|
|
498
|
-
const probe = await this.sessions.probeHostRuntime({
|
|
499
|
-
...request,
|
|
500
|
-
runnerId: this.config.runnerId,
|
|
501
|
-
repoRoot: this.config.defaultRepoRoot,
|
|
502
|
-
cleanupWorktrees: this.config.cleanupWorktrees,
|
|
503
|
-
}, controller.signal);
|
|
504
|
-
result = {
|
|
1207
|
+
const accepted = {
|
|
505
1208
|
schemaVersion: 1,
|
|
506
1209
|
requestId: request.requestId,
|
|
507
1210
|
fencingToken: request.fencingToken,
|
|
508
1211
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
509
|
-
|
|
1212
|
+
acceptedAt: new Date().toISOString(),
|
|
510
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
|
+
}
|
|
511
1233
|
}
|
|
512
1234
|
catch (error) {
|
|
1235
|
+
const deferredReason = readinessDeferralReason(controller.signal);
|
|
513
1236
|
result = {
|
|
514
1237
|
schemaVersion: 1,
|
|
515
1238
|
requestId: request.requestId,
|
|
516
1239
|
fencingToken: request.fencingToken,
|
|
517
1240
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
518
1241
|
status: "failed",
|
|
519
|
-
reasonCode: "host_runtime_probe_failed",
|
|
520
|
-
reasonMessage: errorMessage(error).slice(0, 1000),
|
|
1242
|
+
reasonCode: deferredReason ? "host_runtime_probe_deferred" : "host_runtime_probe_failed",
|
|
1243
|
+
reasonMessage: (deferredReason ?? errorMessage(error)).slice(0, 1000),
|
|
521
1244
|
checkedAt: new Date().toISOString(),
|
|
522
1245
|
};
|
|
523
1246
|
}
|
|
@@ -525,9 +1248,69 @@ export class ForgeBridgeService {
|
|
|
525
1248
|
clearTimeout(timer);
|
|
526
1249
|
this.activeReadinessProbes.delete(request.requestId);
|
|
527
1250
|
}
|
|
528
|
-
|
|
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
|
+
}
|
|
529
1273
|
await this.sendHeartbeat().catch(() => undefined);
|
|
530
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
|
+
}
|
|
531
1314
|
abortActiveSessions(reason) {
|
|
532
1315
|
for (const active of this.activeSessions.values()) {
|
|
533
1316
|
active.controller.abort(reason);
|
|
@@ -539,8 +1322,42 @@ export class ForgeBridgeService {
|
|
|
539
1322
|
controller.abort(reason);
|
|
540
1323
|
this.activeReadinessProbes.clear();
|
|
541
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
|
+
}
|
|
542
1359
|
normalizeDispatch(dispatch) {
|
|
543
|
-
const mapping = findRepoMapping(dispatch, repoMappingsFor(this.config));
|
|
1360
|
+
const mapping = findRepoMapping(dispatch.repo, repoMappingsFor(this.config));
|
|
544
1361
|
const localPath = mapping?.localPath?.trim();
|
|
545
1362
|
const repoRoot = localPath ? path.dirname(path.resolve(localPath)) : this.config.defaultRepoRoot;
|
|
546
1363
|
const qaLaunchTarget = normalizeQaAppLaunchTarget(mapping?.qaAppLaunchTarget) ?? dispatch.qaBrowser?.launchTarget ?? null;
|
|
@@ -569,24 +1386,132 @@ export class ForgeBridgeService {
|
|
|
569
1386
|
fencingToken: dispatch.lease.fencingToken,
|
|
570
1387
|
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
571
1388
|
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
572
|
-
|
|
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))
|
|
573
1392
|
};
|
|
574
|
-
await this.sendResultPayload(payload);
|
|
1393
|
+
await this.sendResultPayload(payload, () => this.releaseActiveSessionAndRefreshCapacity(dispatch.lease.id, dispatch));
|
|
575
1394
|
}
|
|
576
1395
|
async sendLegacyResult(leaseId, fencingToken, result) {
|
|
577
1396
|
await this.sendResultPayload({ leaseId, fencingToken, result });
|
|
578
1397
|
}
|
|
579
|
-
async sendResultPayload(payload) {
|
|
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) {
|
|
580
1432
|
try {
|
|
581
1433
|
await this.invokeAck("DispatchResult", payload);
|
|
582
1434
|
}
|
|
583
1435
|
catch (error) {
|
|
584
|
-
if (isDispatchNoLongerPending(error))
|
|
1436
|
+
if (isDispatchNoLongerPending(error))
|
|
585
1437
|
return;
|
|
586
|
-
}
|
|
587
1438
|
throw error;
|
|
588
1439
|
}
|
|
589
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)
|
|
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
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if (records.length < 3)
|
|
1495
|
+
break;
|
|
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();
|
|
1514
|
+
}
|
|
590
1515
|
startHeartbeat() {
|
|
591
1516
|
this.stopHeartbeat();
|
|
592
1517
|
this.consecutiveHeartbeatFailures = 0;
|
|
@@ -605,6 +1530,11 @@ export class ForgeBridgeService {
|
|
|
605
1530
|
return;
|
|
606
1531
|
this.heartbeatInFlight = true;
|
|
607
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"));
|
|
608
1538
|
await this.sendHeartbeat();
|
|
609
1539
|
this.consecutiveHeartbeatFailures = 0;
|
|
610
1540
|
}
|
|
@@ -637,17 +1567,20 @@ export class ForgeBridgeService {
|
|
|
637
1567
|
}
|
|
638
1568
|
expireLeases() {
|
|
639
1569
|
const now = Date.now();
|
|
640
|
-
|
|
641
|
-
if (Date.parse(reservation.expiresAt) <= now || Date.parse(reservation.reservedUntil) <= now) {
|
|
642
|
-
this.reservations.delete(attemptId);
|
|
643
|
-
}
|
|
644
|
-
}
|
|
1570
|
+
this.expireReservations(now);
|
|
645
1571
|
for (const active of this.activeSessions.values()) {
|
|
646
1572
|
if (Date.parse(active.leaseExpiresAt) <= now && !active.controller.signal.aborted) {
|
|
647
1573
|
active.controller.abort("dispatch lease expired");
|
|
648
1574
|
}
|
|
649
1575
|
}
|
|
650
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
|
+
}
|
|
651
1584
|
stopHeartbeat() {
|
|
652
1585
|
if (this.heartbeatTimer) {
|
|
653
1586
|
clearInterval(this.heartbeatTimer);
|
|
@@ -676,6 +1609,7 @@ export class ForgeBridgeService {
|
|
|
676
1609
|
runnerId: this.config.runnerId,
|
|
677
1610
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
678
1611
|
});
|
|
1612
|
+
this.rememberRecoveredHostAttempts(hostReap);
|
|
679
1613
|
if (hostReap && (hostReap.reaped > 0 || hostReap.degraded > 0)) {
|
|
680
1614
|
logBridgeStatus(`Managed-host maintenance reaped ${hostReap.reaped} stale attempt(s) and left ${hostReap.degraded} degraded attempt(s) for reconciliation.`);
|
|
681
1615
|
}
|
|
@@ -716,22 +1650,50 @@ export class ForgeBridgeService {
|
|
|
716
1650
|
}
|
|
717
1651
|
}
|
|
718
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) {
|
|
719
1670
|
await this.invokeAck("Heartbeat", {
|
|
720
1671
|
status: "online",
|
|
721
1672
|
capabilities: this.capabilities(),
|
|
722
1673
|
version: this.config.version,
|
|
723
1674
|
protocolVersion: this.config.protocolVersion
|
|
724
|
-
});
|
|
1675
|
+
}, { signal });
|
|
725
1676
|
}
|
|
726
1677
|
capabilities() {
|
|
727
1678
|
const preflight = this.preflight.current();
|
|
1679
|
+
const dockerEngine = this.dockerEngineProbe.current();
|
|
728
1680
|
const runtimeState = this.sandboxRuntime.snapshot();
|
|
729
1681
|
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
730
1682
|
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
731
1683
|
const activeResources = this.activeSandboxResources(runtimeState.degraded);
|
|
732
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;
|
|
733
1695
|
return {
|
|
734
|
-
schemaVersion:
|
|
1696
|
+
schemaVersion: 7,
|
|
735
1697
|
activeSessionCount: this.activeSessions.size,
|
|
736
1698
|
cliProviders: this.config.cliProviders,
|
|
737
1699
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -741,6 +1703,21 @@ export class ForgeBridgeService {
|
|
|
741
1703
|
sandboxProfiles: this.config.sandboxProfiles,
|
|
742
1704
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
743
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(),
|
|
744
1721
|
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
745
1722
|
reservedSandboxCount: reserved,
|
|
746
1723
|
activeSandboxCount: runtimeState.active,
|
|
@@ -752,7 +1729,7 @@ export class ForgeBridgeService {
|
|
|
752
1729
|
allowsOpenPublicSandbox: this.config.allowOpenPublicSandbox,
|
|
753
1730
|
sandboxPublicationModes: [this.config.sandboxPublicationMode ?? "shared_filesystem"],
|
|
754
1731
|
sandboxAuthModes: sandboxAuthModesFor(this.config),
|
|
755
|
-
availableMemoryBytes:
|
|
1732
|
+
availableMemoryBytes: memoryAdmission?.availableForAdmissionBytes ?? null,
|
|
756
1733
|
availableCpuMillis: preflight ? Math.max(0, capacity.cpuMillis - used.cpuMillis) : null,
|
|
757
1734
|
availableWorkspaceBytes: preflight ? Math.max(0, capacity.workspaceBytes - used.workspaceBytes) : null,
|
|
758
1735
|
diskLow: preflight?.diskLow ?? null,
|
|
@@ -766,8 +1743,11 @@ export class ForgeBridgeService {
|
|
|
766
1743
|
hostReserveBytes: preflight.hostReserveBytes,
|
|
767
1744
|
activeReservationBytes: used.memoryBytes,
|
|
768
1745
|
daemonTotalBytes: preflight.totalMemoryBytes,
|
|
769
|
-
daemonAvailableBytes: preflight.
|
|
770
|
-
|
|
1746
|
+
daemonAvailableBytes: preflight.rawDaemonAvailableMemoryBytes ?? 0,
|
|
1747
|
+
hostAvailableBytes: preflight.rawHostAvailableMemoryBytes,
|
|
1748
|
+
conservativeAvailableBytes: preflight.rawAvailableMemoryBytes,
|
|
1749
|
+
availableForAdmissionBytes: memoryAdmission.availableForAdmissionBytes,
|
|
1750
|
+
memoryAdmission: memoryAdmission,
|
|
771
1751
|
} : null,
|
|
772
1752
|
hostRuntime: this.sessions.runtimeCapacity?.() ?? null,
|
|
773
1753
|
supportsApiSecretGrant: this.config.supportsApiSecretGrant,
|
|
@@ -776,9 +1756,20 @@ export class ForgeBridgeService {
|
|
|
776
1756
|
supportsRunnerAuthoredPhaseArtifacts: this.config.supportsRunnerAuthoredPhaseArtifacts,
|
|
777
1757
|
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
778
1758
|
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
779
|
-
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments
|
|
1759
|
+
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
|
|
1760
|
+
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
|
|
780
1761
|
};
|
|
781
1762
|
}
|
|
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
|
+
}
|
|
782
1773
|
usedSandboxResources(degradedReservations) {
|
|
783
1774
|
const resources = [
|
|
784
1775
|
...[...this.reservations.values()]
|
|
@@ -811,9 +1802,7 @@ export class ForgeBridgeService {
|
|
|
811
1802
|
workerMemoryLimitBytes: 0,
|
|
812
1803
|
serviceMemoryLimitBytes: 0,
|
|
813
1804
|
runtimeOverheadBytes: 0,
|
|
814
|
-
memoryBytes:
|
|
815
|
-
- (this.config.sandboxHostMemoryReserveBytes ?? 2 * 1024 ** 3)
|
|
816
|
-
+ activeResources.memoryBytes),
|
|
1805
|
+
memoryBytes: sandboxMemoryCommitmentCapacity(preflight, activeResources.memoryBytes),
|
|
817
1806
|
workspaceBytes: Math.max(0, preflight.availableWorkspaceBytes
|
|
818
1807
|
- this.config.minimumWorkspaceBytes
|
|
819
1808
|
+ activeResources.workspaceBytes),
|
|
@@ -821,22 +1810,96 @@ export class ForgeBridgeService {
|
|
|
821
1810
|
buildSlots: this.config.maxConcurrentSandboxBuilds
|
|
822
1811
|
};
|
|
823
1812
|
}
|
|
824
|
-
async invokeAck(methodName, payload) {
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
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
|
+
}
|
|
828
1859
|
}
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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;
|
|
832
1890
|
}
|
|
833
|
-
|
|
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;
|
|
834
1897
|
}
|
|
835
1898
|
async waitForClose(signal) {
|
|
836
1899
|
if (!this.closed) {
|
|
837
1900
|
return;
|
|
838
1901
|
}
|
|
839
|
-
await
|
|
1902
|
+
await waitForPromiseOrAbort(this.closed, signal);
|
|
840
1903
|
}
|
|
841
1904
|
async stopConnection() {
|
|
842
1905
|
this.stopHeartbeat();
|
|
@@ -856,17 +1919,36 @@ class BridgeCallbackRejectedError extends Error {
|
|
|
856
1919
|
this.name = "BridgeCallbackRejectedError";
|
|
857
1920
|
}
|
|
858
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
|
+
}
|
|
859
1929
|
function isDispatchNoLongerPending(error) {
|
|
860
1930
|
if (error instanceof BridgeCallbackRejectedError) {
|
|
861
1931
|
return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
|
|
862
1932
|
}
|
|
863
1933
|
return error instanceof Error && error.message === "Dispatch is no longer pending.";
|
|
864
1934
|
}
|
|
865
|
-
function
|
|
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) {
|
|
866
1948
|
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
867
1949
|
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
868
1950
|
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
869
|
-
return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner)), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, 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)));
|
|
870
1952
|
}
|
|
871
1953
|
export class SignalRBridgeConnectionFactory {
|
|
872
1954
|
create(config) {
|
|
@@ -890,10 +1972,11 @@ export class SignalRBridgeConnection {
|
|
|
890
1972
|
Authorization: `Bearer ${config.deviceToken}`
|
|
891
1973
|
}
|
|
892
1974
|
})
|
|
1975
|
+
.withAutomaticReconnect([...config.reconnectBackoffMs])
|
|
893
1976
|
.configureLogging(LogLevel.Warning)
|
|
894
1977
|
.build();
|
|
895
1978
|
this.connection.on("Superseded", () => {
|
|
896
|
-
void this.connection.stop();
|
|
1979
|
+
void this.connection.stop().catch(() => undefined);
|
|
897
1980
|
});
|
|
898
1981
|
}
|
|
899
1982
|
start() {
|
|
@@ -905,11 +1988,24 @@ export class SignalRBridgeConnection {
|
|
|
905
1988
|
onClose(handler) {
|
|
906
1989
|
this.connection.onclose(handler);
|
|
907
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
|
+
}
|
|
908
1999
|
onDispatch(handler) {
|
|
909
2000
|
this.connection.on("Dispatch", (raw) => {
|
|
910
2001
|
void handler(raw).catch(() => undefined);
|
|
911
2002
|
});
|
|
912
2003
|
}
|
|
2004
|
+
onChatTurn(handler) {
|
|
2005
|
+
this.connection.on("ChatTurn", (raw) => {
|
|
2006
|
+
void handler(raw).catch(() => undefined);
|
|
2007
|
+
});
|
|
2008
|
+
}
|
|
913
2009
|
onOffer(handler) {
|
|
914
2010
|
this.connection.on("Offer", (raw) => {
|
|
915
2011
|
void handler(raw).catch(() => undefined);
|
|
@@ -947,9 +2043,7 @@ export class SignalRBridgeConnection {
|
|
|
947
2043
|
export function defaultBridgeServiceConfig(overrides = {}) {
|
|
948
2044
|
const defaults = defaultForgeBridgeConfig();
|
|
949
2045
|
const cliProviders = splitCsv(process.env.FORGE_CLI_PROVIDERS ?? "codex");
|
|
950
|
-
const
|
|
951
|
-
? 2 * 1024 ** 3
|
|
952
|
-
: 1024 ** 3;
|
|
2046
|
+
const configuredSandboxHostMemoryReserveBytes = optionalPositiveFiniteNumber(process.env.FORGE_SANDBOX_HOST_MEMORY_RESERVE_BYTES);
|
|
953
2047
|
const sandboxPublicationMode = process.env.FORGE_SANDBOX_PUBLICATION_MODE === "bridge_push" ? "bridge_push" : "shared_filesystem";
|
|
954
2048
|
const config = {
|
|
955
2049
|
serverUrl: process.env.FORGE_URL ?? "http://localhost:5208",
|
|
@@ -964,12 +2058,19 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
964
2058
|
sandboxPublicationMode,
|
|
965
2059
|
dockerExecutable: process.env.FORGE_DOCKER_EXECUTABLE ?? "docker",
|
|
966
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),
|
|
967
2065
|
sandboxStateRoot: process.env.FORGE_SANDBOX_STATE_ROOT ?? path.join(os.homedir(), ".forge", "bridge", "sandboxes"),
|
|
2066
|
+
sandboxExecutionRoot: defaultHostExecutionRoot(),
|
|
968
2067
|
requireRootlessDocker: process.env.FORGE_REQUIRE_ROOTLESS_DOCKER === "true" || process.platform === "linux",
|
|
969
2068
|
diskHighWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_HIGH_WATERMARK_PERCENT ?? 85), 85),
|
|
970
2069
|
diskLowWatermarkPercent: positiveFiniteNumber(Number(process.env.FORGE_DISK_LOW_WATERMARK_PERCENT ?? 75), 75),
|
|
971
2070
|
minimumWorkspaceBytes: positiveFiniteNumber(Number(process.env.FORGE_MINIMUM_WORKSPACE_BYTES ?? 10 * 1024 ** 3), 10 * 1024 ** 3),
|
|
972
|
-
|
|
2071
|
+
// Undefined means preflight derives the bounded reserve from the actual
|
|
2072
|
+
// Docker/host capacity domain after sampling it.
|
|
2073
|
+
sandboxHostMemoryReserveBytes: configuredSandboxHostMemoryReserveBytes,
|
|
973
2074
|
defaultSandboxWorkerMemoryLimitBytes: positiveFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_WORKER_MEMORY_LIMIT_BYTES ?? 2 * 1024 ** 3), 2 * 1024 ** 3),
|
|
974
2075
|
defaultSandboxServiceMemoryLimitBytes: nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_DEFAULT_SERVICE_MEMORY_LIMIT_BYTES ?? 0), 0),
|
|
975
2076
|
sandboxRuntimeOverheadBytes: Math.max(128 * 1024 ** 2, nonNegativeFiniteNumber(Number(process.env.FORGE_SANDBOX_RUNTIME_OVERHEAD_BYTES ?? 128 * 1024 ** 2), 128 * 1024 ** 2)),
|
|
@@ -995,10 +2096,12 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
995
2096
|
supportsDraftRunOnce: true,
|
|
996
2097
|
supportsDraftAttachments: true,
|
|
997
2098
|
supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(cliProviders),
|
|
2099
|
+
bridgeChat: bridgeChatCapabilityFor(cliProviders, providerStatusesFor(cliProviders)),
|
|
998
2100
|
version: process.env.FORGE_BRIDGE_VERSION ?? forgeBridgeVersion,
|
|
999
|
-
protocolVersion:
|
|
2101
|
+
protocolVersion: 4,
|
|
1000
2102
|
minServerVersion: null,
|
|
1001
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),
|
|
1002
2105
|
reconnectBackoffMs: [1000, 2000, 5000, 10000, 30000],
|
|
1003
2106
|
...overrides
|
|
1004
2107
|
};
|
|
@@ -1007,7 +2110,9 @@ export function defaultBridgeServiceConfig(overrides = {}) {
|
|
|
1007
2110
|
providerStatuses: overrides.providerStatuses ?? providerStatusesFor(config.cliProviders),
|
|
1008
2111
|
sandboxProfiles: config.sandboxProfiles ?? defaultSandboxProfiles(config.cliProviders),
|
|
1009
2112
|
supportsDraftImageAttachments: (overrides.supportsDraftImageAttachments ?? true) && supportsDraftImageAttachmentsFor(config.cliProviders),
|
|
1010
|
-
|
|
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),
|
|
1011
2116
|
};
|
|
1012
2117
|
}
|
|
1013
2118
|
export function resolveBridgeRunnerHubUrl(serverUrl) {
|
|
@@ -1022,6 +2127,12 @@ function normalizeServerUrl(serverUrl) {
|
|
|
1022
2127
|
function positiveFiniteNumber(value, fallback) {
|
|
1023
2128
|
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
1024
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
|
+
}
|
|
1025
2136
|
function nonNegativeFiniteNumber(value, fallback) {
|
|
1026
2137
|
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
1027
2138
|
}
|
|
@@ -1126,15 +2237,32 @@ function mappingKeys(mapping) {
|
|
|
1126
2237
|
mapping.localPath ? `path:${path.resolve(mapping.localPath).toLowerCase()}` : null
|
|
1127
2238
|
].filter((key) => Boolean(key));
|
|
1128
2239
|
}
|
|
1129
|
-
function findRepoMapping(
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
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}.`);
|
|
1133
2245
|
}
|
|
1134
|
-
return
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
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;
|
|
1138
2266
|
}
|
|
1139
2267
|
function normalizeQaAppLaunchTarget(target) {
|
|
1140
2268
|
if (!target) {
|
|
@@ -1183,6 +2311,10 @@ function invalidDispatchSummary(error) {
|
|
|
1183
2311
|
const detail = error instanceof Error ? error.message : String(error);
|
|
1184
2312
|
return `Invalid bridge dispatch packet: ${detail}`;
|
|
1185
2313
|
}
|
|
2314
|
+
function invalidChatTurnSummary(error) {
|
|
2315
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2316
|
+
return `Invalid Bridge Chat turn packet: ${detail}`;
|
|
2317
|
+
}
|
|
1186
2318
|
function errorMessage(error) {
|
|
1187
2319
|
return error instanceof Error ? error.message : String(error);
|
|
1188
2320
|
}
|
|
@@ -1192,29 +2324,328 @@ function formatDelay(ms) {
|
|
|
1192
2324
|
}
|
|
1193
2325
|
return `${ms}ms`;
|
|
1194
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
|
+
}
|
|
1195
2351
|
function logBridgeStatus(message) {
|
|
1196
2352
|
process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
|
|
1197
2353
|
}
|
|
1198
|
-
function delay(ms, signal) {
|
|
2354
|
+
export function delay(ms, signal) {
|
|
1199
2355
|
if (signal?.aborted) {
|
|
1200
2356
|
return Promise.resolve();
|
|
1201
2357
|
}
|
|
1202
2358
|
return new Promise((resolve) => {
|
|
1203
|
-
const
|
|
1204
|
-
signal?.addEventListener("abort", () => {
|
|
2359
|
+
const complete = () => {
|
|
1205
2360
|
clearTimeout(timeout);
|
|
2361
|
+
signal?.removeEventListener("abort", complete);
|
|
1206
2362
|
resolve();
|
|
1207
|
-
}
|
|
2363
|
+
};
|
|
2364
|
+
const timeout = setTimeout(complete, ms);
|
|
2365
|
+
signal?.addEventListener("abort", complete, { once: true });
|
|
2366
|
+
if (signal?.aborted)
|
|
2367
|
+
complete();
|
|
1208
2368
|
});
|
|
1209
2369
|
}
|
|
1210
|
-
function
|
|
2370
|
+
export async function waitForPromiseOrAbort(promise, signal) {
|
|
1211
2371
|
if (!signal) {
|
|
1212
|
-
|
|
2372
|
+
await promise;
|
|
2373
|
+
return;
|
|
1213
2374
|
}
|
|
1214
2375
|
if (signal.aborted) {
|
|
1215
|
-
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 } };
|
|
1216
2482
|
}
|
|
1217
|
-
|
|
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);
|
|
1218
2649
|
}
|
|
1219
2650
|
export function canReapManagedSandboxes(preflight) {
|
|
1220
2651
|
return canRunDockerMaintenance(preflight);
|
|
@@ -1234,24 +2665,15 @@ function sandboxNetworkPolicyFailure(dispatch, config) {
|
|
|
1234
2665
|
}
|
|
1235
2666
|
return null;
|
|
1236
2667
|
}
|
|
1237
|
-
function
|
|
1238
|
-
if (
|
|
1239
|
-
return
|
|
1240
|
-
if (
|
|
1241
|
-
return "
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
if (summary.startsWith("host_runtime_listener_timeout:"))
|
|
1247
|
-
return "host_runtime_listener_timeout";
|
|
1248
|
-
if (summary.startsWith("host_runtime_http_readiness_timeout:"))
|
|
1249
|
-
return "host_runtime_http_readiness_timeout";
|
|
1250
|
-
if (summary.startsWith("attempt_process_supervisor_start_failed:"))
|
|
1251
|
-
return "attempt_process_supervisor_start_failed";
|
|
1252
|
-
if (summary.startsWith("attempt_process_supervisor_start_timeout:"))
|
|
1253
|
-
return "attempt_process_supervisor_start_timeout";
|
|
1254
|
-
return null;
|
|
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."}`;
|
|
1255
2677
|
}
|
|
1256
2678
|
function parseReadinessProbe(value) {
|
|
1257
2679
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
@@ -1279,6 +2701,24 @@ function parseReadinessProbe(value) {
|
|
|
1279
2701
|
}
|
|
1280
2702
|
return request;
|
|
1281
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
|
+
}
|
|
1282
2722
|
function sandboxProviderNetworkFailure(dispatch, config) {
|
|
1283
2723
|
const sandbox = dispatch.sandbox;
|
|
1284
2724
|
if (!sandbox || sandbox.networkPolicy.mode !== "offline")
|
|
@@ -1308,6 +2748,15 @@ function sandboxAuthFailure(dispatch, config) {
|
|
|
1308
2748
|
const doctor = adapter.doctor();
|
|
1309
2749
|
return doctor.available ? null : doctor.message;
|
|
1310
2750
|
}
|
|
2751
|
+
function rejectedOfferReservation(code, message) {
|
|
2752
|
+
return {
|
|
2753
|
+
accepted: false,
|
|
2754
|
+
code,
|
|
2755
|
+
message,
|
|
2756
|
+
reservedUntil: null,
|
|
2757
|
+
resources: null,
|
|
2758
|
+
};
|
|
2759
|
+
}
|
|
1311
2760
|
export function canReserveSandboxResources(used, requested, capacity) {
|
|
1312
2761
|
return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
|
|
1313
2762
|
&& used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
|
|
@@ -1316,6 +2765,14 @@ export function canReserveSandboxResources(used, requested, capacity) {
|
|
|
1316
2765
|
&& used.pids + requested.pids <= capacity.pids
|
|
1317
2766
|
&& used.buildSlots + requested.buildSlots <= capacity.buildSlots;
|
|
1318
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
|
+
}
|
|
1319
2776
|
export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
|
|
1320
2777
|
const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
|
|
1321
2778
|
if (requested.sandboxSlots > availableSlots) {
|
|
@@ -1346,14 +2803,6 @@ export function sandboxCapacityFailureMessage(used, requested, capacity, preflig
|
|
|
1346
2803
|
const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
|
|
1347
2804
|
return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
|
|
1348
2805
|
}
|
|
1349
|
-
function formatBytes(bytes) {
|
|
1350
|
-
if (!Number.isFinite(bytes) || bytes <= 0)
|
|
1351
|
-
return "0 B";
|
|
1352
|
-
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
|
|
1353
|
-
const power = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
|
|
1354
|
-
const value = bytes / 1024 ** power;
|
|
1355
|
-
return `${value >= 10 || power === 0 ? value.toFixed(0) : value.toFixed(2)} ${units[power]}`;
|
|
1356
|
-
}
|
|
1357
2806
|
function sumSandboxResources(resources) {
|
|
1358
2807
|
return resources.reduce((total, resource) => ({
|
|
1359
2808
|
sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
|
|
@@ -1425,8 +2874,16 @@ export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverh
|
|
|
1425
2874
|
throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
|
|
1426
2875
|
}
|
|
1427
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
|
+
});
|
|
1428
2882
|
return {
|
|
1429
|
-
resources: resolveDynamicSandboxResources(
|
|
2883
|
+
resources: resolveDynamicSandboxResources({
|
|
2884
|
+
...sandbox.requestedResources,
|
|
2885
|
+
workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
|
|
2886
|
+
}, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
|
|
1430
2887
|
sandboxConfigCommitSha: configCommitSha,
|
|
1431
2888
|
};
|
|
1432
2889
|
}
|