@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366
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 +142 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +88 -14
- package/dist/bridge/bridge.service.js +406 -345
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +3 -0
- package/dist/bridge/runner-host-capabilities.js +13 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +11 -1
- package/dist/cleanup/cleanup.service.js +80 -62
- package/dist/cleanup/cleanup.types.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.js +30 -9
- package/dist/cli/cli.help.js +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +142 -185
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-load-admission.d.ts +18 -3
- package/dist/runtime/host-load-admission.js +19 -4
- package/dist/runtime/host-load-child-environment.d.ts +11 -6
- package/dist/runtime/host-load-child-environment.js +22 -11
- package/dist/runtime/host-load-governor-config.d.ts +19 -1
- package/dist/runtime/host-load-governor-config.js +37 -0
- package/dist/runtime/host-load-governor.d.ts +14 -0
- package/dist/runtime/host-load-governor.js +139 -26
- package/dist/runtime/host-load-ledger-lock.js +6 -4
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +34 -4
- package/dist/runtime/host-load-sampler.js +73 -7
- package/dist/runtime/host-load-step-class.d.ts +3 -1
- package/dist/runtime/host-load-step-class.js +60 -5
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +26 -0
- package/dist/runtime/host-load-token-ledger.js +93 -61
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-runtime-contract.d.ts +12 -0
- package/dist/runtime/host-runtime-contract.js +29 -1
- package/dist/runtime/host-runtime-lease.d.ts +62 -4
- package/dist/runtime/host-runtime-lease.js +235 -168
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +36 -0
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +10 -2
- package/dist/sandbox/host-capacity-broker.js +27 -6
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.js +2 -6
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +0 -7
- package/dist/session/managed-attempt-tools.js +58 -91
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +2 -0
- package/dist/session/managed-command-host-load.js +2 -1
- package/dist/session/phase-completion.artifacts.js +2 -1
- package/dist/session/phase-completion.d.ts +8 -0
- package/dist/session/phase-completion.js +1 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.runtime.d.ts +0 -8
- package/dist/session/phase-completion.runtime.js +43 -197
- package/dist/session/phase-completion.schemas.js +25 -23
- package/dist/session/phase-completion.validation.js +3 -1
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.js +10 -10
- package/dist/session/pre-publication-step-execution.d.ts +2 -1
- package/dist/session/pre-publication-step-execution.js +6 -5
- package/dist/session/pre-publication-validation.d.ts +30 -14
- package/dist/session/pre-publication-validation.js +207 -134
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +39 -430
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
- package/dist/session/provider-cli/provider-cli.service.js +78 -171
- package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
- package/dist/session/sandbox-host-capacity-gate.js +42 -14
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +6 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +169 -66
- package/dist/session/session.types.js +4 -4
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +13 -1
- package/dist/shared/process/host-process-supervisor.js +66 -14
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +14 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +50 -0
- package/dist/worktree/worktree-wip.js +185 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +27 -5
- package/dist/worktree/worktree.service.js +110 -181
- package/dist/worktree/worktree.types.d.ts +31 -0
- package/package.json +2 -2
|
@@ -8,13 +8,16 @@ import { defaultForgeBridgeConfig } from "../config.js";
|
|
|
8
8
|
import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
9
9
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
10
10
|
import { BridgeSessionService } from "../session/session.service.js";
|
|
11
|
-
import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
12
|
-
import {
|
|
11
|
+
import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
12
|
+
import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
|
|
13
13
|
import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
|
|
14
14
|
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
15
15
|
import { PrePublicationValidator } from "../session/pre-publication-validation.js";
|
|
16
16
|
import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
|
|
17
|
-
import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
|
|
17
|
+
import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
|
|
18
|
+
import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
|
|
19
|
+
import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
|
|
20
|
+
import { readLocalYieldFlag } from "./local-yield-flag.js";
|
|
18
21
|
import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
|
|
19
22
|
import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
|
|
20
23
|
import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
@@ -28,16 +31,17 @@ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegist
|
|
|
28
31
|
import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
29
32
|
import { forgeBridgeVersion } from "../version.js";
|
|
30
33
|
import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
|
|
31
|
-
import {
|
|
32
|
-
import { runSandboxProcess } from "../sandbox/process.js";
|
|
33
|
-
import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
|
|
34
|
+
import { DockerSandboxRuntime } from "../sandbox/runtime.js";
|
|
34
35
|
import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
|
|
35
36
|
import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
|
|
36
|
-
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
37
37
|
import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
|
|
38
38
|
import { HostLoadSampler } from "../runtime/host-load-sampler.js";
|
|
39
|
-
import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
|
|
39
|
+
import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
|
|
40
40
|
import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
41
|
+
import { BridgeStatePublisher } from "./bridge-state-file.js";
|
|
42
|
+
import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
|
|
43
|
+
import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
|
|
44
|
+
export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
|
|
41
45
|
/**
|
|
42
46
|
* Protocol-v2 events are acknowledged one at a time before runOnce returns.
|
|
43
47
|
* Sending the complete transcript again in DispatchResult made long QA and CI
|
|
@@ -65,13 +69,17 @@ export class ForgeBridgeService {
|
|
|
65
69
|
leaseWatchdogTimer = null;
|
|
66
70
|
sandboxMaintenanceTimer = null;
|
|
67
71
|
sandboxMaintenanceRunning = false;
|
|
72
|
+
attemptSnapshotPending = null;
|
|
68
73
|
closed = null;
|
|
69
74
|
transportRecovery = null;
|
|
70
75
|
transportRecoveryGeneration = 0;
|
|
71
76
|
stopped = false;
|
|
77
|
+
revokedReason = null;
|
|
72
78
|
activeSessions = new Map();
|
|
73
79
|
reservations = new Map();
|
|
74
80
|
activeReadinessProbes = new Map();
|
|
81
|
+
/** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
|
|
82
|
+
inFlight = new BridgeInFlightRegistry();
|
|
75
83
|
readinessResultOutbox;
|
|
76
84
|
readinessResultFlush = null;
|
|
77
85
|
dispatchResultOutbox;
|
|
@@ -87,6 +95,22 @@ export class ForgeBridgeService {
|
|
|
87
95
|
enforceHostDatabaseCapabilityBoundary;
|
|
88
96
|
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
89
97
|
dockerAvailable = false;
|
|
98
|
+
// Decision 0014 settings push. The last applied server document (null until one
|
|
99
|
+
// arrives: an old server never sends one), the local `forge-bridge yield` flag,
|
|
100
|
+
// and the effective settings computed from both and the host's env bounds.
|
|
101
|
+
appliedSettingsDocument = null;
|
|
102
|
+
localYield = false;
|
|
103
|
+
/** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
|
|
104
|
+
forgeAckedYield = false;
|
|
105
|
+
publishState = () => undefined;
|
|
106
|
+
effectiveSettings;
|
|
107
|
+
settingsReport;
|
|
108
|
+
/** Applies run one at a time; offers wait for every apply queued before them. */
|
|
109
|
+
settingsTail = Promise.resolve();
|
|
110
|
+
// Server documents that turn yield on and are queued but not applied yet. The
|
|
111
|
+
// reservation commit is synchronous and can't wait for the apply, so it counts these.
|
|
112
|
+
pendingYieldOn = 0;
|
|
113
|
+
settingsStarted = null;
|
|
90
114
|
hostRequirementFacts() {
|
|
91
115
|
const facts = this.hostLoad.facts();
|
|
92
116
|
return {
|
|
@@ -152,8 +176,19 @@ export class ForgeBridgeService {
|
|
|
152
176
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
153
177
|
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
154
178
|
this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
|
|
179
|
+
// With no server document and no local flag these equal today's env/default behaviour.
|
|
180
|
+
this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
|
|
181
|
+
this.settingsReport = this.effectiveSettings.report;
|
|
182
|
+
this.inFlight.addSource(() => [
|
|
183
|
+
...reservationInFlightEntries(this.reservations),
|
|
184
|
+
...sessionInFlightEntries(this.activeSessions),
|
|
185
|
+
...readinessInFlightEntries(this.activeReadinessProbes),
|
|
186
|
+
]);
|
|
155
187
|
}
|
|
156
188
|
async connectOnce() {
|
|
189
|
+
if (this.revokedReason !== null) {
|
|
190
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
191
|
+
}
|
|
157
192
|
await this.stopConnection();
|
|
158
193
|
this.stopped = false;
|
|
159
194
|
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
@@ -183,6 +218,7 @@ export class ForgeBridgeService {
|
|
|
183
218
|
// keeps refreshing its cached snapshot for later heartbeats.
|
|
184
219
|
await this.hostLoad.start().catch(() => undefined);
|
|
185
220
|
this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
|
|
221
|
+
await this.startSettings();
|
|
186
222
|
const connection = this.connections.create(this.config);
|
|
187
223
|
this.connection = connection;
|
|
188
224
|
this.transportRecovery = null;
|
|
@@ -224,14 +260,16 @@ export class ForgeBridgeService {
|
|
|
224
260
|
await connection.stop().catch(() => undefined);
|
|
225
261
|
}
|
|
226
262
|
});
|
|
227
|
-
connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
|
|
228
|
-
connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
|
|
229
|
-
connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
|
|
230
|
-
connection.onStart?.((dispatch) => this.handleStart(dispatch));
|
|
263
|
+
connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
|
|
264
|
+
connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
|
|
265
|
+
connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
|
|
266
|
+
connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
|
|
231
267
|
connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
|
|
232
268
|
connection.onCancel((request) => this.handleCancel(request));
|
|
233
269
|
connection.onReap?.((request) => this.handleReap(request));
|
|
234
|
-
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
270
|
+
connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
|
|
271
|
+
connection.onRevoked?.((notice) => this.handleRevoked(notice));
|
|
272
|
+
connection.onApplySettings?.((document) => this.handleApplySettings(document));
|
|
235
273
|
await connection.start();
|
|
236
274
|
await this.registerConnection(connection);
|
|
237
275
|
await this.flushDispatchResults(true).catch(error => {
|
|
@@ -268,6 +306,7 @@ export class ForgeBridgeService {
|
|
|
268
306
|
while (true) {
|
|
269
307
|
try {
|
|
270
308
|
const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
|
|
309
|
+
const reportedYield = this.settingsReport.values.yieldToForeground;
|
|
271
310
|
const ack = await connection.invoke("Hello", {
|
|
272
311
|
version: this.config.version,
|
|
273
312
|
protocolVersion: this.config.protocolVersion,
|
|
@@ -280,6 +319,7 @@ export class ForgeBridgeService {
|
|
|
280
319
|
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
|
|
281
320
|
}
|
|
282
321
|
this.recoveredHostAttempts.clear();
|
|
322
|
+
this.ackYield(reportedYield);
|
|
283
323
|
logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
|
|
284
324
|
return;
|
|
285
325
|
}
|
|
@@ -295,6 +335,7 @@ export class ForgeBridgeService {
|
|
|
295
335
|
}
|
|
296
336
|
}
|
|
297
337
|
async run(signal) {
|
|
338
|
+
const statePublisher = await this.startStatePublisher();
|
|
298
339
|
let attempt = 0;
|
|
299
340
|
try {
|
|
300
341
|
while (!this.stopped && !signal?.aborted) {
|
|
@@ -310,7 +351,7 @@ export class ForgeBridgeService {
|
|
|
310
351
|
}
|
|
311
352
|
}
|
|
312
353
|
catch (error) {
|
|
313
|
-
if (this.stopped || signal?.aborted) {
|
|
354
|
+
if (this.stopped || signal?.aborted || this.revokedReason !== null) {
|
|
314
355
|
break;
|
|
315
356
|
}
|
|
316
357
|
const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
|
|
@@ -326,6 +367,214 @@ export class ForgeBridgeService {
|
|
|
326
367
|
this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
|
|
327
368
|
}
|
|
328
369
|
await this.stopConnection();
|
|
370
|
+
await statePublisher?.stop();
|
|
371
|
+
}
|
|
372
|
+
if (this.revokedReason !== null) {
|
|
373
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async startStatePublisher() {
|
|
377
|
+
if (!this.config.bridgeStatePath)
|
|
378
|
+
return null;
|
|
379
|
+
const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
|
|
380
|
+
inFlight: () => this.inFlight.snapshot(),
|
|
381
|
+
// Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
|
|
382
|
+
yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
|
|
383
|
+
yieldApplied: () => this.effectiveSettings.yielding,
|
|
384
|
+
connected: () => this.connection !== null && this.transportRecovery === null,
|
|
385
|
+
}, { log: logBridgeStatus });
|
|
386
|
+
this.publishState = () => void publisher.publish();
|
|
387
|
+
this.inFlight.onChange(this.publishState);
|
|
388
|
+
await publisher.start();
|
|
389
|
+
logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
|
|
390
|
+
return publisher;
|
|
391
|
+
}
|
|
392
|
+
/** The reason Forge gave when it removed this runner, or null while it is paired. */
|
|
393
|
+
get revoked() {
|
|
394
|
+
return this.revokedReason;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
|
|
398
|
+
* reconnecting; its attempts were already settled on the server, so local work is
|
|
399
|
+
* aborted rather than reported.
|
|
400
|
+
*/
|
|
401
|
+
handleRevoked(notice) {
|
|
402
|
+
if (this.revokedReason !== null)
|
|
403
|
+
return;
|
|
404
|
+
const reason = typeof notice?.reason === "string" && notice.reason.trim()
|
|
405
|
+
? notice.reason.trim()
|
|
406
|
+
: bridgeRevokedMessage;
|
|
407
|
+
this.revokedReason = reason;
|
|
408
|
+
this.stopped = true;
|
|
409
|
+
logBridgeStatus(reason);
|
|
410
|
+
this.abortActiveSessions("runner removed from Forge");
|
|
411
|
+
this.abortActiveReadinessProbes("runner removed from Forge");
|
|
412
|
+
void this.stopConnection().catch(() => undefined);
|
|
413
|
+
}
|
|
414
|
+
/** The effective settings and how they were derived, as last reported (decision 0014). */
|
|
415
|
+
get runnerSettings() {
|
|
416
|
+
return this.settingsReport;
|
|
417
|
+
}
|
|
418
|
+
runnerHostDefaults() {
|
|
419
|
+
return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Once per bridge process: drop governor overrides an earlier process left on
|
|
423
|
+
* the state root, then put today's effective settings (env bounds and the local
|
|
424
|
+
* yield flag, no server document yet) in force.
|
|
425
|
+
*/
|
|
426
|
+
async startSettings() {
|
|
427
|
+
this.settingsStarted ??= (async () => {
|
|
428
|
+
await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
|
|
429
|
+
logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
|
|
430
|
+
});
|
|
431
|
+
this.localYield = await this.readLocalYield();
|
|
432
|
+
await this.enqueueSettings({ kind: "local" });
|
|
433
|
+
})();
|
|
434
|
+
await this.settingsStarted;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Decision 0014 `ApplySettings`. Applies only a document newer than the one
|
|
438
|
+
* applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
|
|
439
|
+
* the applied version is acknowledged again without applying it; an older one is
|
|
440
|
+
* ignored.
|
|
441
|
+
*/
|
|
442
|
+
async handleApplySettings(raw) {
|
|
443
|
+
const document = parseRunnerSettingsDocument(raw);
|
|
444
|
+
if (!document) {
|
|
445
|
+
logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (document.runnerId && document.runnerId !== this.config.runnerId) {
|
|
449
|
+
logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
await this.enqueueSettings({ kind: "server", document });
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Polls the local `forge-bridge yield` flag (every heartbeat and before each
|
|
456
|
+
* offer decision). A change is applied at once and reported again under the
|
|
457
|
+
* same settings version.
|
|
458
|
+
*/
|
|
459
|
+
/** Yielding now, or about to: a received yield-on that is still being applied counts. */
|
|
460
|
+
yieldingOrQueued() {
|
|
461
|
+
return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
|
|
462
|
+
}
|
|
463
|
+
async refreshLocalYield() {
|
|
464
|
+
if (!this.config.localYieldFlagPath)
|
|
465
|
+
return;
|
|
466
|
+
const localYield = await this.readLocalYield();
|
|
467
|
+
if (localYield === this.localYield)
|
|
468
|
+
return;
|
|
469
|
+
this.localYield = localYield;
|
|
470
|
+
logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
|
|
471
|
+
await this.enqueueSettings({ kind: "local" });
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* A setting the host couldn't put in force holds placement on the server, so
|
|
475
|
+
* every heartbeat tries the applied document again until it takes.
|
|
476
|
+
*/
|
|
477
|
+
async retryFailedSettings() {
|
|
478
|
+
if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
|
|
479
|
+
return;
|
|
480
|
+
await this.enqueueSettings({ kind: "local" });
|
|
481
|
+
}
|
|
482
|
+
async readLocalYield() {
|
|
483
|
+
const flagPath = this.config.localYieldFlagPath;
|
|
484
|
+
return flagPath ? await readLocalYieldFlag(flagPath) : false;
|
|
485
|
+
}
|
|
486
|
+
enqueueSettings(change) {
|
|
487
|
+
const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
|
|
488
|
+
if (turnsYieldOn)
|
|
489
|
+
this.pendingYieldOn += 1;
|
|
490
|
+
const applied = this.settingsTail
|
|
491
|
+
.then(() => this.applySettings(change))
|
|
492
|
+
.finally(() => {
|
|
493
|
+
if (turnsYieldOn)
|
|
494
|
+
this.pendingYieldOn -= 1;
|
|
495
|
+
});
|
|
496
|
+
// A failed apply must not wedge later applies or the offers waiting on them.
|
|
497
|
+
this.settingsTail = applied.catch(error => {
|
|
498
|
+
logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
|
|
499
|
+
});
|
|
500
|
+
return this.settingsTail;
|
|
501
|
+
}
|
|
502
|
+
async applySettings(change) {
|
|
503
|
+
const applied = this.appliedSettingsDocument;
|
|
504
|
+
if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
|
|
505
|
+
if (change.document.version === applied.version) {
|
|
506
|
+
// The server sends the current version again at each Hello. After a reconnect it may never
|
|
507
|
+
// have seen this version's ack (the old connection dropped first), and its offer gate waits
|
|
508
|
+
// for one from this connection, so acknowledge what is in force again rather than nothing.
|
|
509
|
+
void this.sendSettingsApplied(this.settingsReport);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const document = change.kind === "server" ? change.document : applied;
|
|
516
|
+
const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
|
|
517
|
+
const failures = await this.putSettingsInForce(effective);
|
|
518
|
+
// Report what is in force: a key the host couldn't take keeps its previous value.
|
|
519
|
+
const report = {
|
|
520
|
+
...runnerSettingsInForce(effective.report, this.settingsReport, failures),
|
|
521
|
+
version: document?.version ?? null,
|
|
522
|
+
};
|
|
523
|
+
const changed = !sameRunnerSettingsReport(report, this.settingsReport);
|
|
524
|
+
this.appliedSettingsDocument = document;
|
|
525
|
+
this.effectiveSettings = effective;
|
|
526
|
+
this.settingsReport = report;
|
|
527
|
+
this.publishState();
|
|
528
|
+
if (change.kind === "server") {
|
|
529
|
+
logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
|
|
530
|
+
}
|
|
531
|
+
// Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
|
|
532
|
+
if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
|
|
533
|
+
void this.sendSettingsApplied(report);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Max attempts and the memory reserve go to host attempt admission; the governor
|
|
538
|
+
* budget (the yield budget while yielding) and the heavy-step limit go to the
|
|
539
|
+
* shared settings file every governor on the state root reads at admission.
|
|
540
|
+
* Neither touches admitted work. Returns the keys the host could not put in
|
|
541
|
+
* force (`apply_failed`); their previous values stay in force.
|
|
542
|
+
*/
|
|
543
|
+
async putSettingsInForce(effective) {
|
|
544
|
+
const { values } = effective.report;
|
|
545
|
+
const rejected = [];
|
|
546
|
+
try {
|
|
547
|
+
await this.sessions.applyRunnerLimits?.({
|
|
548
|
+
maxConcurrentAttempts: values.maxConcurrentAttempts,
|
|
549
|
+
memoryReserveBytes: values.memoryReserveBytes,
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
|
|
554
|
+
rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
|
|
555
|
+
}
|
|
556
|
+
try {
|
|
557
|
+
await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
|
|
558
|
+
cpuBudgetFraction: effective.governorCpuBudgetFraction,
|
|
559
|
+
maxHeavySteps: values.maxHeavySteps,
|
|
560
|
+
yielding: effective.yielding,
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
catch (error) {
|
|
564
|
+
const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
|
|
565
|
+
rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
|
|
566
|
+
}
|
|
567
|
+
return rejected;
|
|
568
|
+
}
|
|
569
|
+
ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
|
|
570
|
+
/** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
|
|
571
|
+
async sendSettingsApplied(report) {
|
|
572
|
+
try {
|
|
573
|
+
await this.invokeAck("SettingsApplied", report);
|
|
574
|
+
this.ackYield(report.values.yieldToForeground);
|
|
575
|
+
}
|
|
576
|
+
catch (error) {
|
|
577
|
+
logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
|
|
329
578
|
}
|
|
330
579
|
}
|
|
331
580
|
async stop() {
|
|
@@ -467,6 +716,7 @@ export class ForgeBridgeService {
|
|
|
467
716
|
env: {
|
|
468
717
|
FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
|
|
469
718
|
FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
|
|
719
|
+
...plan.env,
|
|
470
720
|
},
|
|
471
721
|
stdin: plan.stdin,
|
|
472
722
|
}, {
|
|
@@ -493,6 +743,7 @@ export class ForgeBridgeService {
|
|
|
493
743
|
content: "Bridge Chat provider process exited.",
|
|
494
744
|
}).catch(() => undefined);
|
|
495
745
|
}
|
|
746
|
+
assertChatTurnFinished(result);
|
|
496
747
|
return { command: plan.command, output, result };
|
|
497
748
|
}
|
|
498
749
|
async sendChatProviderEvent(packet, active, event, providerThreadId) {
|
|
@@ -678,19 +929,7 @@ export class ForgeBridgeService {
|
|
|
678
929
|
return;
|
|
679
930
|
}
|
|
680
931
|
const controller = reservationHandoff?.controller ?? new AbortController();
|
|
681
|
-
this.
|
|
682
|
-
leaseId,
|
|
683
|
-
kind: "dispatch",
|
|
684
|
-
fencingToken,
|
|
685
|
-
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
686
|
-
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
687
|
-
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
688
|
-
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
689
|
-
resources: dispatch.sandbox?.executionMode === "docker"
|
|
690
|
-
? dispatch.sandbox.requestedResources
|
|
691
|
-
: zeroSandboxResources(),
|
|
692
|
-
controller
|
|
693
|
-
});
|
|
932
|
+
this.registerActiveDispatch(dispatch, controller);
|
|
694
933
|
if (reservationHandoff) {
|
|
695
934
|
// Promotion is synchronous with active-session registration. A qualified
|
|
696
935
|
// pre-start Cancel therefore sees either the cancellable reservation or
|
|
@@ -714,43 +953,10 @@ export class ForgeBridgeService {
|
|
|
714
953
|
};
|
|
715
954
|
await this.invokeAck("DispatchStarted", started);
|
|
716
955
|
}
|
|
717
|
-
const sink =
|
|
718
|
-
|
|
719
|
-
if (event.eventType === "provider_cli_started") {
|
|
720
|
-
const active = this.activeSessions.get(leaseId);
|
|
721
|
-
if (active)
|
|
722
|
-
active.resources = { ...active.resources, buildSlots: 0 };
|
|
723
|
-
}
|
|
724
|
-
try {
|
|
725
|
-
await this.invokeAck("DispatchEvent", {
|
|
726
|
-
leaseId,
|
|
727
|
-
fencingToken,
|
|
728
|
-
...(dispatch.sandbox ? {
|
|
729
|
-
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
730
|
-
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
731
|
-
} : {}),
|
|
732
|
-
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
733
|
-
}, {
|
|
734
|
-
replayCallbackTimeout: true,
|
|
735
|
-
signal: controller.signal,
|
|
736
|
-
});
|
|
737
|
-
}
|
|
738
|
-
catch (error) {
|
|
739
|
-
if (isDispatchNoLongerPending(error)) {
|
|
740
|
-
controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
throw error;
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
const result = normalized.sandbox?.executionMode === "docker"
|
|
748
|
-
? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
|
|
749
|
-
: await this.sessions.runOnce(normalized, sink, controller.signal);
|
|
750
|
-
if (normalized.sandbox?.executionMode === "docker") {
|
|
751
|
-
await this.flushCleanupReports().catch(() => undefined);
|
|
752
|
-
}
|
|
956
|
+
const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
|
|
957
|
+
const result = await this.runDispatchOnce(normalized, sink, controller.signal);
|
|
753
958
|
const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
|
|
959
|
+
this.inFlight.notePhase(leaseId, "result_delivery");
|
|
754
960
|
await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
|
|
755
961
|
}
|
|
756
962
|
catch (error) {
|
|
@@ -774,6 +980,77 @@ export class ForgeBridgeService {
|
|
|
774
980
|
await this.releaseActiveSessionAndRefreshCapacity(leaseId);
|
|
775
981
|
}
|
|
776
982
|
}
|
|
983
|
+
registerActiveDispatch(dispatch, controller) {
|
|
984
|
+
this.activeSessions.set(dispatch.lease.id, {
|
|
985
|
+
leaseId: dispatch.lease.id,
|
|
986
|
+
kind: "dispatch",
|
|
987
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
988
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
989
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
990
|
+
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
991
|
+
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
992
|
+
resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
|
|
993
|
+
controller
|
|
994
|
+
});
|
|
995
|
+
this.inFlight.notePhase(dispatch.lease.id, "accepted");
|
|
996
|
+
logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
|
|
997
|
+
}
|
|
998
|
+
dispatchEventSink(dispatch, controller, redactionSecrets) {
|
|
999
|
+
const leaseId = dispatch.lease.id;
|
|
1000
|
+
return {
|
|
1001
|
+
emit: async (event) => {
|
|
1002
|
+
this.inFlight.notePhase(leaseId, event.eventType);
|
|
1003
|
+
if (event.eventType === "provider_cli_started") {
|
|
1004
|
+
const active = this.activeSessions.get(leaseId);
|
|
1005
|
+
if (active)
|
|
1006
|
+
active.resources = { ...active.resources, buildSlots: 0 };
|
|
1007
|
+
}
|
|
1008
|
+
try {
|
|
1009
|
+
await this.invokeAck("DispatchEvent", {
|
|
1010
|
+
leaseId,
|
|
1011
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1012
|
+
...(dispatch.sandbox ? {
|
|
1013
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
1014
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
1015
|
+
} : {}),
|
|
1016
|
+
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
1017
|
+
}, {
|
|
1018
|
+
replayCallbackTimeout: true,
|
|
1019
|
+
signal: controller.signal,
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
if (isDispatchNoLongerPending(error)) {
|
|
1024
|
+
controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
throw error;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
/** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
|
|
1033
|
+
async runDispatchOnce(dispatch, sink, signal) {
|
|
1034
|
+
const docker = dispatch.sandbox?.executionMode === "docker";
|
|
1035
|
+
const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
|
|
1036
|
+
const startedAt = Date.now();
|
|
1037
|
+
this.inFlight.notePhase(dispatch.lease.id, "run_once");
|
|
1038
|
+
logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
|
|
1039
|
+
try {
|
|
1040
|
+
const result = docker
|
|
1041
|
+
? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
|
|
1042
|
+
: await this.sessions.runOnce(dispatch, sink, signal);
|
|
1043
|
+
if (docker) {
|
|
1044
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
1045
|
+
}
|
|
1046
|
+
logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
|
|
1047
|
+
return result;
|
|
1048
|
+
}
|
|
1049
|
+
catch (error) {
|
|
1050
|
+
logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
|
|
1051
|
+
throw error;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
777
1054
|
reservedDispatchHandoffIsCurrent(handoff, dispatch) {
|
|
778
1055
|
const sandbox = dispatch.sandbox;
|
|
779
1056
|
const reservation = handoff.reservation;
|
|
@@ -861,6 +1138,16 @@ export class ForgeBridgeService {
|
|
|
861
1138
|
await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
|
|
862
1139
|
return;
|
|
863
1140
|
}
|
|
1141
|
+
// Decision 0014: decide under the settings Forge sent (an offer never races an
|
|
1142
|
+
// apply), and refuse new work while yielding to the foreground. The local flag
|
|
1143
|
+
// is read here too, before Forge has heard about it.
|
|
1144
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1145
|
+
// Every apply queued so far, including one a concurrent offer or heartbeat started.
|
|
1146
|
+
await this.settingsTail;
|
|
1147
|
+
if (this.effectiveSettings.yielding) {
|
|
1148
|
+
await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
864
1151
|
const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
|
|
865
1152
|
? await this.preflight.run()
|
|
866
1153
|
: this.preflight.current();
|
|
@@ -945,6 +1232,11 @@ export class ForgeBridgeService {
|
|
|
945
1232
|
if (Date.parse(dispatch.lease.expiresAt) <= now) {
|
|
946
1233
|
return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
|
|
947
1234
|
}
|
|
1235
|
+
// Yield may have turned on while the offer was being profiled, including a
|
|
1236
|
+
// yield Forge sent or the local flag set that hasn't finished applying yet.
|
|
1237
|
+
if (this.yieldingOrQueued()) {
|
|
1238
|
+
return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1239
|
+
}
|
|
948
1240
|
if (sandbox.executionMode === "docker") {
|
|
949
1241
|
// A concurrent heartbeat/preflight refresh may have produced a newer
|
|
950
1242
|
// conservative dual-domain sample while this offer was being profiled.
|
|
@@ -1120,6 +1412,8 @@ export class ForgeBridgeService {
|
|
|
1120
1412
|
reservedResources: accepted ? reservedResources : null,
|
|
1121
1413
|
sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
|
|
1122
1414
|
};
|
|
1415
|
+
if (accepted)
|
|
1416
|
+
logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
|
|
1123
1417
|
await this.invokeAck("OfferDecision", payload);
|
|
1124
1418
|
}
|
|
1125
1419
|
async parseDispatchOrReport(rawDispatch) {
|
|
@@ -1233,7 +1527,13 @@ export class ForgeBridgeService {
|
|
|
1233
1527
|
acceptedAt: new Date().toISOString(),
|
|
1234
1528
|
};
|
|
1235
1529
|
await this.invokeAck("ReadinessAccepted", accepted);
|
|
1236
|
-
|
|
1530
|
+
// While yielding, background readiness waits too; Forge retries a deferred probe.
|
|
1531
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1532
|
+
await this.settingsTail;
|
|
1533
|
+
if (this.yieldingOrQueued()) {
|
|
1534
|
+
result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
|
|
1535
|
+
}
|
|
1536
|
+
else if (this.activeSessions.size > 0) {
|
|
1237
1537
|
result = deferredReadinessResult(request, this.config.runnerInstanceId);
|
|
1238
1538
|
}
|
|
1239
1539
|
else if (!this.sessions.probeHostRuntime) {
|
|
@@ -1556,6 +1856,9 @@ export class ForgeBridgeService {
|
|
|
1556
1856
|
// force reconnects. Transport failures still do.
|
|
1557
1857
|
await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
|
|
1558
1858
|
await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
|
|
1859
|
+
// The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
|
|
1860
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1861
|
+
await this.retryFailedSettings().catch(() => undefined);
|
|
1559
1862
|
await this.sendHeartbeat();
|
|
1560
1863
|
this.consecutiveHeartbeatFailures = 0;
|
|
1561
1864
|
}
|
|
@@ -1611,7 +1914,8 @@ export class ForgeBridgeService {
|
|
|
1611
1914
|
startSandboxMaintenance() {
|
|
1612
1915
|
this.stopSandboxMaintenance();
|
|
1613
1916
|
this.sandboxMaintenanceTimer = setInterval(() => {
|
|
1614
|
-
this.runSandboxMaintenance().catch(
|
|
1917
|
+
this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
|
|
1918
|
+
logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
|
|
1615
1919
|
}, 60_000);
|
|
1616
1920
|
this.sandboxMaintenanceTimer.unref?.();
|
|
1617
1921
|
}
|
|
@@ -1651,9 +1955,15 @@ export class ForgeBridgeService {
|
|
|
1651
1955
|
const connection = this.connection;
|
|
1652
1956
|
if (!connection)
|
|
1653
1957
|
throw new Error("Bridge is not connected.");
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1958
|
+
// Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
|
|
1959
|
+
const pending = { connection, generation: this.transportRecoveryGeneration };
|
|
1960
|
+
if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
|
|
1961
|
+
throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
|
|
1962
|
+
this.attemptSnapshotPending = pending;
|
|
1963
|
+
const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
|
|
1964
|
+
invocation.finally(() => { if (this.attemptSnapshotPending === pending)
|
|
1965
|
+
this.attemptSnapshotPending = null; }).catch(() => undefined);
|
|
1966
|
+
const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
|
|
1657
1967
|
if (!response.accepted) {
|
|
1658
1968
|
throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
|
|
1659
1969
|
}
|
|
@@ -1688,12 +1998,14 @@ export class ForgeBridgeService {
|
|
|
1688
1998
|
await this.sendHeartbeatSnapshot();
|
|
1689
1999
|
}
|
|
1690
2000
|
async sendHeartbeatSnapshot(signal) {
|
|
2001
|
+
const reportedYield = this.settingsReport.values.yieldToForeground;
|
|
1691
2002
|
await this.invokeAck("Heartbeat", {
|
|
1692
2003
|
status: "online",
|
|
1693
2004
|
capabilities: this.capabilities(),
|
|
1694
2005
|
version: this.config.version,
|
|
1695
2006
|
protocolVersion: this.config.protocolVersion
|
|
1696
2007
|
}, { signal });
|
|
2008
|
+
this.ackYield(reportedYield);
|
|
1697
2009
|
}
|
|
1698
2010
|
capabilities() {
|
|
1699
2011
|
const preflight = this.preflight.current();
|
|
@@ -1715,7 +2027,7 @@ export class ForgeBridgeService {
|
|
|
1715
2027
|
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
1716
2028
|
}) : null;
|
|
1717
2029
|
return {
|
|
1718
|
-
schemaVersion:
|
|
2030
|
+
schemaVersion: 8,
|
|
1719
2031
|
activeSessionCount: this.activeSessions.size,
|
|
1720
2032
|
cliProviders: this.config.cliProviders,
|
|
1721
2033
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -1780,7 +2092,8 @@ export class ForgeBridgeService {
|
|
|
1780
2092
|
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
1781
2093
|
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
1782
2094
|
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
|
|
1783
|
-
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
|
|
2095
|
+
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
|
|
2096
|
+
settings: { supportsServerSettings: true, ...this.settingsReport },
|
|
1784
2097
|
};
|
|
1785
2098
|
}
|
|
1786
2099
|
async requiredCapabilityFailure(dispatch) {
|
|
@@ -1934,6 +2247,16 @@ export class ForgeBridgeService {
|
|
|
1934
2247
|
}
|
|
1935
2248
|
}
|
|
1936
2249
|
}
|
|
2250
|
+
/** The `run` command's exit code after Forge removed the runner. */
|
|
2251
|
+
export const bridgeRevokedExitCode = 3;
|
|
2252
|
+
export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
|
|
2253
|
+
/** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
|
|
2254
|
+
export class BridgeRevokedError extends Error {
|
|
2255
|
+
constructor(message = bridgeRevokedMessage) {
|
|
2256
|
+
super(message);
|
|
2257
|
+
this.name = "BridgeRevokedError";
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
1937
2260
|
class BridgeCallbackRejectedError extends Error {
|
|
1938
2261
|
code;
|
|
1939
2262
|
constructor(code, message) {
|
|
@@ -2004,6 +2327,18 @@ export class SignalRBridgeConnection {
|
|
|
2004
2327
|
void this.connection.stop().catch(() => undefined);
|
|
2005
2328
|
});
|
|
2006
2329
|
}
|
|
2330
|
+
onApplySettings(handler) {
|
|
2331
|
+
this.connection.on("ApplySettings", (raw) => {
|
|
2332
|
+
void Promise.resolve(handler(raw)).catch(() => undefined);
|
|
2333
|
+
});
|
|
2334
|
+
}
|
|
2335
|
+
onRevoked(handler) {
|
|
2336
|
+
this.connection.on("Revoked", (raw) => {
|
|
2337
|
+
const notice = raw && typeof raw === "object" ? raw : {};
|
|
2338
|
+
handler(notice);
|
|
2339
|
+
void this.connection.stop().catch(() => undefined);
|
|
2340
|
+
});
|
|
2341
|
+
}
|
|
2007
2342
|
start() {
|
|
2008
2343
|
return this.connection.start();
|
|
2009
2344
|
}
|
|
@@ -2344,10 +2679,7 @@ function errorMessage(error) {
|
|
|
2344
2679
|
return error instanceof Error ? error.message : String(error);
|
|
2345
2680
|
}
|
|
2346
2681
|
function formatDelay(ms) {
|
|
2347
|
-
|
|
2348
|
-
return `${ms / 1000}s`;
|
|
2349
|
-
}
|
|
2350
|
-
return `${ms}ms`;
|
|
2682
|
+
return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
|
|
2351
2683
|
}
|
|
2352
2684
|
async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
|
|
2353
2685
|
let timeout = null;
|
|
@@ -2416,7 +2748,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
|
|
|
2416
2748
|
const maxChatEventContentChars = 4000;
|
|
2417
2749
|
const maxChatTerminalTextChars = 120_000;
|
|
2418
2750
|
const maxChatExactSecretChars = 8 * 1024;
|
|
2419
|
-
const chatTurnMetadataFileName = "forge-chat-metadata.json";
|
|
2420
2751
|
async function materializeChatTurnMetadata(packet, workspacePath) {
|
|
2421
2752
|
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2422
2753
|
return;
|
|
@@ -2476,113 +2807,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
|
|
|
2476
2807
|
};
|
|
2477
2808
|
}
|
|
2478
2809
|
}
|
|
2479
|
-
function buildChatProviderCommand(packet, cwd) {
|
|
2480
|
-
const provider = packet.providerKind.trim().toLowerCase();
|
|
2481
|
-
const model = packet.model.trim();
|
|
2482
|
-
const prompt = buildChatPrompt(packet);
|
|
2483
|
-
const resumeThreadId = packet.providerThreadId?.trim() || null;
|
|
2484
|
-
if (provider === "codex") {
|
|
2485
|
-
const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
|
|
2486
|
-
if (resumeThreadId) {
|
|
2487
|
-
args.push("--cd", cwd, "resume");
|
|
2488
|
-
}
|
|
2489
|
-
args.push("--model", model, "--json");
|
|
2490
|
-
if (!resumeThreadId) {
|
|
2491
|
-
args.push("--cd", cwd);
|
|
2492
|
-
}
|
|
2493
|
-
args.push("--skip-git-repo-check");
|
|
2494
|
-
if (resumeThreadId) {
|
|
2495
|
-
args.push(resumeThreadId);
|
|
2496
|
-
}
|
|
2497
|
-
args.push("-");
|
|
2498
|
-
return { command: { command: "codex", args }, stdin: prompt };
|
|
2499
|
-
}
|
|
2500
|
-
if (provider === "cursor") {
|
|
2501
|
-
const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
|
|
2502
|
-
if (resumeThreadId) {
|
|
2503
|
-
args.push("--resume", resumeThreadId);
|
|
2504
|
-
}
|
|
2505
|
-
args.push("--yolo", "--approve-mcps", "--trust", prompt);
|
|
2506
|
-
return { command: { command: "cursor-agent", args } };
|
|
2507
|
-
}
|
|
2508
|
-
if (provider === "claude") {
|
|
2509
|
-
const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
|
|
2510
|
-
if (resumeThreadId) {
|
|
2511
|
-
args.push("--resume", resumeThreadId);
|
|
2512
|
-
}
|
|
2513
|
-
return { command: { command: "claude", args }, stdin: prompt };
|
|
2514
|
-
}
|
|
2515
|
-
return {
|
|
2516
|
-
command: {
|
|
2517
|
-
command: provider,
|
|
2518
|
-
args: ["--model", model, prompt],
|
|
2519
|
-
},
|
|
2520
|
-
};
|
|
2521
|
-
}
|
|
2522
|
-
function buildChatPrompt(packet) {
|
|
2523
|
-
const messages = packet.messages
|
|
2524
|
-
.map((message, index) => {
|
|
2525
|
-
const role = message.role.trim() || `message-${index + 1}`;
|
|
2526
|
-
return `[${role}]\n${message.content}`;
|
|
2527
|
-
})
|
|
2528
|
-
.join("\n\n");
|
|
2529
|
-
const contextRefs = packet.contextRefs.length === 0
|
|
2530
|
-
? ""
|
|
2531
|
-
: `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
|
|
2532
|
-
const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
|
|
2533
|
-
const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
|
|
2534
|
-
return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
|
|
2535
|
-
}).join("\n\n")}`;
|
|
2536
|
-
const continuation = packet.providerThreadId
|
|
2537
|
-
? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
|
|
2538
|
-
: "";
|
|
2539
|
-
const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
|
|
2540
|
-
return `You are handling a Forge Bridge Chat turn.
|
|
2541
|
-
|
|
2542
|
-
Conversation ID: ${packet.conversationId}
|
|
2543
|
-
Turn ID: ${packet.turnId}
|
|
2544
|
-
Provider: ${packet.providerKind}
|
|
2545
|
-
Model: ${packet.model}${continuation}${boundedMetadata}
|
|
2546
|
-
|
|
2547
|
-
# Conversation
|
|
2548
|
-
|
|
2549
|
-
${messages}${contextRefs}
|
|
2550
|
-
`;
|
|
2551
|
-
}
|
|
2552
|
-
function buildChatBoundedMetadataPrompt(packet) {
|
|
2553
|
-
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2554
|
-
return "";
|
|
2555
|
-
}
|
|
2556
|
-
const sections = [
|
|
2557
|
-
`\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.`,
|
|
2558
|
-
];
|
|
2559
|
-
if (packet.attachmentHandoffs.length > 0) {
|
|
2560
|
-
sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
|
|
2561
|
-
`${index + 1}. turnId: ${handoff.turnId}`,
|
|
2562
|
-
` attachmentId: ${handoff.attachmentId}`,
|
|
2563
|
-
` tempFileToken: ${handoff.tempFileToken}`,
|
|
2564
|
-
` mimeType: ${handoff.mimeType}`,
|
|
2565
|
-
` sizeBytes: ${handoff.sizeBytes}`,
|
|
2566
|
-
` sha256: ${handoff.sha256}`,
|
|
2567
|
-
` fileNameDisplay: ${handoff.fileNameDisplay}`,
|
|
2568
|
-
` expiresAt: ${handoff.expiresAt}`,
|
|
2569
|
-
` status: ${handoff.status}`,
|
|
2570
|
-
].join("\n")).join("\n\n")}`);
|
|
2571
|
-
}
|
|
2572
|
-
if (packet.actionBrokerGrants.length > 0) {
|
|
2573
|
-
sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
|
|
2574
|
-
`${index + 1}. grantId: ${grant.grantId}`,
|
|
2575
|
-
` turnId: ${grant.turnId}`,
|
|
2576
|
-
` leaseId: ${grant.leaseId}`,
|
|
2577
|
-
` fencingToken: ${grant.fencingToken}`,
|
|
2578
|
-
` allowedScopes: ${grant.allowedScopes.join(", ")}`,
|
|
2579
|
-
` expiresAt: ${grant.expiresAt}`,
|
|
2580
|
-
` redactionStatus: ${grant.redactionStatus}`,
|
|
2581
|
-
" nonce: held by bridge",
|
|
2582
|
-
].join("\n")).join("\n\n")}`);
|
|
2583
|
-
}
|
|
2584
|
-
return sections.join("\n\n");
|
|
2585
|
-
}
|
|
2586
2810
|
function chatProviderExitFailure(command, result, redactionSecrets) {
|
|
2587
2811
|
const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
|
|
2588
2812
|
const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
|
|
@@ -2726,24 +2950,6 @@ function parseReadinessProbe(value) {
|
|
|
2726
2950
|
}
|
|
2727
2951
|
return request;
|
|
2728
2952
|
}
|
|
2729
|
-
function deferredReadinessResult(request, runnerInstanceId) {
|
|
2730
|
-
return {
|
|
2731
|
-
schemaVersion: 1,
|
|
2732
|
-
requestId: request.requestId,
|
|
2733
|
-
fencingToken: request.fencingToken,
|
|
2734
|
-
runnerInstanceId,
|
|
2735
|
-
status: "failed",
|
|
2736
|
-
reasonCode: "host_runtime_probe_deferred",
|
|
2737
|
-
reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
|
|
2738
|
-
checkedAt: new Date().toISOString(),
|
|
2739
|
-
};
|
|
2740
|
-
}
|
|
2741
|
-
function readinessDeferralReason(signal) {
|
|
2742
|
-
if (!signal.aborted)
|
|
2743
|
-
return null;
|
|
2744
|
-
const reason = errorMessage(signal.reason);
|
|
2745
|
-
return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
|
|
2746
|
-
}
|
|
2747
2953
|
function sandboxProviderNetworkFailure(dispatch, config) {
|
|
2748
2954
|
const sandbox = dispatch.sandbox;
|
|
2749
2955
|
if (!sandbox || sandbox.networkPolicy.mode !== "offline")
|
|
@@ -2782,151 +2988,6 @@ function rejectedOfferReservation(code, message) {
|
|
|
2782
2988
|
resources: null,
|
|
2783
2989
|
};
|
|
2784
2990
|
}
|
|
2785
|
-
export function canReserveSandboxResources(used, requested, capacity) {
|
|
2786
|
-
return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
|
|
2787
|
-
&& used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
|
|
2788
|
-
&& used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
|
|
2789
|
-
&& used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
|
|
2790
|
-
&& used.pids + requested.pids <= capacity.pids
|
|
2791
|
-
&& used.buildSlots + requested.buildSlots <= capacity.buildSlots;
|
|
2792
|
-
}
|
|
2793
|
-
export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
|
|
2794
|
-
const ambientCapacity = preflight.availableMemoryBytes
|
|
2795
|
-
- preflight.hostReserveBytes
|
|
2796
|
-
+ activeMemoryBytes;
|
|
2797
|
-
const commitmentCapacity = preflight.totalMemoryBytes
|
|
2798
|
-
- preflight.hostReserveBytes;
|
|
2799
|
-
return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
|
|
2800
|
-
}
|
|
2801
|
-
export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
|
|
2802
|
-
const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
|
|
2803
|
-
if (requested.sandboxSlots > availableSlots) {
|
|
2804
|
-
return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
|
|
2805
|
-
}
|
|
2806
|
-
const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
|
|
2807
|
-
if (requested.memoryBytes > availableMemoryBytes) {
|
|
2808
|
-
return [
|
|
2809
|
-
`Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
|
|
2810
|
-
`(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
|
|
2811
|
-
`but ${formatBytes(availableMemoryBytes)} is available for admission.`,
|
|
2812
|
-
`Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
|
|
2813
|
-
`Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
|
|
2814
|
-
].join(" ");
|
|
2815
|
-
}
|
|
2816
|
-
const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
|
|
2817
|
-
if (requested.cpuMillis > availableCpuMillis) {
|
|
2818
|
-
return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
|
|
2819
|
-
}
|
|
2820
|
-
const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
|
|
2821
|
-
if (requested.workspaceBytes > availableWorkspaceBytes) {
|
|
2822
|
-
return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
|
|
2823
|
-
}
|
|
2824
|
-
const availablePids = Math.max(0, capacity.pids - used.pids);
|
|
2825
|
-
if (requested.pids > availablePids) {
|
|
2826
|
-
return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
|
|
2827
|
-
}
|
|
2828
|
-
const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
|
|
2829
|
-
return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
|
|
2830
|
-
}
|
|
2831
|
-
function sumSandboxResources(resources) {
|
|
2832
|
-
return resources.reduce((total, resource) => ({
|
|
2833
|
-
sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
|
|
2834
|
-
cpuMillis: total.cpuMillis + resource.cpuMillis,
|
|
2835
|
-
workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
|
|
2836
|
-
serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
|
|
2837
|
-
runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
|
|
2838
|
-
memoryBytes: total.memoryBytes + resource.memoryBytes,
|
|
2839
|
-
workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
|
|
2840
|
-
pids: total.pids + resource.pids,
|
|
2841
|
-
buildSlots: total.buildSlots + resource.buildSlots
|
|
2842
|
-
}), zeroSandboxResources());
|
|
2843
|
-
}
|
|
2844
|
-
function zeroSandboxResources() {
|
|
2845
|
-
return {
|
|
2846
|
-
sandboxSlots: 0,
|
|
2847
|
-
cpuMillis: 0,
|
|
2848
|
-
workerMemoryLimitBytes: 0,
|
|
2849
|
-
serviceMemoryLimitBytes: 0,
|
|
2850
|
-
runtimeOverheadBytes: 0,
|
|
2851
|
-
memoryBytes: 0,
|
|
2852
|
-
workspaceBytes: 0,
|
|
2853
|
-
pids: 0,
|
|
2854
|
-
buildSlots: 0,
|
|
2855
|
-
};
|
|
2856
|
-
}
|
|
2857
|
-
function defaultSandboxResources() {
|
|
2858
|
-
return {
|
|
2859
|
-
sandboxSlots: 1,
|
|
2860
|
-
cpuMillis: 2000,
|
|
2861
|
-
workerMemoryLimitBytes: 2 * 1024 ** 3,
|
|
2862
|
-
serviceMemoryLimitBytes: 0,
|
|
2863
|
-
runtimeOverheadBytes: 128 * 1024 ** 2,
|
|
2864
|
-
memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
|
|
2865
|
-
workspaceBytes: 10 * 1024 ** 3,
|
|
2866
|
-
pids: 512,
|
|
2867
|
-
buildSlots: 0
|
|
2868
|
-
};
|
|
2869
|
-
}
|
|
2870
|
-
export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2871
|
-
const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
|
|
2872
|
-
const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
|
|
2873
|
-
+ (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
|
|
2874
|
-
return {
|
|
2875
|
-
...requested,
|
|
2876
|
-
serviceMemoryLimitBytes,
|
|
2877
|
-
runtimeOverheadBytes,
|
|
2878
|
-
memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
|
|
2879
|
-
};
|
|
2880
|
-
}
|
|
2881
|
-
export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2882
|
-
const repoPath = dispatch.repo.serverLocalPath;
|
|
2883
|
-
const sandbox = dispatch.sandbox;
|
|
2884
|
-
if (!repoPath || !sandbox) {
|
|
2885
|
-
throw new Error("Sandbox admission needs a mapped repository.");
|
|
2886
|
-
}
|
|
2887
|
-
const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
|
|
2888
|
-
const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
|
|
2889
|
-
if (!configCommitSha) {
|
|
2890
|
-
throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
|
|
2891
|
-
}
|
|
2892
|
-
const contractResult = await runSandboxProcess({
|
|
2893
|
-
command: "git",
|
|
2894
|
-
args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
|
|
2895
|
-
timeoutMs: 30_000,
|
|
2896
|
-
maxOutputBytes: 1024 * 1024,
|
|
2897
|
-
});
|
|
2898
|
-
if (contractResult.exitCode !== 0) {
|
|
2899
|
-
throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
|
|
2900
|
-
}
|
|
2901
|
-
const contract = validateSandboxContract(contractResult.stdout);
|
|
2902
|
-
const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
|
|
2903
|
-
role: dispatch.execution.role,
|
|
2904
|
-
serviceCount: contract.contract.services.length,
|
|
2905
|
-
browser: contract.contract.browser,
|
|
2906
|
-
});
|
|
2907
|
-
return {
|
|
2908
|
-
resources: resolveDynamicSandboxResources({
|
|
2909
|
-
...sandbox.requestedResources,
|
|
2910
|
-
workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
|
|
2911
|
-
}, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
|
|
2912
|
-
sandboxConfigCommitSha: configCommitSha,
|
|
2913
|
-
};
|
|
2914
|
-
}
|
|
2915
|
-
async function resolveFirstGitCommit(repoPath, refs) {
|
|
2916
|
-
for (const ref of refs) {
|
|
2917
|
-
const result = await runSandboxProcess({
|
|
2918
|
-
command: "git",
|
|
2919
|
-
args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
|
|
2920
|
-
timeoutMs: 30_000,
|
|
2921
|
-
maxOutputBytes: 1024 * 1024,
|
|
2922
|
-
});
|
|
2923
|
-
const commitSha = result.stdout.trim().toLowerCase();
|
|
2924
|
-
if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
|
|
2925
|
-
return commitSha;
|
|
2926
|
-
}
|
|
2927
|
-
}
|
|
2928
|
-
return null;
|
|
2929
|
-
}
|
|
2930
2991
|
function parseOfferEnvelope(value) {
|
|
2931
2992
|
return parseDispatchEnvelope(value);
|
|
2932
2993
|
}
|