@loucompanion/forge-bridge 0.1.4-dev.494233aa2e50 → 0.1.4-dev.60e18c3cfec6

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.
Files changed (141) hide show
  1. package/README.md +35 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +279 -10
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  64. package/dist/runtime/runner-settings.d.ts +100 -0
  65. package/dist/runtime/runner-settings.js +214 -0
  66. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  67. package/dist/sandbox/host-capacity-broker.js +315 -0
  68. package/dist/sandbox/runtime.d.ts +10 -1
  69. package/dist/sandbox/runtime.js +45 -2
  70. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  71. package/dist/sandbox/sandbox-cgroups.js +42 -0
  72. package/dist/session/managed-attempt-tools.d.ts +2 -0
  73. package/dist/session/managed-attempt-tools.js +156 -37
  74. package/dist/session/managed-command-host-load.d.ts +45 -0
  75. package/dist/session/managed-command-host-load.js +82 -0
  76. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  77. package/dist/session/mcp-argument-coercion.js +121 -0
  78. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  79. package/dist/session/phase-completion.artifacts.js +94 -25
  80. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  81. package/dist/session/phase-completion.command-validation.js +77 -0
  82. package/dist/session/phase-completion.d.ts +4 -0
  83. package/dist/session/phase-completion.helpers.js +13 -12
  84. package/dist/session/phase-completion.js +4 -0
  85. package/dist/session/phase-completion.prompts.js +6 -1
  86. package/dist/session/phase-completion.runtime.d.ts +5 -3
  87. package/dist/session/phase-completion.runtime.js +49 -19
  88. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  89. package/dist/session/phase-completion.schema-parts.js +188 -0
  90. package/dist/session/phase-completion.schemas.d.ts +3 -3
  91. package/dist/session/phase-completion.schemas.js +184 -209
  92. package/dist/session/phase-completion.validation.d.ts +2 -3
  93. package/dist/session/phase-completion.validation.js +46 -92
  94. package/dist/session/pre-publication-host-load.d.ts +27 -0
  95. package/dist/session/pre-publication-host-load.js +111 -0
  96. package/dist/session/pre-publication-process.d.ts +3 -0
  97. package/dist/session/pre-publication-process.js +23 -11
  98. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  99. package/dist/session/pre-publication-step-execution.js +49 -0
  100. package/dist/session/pre-publication-validation.d.ts +9 -9
  101. package/dist/session/pre-publication-validation.js +21 -55
  102. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  103. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  104. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  105. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  106. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  107. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  108. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  109. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  110. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  111. package/dist/session/provider-cli/provider-cli.service.js +183 -26
  112. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  113. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  114. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  115. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  116. package/dist/session/provider-cli/provider-output-state.js +9 -0
  117. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  118. package/dist/session/publishable-worktree-changes.js +21 -5
  119. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  120. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  121. package/dist/session/session.base.d.ts +9 -1
  122. package/dist/session/session.service.d.ts +9 -2
  123. package/dist/session/session.service.js +120 -5
  124. package/dist/session/session.types.d.ts +3 -0
  125. package/dist/session/session.types.js +12 -3
  126. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  127. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  128. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  129. package/dist/shared/process/host-process-supervisor.js +1 -1
  130. package/dist/shared/process/process-tree.d.ts +52 -0
  131. package/dist/shared/process/process-tree.js +144 -0
  132. package/dist/shared/process/process.d.ts +67 -0
  133. package/dist/shared/process/process.js +213 -11
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/dist/worktree/dependency-warmer.d.ts +25 -0
  137. package/dist/worktree/dependency-warmer.js +46 -10
  138. package/dist/worktree/worktree.service.d.ts +10 -1
  139. package/dist/worktree/worktree.service.js +42 -2
  140. package/dist/worktree/worktree.types.d.ts +7 -0
  141. package/package.json +1 -1
package/README.md CHANGED
@@ -23,6 +23,16 @@ forge-bridge status
23
23
  forge-bridge connect --server <forge-url> --runner-id <runner-id> --device-token <device-token>
24
24
  ```
25
25
 
26
+ To pair, open **Settings → Runners → Connect a bridge** in Forge and run the command it shows:
27
+
28
+ ```bash
29
+ forge-bridge pair <code> --server <forge-url>
30
+ ```
31
+
32
+ The runner name, provider CLIs and repo folder chosen in that dialog come back with the claim
33
+ and are saved to `bridge.json`; `--repo-root` and `--cli-provider` on the command line win over
34
+ them. `bridge.json` holds the device token, so the bridge writes it with mode `0600`.
35
+
26
36
  The bridge can also read connection settings from environment variables:
27
37
 
28
38
  - `FORGE_URL`
@@ -129,6 +139,29 @@ enters a ten-minute cooldown after an unsuccessful attempt. Remote `DOCKER_HOST`
129
139
  restarted. Operators can tune the bounded policy with `FORGE_DOCKER_RECOVERY_FAILURE_THRESHOLD`,
130
140
  `FORGE_DOCKER_RECOVERY_COOLDOWN_MS`, and `FORGE_DOCKER_RECOVERY_STARTUP_TIMEOUT_MS`.
131
141
 
142
+ ## Runner limits and yield
143
+
144
+ Forge owns each runner's limits (Settings → Runners → Limits) and pushes them to the bridge, which
145
+ applies them without a restart and without stopping admitted work: max attempts and the memory reserve
146
+ apply at the next attempt admission, the CPU budget, yield budget and max heavy steps at the next heavy
147
+ step. Host env vars only bound the server's values and are reported back to Forge: a ceiling on
148
+ capacity (`FORGE_HOST_MAX_CONCURRENT_ATTEMPTS`, `FORGE_HOST_CPU_BUDGET_PERCENT`,
149
+ `FORGE_HOST_LOAD_CPU_BUDGET_FRACTION`, `FORGE_HOST_MAX_HEAVY_STEPS`) and a floor on the reserve
150
+ (`FORGE_HOST_MEMORY_RESERVE_BYTES`). Without a server value, the env var or the bridge default applies.
151
+ The CPU budget, yield budget and heavy-step limit take effect only with `FORGE_HOST_LOAD_GOVERNOR=on`.
152
+
153
+ Yield this machine to foreground work (for example while gaming) from the host itself:
154
+
155
+ ```bash
156
+ forge-bridge yield on
157
+ forge-bridge yield status
158
+ forge-bridge yield off
159
+ ```
160
+
161
+ While yielding, the bridge takes no new attempts and heavy steps of running attempts use the yield CPU
162
+ budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
163
+ in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
164
+
132
165
  ## Docker sandbox runners
133
166
 
134
167
  Protocol-v2 bridges preflight Docker before advertising the `docker` sandbox runtime. Validate a repository contract and the local runner before enabling a project's `sandbox_required` policy:
@@ -190,9 +223,9 @@ Production shared runners require a Linux rootless Docker daemon. Docker Desktop
190
223
 
191
224
  Before selecting `sandbox_required`, save the full approved 40- or 64-character Git commit SHA in the project's Sandbox policy dialog. The server persists that SHA on the immutable attempt and the bridge reads `.forge/forge.sandbox.yml`, `.forge/Dockerfile`, and the tracked build context only from that commit. API-key dispatches carry an opaque one-time grant handle; the authenticated current runner instance redeems it after reservation, and plaintext stays out of offers, database payloads, Docker metadata, and host-persisted control files.
192
225
 
193
- Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Profile Settings. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
226
+ Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
194
227
 
195
- The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Profile Settings before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Profile Settings also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
228
+ The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
196
229
 
197
230
  Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
198
231
 
@@ -18,8 +18,17 @@ export interface BridgeConnection {
18
18
  onCancel(handler: BridgeCancelHandler): void;
19
19
  onReap?(handler: BridgeReapHandler): void;
20
20
  onReadinessProbe?(handler: BridgeReadinessProbeHandler): void;
21
+ /** Decision 0014: the owner removed this runner from Forge; the bridge must stop, not reconnect. */
22
+ onRevoked?(handler: (notice: BridgeRevokedNotice) => void): void;
23
+ /** Decision 0014: the server pushes the runner settings document (`ApplySettings`, schema 8 bridges only). */
24
+ onApplySettings?(handler: (document: unknown) => void | Promise<void>): void;
21
25
  invoke<TResponse>(methodName: string, payload: unknown): Promise<TResponse>;
22
26
  }
27
+ /** The `Revoked` hub message: the runner was removed from Forge and must be paired again. */
28
+ export interface BridgeRevokedNotice {
29
+ runnerId?: string;
30
+ reason?: string;
31
+ }
23
32
  export interface BridgeConnectionFactory {
24
33
  create(config: BridgeServiceConfig): BridgeConnection;
25
34
  }
@@ -1,11 +1,12 @@
1
1
  import type { SessionService } from "../session/session.base.js";
2
2
  import type { ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
3
+ import { type RunnerSettingsReport } from "../runtime/runner-settings.js";
3
4
  import { DockerEngineProbe, type DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
4
5
  import { type DispatchSandboxResourceRequest, type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
5
6
  import { DockerPreflight } from "../sandbox/preflight.js";
6
7
  import type { SandboxPreflightResult } from "../sandbox/sandbox.types.js";
7
8
  import { type SandboxRuntime } from "../sandbox/runtime.js";
8
- import type { BridgeConnection, BridgeConnectionFactory, BridgeService } from "./bridge.base.js";
9
+ import type { BridgeConnection, BridgeConnectionFactory, BridgeRevokedNotice, BridgeService } from "./bridge.base.js";
9
10
  import { type RunnerHostCapabilityProbe } from "./runner-host-capabilities.js";
10
11
  import { type HostLoadSource } from "../runtime/host-load-sampler.js";
11
12
  import type { BridgeCancelHandler, BridgeChatTurnHandler, BridgeDispatchHandler, BridgeLeaseUpdateRequest, BridgeReapRequest, BridgeServiceConfig } from "./bridge.types.js";
@@ -43,6 +44,7 @@ export declare class ForgeBridgeService implements BridgeService {
43
44
  private transportRecovery;
44
45
  private transportRecoveryGeneration;
45
46
  private stopped;
47
+ private revokedReason;
46
48
  private readonly activeSessions;
47
49
  private readonly reservations;
48
50
  private readonly activeReadinessProbes;
@@ -60,6 +62,16 @@ export declare class ForgeBridgeService implements BridgeService {
60
62
  private readonly sessions;
61
63
  private readonly enforceHostDatabaseCapabilityBoundary;
62
64
  private hostCapabilities;
65
+ private dockerAvailable;
66
+ private appliedSettingsDocument;
67
+ private localYield;
68
+ private effectiveSettings;
69
+ private settingsReport;
70
+ /** Applies run one at a time; offers wait for every apply queued before them. */
71
+ private settingsTail;
72
+ private pendingYieldOn;
73
+ private settingsStarted;
74
+ private hostRequirementFacts;
63
75
  private readonly recoveredHostAttempts;
64
76
  private hostCapabilitiesDetected;
65
77
  constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
@@ -68,6 +80,56 @@ export declare class ForgeBridgeService implements BridgeService {
68
80
  private recoveredHostAttemptsForHello;
69
81
  private registerConnection;
70
82
  run(signal?: AbortSignal): Promise<void>;
83
+ /** The reason Forge gave when it removed this runner, or null while it is paired. */
84
+ get revoked(): string | null;
85
+ /**
86
+ * Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
87
+ * reconnecting; its attempts were already settled on the server, so local work is
88
+ * aborted rather than reported.
89
+ */
90
+ private handleRevoked;
91
+ /** The effective settings and how they were derived, as last reported (decision 0014). */
92
+ get runnerSettings(): RunnerSettingsReport;
93
+ private runnerHostDefaults;
94
+ /**
95
+ * Once per bridge process: drop governor overrides an earlier process left on
96
+ * the state root, then put today's effective settings (env bounds and the local
97
+ * yield flag, no server document yet) in force.
98
+ */
99
+ private startSettings;
100
+ /**
101
+ * Decision 0014 `ApplySettings`. Applies only a document newer than the one
102
+ * applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
103
+ * the applied version is acknowledged again without applying it; an older one is
104
+ * ignored.
105
+ */
106
+ private handleApplySettings;
107
+ /**
108
+ * Polls the local `forge-bridge yield` flag (every heartbeat and before each
109
+ * offer decision). A change is applied at once and reported again under the
110
+ * same settings version.
111
+ */
112
+ /** Yielding now, or about to: a received yield-on that is still being applied counts. */
113
+ private yieldingOrQueued;
114
+ private refreshLocalYield;
115
+ /**
116
+ * A setting the host couldn't put in force holds placement on the server, so
117
+ * every heartbeat tries the applied document again until it takes.
118
+ */
119
+ private retryFailedSettings;
120
+ private readLocalYield;
121
+ private enqueueSettings;
122
+ private applySettings;
123
+ /**
124
+ * Max attempts and the memory reserve go to host attempt admission; the governor
125
+ * budget (the yield budget while yielding) and the heavy-step limit go to the
126
+ * shared settings file every governor on the state root reads at admission.
127
+ * Neither touches admitted work. Returns the keys the host could not put in
128
+ * force (`apply_failed`); their previous values stay in force.
129
+ */
130
+ private putSettingsInForce;
131
+ /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
132
+ private sendSettingsApplied;
71
133
  stop(): Promise<void>;
72
134
  private handleChatTurn;
73
135
  private createChatTurnWorkspace;
@@ -144,6 +206,13 @@ export declare class ForgeBridgeService implements BridgeService {
144
206
  private waitForClose;
145
207
  private stopConnection;
146
208
  }
209
+ /** The `run` command's exit code after Forge removed the runner. */
210
+ export declare const bridgeRevokedExitCode = 3;
211
+ export declare const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
212
+ /** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
213
+ export declare class BridgeRevokedError extends Error {
214
+ constructor(message?: string);
215
+ }
147
216
  export declare class SignalRBridgeConnectionFactory implements BridgeConnectionFactory {
148
217
  create(config: BridgeServiceConfig): BridgeConnection;
149
218
  }
@@ -151,6 +220,8 @@ export declare class SignalRBridgeConnection implements BridgeConnection {
151
220
  private readonly config;
152
221
  private readonly connection;
153
222
  constructor(config: BridgeServiceConfig);
223
+ onApplySettings(handler: (document: unknown) => void | Promise<void>): void;
224
+ onRevoked(handler: (notice: BridgeRevokedNotice) => void): void;
154
225
  start(): Promise<void>;
155
226
  stop(): Promise<void>;
156
227
  onClose(handler: (error?: Error) => void): void;
@@ -1,3 +1,4 @@
1
+ import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
1
2
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
@@ -12,7 +13,11 @@ import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } fr
12
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
13
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
14
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
15
- import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
+ import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
18
+ import { computeEffectiveRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
+ import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
+ import { readLocalYieldFlag } from "./local-yield-flag.js";
16
21
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
17
22
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
18
23
  import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
@@ -67,6 +72,7 @@ export class ForgeBridgeService {
67
72
  transportRecovery = null;
68
73
  transportRecoveryGeneration = 0;
69
74
  stopped = false;
75
+ revokedReason = null;
70
76
  activeSessions = new Map();
71
77
  reservations = new Map();
72
78
  activeReadinessProbes = new Map();
@@ -84,12 +90,41 @@ export class ForgeBridgeService {
84
90
  sessions;
85
91
  enforceHostDatabaseCapabilityBoundary;
86
92
  hostCapabilities = emptyRunnerHostCapabilitySnapshot();
93
+ dockerAvailable = false;
94
+ // Decision 0014 settings push. The last applied server document (null until one
95
+ // arrives: an old server never sends one), the local `forge-bridge yield` flag,
96
+ // and the effective settings computed from both and the host's env bounds.
97
+ appliedSettingsDocument = null;
98
+ localYield = false;
99
+ effectiveSettings;
100
+ settingsReport;
101
+ /** Applies run one at a time; offers wait for every apply queued before them. */
102
+ settingsTail = Promise.resolve();
103
+ // Server documents that turn yield on and are queued but not applied yet. The
104
+ // reservation commit is synchronous and can't wait for the apply, so it counts these.
105
+ pendingYieldOn = 0;
106
+ settingsStarted = null;
107
+ hostRequirementFacts() {
108
+ const facts = this.hostLoad.facts();
109
+ return {
110
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
111
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
112
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
113
+ .filter(([, tool]) => tool?.available === true)
114
+ .map(([name]) => name),
115
+ dockerAvailable: this.dockerAvailable,
116
+ browserLaunch: this.hostCapabilities.browserLaunch,
117
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
118
+ };
119
+ }
87
120
  // Reaping deletes the stale ledger, so its stopped-process proof is held here
88
121
  // until a Hello carrying it is accepted. A bridge restart forgets it, which
89
122
  // leaves those attempts on Forge's conservative unknown-outcome path.
90
123
  recoveredHostAttempts = new Map();
91
124
  hostCapabilitiesDetected = false;
92
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
125
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
126
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
127
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
93
128
  this.config = config;
94
129
  this.connections = connections;
95
130
  this.hostCapabilityProbe = hostCapabilityProbe;
@@ -126,14 +161,22 @@ export class ForgeBridgeService {
126
161
  },
127
162
  onStatus: logBridgeStatus,
128
163
  });
129
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
130
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
164
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
165
+ this.sessions = sessions ?? defaultSessions.sessions;
166
+ // Docker sandboxes ask the same host load governor for their validation tokens.
167
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
131
168
  this.sandboxResourceResolver = sandboxResourceResolver
132
169
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
133
170
  this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
134
171
  this.dispatchResultOutbox = dispatchResultOutbox ?? new FileDispatchResultOutbox(config.sandboxStateRoot);
172
+ // With no server document and no local flag these equal today's env/default behaviour.
173
+ this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
174
+ this.settingsReport = this.effectiveSettings.report;
135
175
  }
136
176
  async connectOnce() {
177
+ if (this.revokedReason !== null) {
178
+ throw new BridgeRevokedError(this.revokedReason);
179
+ }
137
180
  await this.stopConnection();
138
181
  this.stopped = false;
139
182
  if (this.enforceHostDatabaseCapabilityBoundary) {
@@ -162,6 +205,8 @@ export class ForgeBridgeService {
162
205
  // Static host facts and the first load sample ride on Hello; the sampler
163
206
  // keeps refreshing its cached snapshot for later heartbeats.
164
207
  await this.hostLoad.start().catch(() => undefined);
208
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
209
+ await this.startSettings();
165
210
  const connection = this.connections.create(this.config);
166
211
  this.connection = connection;
167
212
  this.transportRecovery = null;
@@ -211,6 +256,8 @@ export class ForgeBridgeService {
211
256
  connection.onCancel((request) => this.handleCancel(request));
212
257
  connection.onReap?.((request) => this.handleReap(request));
213
258
  connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
259
+ connection.onRevoked?.((notice) => this.handleRevoked(notice));
260
+ connection.onApplySettings?.((document) => this.handleApplySettings(document));
214
261
  await connection.start();
215
262
  await this.registerConnection(connection);
216
263
  await this.flushDispatchResults(true).catch(error => {
@@ -289,7 +336,7 @@ export class ForgeBridgeService {
289
336
  }
290
337
  }
291
338
  catch (error) {
292
- if (this.stopped || signal?.aborted) {
339
+ if (this.stopped || signal?.aborted || this.revokedReason !== null) {
293
340
  break;
294
341
  }
295
342
  const backoff = this.config.reconnectBackoffMs[Math.min(attempt, this.config.reconnectBackoffMs.length - 1)] ?? 5000;
@@ -306,6 +353,194 @@ export class ForgeBridgeService {
306
353
  }
307
354
  await this.stopConnection();
308
355
  }
356
+ if (this.revokedReason !== null) {
357
+ throw new BridgeRevokedError(this.revokedReason);
358
+ }
359
+ }
360
+ /** The reason Forge gave when it removed this runner, or null while it is paired. */
361
+ get revoked() {
362
+ return this.revokedReason;
363
+ }
364
+ /**
365
+ * Decision 0014 §3 "Remove": Forge removed this runner. Stop for good instead of
366
+ * reconnecting; its attempts were already settled on the server, so local work is
367
+ * aborted rather than reported.
368
+ */
369
+ handleRevoked(notice) {
370
+ if (this.revokedReason !== null)
371
+ return;
372
+ const reason = typeof notice?.reason === "string" && notice.reason.trim()
373
+ ? notice.reason.trim()
374
+ : bridgeRevokedMessage;
375
+ this.revokedReason = reason;
376
+ this.stopped = true;
377
+ logBridgeStatus(reason);
378
+ this.abortActiveSessions("runner removed from Forge");
379
+ this.abortActiveReadinessProbes("runner removed from Forge");
380
+ void this.stopConnection().catch(() => undefined);
381
+ }
382
+ /** The effective settings and how they were derived, as last reported (decision 0014). */
383
+ get runnerSettings() {
384
+ return this.settingsReport;
385
+ }
386
+ runnerHostDefaults() {
387
+ return this.sessions.runnerLimitDefaults?.() ?? hostCapacityLimitDefaults();
388
+ }
389
+ /**
390
+ * Once per bridge process: drop governor overrides an earlier process left on
391
+ * the state root, then put today's effective settings (env bounds and the local
392
+ * yield flag, no server document yet) in force.
393
+ */
394
+ async startSettings() {
395
+ this.settingsStarted ??= (async () => {
396
+ await resetHostLoadRuntimeSettings(this.config.sandboxStateRoot).catch(error => {
397
+ logBridgeStatus(`Could not reset the host load settings file: ${errorMessage(error)}.`);
398
+ });
399
+ this.localYield = await this.readLocalYield();
400
+ await this.enqueueSettings({ kind: "local" });
401
+ })();
402
+ await this.settingsStarted;
403
+ }
404
+ /**
405
+ * Decision 0014 `ApplySettings`. Applies only a document newer than the one
406
+ * applied, one at a time, then acknowledges it with `SettingsApplied`. A replay of
407
+ * the applied version is acknowledged again without applying it; an older one is
408
+ * ignored.
409
+ */
410
+ async handleApplySettings(raw) {
411
+ const document = parseRunnerSettingsDocument(raw);
412
+ if (!document) {
413
+ logBridgeStatus("Ignored an ApplySettings message without a valid settings version.");
414
+ return;
415
+ }
416
+ if (document.runnerId && document.runnerId !== this.config.runnerId) {
417
+ logBridgeStatus(`Ignored settings v${document.version} addressed to runner ${document.runnerId}.`);
418
+ return;
419
+ }
420
+ await this.enqueueSettings({ kind: "server", document });
421
+ }
422
+ /**
423
+ * Polls the local `forge-bridge yield` flag (every heartbeat and before each
424
+ * offer decision). A change is applied at once and reported again under the
425
+ * same settings version.
426
+ */
427
+ /** Yielding now, or about to: a received yield-on that is still being applied counts. */
428
+ yieldingOrQueued() {
429
+ return this.effectiveSettings.yielding || this.localYield || this.pendingYieldOn > 0;
430
+ }
431
+ async refreshLocalYield() {
432
+ if (!this.config.localYieldFlagPath)
433
+ return;
434
+ const localYield = await this.readLocalYield();
435
+ if (localYield === this.localYield)
436
+ return;
437
+ this.localYield = localYield;
438
+ logBridgeStatus(`Local yield to foreground turned ${localYield ? "on" : "off"} (forge-bridge yield).`);
439
+ await this.enqueueSettings({ kind: "local" });
440
+ }
441
+ /**
442
+ * A setting the host couldn't put in force holds placement on the server, so
443
+ * every heartbeat tries the applied document again until it takes.
444
+ */
445
+ async retryFailedSettings() {
446
+ if (!this.settingsReport.rejected.some(entry => entry.kind === "apply_failed"))
447
+ return;
448
+ await this.enqueueSettings({ kind: "local" });
449
+ }
450
+ async readLocalYield() {
451
+ const flagPath = this.config.localYieldFlagPath;
452
+ return flagPath ? await readLocalYieldFlag(flagPath) : false;
453
+ }
454
+ enqueueSettings(change) {
455
+ const turnsYieldOn = change.kind === "server" && change.document.yieldToForeground;
456
+ if (turnsYieldOn)
457
+ this.pendingYieldOn += 1;
458
+ const applied = this.settingsTail
459
+ .then(() => this.applySettings(change))
460
+ .finally(() => {
461
+ if (turnsYieldOn)
462
+ this.pendingYieldOn -= 1;
463
+ });
464
+ // A failed apply must not wedge later applies or the offers waiting on them.
465
+ this.settingsTail = applied.catch(error => {
466
+ logBridgeStatus(`Applying runner settings failed: ${errorMessage(error)}.`);
467
+ });
468
+ return this.settingsTail;
469
+ }
470
+ async applySettings(change) {
471
+ const applied = this.appliedSettingsDocument;
472
+ if (change.kind === "server" && applied !== null && change.document.version <= applied.version) {
473
+ if (change.document.version === applied.version) {
474
+ // The server sends the current version again at each Hello. After a reconnect it may never
475
+ // have seen this version's ack (the old connection dropped first), and its offer gate waits
476
+ // for one from this connection, so acknowledge what is in force again rather than nothing.
477
+ void this.sendSettingsApplied(this.settingsReport);
478
+ return;
479
+ }
480
+ logBridgeStatus(`Ignored runner settings v${change.document.version}; v${applied.version} is already applied.`);
481
+ return;
482
+ }
483
+ const document = change.kind === "server" ? change.document : applied;
484
+ const effective = computeEffectiveRunnerSettings(document, process.env, this.runnerHostDefaults(), this.localYield);
485
+ const failures = await this.putSettingsInForce(effective);
486
+ // Report what is in force: a key the host couldn't take keeps its previous value.
487
+ const report = {
488
+ ...runnerSettingsInForce(effective.report, this.settingsReport, failures),
489
+ version: document?.version ?? null,
490
+ };
491
+ const changed = !sameRunnerSettingsReport(report, this.settingsReport);
492
+ this.appliedSettingsDocument = document;
493
+ this.effectiveSettings = effective;
494
+ this.settingsReport = report;
495
+ if (change.kind === "server") {
496
+ logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
497
+ }
498
+ // Only a server that has sent ApplySettings knows SettingsApplied; an old one learns nothing new.
499
+ if (this.appliedSettingsDocument !== null && (change.kind === "server" || changed)) {
500
+ void this.sendSettingsApplied(report);
501
+ }
502
+ }
503
+ /**
504
+ * Max attempts and the memory reserve go to host attempt admission; the governor
505
+ * budget (the yield budget while yielding) and the heavy-step limit go to the
506
+ * shared settings file every governor on the state root reads at admission.
507
+ * Neither touches admitted work. Returns the keys the host could not put in
508
+ * force (`apply_failed`); their previous values stay in force.
509
+ */
510
+ async putSettingsInForce(effective) {
511
+ const { values } = effective.report;
512
+ const rejected = [];
513
+ try {
514
+ await this.sessions.applyRunnerLimits?.({
515
+ maxConcurrentAttempts: values.maxConcurrentAttempts,
516
+ memoryReserveBytes: values.memoryReserveBytes,
517
+ });
518
+ }
519
+ catch (error) {
520
+ const reason = `host attempt admission did not take the limit: ${errorMessage(error)}`;
521
+ rejected.push({ key: "maxConcurrentAttempts", reason, kind: "apply_failed" }, { key: "memoryReserveBytes", reason, kind: "apply_failed" });
522
+ }
523
+ try {
524
+ await writeHostLoadRuntimeSettings(this.config.sandboxStateRoot, {
525
+ cpuBudgetFraction: effective.governorCpuBudgetFraction,
526
+ maxHeavySteps: values.maxHeavySteps,
527
+ yielding: effective.yielding,
528
+ });
529
+ }
530
+ catch (error) {
531
+ const reason = `the host load governor settings could not be written: ${errorMessage(error)}`;
532
+ rejected.push({ key: "cpuBudgetPercent", reason, kind: "apply_failed" }, { key: "yieldCpuBudgetPercent", reason, kind: "apply_failed" }, { key: "maxHeavySteps", reason, kind: "apply_failed" });
533
+ }
534
+ return rejected;
535
+ }
536
+ /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
537
+ async sendSettingsApplied(report) {
538
+ try {
539
+ await this.invokeAck("SettingsApplied", report);
540
+ }
541
+ catch (error) {
542
+ logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
543
+ }
309
544
  }
310
545
  async stop() {
311
546
  this.stopped = true;
@@ -840,6 +1075,16 @@ export class ForgeBridgeService {
840
1075
  await this.sendOfferDecision(dispatch, false, "lease_expired", "Offer lease is already expired.");
841
1076
  return;
842
1077
  }
1078
+ // Decision 0014: decide under the settings Forge sent (an offer never races an
1079
+ // apply), and refuse new work while yielding to the foreground. The local flag
1080
+ // is read here too, before Forge has heard about it.
1081
+ await this.refreshLocalYield().catch(() => undefined);
1082
+ // Every apply queued so far, including one a concurrent offer or heartbeat started.
1083
+ await this.settingsTail;
1084
+ if (this.effectiveSettings.yielding) {
1085
+ await this.sendOfferDecision(dispatch, false, "runner_yielding", runnerYieldingMessage(this.settingsReport));
1086
+ return;
1087
+ }
843
1088
  const preflight = sandbox.executionMode === "docker" && this.config.dockerEnabled
844
1089
  ? await this.preflight.run()
845
1090
  : this.preflight.current();
@@ -924,6 +1169,11 @@ export class ForgeBridgeService {
924
1169
  if (Date.parse(dispatch.lease.expiresAt) <= now) {
925
1170
  return rejectedOfferReservation("lease_expired", "Offer lease is already expired.");
926
1171
  }
1172
+ // Yield may have turned on while the offer was being profiled, including a
1173
+ // yield Forge sent or the local flag set that hasn't finished applying yet.
1174
+ if (this.yieldingOrQueued()) {
1175
+ return rejectedOfferReservation("runner_yielding", runnerYieldingMessage(this.settingsReport));
1176
+ }
927
1177
  if (sandbox.executionMode === "docker") {
928
1178
  // A concurrent heartbeat/preflight refresh may have produced a newer
929
1179
  // conservative dual-domain sample while this offer was being profiled.
@@ -1535,6 +1785,9 @@ export class ForgeBridgeService {
1535
1785
  // force reconnects. Transport failures still do.
1536
1786
  await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
1537
1787
  await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
1788
+ // The heartbeat carries the effective settings, so pick up `forge-bridge yield` first.
1789
+ await this.refreshLocalYield().catch(() => undefined);
1790
+ await this.retryFailedSettings().catch(() => undefined);
1538
1791
  await this.sendHeartbeat();
1539
1792
  this.consecutiveHeartbeatFailures = 0;
1540
1793
  }
@@ -1677,6 +1930,7 @@ export class ForgeBridgeService {
1677
1930
  capabilities() {
1678
1931
  const preflight = this.preflight.current();
1679
1932
  const dockerEngine = this.dockerEngineProbe.current();
1933
+ this.dockerAvailable = dockerEngine?.available === true;
1680
1934
  const runtimeState = this.sandboxRuntime.snapshot();
1681
1935
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
1682
1936
  const used = this.usedSandboxResources(runtimeState.degraded);
@@ -1693,7 +1947,7 @@ export class ForgeBridgeService {
1693
1947
  pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
1694
1948
  }) : null;
1695
1949
  return {
1696
- schemaVersion: 7,
1950
+ schemaVersion: 8,
1697
1951
  activeSessionCount: this.activeSessions.size,
1698
1952
  cliProviders: this.config.cliProviders,
1699
1953
  providerStatuses: this.config.providerStatuses,
@@ -1716,6 +1970,7 @@ export class ForgeBridgeService {
1716
1970
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1717
1971
  browserLaunch: this.hostCapabilities.browserLaunch,
1718
1972
  providerConnectivity: this.hostCapabilities.providerConnectivity,
1973
+ testPostgres: this.hostCapabilities.testPostgres,
1719
1974
  host: this.hostLoad.facts(),
1720
1975
  load: this.hostLoad.current(),
1721
1976
  maxConcurrentSandboxes: capacity.sandboxSlots,
@@ -1757,7 +2012,8 @@ export class ForgeBridgeService {
1757
2012
  supportsDraftRunOnce: this.config.supportsDraftRunOnce,
1758
2013
  supportsDraftAttachments: this.config.supportsDraftAttachments,
1759
2014
  supportsDraftImageAttachments: this.config.supportsDraftImageAttachments,
1760
- bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat)
2015
+ bridgeChat: bridgeChatCapabilityFor(this.config.cliProviders, this.config.providerStatuses, this.config.bridgeChat),
2016
+ settings: { supportsServerSettings: true, ...this.settingsReport },
1761
2017
  };
1762
2018
  }
1763
2019
  async requiredCapabilityFailure(dispatch) {
@@ -1911,6 +2167,35 @@ export class ForgeBridgeService {
1911
2167
  }
1912
2168
  }
1913
2169
  }
2170
+ function runnerYieldingMessage(report) {
2171
+ const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
2172
+ return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
2173
+ }
2174
+ function describeRunnerSettings(report) {
2175
+ const { values } = report;
2176
+ const parts = [
2177
+ `max attempts ${values.maxConcurrentAttempts}`,
2178
+ `CPU budget ${values.cpuBudgetPercent}%`,
2179
+ `yield budget ${values.yieldCpuBudgetPercent}%`,
2180
+ `memory reserve ${formatBytes(values.memoryReserveBytes)}`,
2181
+ `heavy steps ${values.maxHeavySteps ?? "budget only"}`,
2182
+ `yield ${values.yieldToForeground ? "on" : "off"}`,
2183
+ ];
2184
+ const capped = report.bounds
2185
+ .filter(bound => report.sources[bound.key] === "host_env")
2186
+ .map(bound => `${bound.envVar}=${bound.value}`);
2187
+ return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
2188
+ }
2189
+ /** The `run` command's exit code after Forge removed the runner. */
2190
+ export const bridgeRevokedExitCode = 3;
2191
+ export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
2192
+ /** Thrown by `run` after Forge removed the runner, so the CLI exits instead of reconnecting. */
2193
+ export class BridgeRevokedError extends Error {
2194
+ constructor(message = bridgeRevokedMessage) {
2195
+ super(message);
2196
+ this.name = "BridgeRevokedError";
2197
+ }
2198
+ }
1914
2199
  class BridgeCallbackRejectedError extends Error {
1915
2200
  code;
1916
2201
  constructor(code, message) {
@@ -1944,11 +2229,13 @@ function isProviderStorageUnavailable(error) {
1944
2229
  function isBridgeCallbackTimeout(error) {
1945
2230
  return errorMessage(error).startsWith("bridge_callback_timeout:");
1946
2231
  }
1947
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
2232
+ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
1948
2233
  const rawProcessRunner = new StreamingProviderProcessRunner();
1949
2234
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1950
2235
  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)));
2236
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2237
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2238
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
1952
2239
  }
1953
2240
  export class SignalRBridgeConnectionFactory {
1954
2241
  create(config) {
@@ -1979,6 +2266,18 @@ export class SignalRBridgeConnection {
1979
2266
  void this.connection.stop().catch(() => undefined);
1980
2267
  });
1981
2268
  }
2269
+ onApplySettings(handler) {
2270
+ this.connection.on("ApplySettings", (raw) => {
2271
+ void Promise.resolve(handler(raw)).catch(() => undefined);
2272
+ });
2273
+ }
2274
+ onRevoked(handler) {
2275
+ this.connection.on("Revoked", (raw) => {
2276
+ const notice = raw && typeof raw === "object" ? raw : {};
2277
+ handler(notice);
2278
+ void this.connection.stop().catch(() => undefined);
2279
+ });
2280
+ }
1982
2281
  start() {
1983
2282
  return this.connection.start();
1984
2283
  }