@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f07274d438b
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 +183 -4
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
- package/dist/bridge/bridge-chat-provider-command.js +230 -0
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -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 +15 -0
- package/dist/bridge/bridge-state-io.js +68 -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 +102 -14
- package/dist/bridge/bridge.service.js +499 -471
- package/dist/bridge/bridge.types.d.ts +37 -0
- package/dist/bridge/bridge.types.js +2 -1
- package/dist/bridge/default-session-service.d.ts +13 -0
- package/dist/bridge/default-session-service.js +22 -0
- package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
- package/dist/bridge/dispatch-offer-policy.js +58 -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 +5 -0
- package/dist/bridge/runner-host-capabilities.js +31 -1
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -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 +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -0
- package/dist/cleanup/forge-owned-paths.d.ts +11 -0
- package/dist/cleanup/forge-owned-paths.js +62 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -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 +75 -13
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +161 -228
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +18 -1
- package/dist/cli/local-config.js +67 -5
- package/dist/cli/provider-cli-advertising.d.ts +24 -0
- package/dist/cli/provider-cli-advertising.js +88 -0
- 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.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -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-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +72 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-capacity.d.ts +198 -0
- package/dist/runtime/host-load-capacity.js +353 -0
- package/dist/runtime/host-load-child-environment.d.ts +40 -0
- package/dist/runtime/host-load-child-environment.js +110 -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 +82 -0
- package/dist/runtime/host-load-governor-config.js +104 -0
- package/dist/runtime/host-load-governor.d.ts +273 -0
- package/dist/runtime/host-load-governor.js +831 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
- package/dist/runtime/host-load-live-test-slots.js +193 -0
- 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 +92 -2
- package/dist/runtime/host-load-sampler.js +166 -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 +107 -0
- package/dist/runtime/host-load-step-run.js +158 -0
- package/dist/runtime/host-load-test-slot.d.ts +46 -0
- package/dist/runtime/host-load-test-slot.js +100 -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 +15 -0
- package/dist/runtime/host-runtime-contract.js +39 -6
- package/dist/runtime/host-runtime-lease.d.ts +101 -6
- package/dist/runtime/host-runtime-lease.js +408 -294
- 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 +101 -2
- package/dist/runtime/host-runtime-promotion.js +355 -14
- 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/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/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
- package/dist/runtime/prepared-runtime-readiness.js +89 -18
- 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 +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- 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.d.ts +11 -3
- package/dist/sandbox/runtime.js +53 -20
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox-input.d.ts +22 -0
- package/dist/sandbox/sandbox-input.js +49 -0
- package/dist/sandbox/workspace.service.js +15 -2
- 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 -7
- package/dist/session/managed-attempt-tools.js +204 -141
- 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 +7 -0
- package/dist/session/managed-build-receipt.js +11 -3
- package/dist/session/managed-command-environment.d.ts +8 -0
- package/dist/session/managed-command-environment.js +28 -0
- package/dist/session/managed-command-host-load.d.ts +52 -0
- package/dist/session/managed-command-host-load.js +87 -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.artifact-bundle.d.ts +20 -0
- package/dist/session/phase-completion.artifact-bundle.js +167 -0
- package/dist/session/phase-completion.artifacts.d.ts +9 -17
- package/dist/session/phase-completion.artifacts.js +158 -190
- 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 +31 -2
- package/dist/session/phase-completion.helpers.js +18 -65
- package/dist/session/phase-completion.js +19 -32
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +195 -0
- package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
- package/dist/session/phase-completion.phase-aliases.js +43 -0
- package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
- package/dist/session/phase-completion.pr-review-schema.js +75 -0
- package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
- package/dist/session/phase-completion.pr-review-validation.js +212 -0
- package/dist/session/phase-completion.pr-review.d.ts +36 -0
- package/dist/session/phase-completion.pr-review.js +294 -0
- package/dist/session/phase-completion.prompts.d.ts +1 -1
- package/dist/session/phase-completion.prompts.js +20 -1
- package/dist/session/phase-completion.runtime.d.ts +13 -12
- package/dist/session/phase-completion.runtime.js +113 -214
- 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 +219 -232
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +58 -94
- package/dist/session/pr-review-diff-base.d.ts +18 -0
- package/dist/session/pr-review-diff-base.js +44 -0
- package/dist/session/pr-review-placement.d.ts +50 -0
- package/dist/session/pr-review-placement.js +91 -0
- package/dist/session/pre-publication-change-set.d.ts +62 -0
- package/dist/session/pre-publication-change-set.js +166 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +112 -0
- 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.d.ts +3 -0
- package/dist/session/pre-publication-process.js +32 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +39 -22
- package/dist/session/pre-publication-validation.js +241 -207
- 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/dispatch-target-branch.d.ts +7 -0
- package/dist/session/provider-cli/dispatch-target-branch.js +8 -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/pr-review-credential-isolation.d.ts +83 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
- package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
- package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
- package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
- package/dist/session/provider-cli/pr-review-prompt.js +119 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +281 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -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.deterministic.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
- package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -3
- package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
- package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
- package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
- package/dist/session/provider-cli/provider-cli.service.js +127 -317
- package/dist/session/provider-cli/provider-cli.types.d.ts +35 -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 +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +279 -0
- package/dist/session/session-host-project.d.ts +22 -0
- package/dist/session/session-host-project.js +98 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.parse-helpers.d.ts +10 -0
- package/dist/session/session.parse-helpers.js +84 -0
- package/dist/session/session.runtime-refresh.d.ts +46 -0
- package/dist/session/session.runtime-refresh.js +116 -0
- package/dist/session/session.service.d.ts +16 -2
- package/dist/session/session.service.js +208 -155
- package/dist/session/session.types.d.ts +8 -0
- package/dist/session/session.types.js +13 -83
- package/dist/session/session.types.pr-review.d.ts +48 -0
- package/dist/session/session.types.pr-review.js +51 -0
- 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 +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- 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.d.ts +2 -0
- package/dist/shared/provider-capabilities.js +23 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.js +24 -0
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +58 -0
- package/dist/worktree/wip-git.js +182 -0
- package/dist/worktree/wip-refs.d.ts +85 -0
- package/dist/worktree/wip-refs.js +169 -0
- package/dist/worktree/wip-restore.d.ts +51 -0
- package/dist/worktree/wip-restore.js +324 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -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 +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +20 -0
- package/dist/worktree/worktree-wip-events.js +148 -0
- package/dist/worktree/worktree-wip.d.ts +57 -0
- package/dist/worktree/worktree-wip.js +200 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +58 -5
- package/dist/worktree/worktree.service.js +237 -161
- package/dist/worktree/worktree.types.d.ts +54 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -4,38 +4,39 @@ import path from "node:path";
|
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { defaultForgeBridgeConfig } from "../config.js";
|
|
7
|
-
import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
7
|
+
import { bridgeChatCapabilityFor, defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
|
|
8
8
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } from "../session/provider-cli/provider-cli.prompts.js";
|
|
9
|
+
import { formatProviderCliCommandForCheckpoint, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
|
|
10
|
+
import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } from "./bridge-chat-provider-command.js";
|
|
12
11
|
import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
|
|
13
12
|
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
13
|
+
import { describeHostTestSlotCapacity } from "../runtime/host-load-governor.js";
|
|
14
|
+
import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
|
|
15
|
+
import { createDefaultSessionService } from "./default-session-service.js";
|
|
16
|
+
import { hostCapacityLimitDefaults, } from "../runtime/host-runtime-lease.js";
|
|
17
|
+
import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
|
|
18
|
+
import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
|
|
19
|
+
import { readLocalYieldFlag } from "./local-yield-flag.js";
|
|
16
20
|
import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
|
|
17
21
|
import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
|
|
18
22
|
import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
19
23
|
import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
|
|
20
|
-
import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
|
|
21
|
-
import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
|
|
22
24
|
import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
|
|
23
|
-
import { GitWorktreeService } from "../worktree/worktree.service.js";
|
|
24
|
-
import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
|
|
25
|
-
import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
|
|
26
25
|
import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
|
|
27
26
|
import { forgeBridgeVersion } from "../version.js";
|
|
28
27
|
import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
|
|
29
|
-
import {
|
|
30
|
-
import { runSandboxProcess } from "../sandbox/process.js";
|
|
31
|
-
import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
|
|
28
|
+
import { DockerSandboxRuntime } from "../sandbox/runtime.js";
|
|
32
29
|
import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
|
|
33
30
|
import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
|
|
34
|
-
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
35
31
|
import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
|
|
36
32
|
import { HostLoadSampler } from "../runtime/host-load-sampler.js";
|
|
37
|
-
import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
|
|
33
|
+
import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
|
|
38
34
|
import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
35
|
+
import { BridgeStatePublisher } from "./bridge-state-file.js";
|
|
36
|
+
import { offerPolicyRefusal, prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning, sandboxProfileRefusalCode, unmetHostRuntimeRequirements, } from "./dispatch-offer-policy.js";
|
|
37
|
+
import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
|
|
38
|
+
import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
|
|
39
|
+
export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
|
|
39
40
|
/**
|
|
40
41
|
* Protocol-v2 events are acknowledged one at a time before runOnce returns.
|
|
41
42
|
* Sending the complete transcript again in DispatchResult made long QA and CI
|
|
@@ -63,13 +64,17 @@ export class ForgeBridgeService {
|
|
|
63
64
|
leaseWatchdogTimer = null;
|
|
64
65
|
sandboxMaintenanceTimer = null;
|
|
65
66
|
sandboxMaintenanceRunning = false;
|
|
67
|
+
attemptSnapshotPending = null;
|
|
66
68
|
closed = null;
|
|
67
69
|
transportRecovery = null;
|
|
68
70
|
transportRecoveryGeneration = 0;
|
|
69
71
|
stopped = false;
|
|
72
|
+
revokedReason = null;
|
|
70
73
|
activeSessions = new Map();
|
|
71
74
|
reservations = new Map();
|
|
72
75
|
activeReadinessProbes = new Map();
|
|
76
|
+
/** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
|
|
77
|
+
inFlight = new BridgeInFlightRegistry();
|
|
73
78
|
readinessResultOutbox;
|
|
74
79
|
readinessResultFlush = null;
|
|
75
80
|
dispatchResultOutbox;
|
|
@@ -84,12 +89,46 @@ export class ForgeBridgeService {
|
|
|
84
89
|
sessions;
|
|
85
90
|
enforceHostDatabaseCapabilityBoundary;
|
|
86
91
|
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
92
|
+
dockerAvailable = false;
|
|
93
|
+
// Decision 0014 settings push. The last applied server document (null until one
|
|
94
|
+
// arrives: an old server never sends one), the local `forge-bridge yield` flag,
|
|
95
|
+
// and the effective settings computed from both and the host's env bounds.
|
|
96
|
+
appliedSettingsDocument = null;
|
|
97
|
+
localYield = false;
|
|
98
|
+
/** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
|
|
99
|
+
forgeAckedYield = false;
|
|
100
|
+
publishState = () => undefined;
|
|
101
|
+
effectiveSettings;
|
|
102
|
+
settingsReport;
|
|
103
|
+
/** Applies run one at a time; offers wait for every apply queued before them. */
|
|
104
|
+
settingsTail = Promise.resolve();
|
|
105
|
+
// Server documents that turn yield on and are queued but not applied yet. The
|
|
106
|
+
// reservation commit is synchronous and can't wait for the apply, so it counts these.
|
|
107
|
+
pendingYieldOn = 0;
|
|
108
|
+
settingsStarted = null;
|
|
109
|
+
hostRequirementFacts() {
|
|
110
|
+
const facts = this.hostLoad.facts();
|
|
111
|
+
return {
|
|
112
|
+
logicalThreads: facts?.logicalThreads ?? os.cpus().length,
|
|
113
|
+
totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
|
|
114
|
+
availableToolchains: Object.entries(this.hostCapabilities.toolchains)
|
|
115
|
+
.filter(([, tool]) => tool?.available === true)
|
|
116
|
+
.map(([name]) => name),
|
|
117
|
+
dockerAvailable: this.dockerAvailable,
|
|
118
|
+
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
119
|
+
testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
87
122
|
// Reaping deletes the stale ledger, so its stopped-process proof is held here
|
|
88
123
|
// until a Hello carrying it is accepted. A bridge restart forgets it, which
|
|
89
124
|
// leaves those attempts on Forge's conservative unknown-outcome path.
|
|
90
125
|
recoveredHostAttempts = new Map();
|
|
91
126
|
hostCapabilitiesDetected = false;
|
|
92
|
-
|
|
127
|
+
/** The default session service's host load governor, for the startup capacity log line. */
|
|
128
|
+
hostLoadGovernor;
|
|
129
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
|
|
130
|
+
// Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
|
|
131
|
+
hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
|
|
93
132
|
this.config = config;
|
|
94
133
|
this.connections = connections;
|
|
95
134
|
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
@@ -126,14 +165,35 @@ export class ForgeBridgeService {
|
|
|
126
165
|
},
|
|
127
166
|
onStatus: logBridgeStatus,
|
|
128
167
|
});
|
|
129
|
-
|
|
130
|
-
this.
|
|
168
|
+
const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
|
|
169
|
+
this.sessions = sessions ?? defaultSessions.sessions;
|
|
170
|
+
this.hostLoadGovernor = defaultSessions?.hostLoadGovernor ?? null;
|
|
171
|
+
// Docker sandboxes ask the same host load governor for their validation tokens.
|
|
172
|
+
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
|
|
131
173
|
this.sandboxResourceResolver = sandboxResourceResolver
|
|
132
174
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
133
175
|
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
134
176
|
this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
|
|
177
|
+
// With no server document and no local flag these equal today's env/default behaviour.
|
|
178
|
+
this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
|
|
179
|
+
this.settingsReport = this.effectiveSettings.report;
|
|
180
|
+
this.inFlight.addSource(() => [
|
|
181
|
+
...reservationInFlightEntries(this.reservations),
|
|
182
|
+
...sessionInFlightEntries(this.activeSessions),
|
|
183
|
+
...readinessInFlightEntries(this.activeReadinessProbes),
|
|
184
|
+
]);
|
|
185
|
+
}
|
|
186
|
+
/** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
|
|
187
|
+
async detectHostCapabilities() {
|
|
188
|
+
this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
|
|
189
|
+
this.hostCapabilitiesDetected = true;
|
|
190
|
+
if (this.hostLoadGovernor?.enabled)
|
|
191
|
+
logBridgeStatus(describeHostTestSlotCapacity(this.hostLoadGovernor.testSlotCapacity()));
|
|
135
192
|
}
|
|
136
193
|
async connectOnce() {
|
|
194
|
+
if (this.revokedReason !== null) {
|
|
195
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
196
|
+
}
|
|
137
197
|
await this.stopConnection();
|
|
138
198
|
this.stopped = false;
|
|
139
199
|
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
@@ -155,13 +215,13 @@ export class ForgeBridgeService {
|
|
|
155
215
|
}
|
|
156
216
|
}
|
|
157
217
|
await this.dockerEngineProbe.refresh(true);
|
|
158
|
-
if (!this.hostCapabilitiesDetected)
|
|
159
|
-
|
|
160
|
-
this.hostCapabilitiesDetected = true;
|
|
161
|
-
}
|
|
218
|
+
if (!this.hostCapabilitiesDetected)
|
|
219
|
+
await this.detectHostCapabilities();
|
|
162
220
|
// Static host facts and the first load sample ride on Hello; the sampler
|
|
163
221
|
// keeps refreshing its cached snapshot for later heartbeats.
|
|
164
222
|
await this.hostLoad.start().catch(() => undefined);
|
|
223
|
+
this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
|
|
224
|
+
await this.startSettings();
|
|
165
225
|
const connection = this.connections.create(this.config);
|
|
166
226
|
this.connection = connection;
|
|
167
227
|
this.transportRecovery = null;
|
|
@@ -203,14 +263,16 @@ export class ForgeBridgeService {
|
|
|
203
263
|
await connection.stop().catch(() => undefined);
|
|
204
264
|
}
|
|
205
265
|
});
|
|
206
|
-
connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
|
|
207
|
-
connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
|
|
208
|
-
connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
|
|
209
|
-
connection.onStart?.((dispatch) => this.handleStart(dispatch));
|
|
266
|
+
connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
|
|
267
|
+
connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
|
|
268
|
+
connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
|
|
269
|
+
connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
|
|
210
270
|
connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
|
|
211
271
|
connection.onCancel((request) => this.handleCancel(request));
|
|
212
272
|
connection.onReap?.((request) => this.handleReap(request));
|
|
213
|
-
connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
|
|
273
|
+
connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
|
|
274
|
+
connection.onRevoked?.((notice) => this.handleRevoked(notice));
|
|
275
|
+
connection.onApplySettings?.((document) => this.handleApplySettings(document));
|
|
214
276
|
await connection.start();
|
|
215
277
|
await this.registerConnection(connection);
|
|
216
278
|
await this.flushDispatchResults(true).catch(error => {
|
|
@@ -247,6 +309,7 @@ export class ForgeBridgeService {
|
|
|
247
309
|
while (true) {
|
|
248
310
|
try {
|
|
249
311
|
const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
|
|
312
|
+
const reportedYield = this.settingsReport.values.yieldToForeground;
|
|
250
313
|
const ack = await connection.invoke("Hello", {
|
|
251
314
|
version: this.config.version,
|
|
252
315
|
protocolVersion: this.config.protocolVersion,
|
|
@@ -259,6 +322,7 @@ export class ForgeBridgeService {
|
|
|
259
322
|
throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
|
|
260
323
|
}
|
|
261
324
|
this.recoveredHostAttempts.clear();
|
|
325
|
+
this.ackYield(reportedYield);
|
|
262
326
|
logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
|
|
263
327
|
return;
|
|
264
328
|
}
|
|
@@ -274,6 +338,7 @@ export class ForgeBridgeService {
|
|
|
274
338
|
}
|
|
275
339
|
}
|
|
276
340
|
async run(signal) {
|
|
341
|
+
const statePublisher = await this.startStatePublisher();
|
|
277
342
|
let attempt = 0;
|
|
278
343
|
try {
|
|
279
344
|
while (!this.stopped && !signal?.aborted) {
|
|
@@ -289,7 +354,7 @@ export class ForgeBridgeService {
|
|
|
289
354
|
}
|
|
290
355
|
}
|
|
291
356
|
catch (error) {
|
|
292
|
-
if (this.stopped || signal?.aborted) {
|
|
357
|
+
if (this.stopped || signal?.aborted || this.revokedReason !== null) {
|
|
293
358
|
break;
|
|
294
359
|
}
|
|
295
360
|
const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
|
|
@@ -305,6 +370,214 @@ export class ForgeBridgeService {
|
|
|
305
370
|
this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
|
|
306
371
|
}
|
|
307
372
|
await this.stopConnection();
|
|
373
|
+
await statePublisher?.stop();
|
|
374
|
+
}
|
|
375
|
+
if (this.revokedReason !== null) {
|
|
376
|
+
throw new BridgeRevokedError(this.revokedReason);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async startStatePublisher() {
|
|
380
|
+
if (!this.config.bridgeStatePath)
|
|
381
|
+
return null;
|
|
382
|
+
const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
|
|
383
|
+
inFlight: () => this.inFlight.snapshot(),
|
|
384
|
+
// Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
|
|
385
|
+
yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
|
|
386
|
+
yieldApplied: () => this.effectiveSettings.yielding,
|
|
387
|
+
connected: () => this.connection !== null && this.transportRecovery === null,
|
|
388
|
+
}, { log: logBridgeStatus });
|
|
389
|
+
this.publishState = () => void publisher.publish();
|
|
390
|
+
this.inFlight.onChange(this.publishState);
|
|
391
|
+
await publisher.start();
|
|
392
|
+
logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
|
|
393
|
+
return publisher;
|
|
394
|
+
}
|
|
395
|
+
/** The reason Forge gave when it removed this runner, or null while it is paired. */
|
|
396
|
+
get revoked() {
|
|
397
|
+
return this.revokedReason;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
|
|
401
|
+
* reconnecting; its attempts were already settled on the server, so local work is
|
|
402
|
+
* aborted rather than reported.
|
|
403
|
+
*/
|
|
404
|
+
handleRevoked(notice) {
|
|
405
|
+
if (this.revokedReason !== null)
|
|
406
|
+
return;
|
|
407
|
+
const reason = typeof notice?.reason === "string" && notice.reason.trim()
|
|
408
|
+
? notice.reason.trim()
|
|
409
|
+
: bridgeRevokedMessage;
|
|
410
|
+
this.revokedReason = reason;
|
|
411
|
+
this.stopped = true;
|
|
412
|
+
logBridgeStatus(reason);
|
|
413
|
+
this.abortActiveSessions("runner removed from Forge");
|
|
414
|
+
this.abortActiveReadinessProbes("runner removed from Forge");
|
|
415
|
+
void this.stopConnection().catch(() => undefined);
|
|
416
|
+
}
|
|
417
|
+
/** The effective settings and how they were derived, as last reported (decision 0014). */
|
|
418
|
+
get runnerSettings() {
|
|
419
|
+
return this.settingsReport;
|
|
420
|
+
}
|
|
421
|
+
runnerHostDefaults() {
|
|
422
|
+
return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Once per bridge process: drop governor overrides an earlier process left on
|
|
426
|
+
* the state root, then put today's effective settings (env bounds and the local
|
|
427
|
+
* yield flag, no server document yet) in force.
|
|
428
|
+
*/
|
|
429
|
+
async startSettings() {
|
|
430
|
+
this.settingsStarted ??= (async () => {
|
|
431
|
+
await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
|
|
432
|
+
logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
|
|
433
|
+
});
|
|
434
|
+
this.localYield = await this.readLocalYield();
|
|
435
|
+
await this.enqueueSettings({ kind: "local" });
|
|
436
|
+
})();
|
|
437
|
+
await this.settingsStarted;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Decision 0014 `ApplySettings`. Applies only a document newer than the one
|
|
441
|
+
* applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
|
|
442
|
+
* the applied version is acknowledged again without applying it; an older one is
|
|
443
|
+
* ignored.
|
|
444
|
+
*/
|
|
445
|
+
async handleApplySettings(raw) {
|
|
446
|
+
const document = parseRunnerSettingsDocument(raw);
|
|
447
|
+
if (!document) {
|
|
448
|
+
logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (document.runnerId && document.runnerId !== this.config.runnerId) {
|
|
452
|
+
logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
await this.enqueueSettings({ kind: "server", document });
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Polls the local `forge-bridge yield` flag (every heartbeat and before each
|
|
459
|
+
* offer decision). A change is applied at once and reported again under the
|
|
460
|
+
* same settings version.
|
|
461
|
+
*/
|
|
462
|
+
/** Yielding now, or about to: a received yield-on that is still being applied counts. */
|
|
463
|
+
yieldingOrQueued() {
|
|
464
|
+
return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
|
|
465
|
+
}
|
|
466
|
+
async refreshLocalYield() {
|
|
467
|
+
if (!this.config.localYieldFlagPath)
|
|
468
|
+
return;
|
|
469
|
+
const localYield = await this.readLocalYield();
|
|
470
|
+
if (localYield === this.localYield)
|
|
471
|
+
return;
|
|
472
|
+
this.localYield = localYield;
|
|
473
|
+
logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
|
|
474
|
+
await this.enqueueSettings({ kind: "local" });
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* A setting the host couldn't put in force holds placement on the server, so
|
|
478
|
+
* every heartbeat tries the applied document again until it takes.
|
|
479
|
+
*/
|
|
480
|
+
async retryFailedSettings() {
|
|
481
|
+
if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
|
|
482
|
+
return;
|
|
483
|
+
await this.enqueueSettings({ kind: "local" });
|
|
484
|
+
}
|
|
485
|
+
async readLocalYield() {
|
|
486
|
+
const flagPath = this.config.localYieldFlagPath;
|
|
487
|
+
return flagPath ? await readLocalYieldFlag(flagPath) : false;
|
|
488
|
+
}
|
|
489
|
+
enqueueSettings(change) {
|
|
490
|
+
const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
|
|
491
|
+
if (turnsYieldOn)
|
|
492
|
+
this.pendingYieldOn += 1;
|
|
493
|
+
const applied = this.settingsTail
|
|
494
|
+
.then(() => this.applySettings(change))
|
|
495
|
+
.finally(() => {
|
|
496
|
+
if (turnsYieldOn)
|
|
497
|
+
this.pendingYieldOn -= 1;
|
|
498
|
+
});
|
|
499
|
+
// A failed apply must not wedge later applies or the offers waiting on them.
|
|
500
|
+
this.settingsTail = applied.catch(error => {
|
|
501
|
+
logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
|
|
502
|
+
});
|
|
503
|
+
return this.settingsTail;
|
|
504
|
+
}
|
|
505
|
+
async applySettings(change) {
|
|
506
|
+
const applied = this.appliedSettingsDocument;
|
|
507
|
+
if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
|
|
508
|
+
if (change.document.version === applied.version) {
|
|
509
|
+
// The server sends the current version again at each Hello. After a reconnect it may never
|
|
510
|
+
// have seen this version's ack (the old connection dropped first), and its offer gate waits
|
|
511
|
+
// for one from this connection, so acknowledge what is in force again rather than nothing.
|
|
512
|
+
void this.sendSettingsApplied(this.settingsReport);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const document = change.kind === "server" ? change.document : applied;
|
|
519
|
+
const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
|
|
520
|
+
const failures = await this.putSettingsInForce(effective);
|
|
521
|
+
// Report what is in force: a key the host couldn't take keeps its previous value.
|
|
522
|
+
const report = {
|
|
523
|
+
...runnerSettingsInForce(effective.report, this.settingsReport, failures),
|
|
524
|
+
version: document?.version ?? null,
|
|
525
|
+
};
|
|
526
|
+
const changed = !sameRunnerSettingsReport(report, this.settingsReport);
|
|
527
|
+
this.appliedSettingsDocument = document;
|
|
528
|
+
this.effectiveSettings = effective;
|
|
529
|
+
this.settingsReport = report;
|
|
530
|
+
this.publishState();
|
|
531
|
+
if (change.kind === "server") {
|
|
532
|
+
logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
|
|
533
|
+
}
|
|
534
|
+
// Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
|
|
535
|
+
if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
|
|
536
|
+
void this.sendSettingsApplied(report);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Max attempts and the memory reserve go to host attempt admission; the governor
|
|
541
|
+
* budget (the yield budget while yielding) and the heavy-step limit go to the
|
|
542
|
+
* shared settings file every governor on the state root reads at admission.
|
|
543
|
+
* Neither touches admitted work. Returns the keys the host could not put in
|
|
544
|
+
* force (`apply_failed`); their previous values stay in force.
|
|
545
|
+
*/
|
|
546
|
+
async putSettingsInForce(effective) {
|
|
547
|
+
const { values } = effective.report;
|
|
548
|
+
const rejected = [];
|
|
549
|
+
try {
|
|
550
|
+
await this.sessions.applyRunnerLimits?.({
|
|
551
|
+
maxConcurrentAttempts: values.maxConcurrentAttempts,
|
|
552
|
+
memoryReserveBytes: values.memoryReserveBytes,
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
|
|
557
|
+
rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
|
|
558
|
+
}
|
|
559
|
+
try {
|
|
560
|
+
await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
|
|
561
|
+
cpuBudgetFraction: effective.governorCpuBudgetFraction,
|
|
562
|
+
maxHeavySteps: values.maxHeavySteps,
|
|
563
|
+
yielding: effective.yielding,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
catch (error) {
|
|
567
|
+
const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
|
|
568
|
+
rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
|
|
569
|
+
}
|
|
570
|
+
return rejected;
|
|
571
|
+
}
|
|
572
|
+
ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
|
|
573
|
+
/** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
|
|
574
|
+
async sendSettingsApplied(report) {
|
|
575
|
+
try {
|
|
576
|
+
await this.invokeAck("SettingsApplied", report);
|
|
577
|
+
this.ackYield(report.values.yieldToForeground);
|
|
578
|
+
}
|
|
579
|
+
catch (error) {
|
|
580
|
+
logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
|
|
308
581
|
}
|
|
309
582
|
}
|
|
310
583
|
async stop() {
|
|
@@ -434,9 +707,18 @@ export class ForgeBridgeService {
|
|
|
434
707
|
await fs.promises.mkdir(root, { recursive: true });
|
|
435
708
|
return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
|
|
436
709
|
}
|
|
710
|
+
/** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
|
|
711
|
+
async lookAtChatGiphyFrames(packet, active, cwd) {
|
|
712
|
+
return await lookAtChatGiphyFrames(packet, cwd, {
|
|
713
|
+
runner: this.chatProcessRunner,
|
|
714
|
+
signal: active.controller.signal,
|
|
715
|
+
log: logBridgeStatus,
|
|
716
|
+
takeFrames: async (request) => await this.connection?.invoke(chatTurnGiphyFramesMethod, request) ?? { accepted: false },
|
|
717
|
+
});
|
|
718
|
+
}
|
|
437
719
|
async runChatProviderProcess(packet, active, cwd) {
|
|
438
720
|
const output = createProviderOutputState(packet.providerKind);
|
|
439
|
-
const plan = buildChatProviderCommand(packet, cwd);
|
|
721
|
+
const plan = buildChatProviderCommand(packet, cwd, await this.lookAtChatGiphyFrames(packet, active, cwd));
|
|
440
722
|
const redactionSecrets = chatRedactionSecrets(packet);
|
|
441
723
|
let started = false;
|
|
442
724
|
const result = await this.chatProcessRunner.run({
|
|
@@ -446,6 +728,7 @@ export class ForgeBridgeService {
|
|
|
446
728
|
env: {
|
|
447
729
|
FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
|
|
448
730
|
FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
|
|
731
|
+
...plan.env,
|
|
449
732
|
},
|
|
450
733
|
stdin: plan.stdin,
|
|
451
734
|
}, {
|
|
@@ -472,6 +755,7 @@ export class ForgeBridgeService {
|
|
|
472
755
|
content: "Bridge Chat provider process exited.",
|
|
473
756
|
}).catch(() => undefined);
|
|
474
757
|
}
|
|
758
|
+
assertChatTurnFinished(result);
|
|
475
759
|
return { command: plan.command, output, result };
|
|
476
760
|
}
|
|
477
761
|
async sendChatProviderEvent(packet, active, event, providerThreadId) {
|
|
@@ -605,37 +889,16 @@ export class ForgeBridgeService {
|
|
|
605
889
|
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
606
890
|
return;
|
|
607
891
|
}
|
|
608
|
-
|
|
609
|
-
try {
|
|
610
|
-
assertHostDatabaseCapabilityBoundary();
|
|
611
|
-
}
|
|
612
|
-
catch (error) {
|
|
613
|
-
const message = errorMessage(error);
|
|
614
|
-
await this.sendResult(dispatch, failureResult(message, [{
|
|
615
|
-
role: "runner",
|
|
616
|
-
kind: "error",
|
|
617
|
-
content: message,
|
|
618
|
-
eventType: "host_database_capability_forbidden",
|
|
619
|
-
}], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
|
|
620
|
-
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
621
|
-
return;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
let capabilityFailure;
|
|
892
|
+
let refusal;
|
|
625
893
|
try {
|
|
626
|
-
|
|
894
|
+
refusal = await this.refusalBeforeRun(dispatch);
|
|
627
895
|
}
|
|
628
896
|
catch (error) {
|
|
629
897
|
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
630
898
|
throw error;
|
|
631
899
|
}
|
|
632
|
-
if (
|
|
633
|
-
await this.sendResult(dispatch,
|
|
634
|
-
role: "runner",
|
|
635
|
-
kind: "error",
|
|
636
|
-
content: capabilityFailure,
|
|
637
|
-
eventType: "docker_engine_unavailable",
|
|
638
|
-
}], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
|
|
900
|
+
if (refusal) {
|
|
901
|
+
await this.sendResult(dispatch, refusal).catch(() => undefined);
|
|
639
902
|
this.releaseReservedDispatchHandoff(reservationHandoff);
|
|
640
903
|
return;
|
|
641
904
|
}
|
|
@@ -657,19 +920,7 @@ export class ForgeBridgeService {
|
|
|
657
920
|
return;
|
|
658
921
|
}
|
|
659
922
|
const controller = reservationHandoff?.controller ?? new AbortController();
|
|
660
|
-
this.
|
|
661
|
-
leaseId,
|
|
662
|
-
kind: "dispatch",
|
|
663
|
-
fencingToken,
|
|
664
|
-
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
665
|
-
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
666
|
-
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
667
|
-
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
668
|
-
resources: dispatch.sandbox?.executionMode === "docker"
|
|
669
|
-
? dispatch.sandbox.requestedResources
|
|
670
|
-
: zeroSandboxResources(),
|
|
671
|
-
controller
|
|
672
|
-
});
|
|
923
|
+
this.registerActiveDispatch(dispatch, controller);
|
|
673
924
|
if (reservationHandoff) {
|
|
674
925
|
// Promotion is synchronous with active-session registration. A qualified
|
|
675
926
|
// pre-start Cancel therefore sees either the cancellable reservation or
|
|
@@ -693,43 +944,10 @@ export class ForgeBridgeService {
|
|
|
693
944
|
};
|
|
694
945
|
await this.invokeAck("DispatchStarted", started);
|
|
695
946
|
}
|
|
696
|
-
const sink =
|
|
697
|
-
|
|
698
|
-
if (event.eventType === "provider_cli_started") {
|
|
699
|
-
const active = this.activeSessions.get(leaseId);
|
|
700
|
-
if (active)
|
|
701
|
-
active.resources = { ...active.resources, buildSlots: 0 };
|
|
702
|
-
}
|
|
703
|
-
try {
|
|
704
|
-
await this.invokeAck("DispatchEvent", {
|
|
705
|
-
leaseId,
|
|
706
|
-
fencingToken,
|
|
707
|
-
...(dispatch.sandbox ? {
|
|
708
|
-
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
709
|
-
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
710
|
-
} : {}),
|
|
711
|
-
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
712
|
-
}, {
|
|
713
|
-
replayCallbackTimeout: true,
|
|
714
|
-
signal: controller.signal,
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
|
-
catch (error) {
|
|
718
|
-
if (isDispatchNoLongerPending(error)) {
|
|
719
|
-
controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
throw error;
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
};
|
|
726
|
-
const result = normalized.sandbox?.executionMode === "docker"
|
|
727
|
-
? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
|
|
728
|
-
: await this.sessions.runOnce(normalized, sink, controller.signal);
|
|
729
|
-
if (normalized.sandbox?.executionMode === "docker") {
|
|
730
|
-
await this.flushCleanupReports().catch(() => undefined);
|
|
731
|
-
}
|
|
947
|
+
const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
|
|
948
|
+
const result = await this.runDispatchOnce(normalized, sink, controller.signal);
|
|
732
949
|
const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
|
|
950
|
+
this.inFlight.notePhase(leaseId, "result_delivery");
|
|
733
951
|
await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
|
|
734
952
|
}
|
|
735
953
|
catch (error) {
|
|
@@ -753,6 +971,77 @@ export class ForgeBridgeService {
|
|
|
753
971
|
await this.releaseActiveSessionAndRefreshCapacity(leaseId);
|
|
754
972
|
}
|
|
755
973
|
}
|
|
974
|
+
registerActiveDispatch(dispatch, controller) {
|
|
975
|
+
this.activeSessions.set(dispatch.lease.id, {
|
|
976
|
+
leaseId: dispatch.lease.id,
|
|
977
|
+
kind: "dispatch",
|
|
978
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
979
|
+
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
980
|
+
runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
|
|
981
|
+
leaseExpiresAt: dispatch.lease.expiresAt,
|
|
982
|
+
sandboxed: dispatch.sandbox?.executionMode === "docker",
|
|
983
|
+
resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
|
|
984
|
+
controller
|
|
985
|
+
});
|
|
986
|
+
this.inFlight.notePhase(dispatch.lease.id, "accepted");
|
|
987
|
+
logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
|
|
988
|
+
}
|
|
989
|
+
dispatchEventSink(dispatch, controller, redactionSecrets) {
|
|
990
|
+
const leaseId = dispatch.lease.id;
|
|
991
|
+
return {
|
|
992
|
+
emit: async (event) => {
|
|
993
|
+
this.inFlight.notePhase(leaseId, event.eventType);
|
|
994
|
+
if (event.eventType === "provider_cli_started") {
|
|
995
|
+
const active = this.activeSessions.get(leaseId);
|
|
996
|
+
if (active)
|
|
997
|
+
active.resources = { ...active.resources, buildSlots: 0 };
|
|
998
|
+
}
|
|
999
|
+
try {
|
|
1000
|
+
await this.invokeAck("DispatchEvent", {
|
|
1001
|
+
leaseId,
|
|
1002
|
+
fencingToken: dispatch.lease.fencingToken,
|
|
1003
|
+
...(dispatch.sandbox ? {
|
|
1004
|
+
dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
|
|
1005
|
+
runnerInstanceId: dispatch.sandbox.runnerInstanceId
|
|
1006
|
+
} : {}),
|
|
1007
|
+
event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
|
|
1008
|
+
}, {
|
|
1009
|
+
replayCallbackTimeout: true,
|
|
1010
|
+
signal: controller.signal,
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
catch (error) {
|
|
1014
|
+
if (isDispatchNoLongerPending(error)) {
|
|
1015
|
+
controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
throw error;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
/** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
|
|
1024
|
+
async runDispatchOnce(dispatch, sink, signal) {
|
|
1025
|
+
const docker = dispatch.sandbox?.executionMode === "docker";
|
|
1026
|
+
const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
|
|
1027
|
+
const startedAt = Date.now();
|
|
1028
|
+
this.inFlight.notePhase(dispatch.lease.id, "run_once");
|
|
1029
|
+
logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
|
|
1030
|
+
try {
|
|
1031
|
+
const result = await runWithUnsandboxedReviewWarning(dispatch, this.config.allowUnsandboxedPrReview, sink, (warning) => logBridgeStatus(`${warning} ${ids}.`), () => docker
|
|
1032
|
+
? this.sandboxRuntime.runOnce(dispatch, sink, signal)
|
|
1033
|
+
: this.sessions.runOnce(dispatch, sink, signal));
|
|
1034
|
+
if (docker) {
|
|
1035
|
+
await this.flushCleanupReports().catch(() => undefined);
|
|
1036
|
+
}
|
|
1037
|
+
logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
|
|
1038
|
+
return result;
|
|
1039
|
+
}
|
|
1040
|
+
catch (error) {
|
|
1041
|
+
logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
|
|
1042
|
+
throw error;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
756
1045
|
reservedDispatchHandoffIsCurrent(handoff, dispatch) {
|
|
757
1046
|
const sandbox = dispatch.sandbox;
|
|
758
1047
|
const reservation = handoff.reservation;
|
|
@@ -840,6 +1129,16 @@ export class ForgeBridgeService {
|
|
|
840
1129
|
await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
|
|
841
1130
|
return;
|
|
842
1131
|
}
|
|
1132
|
+
// Decision 0014: decide under the settings Forge sent (an offer never races an
|
|
1133
|
+
// apply), and refuse new work while yielding to the foreground. The local flag
|
|
1134
|
+
// is read here too, before Forge has heard about it.
|
|
1135
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1136
|
+
// Every apply queued so far, including one a concurrent offer or heartbeat started.
|
|
1137
|
+
await this.settingsTail;
|
|
1138
|
+
if (this.effectiveSettings.yielding) {
|
|
1139
|
+
await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
843
1142
|
const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
|
|
844
1143
|
? await this.preflight.run()
|
|
845
1144
|
: this.preflight.current();
|
|
@@ -848,21 +1147,11 @@ export class ForgeBridgeService {
|
|
|
848
1147
|
await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
|
|
849
1148
|
return;
|
|
850
1149
|
}
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
|
|
857
|
-
if (providerNetworkFailure) {
|
|
858
|
-
await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
const authFailure = sandboxAuthFailure(dispatch, this.config);
|
|
862
|
-
if (authFailure) {
|
|
863
|
-
await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
|
|
864
|
-
return;
|
|
865
|
-
}
|
|
1150
|
+
}
|
|
1151
|
+
const policyRefusal = offerPolicyRefusal(dispatch, this.config, () => sandboxAuthFailure(dispatch, this.config));
|
|
1152
|
+
if (policyRefusal) {
|
|
1153
|
+
await this.sendOfferDecision(dispatch, false, policyRefusal.code, policyRefusal.message);
|
|
1154
|
+
return;
|
|
866
1155
|
}
|
|
867
1156
|
let requestedResources = sandbox.requestedResources;
|
|
868
1157
|
let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
|
|
@@ -874,7 +1163,7 @@ export class ForgeBridgeService {
|
|
|
874
1163
|
sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
|
|
875
1164
|
}
|
|
876
1165
|
catch (error) {
|
|
877
|
-
await this.sendOfferDecision(dispatch, false,
|
|
1166
|
+
await this.sendOfferDecision(dispatch, false, sandboxProfileRefusalCode(dispatch), error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
|
|
878
1167
|
return;
|
|
879
1168
|
}
|
|
880
1169
|
}
|
|
@@ -924,6 +1213,11 @@ export class ForgeBridgeService {
|
|
|
924
1213
|
if (Date.parse(dispatch.lease.expiresAt) <= now) {
|
|
925
1214
|
return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
|
|
926
1215
|
}
|
|
1216
|
+
// Yield may have turned on while the offer was being profiled, including a
|
|
1217
|
+
// yield Forge sent or the local flag set that hasn't finished applying yet.
|
|
1218
|
+
if (this.yieldingOrQueued()) {
|
|
1219
|
+
return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
|
|
1220
|
+
}
|
|
927
1221
|
if (sandbox.executionMode === "docker") {
|
|
928
1222
|
// A concurrent heartbeat/preflight refresh may have produced a newer
|
|
929
1223
|
// conservative dual-domain sample while this offer was being profiled.
|
|
@@ -1099,8 +1393,41 @@ export class ForgeBridgeService {
|
|
|
1099
1393
|
reservedResources: accepted ? reservedResources : null,
|
|
1100
1394
|
sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
|
|
1101
1395
|
};
|
|
1396
|
+
if (accepted)
|
|
1397
|
+
logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
|
|
1102
1398
|
await this.invokeAck("OfferDecision", payload);
|
|
1103
1399
|
}
|
|
1400
|
+
/**
|
|
1401
|
+
* The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
|
|
1402
|
+
* database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
|
|
1403
|
+
* without the owner's opt-in. Null when it may run.
|
|
1404
|
+
*/
|
|
1405
|
+
async refusalBeforeRun(dispatch) {
|
|
1406
|
+
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
1407
|
+
try {
|
|
1408
|
+
assertHostDatabaseCapabilityBoundary();
|
|
1409
|
+
}
|
|
1410
|
+
catch (error) {
|
|
1411
|
+
const message = errorMessage(error);
|
|
1412
|
+
return failureResult(message, [{
|
|
1413
|
+
role: "runner",
|
|
1414
|
+
kind: "error",
|
|
1415
|
+
content: message,
|
|
1416
|
+
eventType: "host_database_capability_forbidden",
|
|
1417
|
+
}], failureFactsFromError(error, { source: "bridge" }));
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
const capabilityFailure = await this.requiredCapabilityFailure(dispatch);
|
|
1421
|
+
if (capabilityFailure) {
|
|
1422
|
+
return failureResult(capabilityFailure, [{
|
|
1423
|
+
role: "runner",
|
|
1424
|
+
kind: "error",
|
|
1425
|
+
content: capabilityFailure,
|
|
1426
|
+
eventType: "docker_engine_unavailable",
|
|
1427
|
+
}], failureFactsForCode("docker_engine_unavailable"));
|
|
1428
|
+
}
|
|
1429
|
+
return prReviewPlacementRefusalResult(dispatch, this.config.allowUnsandboxedPrReview);
|
|
1430
|
+
}
|
|
1104
1431
|
async parseDispatchOrReport(rawDispatch) {
|
|
1105
1432
|
try {
|
|
1106
1433
|
return parseRunOnceDispatchPacket(rawDispatch);
|
|
@@ -1212,7 +1539,13 @@ export class ForgeBridgeService {
|
|
|
1212
1539
|
acceptedAt: new Date().toISOString(),
|
|
1213
1540
|
};
|
|
1214
1541
|
await this.invokeAck("ReadinessAccepted", accepted);
|
|
1215
|
-
|
|
1542
|
+
// While yielding, background readiness waits too; Forge retries a deferred probe.
|
|
1543
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1544
|
+
await this.settingsTail;
|
|
1545
|
+
if (this.yieldingOrQueued()) {
|
|
1546
|
+
result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
|
|
1547
|
+
}
|
|
1548
|
+
else if (this.activeSessions.size > 0) {
|
|
1216
1549
|
result = deferredReadinessResult(request, this.config.runnerInstanceId);
|
|
1217
1550
|
}
|
|
1218
1551
|
else if (!this.sessions.probeHostRuntime) {
|
|
@@ -1535,6 +1868,9 @@ export class ForgeBridgeService {
|
|
|
1535
1868
|
// force reconnects. Transport failures still do.
|
|
1536
1869
|
await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
|
|
1537
1870
|
await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
|
|
1871
|
+
// The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
|
|
1872
|
+
await this.refreshLocalYield().catch(() => undefined);
|
|
1873
|
+
await this.retryFailedSettings().catch(() => undefined);
|
|
1538
1874
|
await this.sendHeartbeat();
|
|
1539
1875
|
this.consecutiveHeartbeatFailures = 0;
|
|
1540
1876
|
}
|
|
@@ -1590,7 +1926,8 @@ export class ForgeBridgeService {
|
|
|
1590
1926
|
startSandboxMaintenance() {
|
|
1591
1927
|
this.stopSandboxMaintenance();
|
|
1592
1928
|
this.sandboxMaintenanceTimer = setInterval(() => {
|
|
1593
|
-
this.runSandboxMaintenance().catch(
|
|
1929
|
+
this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
|
|
1930
|
+
logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
|
|
1594
1931
|
}, 60_000);
|
|
1595
1932
|
this.sandboxMaintenanceTimer.unref?.();
|
|
1596
1933
|
}
|
|
@@ -1630,9 +1967,15 @@ export class ForgeBridgeService {
|
|
|
1630
1967
|
const connection = this.connection;
|
|
1631
1968
|
if (!connection)
|
|
1632
1969
|
throw new Error("Bridge is not connected.");
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1970
|
+
// Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
|
|
1971
|
+
const pending = { connection, generation: this.transportRecoveryGeneration };
|
|
1972
|
+
if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
|
|
1973
|
+
throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
|
|
1974
|
+
this.attemptSnapshotPending = pending;
|
|
1975
|
+
const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
|
|
1976
|
+
invocation.finally(() => { if (this.attemptSnapshotPending === pending)
|
|
1977
|
+
this.attemptSnapshotPending = null; }).catch(() => undefined);
|
|
1978
|
+
const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
|
|
1636
1979
|
if (!response.accepted) {
|
|
1637
1980
|
throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
|
|
1638
1981
|
}
|
|
@@ -1667,16 +2010,19 @@ export class ForgeBridgeService {
|
|
|
1667
2010
|
await this.sendHeartbeatSnapshot();
|
|
1668
2011
|
}
|
|
1669
2012
|
async sendHeartbeatSnapshot(signal) {
|
|
2013
|
+
const reportedYield = this.settingsReport.values.yieldToForeground;
|
|
1670
2014
|
await this.invokeAck("Heartbeat", {
|
|
1671
2015
|
status: "online",
|
|
1672
2016
|
capabilities: this.capabilities(),
|
|
1673
2017
|
version: this.config.version,
|
|
1674
2018
|
protocolVersion: this.config.protocolVersion
|
|
1675
2019
|
}, { signal });
|
|
2020
|
+
this.ackYield(reportedYield);
|
|
1676
2021
|
}
|
|
1677
2022
|
capabilities() {
|
|
1678
2023
|
const preflight = this.preflight.current();
|
|
1679
2024
|
const dockerEngine = this.dockerEngineProbe.current();
|
|
2025
|
+
this.dockerAvailable = dockerEngine?.available === true;
|
|
1680
2026
|
const runtimeState = this.sandboxRuntime.snapshot();
|
|
1681
2027
|
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
1682
2028
|
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
@@ -1693,7 +2039,7 @@ export class ForgeBridgeService {
|
|
|
1693
2039
|
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
1694
2040
|
}) : null;
|
|
1695
2041
|
return {
|
|
1696
|
-
schemaVersion:
|
|
2042
|
+
schemaVersion: 8,
|
|
1697
2043
|
activeSessionCount: this.activeSessions.size,
|
|
1698
2044
|
cliProviders: this.config.cliProviders,
|
|
1699
2045
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -1703,7 +2049,7 @@ export class ForgeBridgeService {
|
|
|
1703
2049
|
sandboxProfiles: this.config.sandboxProfiles,
|
|
1704
2050
|
runnerInstanceId: this.config.runnerInstanceId,
|
|
1705
2051
|
trustDomainId: this.config.trustDomainId,
|
|
1706
|
-
executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
|
|
2052
|
+
executionFacilities: [...(dockerEngine?.available ? ["docker_engine"] : []), ...prReviewExecutionFacilities(this.config.allowUnsandboxedPrReview)],
|
|
1707
2053
|
dockerEngine,
|
|
1708
2054
|
toolchains: {
|
|
1709
2055
|
...this.hostCapabilities.toolchains,
|
|
@@ -1716,6 +2062,7 @@ export class ForgeBridgeService {
|
|
|
1716
2062
|
playwrightProjects: this.hostCapabilities.playwrightProjects,
|
|
1717
2063
|
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
1718
2064
|
providerConnectivity: this.hostCapabilities.providerConnectivity,
|
|
2065
|
+
testPostgres: this.hostCapabilities.testPostgres,
|
|
1719
2066
|
host: this.hostLoad.facts(),
|
|
1720
2067
|
load: this.hostLoad.current(),
|
|
1721
2068
|
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
@@ -1757,7 +2104,8 @@ export class ForgeBridgeService {
|
|
|
1757
2104
|
supportsDraftRunOnce: this.config.supportsDraftRunOnce,
|
|
1758
2105
|
supportsDraftAttachments: this.config.supportsDraftAttachments,
|
|
1759
2106
|
supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
|
|
1760
|
-
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
|
|
2107
|
+
bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
|
|
2108
|
+
settings: { supportsServerSettings: true, ...this.settingsReport },
|
|
1761
2109
|
};
|
|
1762
2110
|
}
|
|
1763
2111
|
async requiredCapabilityFailure(dispatch) {
|
|
@@ -1911,6 +2259,16 @@ export class ForgeBridgeService {
|
|
|
1911
2259
|
}
|
|
1912
2260
|
}
|
|
1913
2261
|
}
|
|
2262
|
+
/** The `run` command's exit code after Forge removed the runner. */
|
|
2263
|
+
export const bridgeRevokedExitCode = 3;
|
|
2264
|
+
export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
|
|
2265
|
+
/** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
|
|
2266
|
+
export class BridgeRevokedError extends Error {
|
|
2267
|
+
constructor(message = bridgeRevokedMessage) {
|
|
2268
|
+
super(message);
|
|
2269
|
+
this.name = "BridgeRevokedError";
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
1914
2272
|
class BridgeCallbackRejectedError extends Error {
|
|
1915
2273
|
code;
|
|
1916
2274
|
constructor(code, message) {
|
|
@@ -1944,12 +2302,6 @@ function isProviderStorageUnavailable(error) {
|
|
|
1944
2302
|
function isBridgeCallbackTimeout(error) {
|
|
1945
2303
|
return errorMessage(error).startsWith("bridge_callback_timeout:");
|
|
1946
2304
|
}
|
|
1947
|
-
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
|
|
1948
|
-
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1949
|
-
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1950
|
-
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1951
|
-
return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback))), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot)));
|
|
1952
|
-
}
|
|
1953
2305
|
export class SignalRBridgeConnectionFactory {
|
|
1954
2306
|
create(config) {
|
|
1955
2307
|
return new SignalRBridgeConnection(config);
|
|
@@ -1979,6 +2331,18 @@ export class SignalRBridgeConnection {
|
|
|
1979
2331
|
void this.connection.stop().catch(() => undefined);
|
|
1980
2332
|
});
|
|
1981
2333
|
}
|
|
2334
|
+
onApplySettings(handler) {
|
|
2335
|
+
this.connection.on("ApplySettings", (raw) => {
|
|
2336
|
+
void Promise.resolve(handler(raw)).catch(() => undefined);
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
onRevoked(handler) {
|
|
2340
|
+
this.connection.on("Revoked", (raw) => {
|
|
2341
|
+
const notice = raw && typeof raw === "object" ? raw : {};
|
|
2342
|
+
handler(notice);
|
|
2343
|
+
void this.connection.stop().catch(() => undefined);
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
1982
2346
|
start() {
|
|
1983
2347
|
return this.connection.start();
|
|
1984
2348
|
}
|
|
@@ -2163,14 +2527,6 @@ function providerStatus(config, provider) {
|
|
|
2163
2527
|
return Object.entries(config.providerStatuses)
|
|
2164
2528
|
.find(([key]) => key.trim().toLowerCase() === normalized)?.[1];
|
|
2165
2529
|
}
|
|
2166
|
-
function defaultSandboxProfiles(providers, platform = process.platform) {
|
|
2167
|
-
if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
|
|
2168
|
-
return ["none"];
|
|
2169
|
-
}
|
|
2170
|
-
return platform === "win32"
|
|
2171
|
-
? ["danger-full-access"]
|
|
2172
|
-
: ["provider-workspace-write"];
|
|
2173
|
-
}
|
|
2174
2530
|
function configuredModelsFor(provider) {
|
|
2175
2531
|
const envName = `FORGE_${provider.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase()}_MODELS`;
|
|
2176
2532
|
return splitCsv(process.env[envName] ?? "");
|
|
@@ -2319,10 +2675,7 @@ function errorMessage(error) {
|
|
|
2319
2675
|
return error instanceof Error ? error.message : String(error);
|
|
2320
2676
|
}
|
|
2321
2677
|
function formatDelay(ms) {
|
|
2322
|
-
|
|
2323
|
-
return `${ms / 1000}s`;
|
|
2324
|
-
}
|
|
2325
|
-
return `${ms}ms`;
|
|
2678
|
+
return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
|
|
2326
2679
|
}
|
|
2327
2680
|
async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
|
|
2328
2681
|
let timeout = null;
|
|
@@ -2391,36 +2744,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
|
|
|
2391
2744
|
const maxChatEventContentChars = 4000;
|
|
2392
2745
|
const maxChatTerminalTextChars = 120_000;
|
|
2393
2746
|
const maxChatExactSecretChars = 8 * 1024;
|
|
2394
|
-
const chatTurnMetadataFileName = "forge-chat-metadata.json";
|
|
2395
|
-
async function materializeChatTurnMetadata(packet, workspacePath) {
|
|
2396
|
-
if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
|
|
2397
|
-
return;
|
|
2398
|
-
}
|
|
2399
|
-
await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
|
|
2400
|
-
schemaVersion: 1,
|
|
2401
|
-
attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
|
|
2402
|
-
turnId: handoff.turnId,
|
|
2403
|
-
attachmentId: handoff.attachmentId,
|
|
2404
|
-
tempFileToken: handoff.tempFileToken,
|
|
2405
|
-
mimeType: handoff.mimeType,
|
|
2406
|
-
sizeBytes: handoff.sizeBytes,
|
|
2407
|
-
sha256: handoff.sha256,
|
|
2408
|
-
fileNameDisplay: handoff.fileNameDisplay,
|
|
2409
|
-
expiresAt: handoff.expiresAt,
|
|
2410
|
-
status: handoff.status,
|
|
2411
|
-
})),
|
|
2412
|
-
actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
|
|
2413
|
-
grantId: grant.grantId,
|
|
2414
|
-
turnId: grant.turnId,
|
|
2415
|
-
leaseId: grant.leaseId,
|
|
2416
|
-
fencingToken: grant.fencingToken,
|
|
2417
|
-
allowedScopes: grant.allowedScopes,
|
|
2418
|
-
expiresAt: grant.expiresAt,
|
|
2419
|
-
redactionStatus: grant.redactionStatus,
|
|
2420
|
-
nonceHeldByBridge: true,
|
|
2421
|
-
})),
|
|
2422
|
-
}, null, 2)}\n`, "utf8");
|
|
2423
|
-
}
|
|
2424
2747
|
function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
|
|
2425
2748
|
const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
|
|
2426
2749
|
const metadataExpiresAtMs = [
|
|
@@ -2451,113 +2774,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
|
|
|
2451
2774
|
};
|
|
2452
2775
|
}
|
|
2453
2776
|
}
|
|
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
2777
|
function chatProviderExitFailure(command, result, redactionSecrets) {
|
|
2562
2778
|
const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
|
|
2563
2779
|
const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
|
|
@@ -2650,21 +2866,6 @@ function containsIgnoreCase(values, value) {
|
|
|
2650
2866
|
export function canReapManagedSandboxes(preflight) {
|
|
2651
2867
|
return canRunDockerMaintenance(preflight);
|
|
2652
2868
|
}
|
|
2653
|
-
function sandboxNetworkPolicyFailure(dispatch, config) {
|
|
2654
|
-
const sandbox = dispatch.sandbox;
|
|
2655
|
-
if (!sandbox)
|
|
2656
|
-
return "Protocol-v2 sandbox context is missing.";
|
|
2657
|
-
if (sandbox.networkPolicy.mode === "open_public"
|
|
2658
|
-
&& (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
|
|
2659
|
-
return "open_public sandbox networking is not permitted by this runner policy.";
|
|
2660
|
-
}
|
|
2661
|
-
if (sandbox.networkPolicy.mode === "public_allowlist"
|
|
2662
|
-
&& sandbox.networkPolicy.allowedHosts.length > 0
|
|
2663
|
-
&& process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
|
|
2664
|
-
return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
|
|
2665
|
-
}
|
|
2666
|
-
return null;
|
|
2667
|
-
}
|
|
2668
2869
|
export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
|
|
2669
2870
|
if (!requiredCapabilities.includes("docker_engine"))
|
|
2670
2871
|
return null;
|
|
@@ -2701,34 +2902,6 @@ function parseReadinessProbe(value) {
|
|
|
2701
2902
|
}
|
|
2702
2903
|
return request;
|
|
2703
2904
|
}
|
|
2704
|
-
function deferredReadinessResult(request, runnerInstanceId) {
|
|
2705
|
-
return {
|
|
2706
|
-
schemaVersion: 1,
|
|
2707
|
-
requestId: request.requestId,
|
|
2708
|
-
fencingToken: request.fencingToken,
|
|
2709
|
-
runnerInstanceId,
|
|
2710
|
-
status: "failed",
|
|
2711
|
-
reasonCode: "host_runtime_probe_deferred",
|
|
2712
|
-
reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
|
|
2713
|
-
checkedAt: new Date().toISOString(),
|
|
2714
|
-
};
|
|
2715
|
-
}
|
|
2716
|
-
function readinessDeferralReason(signal) {
|
|
2717
|
-
if (!signal.aborted)
|
|
2718
|
-
return null;
|
|
2719
|
-
const reason = errorMessage(signal.reason);
|
|
2720
|
-
return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
|
|
2721
|
-
}
|
|
2722
|
-
function sandboxProviderNetworkFailure(dispatch, config) {
|
|
2723
|
-
const sandbox = dispatch.sandbox;
|
|
2724
|
-
if (!sandbox || sandbox.networkPolicy.mode !== "offline")
|
|
2725
|
-
return null;
|
|
2726
|
-
const provider = dispatch.execution.provider.trim().toLowerCase();
|
|
2727
|
-
const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
|
|
2728
|
-
if (!isNetworkProvider)
|
|
2729
|
-
return null;
|
|
2730
|
-
return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
|
|
2731
|
-
}
|
|
2732
2905
|
function sandboxAuthFailure(dispatch, config) {
|
|
2733
2906
|
const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
|
|
2734
2907
|
if (unsupported) {
|
|
@@ -2757,151 +2930,6 @@ function rejectedOfferReservation(code, message) {
|
|
|
2757
2930
|
resources: null,
|
|
2758
2931
|
};
|
|
2759
2932
|
}
|
|
2760
|
-
export function canReserveSandboxResources(used, requested, capacity) {
|
|
2761
|
-
return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
|
|
2762
|
-
&& used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
|
|
2763
|
-
&& used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
|
|
2764
|
-
&& used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
|
|
2765
|
-
&& used.pids + requested.pids <= capacity.pids
|
|
2766
|
-
&& used.buildSlots + requested.buildSlots <= capacity.buildSlots;
|
|
2767
|
-
}
|
|
2768
|
-
export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
|
|
2769
|
-
const ambientCapacity = preflight.availableMemoryBytes
|
|
2770
|
-
- preflight.hostReserveBytes
|
|
2771
|
-
+ activeMemoryBytes;
|
|
2772
|
-
const commitmentCapacity = preflight.totalMemoryBytes
|
|
2773
|
-
- preflight.hostReserveBytes;
|
|
2774
|
-
return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
|
|
2775
|
-
}
|
|
2776
|
-
export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
|
|
2777
|
-
const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
|
|
2778
|
-
if (requested.sandboxSlots > availableSlots) {
|
|
2779
|
-
return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
|
|
2780
|
-
}
|
|
2781
|
-
const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
|
|
2782
|
-
if (requested.memoryBytes > availableMemoryBytes) {
|
|
2783
|
-
return [
|
|
2784
|
-
`Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
|
|
2785
|
-
`(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
|
|
2786
|
-
`but ${formatBytes(availableMemoryBytes)} is available for admission.`,
|
|
2787
|
-
`Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
|
|
2788
|
-
`Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
|
|
2789
|
-
].join(" ");
|
|
2790
|
-
}
|
|
2791
|
-
const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
|
|
2792
|
-
if (requested.cpuMillis > availableCpuMillis) {
|
|
2793
|
-
return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
|
|
2794
|
-
}
|
|
2795
|
-
const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
|
|
2796
|
-
if (requested.workspaceBytes > availableWorkspaceBytes) {
|
|
2797
|
-
return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
|
|
2798
|
-
}
|
|
2799
|
-
const availablePids = Math.max(0, capacity.pids - used.pids);
|
|
2800
|
-
if (requested.pids > availablePids) {
|
|
2801
|
-
return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
|
|
2802
|
-
}
|
|
2803
|
-
const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
|
|
2804
|
-
return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
|
|
2805
|
-
}
|
|
2806
|
-
function sumSandboxResources(resources) {
|
|
2807
|
-
return resources.reduce((total, resource) => ({
|
|
2808
|
-
sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
|
|
2809
|
-
cpuMillis: total.cpuMillis + resource.cpuMillis,
|
|
2810
|
-
workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
|
|
2811
|
-
serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
|
|
2812
|
-
runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
|
|
2813
|
-
memoryBytes: total.memoryBytes + resource.memoryBytes,
|
|
2814
|
-
workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
|
|
2815
|
-
pids: total.pids + resource.pids,
|
|
2816
|
-
buildSlots: total.buildSlots + resource.buildSlots
|
|
2817
|
-
}), zeroSandboxResources());
|
|
2818
|
-
}
|
|
2819
|
-
function zeroSandboxResources() {
|
|
2820
|
-
return {
|
|
2821
|
-
sandboxSlots: 0,
|
|
2822
|
-
cpuMillis: 0,
|
|
2823
|
-
workerMemoryLimitBytes: 0,
|
|
2824
|
-
serviceMemoryLimitBytes: 0,
|
|
2825
|
-
runtimeOverheadBytes: 0,
|
|
2826
|
-
memoryBytes: 0,
|
|
2827
|
-
workspaceBytes: 0,
|
|
2828
|
-
pids: 0,
|
|
2829
|
-
buildSlots: 0,
|
|
2830
|
-
};
|
|
2831
|
-
}
|
|
2832
|
-
function defaultSandboxResources() {
|
|
2833
|
-
return {
|
|
2834
|
-
sandboxSlots: 1,
|
|
2835
|
-
cpuMillis: 2000,
|
|
2836
|
-
workerMemoryLimitBytes: 2 * 1024 ** 3,
|
|
2837
|
-
serviceMemoryLimitBytes: 0,
|
|
2838
|
-
runtimeOverheadBytes: 128 * 1024 ** 2,
|
|
2839
|
-
memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
|
|
2840
|
-
workspaceBytes: 10 * 1024 ** 3,
|
|
2841
|
-
pids: 512,
|
|
2842
|
-
buildSlots: 0
|
|
2843
|
-
};
|
|
2844
|
-
}
|
|
2845
|
-
export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2846
|
-
const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
|
|
2847
|
-
const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
|
|
2848
|
-
+ (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
|
|
2849
|
-
return {
|
|
2850
|
-
...requested,
|
|
2851
|
-
serviceMemoryLimitBytes,
|
|
2852
|
-
runtimeOverheadBytes,
|
|
2853
|
-
memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
|
|
2854
|
-
};
|
|
2855
|
-
}
|
|
2856
|
-
export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
|
|
2857
|
-
const repoPath = dispatch.repo.serverLocalPath;
|
|
2858
|
-
const sandbox = dispatch.sandbox;
|
|
2859
|
-
if (!repoPath || !sandbox) {
|
|
2860
|
-
throw new Error("Sandbox admission needs a mapped repository.");
|
|
2861
|
-
}
|
|
2862
|
-
const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
|
|
2863
|
-
const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
|
|
2864
|
-
if (!configCommitSha) {
|
|
2865
|
-
throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
|
|
2866
|
-
}
|
|
2867
|
-
const contractResult = await runSandboxProcess({
|
|
2868
|
-
command: "git",
|
|
2869
|
-
args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
|
|
2870
|
-
timeoutMs: 30_000,
|
|
2871
|
-
maxOutputBytes: 1024 * 1024,
|
|
2872
|
-
});
|
|
2873
|
-
if (contractResult.exitCode !== 0) {
|
|
2874
|
-
throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
|
|
2875
|
-
}
|
|
2876
|
-
const contract = validateSandboxContract(contractResult.stdout);
|
|
2877
|
-
const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
|
|
2878
|
-
role: dispatch.execution.role,
|
|
2879
|
-
serviceCount: contract.contract.services.length,
|
|
2880
|
-
browser: contract.contract.browser,
|
|
2881
|
-
});
|
|
2882
|
-
return {
|
|
2883
|
-
resources: resolveDynamicSandboxResources({
|
|
2884
|
-
...sandbox.requestedResources,
|
|
2885
|
-
workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
|
|
2886
|
-
}, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
|
|
2887
|
-
sandboxConfigCommitSha: configCommitSha,
|
|
2888
|
-
};
|
|
2889
|
-
}
|
|
2890
|
-
async function resolveFirstGitCommit(repoPath, refs) {
|
|
2891
|
-
for (const ref of refs) {
|
|
2892
|
-
const result = await runSandboxProcess({
|
|
2893
|
-
command: "git",
|
|
2894
|
-
args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
|
|
2895
|
-
timeoutMs: 30_000,
|
|
2896
|
-
maxOutputBytes: 1024 * 1024,
|
|
2897
|
-
});
|
|
2898
|
-
const commitSha = result.stdout.trim().toLowerCase();
|
|
2899
|
-
if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
|
|
2900
|
-
return commitSha;
|
|
2901
|
-
}
|
|
2902
|
-
}
|
|
2903
|
-
return null;
|
|
2904
|
-
}
|
|
2905
2933
|
function parseOfferEnvelope(value) {
|
|
2906
2934
|
return parseDispatchEnvelope(value);
|
|
2907
2935
|
}
|