@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.ccffca94938b
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 +57 -2
- package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
- package/dist/bridge/bridge-chat-provider-command.js +137 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +73 -2
- package/dist/bridge/bridge.service.js +312 -119
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +17 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +18 -0
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +142 -16
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +184 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +75 -2
- package/dist/runtime/host-load-sampler.js +142 -8
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +74 -4
- package/dist/runtime/host-runtime-lease.js +281 -11
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +48 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/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 +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +113 -0
- package/dist/sandbox/host-capacity-broker.js +334 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +157 -39
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +94 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +208 -231
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +49 -93
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +32 -20
- package/dist/session/pre-publication-validation.js +195 -158
- package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
- package/dist/session/provider-cli/claude-background-work.js +180 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +39 -17
- package/dist/session/provider-cli/provider-cli.process.js +136 -345
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
- package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +142 -162
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
- package/dist/session/provider-cli/provider-output-state.js +15 -0
- package/dist/session/publishable-worktree-changes.d.ts +10 -1
- package/dist/session/publishable-worktree-changes.js +21 -5
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +238 -0
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +120 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +12 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +5 -6
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +2 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
|
|
1
2
|
import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
@@ -7,12 +8,16 @@ import { defaultForgeBridgeConfig } from "../config.js";
|
|
|
7
8
|
import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
8
9
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
9
10
|
import { BridgeSessionService } from "../session/session.service.js";
|
|
10
|
-
import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
11
|
-
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";
|
|
12
13
|
import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
|
|
13
14
|
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
14
15
|
import { PrePublicationValidator } from "../session/pre-publication-validation.js";
|
|
15
|
-
import {
|
|
16
|
+
import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
|
|
17
|
+
import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
|
|
18
|
+
import { computeEffectiveRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, 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";
|
|
16
21
|
import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
|
|
17
22
|
import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
|
|
18
23
|
import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
@@ -67,6 +72,7 @@ export class ForgeBridgeService {
|
|
|
67
72
|
transportRecovery = null;
|
|
68
73
|
transportRecoveryGeneration = 0;
|
|
69
74
|
stopped = false;
|
|
75
|
+
revokedReason = null;
|
|
70
76
|
activeSessions = new Map();
|
|
71
77
|
reservations = new Map();
|
|
72
78
|
activeReadinessProbes = new Map();
|
|
@@ -84,12 +90,41 @@ export class ForgeBridgeService {
|
|
|
84
90
|
sessions;
|
|
85
91
|
enforceHostDatabaseCapabilityBoundary;
|
|
86
92
|
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
93
|
+
dockerAvailable = false;
|
|
94
|
+
// Decision 0014 settings push. The last applied server document (null until one
|
|
95
|
+
// arrives: an old server never sends one), the local `forge-bridge yield` flag,
|
|
96
|
+
// and the effective settings computed from both and the host's env bounds.
|
|
97
|
+
appliedSettingsDocument = null;
|
|
98
|
+
localYield = false;
|
|
99
|
+
effectiveSettings;
|
|
100
|
+
settingsReport;
|
|
101
|
+
/** Applies run one at a time; offers wait for every apply queued before them. */
|
|
102
|
+
settingsTail = Promise.resolve();
|
|
103
|
+
// Server documents that turn yield on and are queued but not applied yet. The
|
|
104
|
+
// reservation commit is synchronous and can't wait for the apply, so it counts these.
|
|
105
|
+
pendingYieldOn = 0;
|
|
106
|
+
settingsStarted = null;
|
|
107
|
+
hostRequirementFacts() {
|
|
108
|
+
const facts = this.hostLoad.facts();
|
|
109
|
+
return {
|
|
110
|
+
logicalThreads: facts?.logicalThreads ?? os.cpus().length,
|
|
111
|
+
totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
|
|
112
|
+
availableToolchains: Object.entries(this.hostCapabilities.toolchains)
|
|
113
|
+
.filter(([, tool]) => tool?.available === true)
|
|
114
|
+
.map(([name]) => name),
|
|
115
|
+
dockerAvailable: this.dockerAvailable,
|
|
116
|
+
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
117
|
+
testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
87
120
|
// Reaping deletes the stale ledger, so its stopped-process proof is held here
|
|
88
121
|
// until a Hello carrying it is accepted. A bridge restart forgets it, which
|
|
89
122
|
// leaves those attempts on Forge's conservative unknown-outcome path.
|
|
90
123
|
recoveredHostAttempts = new Map();
|
|
91
124
|
hostCapabilitiesDetected = false;
|
|
92
|
-
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
|
|
125
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
|
|
126
|
+
// Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
|
|
127
|
+
hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
|
|
93
128
|
this.config = config;
|
|
94
129
|
this.connections = connections;
|
|
95
130
|
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
@@ -126,14 +161,22 @@ export class ForgeBridgeService {
|
|
|
126
161
|
},
|
|
127
162
|
onStatus: logBridgeStatus,
|
|
128
163
|
});
|
|
129
|
-
|
|
130
|
-
this.
|
|
164
|
+
const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
|
|
165
|
+
this.sessions = sessions ?? defaultSessions.sessions;
|
|
166
|
+
// Docker sandboxes ask the same host load governor for their validation tokens.
|
|
167
|
+
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
|
|
131
168
|
this.sandboxResourceResolver = sandboxResourceResolver
|
|
132
169
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
133
170
|
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
134
171
|
this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
|
|
172
|
+
// With no server document and no local flag these equal today's env/default behaviour.
|
|
173
|
+
this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
|
|
174
|
+
this.settingsReport = this.effectiveSettings.report;
|
|
135
175
|
}
|
|
136
176
|
async connectOnce() {
|
|
177
|
+
if (this.revokedReason !== null) {
|
|
178
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
179
|
+
}
|
|
137
180
|
await this.stopConnection();
|
|
138
181
|
this.stopped = false;
|
|
139
182
|
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
@@ -162,6 +205,8 @@ export class ForgeBridgeService {
|
|
|
162
205
|
// Static host facts and the first load sample ride on Hello; the sampler
|
|
163
206
|
// keeps refreshing its cached snapshot for later heartbeats.
|
|
164
207
|
await this.hostLoad.start().catch(() => undefined);
|
|
208
|
+
this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
|
|
209
|
+
await this.startSettings();
|
|
165
210
|
const connection = this.connections.create(this.config);
|
|
166
211
|
this.connection = connection;
|
|
167
212
|
this.transportRecovery = null;
|
|
@@ -211,6 +256,8 @@ export class ForgeBridgeService {
|
|
|
211
256
|
connection.onCancel((request) => this.handleCancel(request));
|
|
212
257
|
connection.onReap?.((request) => this.handleReap(request));
|
|
213
258
|
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
259
|
+
connection.onRevoked?.((notice) => this.handleRevoked(notice));
|
|
260
|
+
connection.onApplySettings?.((document) => this.handleApplySettings(document));
|
|
214
261
|
await connection.start();
|
|
215
262
|
await this.registerConnection(connection);
|
|
216
263
|
await this.flushDispatchResults(true).catch(error => {
|
|
@@ -289,7 +336,7 @@ export class ForgeBridgeService {
|
|
|
289
336
|
}
|
|
290
337
|
}
|
|
291
338
|
catch (error) {
|
|
292
|
-
if (this.stopped || signal?.aborted) {
|
|
339
|
+
if (this.stopped || signal?.aborted || this.revokedReason !== null) {
|
|
293
340
|
break;
|
|
294
341
|
}
|
|
295
342
|
const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
|
|
@@ -306,6 +353,194 @@ export class ForgeBridgeService {
|
|
|
306
353
|
}
|
|
307
354
|
await this.stopConnection();
|
|
308
355
|
}
|
|
356
|
+
if (this.revokedReason !== null) {
|
|
357
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/** The reason Forge gave when it removed this runner, or null while it is paired. */
|
|
361
|
+
get revoked() {
|
|
362
|
+
return this.revokedReason;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
|
|
366
|
+
* reconnecting; its attempts were already settled on the server, so local work is
|
|
367
|
+
* aborted rather than reported.
|
|
368
|
+
*/
|
|
369
|
+
handleRevoked(notice) {
|
|
370
|
+
if (this.revokedReason !== null)
|
|
371
|
+
return;
|
|
372
|
+
const reason = typeof notice?.reason === "string" && notice.reason.trim()
|
|
373
|
+
? notice.reason.trim()
|
|
374
|
+
: bridgeRevokedMessage;
|
|
375
|
+
this.revokedReason = reason;
|
|
376
|
+
this.stopped = true;
|
|
377
|
+
logBridgeStatus(reason);
|
|
378
|
+
this.abortActiveSessions("runner removed from Forge");
|
|
379
|
+
this.abortActiveReadinessProbes("runner removed from Forge");
|
|
380
|
+
void this.stopConnection().catch(() => undefined);
|
|
381
|
+
}
|
|
382
|
+
/** The effective settings and how they were derived, as last reported (decision 0014). */
|
|
383
|
+
get runnerSettings() {
|
|
384
|
+
return this.settingsReport;
|
|
385
|
+
}
|
|
386
|
+
runnerHostDefaults() {
|
|
387
|
+
return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Once per bridge process: drop governor overrides an earlier process left on
|
|
391
|
+
* the state root, then put today's effective settings (env bounds and the local
|
|
392
|
+
* yield flag, no server document yet) in force.
|
|
393
|
+
*/
|
|
394
|
+
async startSettings() {
|
|
395
|
+
this.settingsStarted ??= (async () => {
|
|
396
|
+
await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
|
|
397
|
+
logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
|
|
398
|
+
});
|
|
399
|
+
this.localYield = await this.readLocalYield();
|
|
400
|
+
await this.enqueueSettings({ kind: "local" });
|
|
401
|
+
})();
|
|
402
|
+
await this.settingsStarted;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Decision 0014 `ApplySettings`. Applies only a document newer than the one
|
|
406
|
+
* applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
|
|
407
|
+
* the applied version is acknowledged again without applying it; an older one is
|
|
408
|
+
* ignored.
|
|
409
|
+
*/
|
|
410
|
+
async handleApplySettings(raw) {
|
|
411
|
+
const document = parseRunnerSettingsDocument(raw);
|
|
412
|
+
if (!document) {
|
|
413
|
+
logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (document.runnerId && document.runnerId !== this.config.runnerId) {
|
|
417
|
+
logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
await this.enqueueSettings({ kind: "server", document });
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Polls the local `forge-bridge yield` flag (every heartbeat and before each
|
|
424
|
+
* offer decision). A change is applied at once and reported again under the
|
|
425
|
+
* same settings version.
|
|
426
|
+
*/
|
|
427
|
+
/** Yielding now, or about to: a received yield-on that is still being applied counts. */
|
|
428
|
+
yieldingOrQueued() {
|
|
429
|
+
return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
|
|
430
|
+
}
|
|
431
|
+
async refreshLocalYield() {
|
|
432
|
+
if (!this.config.localYieldFlagPath)
|
|
433
|
+
return;
|
|
434
|
+
const localYield = await this.readLocalYield();
|
|
435
|
+
if (localYield === this.localYield)
|
|
436
|
+
return;
|
|
437
|
+
this.localYield = localYield;
|
|
438
|
+
logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
|
|
439
|
+
await this.enqueueSettings({ kind: "local" });
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* A setting the host couldn't put in force holds placement on the server, so
|
|
443
|
+
* every heartbeat tries the applied document again until it takes.
|
|
444
|
+
*/
|
|
445
|
+
async retryFailedSettings() {
|
|
446
|
+
if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
|
|
447
|
+
return;
|
|
448
|
+
await this.enqueueSettings({ kind: "local" });
|
|
449
|
+
}
|
|
450
|
+
async readLocalYield() {
|
|
451
|
+
const flagPath = this.config.localYieldFlagPath;
|
|
452
|
+
return flagPath ? await readLocalYieldFlag(flagPath) : false;
|
|
453
|
+
}
|
|
454
|
+
enqueueSettings(change) {
|
|
455
|
+
const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
|
|
456
|
+
if (turnsYieldOn)
|
|
457
|
+
this.pendingYieldOn += 1;
|
|
458
|
+
const applied = this.settingsTail
|
|
459
|
+
.then(() => this.applySettings(change))
|
|
460
|
+
.finally(() => {
|
|
461
|
+
if (turnsYieldOn)
|
|
462
|
+
this.pendingYieldOn -= 1;
|
|
463
|
+
});
|
|
464
|
+
// A failed apply must not wedge later applies or the offers waiting on them.
|
|
465
|
+
this.settingsTail = applied.catch(error => {
|
|
466
|
+
logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
|
|
467
|
+
});
|
|
468
|
+
return this.settingsTail;
|
|
469
|
+
}
|
|
470
|
+
async applySettings(change) {
|
|
471
|
+
const applied = this.appliedSettingsDocument;
|
|
472
|
+
if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
|
|
473
|
+
if (change.document.version === applied.version) {
|
|
474
|
+
// The server sends the current version again at each Hello. After a reconnect it may never
|
|
475
|
+
// have seen this version's ack (the old connection dropped first), and its offer gate waits
|
|
476
|
+
// for one from this connection, so acknowledge what is in force again rather than nothing.
|
|
477
|
+
void this.sendSettingsApplied(this.settingsReport);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const document = change.kind === "server" ? change.document : applied;
|
|
484
|
+
const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
|
|
485
|
+
const failures = await this.putSettingsInForce(effective);
|
|
486
|
+
// Report what is in force: a key the host couldn't take keeps its previous value.
|
|
487
|
+
const report = {
|
|
488
|
+
...runnerSettingsInForce(effective.report, this.settingsReport, failures),
|
|
489
|
+
version: document?.version ?? null,
|
|
490
|
+
};
|
|
491
|
+
const changed = !sameRunnerSettingsReport(report, this.settingsReport);
|
|
492
|
+
this.appliedSettingsDocument = document;
|
|
493
|
+
this.effectiveSettings = effective;
|
|
494
|
+
this.settingsReport = report;
|
|
495
|
+
if (change.kind === "server") {
|
|
496
|
+
logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
|
|
497
|
+
}
|
|
498
|
+
// Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
|
|
499
|
+
if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
|
|
500
|
+
void this.sendSettingsApplied(report);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Max attempts and the memory reserve go to host attempt admission; the governor
|
|
505
|
+
* budget (the yield budget while yielding) and the heavy-step limit go to the
|
|
506
|
+
* shared settings file every governor on the state root reads at admission.
|
|
507
|
+
* Neither touches admitted work. Returns the keys the host could not put in
|
|
508
|
+
* force (`apply_failed`); their previous values stay in force.
|
|
509
|
+
*/
|
|
510
|
+
async putSettingsInForce(effective) {
|
|
511
|
+
const { values } = effective.report;
|
|
512
|
+
const rejected = [];
|
|
513
|
+
try {
|
|
514
|
+
await this.sessions.applyRunnerLimits?.({
|
|
515
|
+
maxConcurrentAttempts: values.maxConcurrentAttempts,
|
|
516
|
+
memoryReserveBytes: values.memoryReserveBytes,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
catch (error) {
|
|
520
|
+
const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
|
|
521
|
+
rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
|
|
522
|
+
}
|
|
523
|
+
try {
|
|
524
|
+
await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
|
|
525
|
+
cpuBudgetFraction: effective.governorCpuBudgetFraction,
|
|
526
|
+
maxHeavySteps: values.maxHeavySteps,
|
|
527
|
+
yielding: effective.yielding,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
|
|
532
|
+
rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
|
|
533
|
+
}
|
|
534
|
+
return rejected;
|
|
535
|
+
}
|
|
536
|
+
/** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
|
|
537
|
+
async sendSettingsApplied(report) {
|
|
538
|
+
try {
|
|
539
|
+
await this.invokeAck("SettingsApplied", report);
|
|
540
|
+
}
|
|
541
|
+
catch (error) {
|
|
542
|
+
logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
|
|
543
|
+
}
|
|
309
544
|
}
|
|
310
545
|
async stop() {
|
|
311
546
|
this.stopped = true;
|
|
@@ -446,6 +681,7 @@ export class ForgeBridgeService {
|
|
|
446
681
|
env: {
|
|
447
682
|
FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
|
|
448
683
|
FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
|
|
684
|
+
...plan.env,
|
|
449
685
|
},
|
|
450
686
|
stdin: plan.stdin,
|
|
451
687
|
}, {
|
|
@@ -472,6 +708,7 @@ export class ForgeBridgeService {
|
|
|
472
708
|
content: "Bridge Chat provider process exited.",
|
|
473
709
|
}).catch(() => undefined);
|
|
474
710
|
}
|
|
711
|
+
assertChatTurnFinished(result);
|
|
475
712
|
return { command: plan.command, output, result };
|
|
476
713
|
}
|
|
477
714
|
async sendChatProviderEvent(packet, active, event, providerThreadId) {
|
|
@@ -840,6 +1077,16 @@ export class ForgeBridgeService {
|
|
|
840
1077
|
await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
|
|
841
1078
|
return;
|
|
842
1079
|
}
|
|
1080
|
+
// Decision 0014: decide under the settings Forge sent (an offer never races an
|
|
1081
|
+
// apply), and refuse new work while yielding to the foreground. The local flag
|
|
1082
|
+
// is read here too, before Forge has heard about it.
|
|
1083
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1084
|
+
// Every apply queued so far, including one a concurrent offer or heartbeat started.
|
|
1085
|
+
await this.settingsTail;
|
|
1086
|
+
if (this.effectiveSettings.yielding) {
|
|
1087
|
+
await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
843
1090
|
const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
|
|
844
1091
|
? await this.preflight.run()
|
|
845
1092
|
: this.preflight.current();
|
|
@@ -924,6 +1171,11 @@ export class ForgeBridgeService {
|
|
|
924
1171
|
if (Date.parse(dispatch.lease.expiresAt) <= now) {
|
|
925
1172
|
return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
|
|
926
1173
|
}
|
|
1174
|
+
// Yield may have turned on while the offer was being profiled, including a
|
|
1175
|
+
// yield Forge sent or the local flag set that hasn't finished applying yet.
|
|
1176
|
+
if (this.yieldingOrQueued()) {
|
|
1177
|
+
return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1178
|
+
}
|
|
927
1179
|
if (sandbox.executionMode === "docker") {
|
|
928
1180
|
// A concurrent heartbeat/preflight refresh may have produced a newer
|
|
929
1181
|
// conservative dual-domain sample while this offer was being profiled.
|
|
@@ -1535,6 +1787,9 @@ export class ForgeBridgeService {
|
|
|
1535
1787
|
// force reconnects. Transport failures still do.
|
|
1536
1788
|
await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
|
|
1537
1789
|
await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
|
|
1790
|
+
// The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
|
|
1791
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1792
|
+
await this.retryFailedSettings().catch(() => undefined);
|
|
1538
1793
|
await this.sendHeartbeat();
|
|
1539
1794
|
this.consecutiveHeartbeatFailures = 0;
|
|
1540
1795
|
}
|
|
@@ -1677,6 +1932,7 @@ export class ForgeBridgeService {
|
|
|
1677
1932
|
capabilities() {
|
|
1678
1933
|
const preflight = this.preflight.current();
|
|
1679
1934
|
const dockerEngine = this.dockerEngineProbe.current();
|
|
1935
|
+
this.dockerAvailable = dockerEngine?.available === true;
|
|
1680
1936
|
const runtimeState = this.sandboxRuntime.snapshot();
|
|
1681
1937
|
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
1682
1938
|
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
@@ -1693,7 +1949,7 @@ export class ForgeBridgeService {
|
|
|
1693
1949
|
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
1694
1950
|
}) : null;
|
|
1695
1951
|
return {
|
|
1696
|
-
schemaVersion:
|
|
1952
|
+
schemaVersion: 8,
|
|
1697
1953
|
activeSessionCount: this.activeSessions.size,
|
|
1698
1954
|
cliProviders: this.config.cliProviders,
|
|
1699
1955
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -1716,6 +1972,7 @@ export class ForgeBridgeService {
|
|
|
1716
1972
|
playwrightProjects: this.hostCapabilities.playwrightProjects,
|
|
1717
1973
|
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
1718
1974
|
providerConnectivity: this.hostCapabilities.providerConnectivity,
|
|
1975
|
+
testPostgres: this.hostCapabilities.testPostgres,
|
|
1719
1976
|
host: this.hostLoad.facts(),
|
|
1720
1977
|
load: this.hostLoad.current(),
|
|
1721
1978
|
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
@@ -1757,7 +2014,8 @@ export class ForgeBridgeService {
|
|
|
1757
2014
|
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
1758
2015
|
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
1759
2016
|
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
|
|
1760
|
-
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
|
|
2017
|
+
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
|
|
2018
|
+
settings: { supportsServerSettings: true, ...this.settingsReport },
|
|
1761
2019
|
};
|
|
1762
2020
|
}
|
|
1763
2021
|
async requiredCapabilityFailure(dispatch) {
|
|
@@ -1911,6 +2169,35 @@ export class ForgeBridgeService {
|
|
|
1911
2169
|
}
|
|
1912
2170
|
}
|
|
1913
2171
|
}
|
|
2172
|
+
function runnerYieldingMessage(report) {
|
|
2173
|
+
const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
|
|
2174
|
+
return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
|
|
2175
|
+
}
|
|
2176
|
+
function describeRunnerSettings(report) {
|
|
2177
|
+
const { values } = report;
|
|
2178
|
+
const parts = [
|
|
2179
|
+
`max attempts ${values.maxConcurrentAttempts}`,
|
|
2180
|
+
`CPU budget ${values.cpuBudgetPercent}%`,
|
|
2181
|
+
`yield budget ${values.yieldCpuBudgetPercent}%`,
|
|
2182
|
+
`memory reserve ${formatBytes(values.memoryReserveBytes)}`,
|
|
2183
|
+
`heavy steps ${values.maxHeavySteps ?? "budget only"}`,
|
|
2184
|
+
`yield ${values.yieldToForeground ? "on" : "off"}`,
|
|
2185
|
+
];
|
|
2186
|
+
const capped = report.bounds
|
|
2187
|
+
.filter(bound => report.sources[bound.key] === "host_env")
|
|
2188
|
+
.map(bound => `${bound.envVar}=${bound.value}`);
|
|
2189
|
+
return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
|
|
2190
|
+
}
|
|
2191
|
+
/** The `run` command's exit code after Forge removed the runner. */
|
|
2192
|
+
export const bridgeRevokedExitCode = 3;
|
|
2193
|
+
export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
|
|
2194
|
+
/** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
|
|
2195
|
+
export class BridgeRevokedError extends Error {
|
|
2196
|
+
constructor(message = bridgeRevokedMessage) {
|
|
2197
|
+
super(message);
|
|
2198
|
+
this.name = "BridgeRevokedError";
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
1914
2201
|
class BridgeCallbackRejectedError extends Error {
|
|
1915
2202
|
code;
|
|
1916
2203
|
constructor(code, message) {
|
|
@@ -1944,11 +2231,13 @@ function isProviderStorageUnavailable(error) {
|
|
|
1944
2231
|
function isBridgeCallbackTimeout(error) {
|
|
1945
2232
|
return errorMessage(error).startsWith("bridge_callback_timeout:");
|
|
1946
2233
|
}
|
|
1947
|
-
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
|
|
2234
|
+
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
|
|
1948
2235
|
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1949
2236
|
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1950
2237
|
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1951
|
-
|
|
2238
|
+
const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
|
|
2239
|
+
const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
|
|
2240
|
+
return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
|
|
1952
2241
|
}
|
|
1953
2242
|
export class SignalRBridgeConnectionFactory {
|
|
1954
2243
|
create(config) {
|
|
@@ -1979,6 +2268,18 @@ export class SignalRBridgeConnection {
|
|
|
1979
2268
|
void this.connection.stop().catch(() => undefined);
|
|
1980
2269
|
});
|
|
1981
2270
|
}
|
|
2271
|
+
onApplySettings(handler) {
|
|
2272
|
+
this.connection.on("ApplySettings", (raw) => {
|
|
2273
|
+
void Promise.resolve(handler(raw)).catch(() => undefined);
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
onRevoked(handler) {
|
|
2277
|
+
this.connection.on("Revoked", (raw) => {
|
|
2278
|
+
const notice = raw && typeof raw === "object" ? raw : {};
|
|
2279
|
+
handler(notice);
|
|
2280
|
+
void this.connection.stop().catch(() => undefined);
|
|
2281
|
+
});
|
|
2282
|
+
}
|
|
1982
2283
|
start() {
|
|
1983
2284
|
return this.connection.start();
|
|
1984
2285
|
}
|
|
@@ -2391,7 +2692,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
|
|
|
2391
2692
|
const maxChatEventContentChars = 4000;
|
|
2392
2693
|
const maxChatTerminalTextChars = 120_000;
|
|
2393
2694
|
const maxChatExactSecretChars = 8 * 1024;
|
|
2394
|
-
const chatTurnMetadataFileName = "forge-chat-metadata.json";
|
|
2395
2695
|
async function materializeChatTurnMetadata(packet, workspacePath) {
|
|
2396
2696
|
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2397
2697
|
return;
|
|
@@ -2451,113 +2751,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
|
|
|
2451
2751
|
};
|
|
2452
2752
|
}
|
|
2453
2753
|
}
|
|
2454
|
-
function buildChatProviderCommand(packet, cwd) {
|
|
2455
|
-
const provider = packet.providerKind.trim().toLowerCase();
|
|
2456
|
-
const model = packet.model.trim();
|
|
2457
|
-
const prompt = buildChatPrompt(packet);
|
|
2458
|
-
const resumeThreadId = packet.providerThreadId?.trim() || null;
|
|
2459
|
-
if (provider === "codex") {
|
|
2460
|
-
const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
|
|
2461
|
-
if (resumeThreadId) {
|
|
2462
|
-
args.push("--cd", cwd, "resume");
|
|
2463
|
-
}
|
|
2464
|
-
args.push("--model", model, "--json");
|
|
2465
|
-
if (!resumeThreadId) {
|
|
2466
|
-
args.push("--cd", cwd);
|
|
2467
|
-
}
|
|
2468
|
-
args.push("--skip-git-repo-check");
|
|
2469
|
-
if (resumeThreadId) {
|
|
2470
|
-
args.push(resumeThreadId);
|
|
2471
|
-
}
|
|
2472
|
-
args.push("-");
|
|
2473
|
-
return { command: { command: "codex", args }, stdin: prompt };
|
|
2474
|
-
}
|
|
2475
|
-
if (provider === "cursor") {
|
|
2476
|
-
const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
|
|
2477
|
-
if (resumeThreadId) {
|
|
2478
|
-
args.push("--resume", resumeThreadId);
|
|
2479
|
-
}
|
|
2480
|
-
args.push("--yolo", "--approve-mcps", "--trust", prompt);
|
|
2481
|
-
return { command: { command: "cursor-agent", args } };
|
|
2482
|
-
}
|
|
2483
|
-
if (provider === "claude") {
|
|
2484
|
-
const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
|
|
2485
|
-
if (resumeThreadId) {
|
|
2486
|
-
args.push("--resume", resumeThreadId);
|
|
2487
|
-
}
|
|
2488
|
-
return { command: { command: "claude", args }, stdin: prompt };
|
|
2489
|
-
}
|
|
2490
|
-
return {
|
|
2491
|
-
command: {
|
|
2492
|
-
command: provider,
|
|
2493
|
-
args: ["--model", model, prompt],
|
|
2494
|
-
},
|
|
2495
|
-
};
|
|
2496
|
-
}
|
|
2497
|
-
function buildChatPrompt(packet) {
|
|
2498
|
-
const messages = packet.messages
|
|
2499
|
-
.map((message, index) => {
|
|
2500
|
-
const role = message.role.trim() || `message-${index + 1}`;
|
|
2501
|
-
return `[${role}]\n${message.content}`;
|
|
2502
|
-
})
|
|
2503
|
-
.join("\n\n");
|
|
2504
|
-
const contextRefs = packet.contextRefs.length === 0
|
|
2505
|
-
? ""
|
|
2506
|
-
: `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
|
|
2507
|
-
const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
|
|
2508
|
-
const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
|
|
2509
|
-
return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
|
|
2510
|
-
}).join("\n\n")}`;
|
|
2511
|
-
const continuation = packet.providerThreadId
|
|
2512
|
-
? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
|
|
2513
|
-
: "";
|
|
2514
|
-
const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
|
|
2515
|
-
return `You are handling a Forge Bridge Chat turn.
|
|
2516
|
-
|
|
2517
|
-
Conversation ID: ${packet.conversationId}
|
|
2518
|
-
Turn ID: ${packet.turnId}
|
|
2519
|
-
Provider: ${packet.providerKind}
|
|
2520
|
-
Model: ${packet.model}${continuation}${boundedMetadata}
|
|
2521
|
-
|
|
2522
|
-
# Conversation
|
|
2523
|
-
|
|
2524
|
-
${messages}${contextRefs}
|
|
2525
|
-
`;
|
|
2526
|
-
}
|
|
2527
|
-
function buildChatBoundedMetadataPrompt(packet) {
|
|
2528
|
-
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2529
|
-
return "";
|
|
2530
|
-
}
|
|
2531
|
-
const sections = [
|
|
2532
|
-
`\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
|
|
2533
|
-
];
|
|
2534
|
-
if (packet.attachmentHandoffs.length > 0) {
|
|
2535
|
-
sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
|
|
2536
|
-
`${index + 1}. turnId: ${handoff.turnId}`,
|
|
2537
|
-
` attachmentId: ${handoff.attachmentId}`,
|
|
2538
|
-
` tempFileToken: ${handoff.tempFileToken}`,
|
|
2539
|
-
` mimeType: ${handoff.mimeType}`,
|
|
2540
|
-
` sizeBytes: ${handoff.sizeBytes}`,
|
|
2541
|
-
` sha256: ${handoff.sha256}`,
|
|
2542
|
-
` fileNameDisplay: ${handoff.fileNameDisplay}`,
|
|
2543
|
-
` expiresAt: ${handoff.expiresAt}`,
|
|
2544
|
-
` status: ${handoff.status}`,
|
|
2545
|
-
].join("\n")).join("\n\n")}`);
|
|
2546
|
-
}
|
|
2547
|
-
if (packet.actionBrokerGrants.length > 0) {
|
|
2548
|
-
sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
|
|
2549
|
-
`${index + 1}. grantId: ${grant.grantId}`,
|
|
2550
|
-
` turnId: ${grant.turnId}`,
|
|
2551
|
-
` leaseId: ${grant.leaseId}`,
|
|
2552
|
-
` fencingToken: ${grant.fencingToken}`,
|
|
2553
|
-
` allowedScopes: ${grant.allowedScopes.join(", ")}`,
|
|
2554
|
-
` expiresAt: ${grant.expiresAt}`,
|
|
2555
|
-
` redactionStatus: ${grant.redactionStatus}`,
|
|
2556
|
-
" nonce: held by bridge",
|
|
2557
|
-
].join("\n")).join("\n\n")}`);
|
|
2558
|
-
}
|
|
2559
|
-
return sections.join("\n\n");
|
|
2560
|
-
}
|
|
2561
2754
|
function chatProviderExitFailure(command, result, redactionSecrets) {
|
|
2562
2755
|
const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
|
|
2563
2756
|
const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
|
|
2
|
+
import type { BridgeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
1
3
|
import type { ApiKeySecretGrant, DispatchSandboxResourceRequest, RunOnceResultPacket, RunnerDispatchEvent } from "../session/session.types.js";
|
|
2
4
|
import type { SandboxFeatureMatrix } from "../sandbox/sandbox.types.js";
|
|
3
5
|
import type { HostRuntimeCapacitySnapshot } from "../runtime/host-runtime-lease.js";
|
|
@@ -5,6 +7,7 @@ import type { MemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
|
5
7
|
import type { DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
|
|
6
8
|
import type { HostFacts } from "../runtime/host-facts.js";
|
|
7
9
|
import type { HostLoadSnapshot } from "../runtime/host-load-sampler.js";
|
|
10
|
+
import type { RunnerSettingsReport } from "../runtime/runner-settings.js";
|
|
8
11
|
import type { BridgeChatCapability, ChatTurnCancelPacket } from "./bridge-chat.types.js";
|
|
9
12
|
export interface BridgeServiceConfig {
|
|
10
13
|
readonly serverUrl: string;
|
|
@@ -63,6 +66,11 @@ export interface BridgeServiceConfig {
|
|
|
63
66
|
readonly callbackAckTimeoutMs?: number;
|
|
64
67
|
readonly heartbeatDockerProbeWaitMs?: number;
|
|
65
68
|
readonly reconnectBackoffMs: readonly number[];
|
|
69
|
+
/**
|
|
70
|
+
* Decision 0014: the `forge-bridge yield` flag file next to the bridge config,
|
|
71
|
+
* polled while running. Null or absent: no local yield flag.
|
|
72
|
+
*/
|
|
73
|
+
readonly localYieldFlagPath?: string | null;
|
|
66
74
|
}
|
|
67
75
|
export interface BridgeRepoMapping {
|
|
68
76
|
readonly repoId?: string | null;
|
|
@@ -144,10 +152,17 @@ export interface BridgeCapabilities {
|
|
|
144
152
|
readonly playwrightProjects?: readonly string[] | null;
|
|
145
153
|
readonly browserLaunch?: boolean | null;
|
|
146
154
|
readonly providerConnectivity?: Readonly<Record<string, boolean>> | null;
|
|
155
|
+
/** Native test PostgreSQL and whether its role is a superuser (decision 0013 placement). */
|
|
156
|
+
readonly testPostgres?: BridgeTestPostgresCapability | null;
|
|
147
157
|
/** Static host hardware facts (schema 7). Material: changes are persisted immediately. */
|
|
148
158
|
readonly host?: HostFacts | null;
|
|
149
159
|
/** Live host load sample (schema 7). Never material: heartbeats with only load changes are not persisted. */
|
|
150
160
|
readonly load?: HostLoadSnapshot | null;
|
|
161
|
+
/** Decision 0014 (schema 8): server settings support and the last `SettingsApplied` report. Material. */
|
|
162
|
+
readonly settings?: BridgeSettingsCapability | null;
|
|
163
|
+
}
|
|
164
|
+
export interface BridgeSettingsCapability extends RunnerSettingsReport {
|
|
165
|
+
readonly supportsServerSettings: true;
|
|
151
166
|
}
|
|
152
167
|
export interface SandboxMemoryCapacityDiagnostics {
|
|
153
168
|
readonly defaultWorkerMemoryLimitBytes: number;
|
|
@@ -298,6 +313,7 @@ export interface BridgeRuntimeReadinessResult {
|
|
|
298
313
|
readonly status: "parallel_ready" | "serialized" | "failed";
|
|
299
314
|
readonly runtimeContractFingerprint?: string | null;
|
|
300
315
|
readonly runtimeContractSource?: string | null;
|
|
316
|
+
readonly runtimeRequirements?: HostRuntimeRequirements | null;
|
|
301
317
|
readonly reasonCode?: string | null;
|
|
302
318
|
readonly reasonMessage?: string | null;
|
|
303
319
|
readonly qaAppLaunchTarget?: BridgeRuntimeReadinessQaLaunchTarget | null;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** `<config dir>/<config name>.yield.json`, e.g. `~/.config/forge/bridge.yield.json` beside `bridge.json`. */
|
|
2
|
+
export declare function localYieldFlagPathFor(configPath: string): string;
|
|
3
|
+
/** The local flag; a missing or unreadable file means off. */
|
|
4
|
+
export declare function readLocalYieldFlag(flagPath: string): Promise<boolean>;
|
|
5
|
+
/** Writes the flag atomically with mode 0600. */
|
|
6
|
+
export declare function writeLocalYieldFlag(flagPath: string, yieldToForeground: boolean): Promise<void>;
|