@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7

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 (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -9,13 +9,13 @@ import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../sh
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { BridgeSessionService } from "../session/session.service.js";
11
11
  import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
- import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
12
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } from "./bridge-chat-provider-command.js";
13
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
16
16
  import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
17
  import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
18
- import { computeEffectiveRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
18
+ import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
19
  import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
20
  import { readLocalYieldFlag } from "./local-yield-flag.js";
21
21
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
@@ -31,16 +31,17 @@ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegist
31
31
  import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
32
32
  import { forgeBridgeVersion } from "../version.js";
33
33
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
34
- import { validateSandboxContract } from "../sandbox/contract.js";
35
- import { runSandboxProcess } from "../sandbox/process.js";
36
- import { DockerSandboxRuntime, selectSandboxConfigRefs } from "../sandbox/runtime.js";
34
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
37
35
  import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "../sandbox/provider-auth/codex.js";
38
36
  import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
39
- import { formatBytes } from "../shared/format/format-bytes.js";
40
37
  import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
41
38
  import { HostLoadSampler } from "../runtime/host-load-sampler.js";
42
- import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
39
+ import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
43
40
  import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
41
+ import { BridgeStatePublisher } from "./bridge-state-file.js";
42
+ import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
43
+ import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
44
+ export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
44
45
  /**
45
46
  * Protocol-v2 events are acknowledged one at a time before runOnce returns.
46
47
  * Sending the complete transcript again in DispatchResult made long QA and CI
@@ -68,6 +69,7 @@ export class ForgeBridgeService {
68
69
  leaseWatchdogTimer = null;
69
70
  sandboxMaintenanceTimer = null;
70
71
  sandboxMaintenanceRunning = false;
72
+ attemptSnapshotPending = null;
71
73
  closed = null;
72
74
  transportRecovery = null;
73
75
  transportRecoveryGeneration = 0;
@@ -76,6 +78,8 @@ export class ForgeBridgeService {
76
78
  activeSessions = new Map();
77
79
  reservations = new Map();
78
80
  activeReadinessProbes = new Map();
81
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
82
+ inFlight = new BridgeInFlightRegistry();
79
83
  readinessResultOutbox;
80
84
  readinessResultFlush = null;
81
85
  dispatchResultOutbox;
@@ -96,6 +100,9 @@ export class ForgeBridgeService {
96
100
  // and the effective settings computed from both and the host's env bounds.
97
101
  appliedSettingsDocument = null;
98
102
  localYield = false;
103
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
104
+ forgeAckedYield = false;
105
+ publishState = () => undefined;
99
106
  effectiveSettings;
100
107
  settingsReport;
101
108
  /** Applies run one at a time; offers wait for every apply queued before them. */
@@ -172,6 +179,11 @@ export class ForgeBridgeService {
172
179
  // With no server document and no local flag these equal today's env/default behaviour.
173
180
  this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
174
181
  this.settingsReport = this.effectiveSettings.report;
182
+ this.inFlight.addSource(() => [
183
+ ...reservationInFlightEntries(this.reservations),
184
+ ...sessionInFlightEntries(this.activeSessions),
185
+ ...readinessInFlightEntries(this.activeReadinessProbes),
186
+ ]);
175
187
  }
176
188
  async connectOnce() {
177
189
  if (this.revokedReason !== null) {
@@ -248,14 +260,14 @@ export class ForgeBridgeService {
248
260
  await connection.stop().catch(() => undefined);
249
261
  }
250
262
  });
251
- connection.onDispatch((dispatch) => this.handleDispatch(dispatch));
252
- connection.onChatTurn?.((dispatch) => this.handleChatTurn(dispatch));
253
- connection.onOffer?.((dispatch) => this.handleOffer(dispatch));
254
- connection.onStart?.((dispatch) => this.handleStart(dispatch));
263
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
264
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
265
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
266
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
255
267
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
256
268
  connection.onCancel((request) => this.handleCancel(request));
257
269
  connection.onReap?.((request) => this.handleReap(request));
258
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
270
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
259
271
  connection.onRevoked?.((notice) => this.handleRevoked(notice));
260
272
  connection.onApplySettings?.((document) => this.handleApplySettings(document));
261
273
  await connection.start();
@@ -294,6 +306,7 @@ export class ForgeBridgeService {
294
306
  while (true) {
295
307
  try {
296
308
  const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
309
+ const reportedYield = this.settingsReport.values.yieldToForeground;
297
310
  const ack = await connection.invoke("Hello", {
298
311
  version: this.config.version,
299
312
  protocolVersion: this.config.protocolVersion,
@@ -306,6 +319,7 @@ export class ForgeBridgeService {
306
319
  throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
307
320
  }
308
321
  this.recoveredHostAttempts.clear();
322
+ this.ackYield(reportedYield);
309
323
  logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
310
324
  return;
311
325
  }
@@ -321,6 +335,7 @@ export class ForgeBridgeService {
321
335
  }
322
336
  }
323
337
  async run(signal) {
338
+ const statePublisher = await this.startStatePublisher();
324
339
  let attempt = 0;
325
340
  try {
326
341
  while (!this.stopped && !signal?.aborted) {
@@ -352,11 +367,28 @@ export class ForgeBridgeService {
352
367
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
353
368
  }
354
369
  await this.stopConnection();
370
+ await statePublisher?.stop();
355
371
  }
356
372
  if (this.revokedReason !== null) {
357
373
  throw new BridgeRevokedError(this.revokedReason);
358
374
  }
359
375
  }
376
+ async startStatePublisher() {
377
+ if (!this.config.bridgeStatePath)
378
+ return null;
379
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
380
+ inFlight: () => this.inFlight.snapshot(),
381
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
382
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
383
+ yieldApplied: () => this.effectiveSettings.yielding,
384
+ connected: () => this.connection !== null && this.transportRecovery === null,
385
+ }, { log: logBridgeStatus });
386
+ this.publishState = () => void publisher.publish();
387
+ this.inFlight.onChange(this.publishState);
388
+ await publisher.start();
389
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
390
+ return publisher;
391
+ }
360
392
  /** The reason Forge gave when it removed this runner, or null while it is paired. */
361
393
  get revoked() {
362
394
  return this.revokedReason;
@@ -492,6 +524,7 @@ export class ForgeBridgeService {
492
524
  this.appliedSettingsDocument = document;
493
525
  this.effectiveSettings = effective;
494
526
  this.settingsReport = report;
527
+ this.publishState();
495
528
  if (change.kind === "server") {
496
529
  logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
497
530
  }
@@ -533,10 +566,12 @@ export class ForgeBridgeService {
533
566
  }
534
567
  return rejected;
535
568
  }
569
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
536
570
  /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
537
571
  async sendSettingsApplied(report) {
538
572
  try {
539
573
  await this.invokeAck("SettingsApplied", report);
574
+ this.ackYield(report.values.yieldToForeground);
540
575
  }
541
576
  catch (error) {
542
577
  logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
@@ -669,9 +704,18 @@ export class ForgeBridgeService {
669
704
  await fs.promises.mkdir(root, { recursive: true });
670
705
  return await fs.promises.mkdtemp(path.join(root, `${safePathComponent(packet.turnId)}-`));
671
706
  }
707
+ /** Has Claude look at the turn's sent GIFs once, pulling their frames from the hub; no looks means text only. */
708
+ async lookAtChatGiphyFrames(packet, active, cwd) {
709
+ return await lookAtChatGiphyFrames(packet, cwd, {
710
+ runner: this.chatProcessRunner,
711
+ signal: active.controller.signal,
712
+ log: logBridgeStatus,
713
+ takeFrames: async (request) => await this.connection?.invoke(chatTurnGiphyFramesMethod, request) ?? { accepted: false },
714
+ });
715
+ }
672
716
  async runChatProviderProcess(packet, active, cwd) {
673
717
  const output = createProviderOutputState(packet.providerKind);
674
- const plan = buildChatProviderCommand(packet, cwd);
718
+ const plan = buildChatProviderCommand(packet, cwd, await this.lookAtChatGiphyFrames(packet, active, cwd));
675
719
  const redactionSecrets = chatRedactionSecrets(packet);
676
720
  let started = false;
677
721
  const result = await this.chatProcessRunner.run({
@@ -894,19 +938,7 @@ export class ForgeBridgeService {
894
938
  return;
895
939
  }
896
940
  const controller = reservationHandoff?.controller ?? new AbortController();
897
- this.activeSessions.set(leaseId, {
898
- leaseId,
899
- kind: "dispatch",
900
- fencingToken,
901
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
902
- runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
903
- leaseExpiresAt: dispatch.lease.expiresAt,
904
- sandboxed: dispatch.sandbox?.executionMode === "docker",
905
- resources: dispatch.sandbox?.executionMode === "docker"
906
- ? dispatch.sandbox.requestedResources
907
- : zeroSandboxResources(),
908
- controller
909
- });
941
+ this.registerActiveDispatch(dispatch, controller);
910
942
  if (reservationHandoff) {
911
943
  // Promotion is synchronous with active-session registration. A qualified
912
944
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -930,43 +962,10 @@ export class ForgeBridgeService {
930
962
  };
931
963
  await this.invokeAck("DispatchStarted", started);
932
964
  }
933
- const sink = {
934
- emit: async (event) => {
935
- if (event.eventType === "provider_cli_started") {
936
- const active = this.activeSessions.get(leaseId);
937
- if (active)
938
- active.resources = { ...active.resources, buildSlots: 0 };
939
- }
940
- try {
941
- await this.invokeAck("DispatchEvent", {
942
- leaseId,
943
- fencingToken,
944
- ...(dispatch.sandbox ? {
945
- dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
946
- runnerInstanceId: dispatch.sandbox.runnerInstanceId
947
- } : {}),
948
- event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
949
- }, {
950
- replayCallbackTimeout: true,
951
- signal: controller.signal,
952
- });
953
- }
954
- catch (error) {
955
- if (isDispatchNoLongerPending(error)) {
956
- controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
957
- return;
958
- }
959
- throw error;
960
- }
961
- }
962
- };
963
- const result = normalized.sandbox?.executionMode === "docker"
964
- ? await this.sandboxRuntime.runOnce(normalized, sink, controller.signal)
965
- : await this.sessions.runOnce(normalized, sink, controller.signal);
966
- if (normalized.sandbox?.executionMode === "docker") {
967
- await this.flushCleanupReports().catch(() => undefined);
968
- }
965
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
966
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
969
967
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
968
+ this.inFlight.notePhase(leaseId, "result_delivery");
970
969
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
971
970
  }
972
971
  catch (error) {
@@ -990,6 +989,77 @@ export class ForgeBridgeService {
990
989
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
991
990
  }
992
991
  }
992
+ registerActiveDispatch(dispatch, controller) {
993
+ this.activeSessions.set(dispatch.lease.id, {
994
+ leaseId: dispatch.lease.id,
995
+ kind: "dispatch",
996
+ fencingToken: dispatch.lease.fencingToken,
997
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
998
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
999
+ leaseExpiresAt: dispatch.lease.expiresAt,
1000
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
1001
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
1002
+ controller
1003
+ });
1004
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
1005
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
1006
+ }
1007
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
1008
+ const leaseId = dispatch.lease.id;
1009
+ return {
1010
+ emit: async (event) => {
1011
+ this.inFlight.notePhase(leaseId, event.eventType);
1012
+ if (event.eventType === "provider_cli_started") {
1013
+ const active = this.activeSessions.get(leaseId);
1014
+ if (active)
1015
+ active.resources = { ...active.resources, buildSlots: 0 };
1016
+ }
1017
+ try {
1018
+ await this.invokeAck("DispatchEvent", {
1019
+ leaseId,
1020
+ fencingToken: dispatch.lease.fencingToken,
1021
+ ...(dispatch.sandbox ? {
1022
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1023
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1024
+ } : {}),
1025
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1026
+ }, {
1027
+ replayCallbackTimeout: true,
1028
+ signal: controller.signal,
1029
+ });
1030
+ }
1031
+ catch (error) {
1032
+ if (isDispatchNoLongerPending(error)) {
1033
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1034
+ return;
1035
+ }
1036
+ throw error;
1037
+ }
1038
+ }
1039
+ };
1040
+ }
1041
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1042
+ async runDispatchOnce(dispatch, sink, signal) {
1043
+ const docker = dispatch.sandbox?.executionMode === "docker";
1044
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1045
+ const startedAt = Date.now();
1046
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1047
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1048
+ try {
1049
+ const result = docker
1050
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1051
+ : await this.sessions.runOnce(dispatch, sink, signal);
1052
+ if (docker) {
1053
+ await this.flushCleanupReports().catch(() => undefined);
1054
+ }
1055
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1056
+ return result;
1057
+ }
1058
+ catch (error) {
1059
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1060
+ throw error;
1061
+ }
1062
+ }
993
1063
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
994
1064
  const sandbox = dispatch.sandbox;
995
1065
  const reservation = handoff.reservation;
@@ -1351,6 +1421,8 @@ export class ForgeBridgeService {
1351
1421
  reservedResources: accepted ? reservedResources : null,
1352
1422
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1353
1423
  };
1424
+ if (accepted)
1425
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1354
1426
  await this.invokeAck("OfferDecision", payload);
1355
1427
  }
1356
1428
  async parseDispatchOrReport(rawDispatch) {
@@ -1464,7 +1536,13 @@ export class ForgeBridgeService {
1464
1536
  acceptedAt: new Date().toISOString(),
1465
1537
  };
1466
1538
  await this.invokeAck("ReadinessAccepted", accepted);
1467
- if (this.activeSessions.size > 0) {
1539
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1540
+ await this.refreshLocalYield().catch(() => undefined);
1541
+ await this.settingsTail;
1542
+ if (this.yieldingOrQueued()) {
1543
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1544
+ }
1545
+ else if (this.activeSessions.size > 0) {
1468
1546
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1469
1547
  }
1470
1548
  else if (!this.sessions.probeHostRuntime) {
@@ -1845,7 +1923,8 @@ export class ForgeBridgeService {
1845
1923
  startSandboxMaintenance() {
1846
1924
  this.stopSandboxMaintenance();
1847
1925
  this.sandboxMaintenanceTimer = setInterval(() => {
1848
- this.runSandboxMaintenance().catch(() => undefined);
1926
+ this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
1927
+ logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
1849
1928
  }, 60_000);
1850
1929
  this.sandboxMaintenanceTimer.unref?.();
1851
1930
  }
@@ -1885,9 +1964,15 @@ export class ForgeBridgeService {
1885
1964
  const connection = this.connection;
1886
1965
  if (!connection)
1887
1966
  throw new Error("Bridge is not connected.");
1888
- const response = await connection.invoke("AttemptSnapshot", {
1889
- runnerInstanceId: this.config.runnerInstanceId
1890
- });
1967
+ // Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
1968
+ const pending = { connection, generation: this.transportRecoveryGeneration };
1969
+ if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
1970
+ throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
1971
+ this.attemptSnapshotPending = pending;
1972
+ const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
1973
+ invocation.finally(() => { if (this.attemptSnapshotPending === pending)
1974
+ this.attemptSnapshotPending = null; }).catch(() => undefined);
1975
+ const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
1891
1976
  if (!response.accepted) {
1892
1977
  throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
1893
1978
  }
@@ -1922,12 +2007,14 @@ export class ForgeBridgeService {
1922
2007
  await this.sendHeartbeatSnapshot();
1923
2008
  }
1924
2009
  async sendHeartbeatSnapshot(signal) {
2010
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1925
2011
  await this.invokeAck("Heartbeat", {
1926
2012
  status: "online",
1927
2013
  capabilities: this.capabilities(),
1928
2014
  version: this.config.version,
1929
2015
  protocolVersion: this.config.protocolVersion
1930
2016
  }, { signal });
2017
+ this.ackYield(reportedYield);
1931
2018
  }
1932
2019
  capabilities() {
1933
2020
  const preflight = this.preflight.current();
@@ -2169,25 +2256,6 @@ export class ForgeBridgeService {
2169
2256
  }
2170
2257
  }
2171
2258
  }
2172
- function runnerYieldingMessage(report) {
2173
- const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
2174
- return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
2175
- }
2176
- function describeRunnerSettings(report) {
2177
- const { values } = report;
2178
- const parts = [
2179
- `max attempts ${values.maxConcurrentAttempts}`,
2180
- `CPU budget ${values.cpuBudgetPercent}%`,
2181
- `yield budget ${values.yieldCpuBudgetPercent}%`,
2182
- `memory reserve ${formatBytes(values.memoryReserveBytes)}`,
2183
- `heavy steps ${values.maxHeavySteps ?? "budget only"}`,
2184
- `yield ${values.yieldToForeground ? "on" : "off"}`,
2185
- ];
2186
- const capped = report.bounds
2187
- .filter(bound => report.sources[bound.key] === "host_env")
2188
- .map(bound => `${bound.envVar}=${bound.value}`);
2189
- return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
2190
- }
2191
2259
  /** The `run` command's exit code after Forge removed the runner. */
2192
2260
  export const bridgeRevokedExitCode = 3;
2193
2261
  export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
@@ -2620,10 +2688,7 @@ function errorMessage(error) {
2620
2688
  return error instanceof Error ? error.message : String(error);
2621
2689
  }
2622
2690
  function formatDelay(ms) {
2623
- if (ms >= 1000 && ms % 1000 === 0) {
2624
- return `${ms / 1000}s`;
2625
- }
2626
- return `${ms}ms`;
2691
+ return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
2627
2692
  }
2628
2693
  async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
2629
2694
  let timeout = null;
@@ -2692,35 +2757,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2692
2757
  const maxChatEventContentChars = 4000;
2693
2758
  const maxChatTerminalTextChars = 120_000;
2694
2759
  const maxChatExactSecretChars = 8 * 1024;
2695
- async function materializeChatTurnMetadata(packet, workspacePath) {
2696
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2697
- return;
2698
- }
2699
- await fs.promises.writeFile(path.join(workspacePath, chatTurnMetadataFileName), `${JSON.stringify({
2700
- schemaVersion: 1,
2701
- attachmentHandoffs: packet.attachmentHandoffs.map((handoff) => ({
2702
- turnId: handoff.turnId,
2703
- attachmentId: handoff.attachmentId,
2704
- tempFileToken: handoff.tempFileToken,
2705
- mimeType: handoff.mimeType,
2706
- sizeBytes: handoff.sizeBytes,
2707
- sha256: handoff.sha256,
2708
- fileNameDisplay: handoff.fileNameDisplay,
2709
- expiresAt: handoff.expiresAt,
2710
- status: handoff.status,
2711
- })),
2712
- actionBrokerGrants: packet.actionBrokerGrants.map((grant) => ({
2713
- grantId: grant.grantId,
2714
- turnId: grant.turnId,
2715
- leaseId: grant.leaseId,
2716
- fencingToken: grant.fencingToken,
2717
- allowedScopes: grant.allowedScopes,
2718
- expiresAt: grant.expiresAt,
2719
- redactionStatus: grant.redactionStatus,
2720
- nonceHeldByBridge: true,
2721
- })),
2722
- }, null, 2)}\n`, "utf8");
2723
- }
2724
2760
  function chatTurnLeaseExpiresAt(packet, nowMs = Date.now()) {
2725
2761
  const defaultExpiresAtMs = nowMs + defaultChatTurnLeaseMs;
2726
2762
  const metadataExpiresAtMs = [
@@ -2894,24 +2930,6 @@ function parseReadinessProbe(value) {
2894
2930
  }
2895
2931
  return request;
2896
2932
  }
2897
- function deferredReadinessResult(request, runnerInstanceId) {
2898
- return {
2899
- schemaVersion: 1,
2900
- requestId: request.requestId,
2901
- fencingToken: request.fencingToken,
2902
- runnerInstanceId,
2903
- status: "failed",
2904
- reasonCode: "host_runtime_probe_deferred",
2905
- reasonMessage: "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.",
2906
- checkedAt: new Date().toISOString(),
2907
- };
2908
- }
2909
- function readinessDeferralReason(signal) {
2910
- if (!signal.aborted)
2911
- return null;
2912
- const reason = errorMessage(signal.reason);
2913
- return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
2914
- }
2915
2933
  function sandboxProviderNetworkFailure(dispatch, config) {
2916
2934
  const sandbox = dispatch.sandbox;
2917
2935
  if (!sandbox || sandbox.networkPolicy.mode !== "offline")
@@ -2950,151 +2968,6 @@ function rejectedOfferReservation(code, message) {
2950
2968
  resources: null,
2951
2969
  };
2952
2970
  }
2953
- export function canReserveSandboxResources(used, requested, capacity) {
2954
- return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
2955
- && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
2956
- && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
2957
- && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
2958
- && used.pids + requested.pids <= capacity.pids
2959
- && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
2960
- }
2961
- export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
2962
- const ambientCapacity = preflight.availableMemoryBytes
2963
- - preflight.hostReserveBytes
2964
- + activeMemoryBytes;
2965
- const commitmentCapacity = preflight.totalMemoryBytes
2966
- - preflight.hostReserveBytes;
2967
- return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
2968
- }
2969
- export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
2970
- const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
2971
- if (requested.sandboxSlots > availableSlots) {
2972
- return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
2973
- }
2974
- const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
2975
- if (requested.memoryBytes > availableMemoryBytes) {
2976
- return [
2977
- `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
2978
- `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
2979
- `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
2980
- `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
2981
- `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
2982
- ].join(" ");
2983
- }
2984
- const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
2985
- if (requested.cpuMillis > availableCpuMillis) {
2986
- return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
2987
- }
2988
- const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
2989
- if (requested.workspaceBytes > availableWorkspaceBytes) {
2990
- return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
2991
- }
2992
- const availablePids = Math.max(0, capacity.pids - used.pids);
2993
- if (requested.pids > availablePids) {
2994
- return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
2995
- }
2996
- const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
2997
- return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
2998
- }
2999
- function sumSandboxResources(resources) {
3000
- return resources.reduce((total, resource) => ({
3001
- sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
3002
- cpuMillis: total.cpuMillis + resource.cpuMillis,
3003
- workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
3004
- serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
3005
- runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
3006
- memoryBytes: total.memoryBytes + resource.memoryBytes,
3007
- workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
3008
- pids: total.pids + resource.pids,
3009
- buildSlots: total.buildSlots + resource.buildSlots
3010
- }), zeroSandboxResources());
3011
- }
3012
- function zeroSandboxResources() {
3013
- return {
3014
- sandboxSlots: 0,
3015
- cpuMillis: 0,
3016
- workerMemoryLimitBytes: 0,
3017
- serviceMemoryLimitBytes: 0,
3018
- runtimeOverheadBytes: 0,
3019
- memoryBytes: 0,
3020
- workspaceBytes: 0,
3021
- pids: 0,
3022
- buildSlots: 0,
3023
- };
3024
- }
3025
- function defaultSandboxResources() {
3026
- return {
3027
- sandboxSlots: 1,
3028
- cpuMillis: 2000,
3029
- workerMemoryLimitBytes: 2 * 1024 ** 3,
3030
- serviceMemoryLimitBytes: 0,
3031
- runtimeOverheadBytes: 128 * 1024 ** 2,
3032
- memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
3033
- workspaceBytes: 10 * 1024 ** 3,
3034
- pids: 512,
3035
- buildSlots: 0
3036
- };
3037
- }
3038
- export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
3039
- const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
3040
- const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
3041
- + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
3042
- return {
3043
- ...requested,
3044
- serviceMemoryLimitBytes,
3045
- runtimeOverheadBytes,
3046
- memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
3047
- };
3048
- }
3049
- export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
3050
- const repoPath = dispatch.repo.serverLocalPath;
3051
- const sandbox = dispatch.sandbox;
3052
- if (!repoPath || !sandbox) {
3053
- throw new Error("Sandbox admission needs a mapped repository.");
3054
- }
3055
- const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
3056
- const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
3057
- if (!configCommitSha) {
3058
- throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
3059
- }
3060
- const contractResult = await runSandboxProcess({
3061
- command: "git",
3062
- args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
3063
- timeoutMs: 30_000,
3064
- maxOutputBytes: 1024 * 1024,
3065
- });
3066
- if (contractResult.exitCode !== 0) {
3067
- throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
3068
- }
3069
- const contract = validateSandboxContract(contractResult.stdout);
3070
- const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
3071
- role: dispatch.execution.role,
3072
- serviceCount: contract.contract.services.length,
3073
- browser: contract.contract.browser,
3074
- });
3075
- return {
3076
- resources: resolveDynamicSandboxResources({
3077
- ...sandbox.requestedResources,
3078
- workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
3079
- }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
3080
- sandboxConfigCommitSha: configCommitSha,
3081
- };
3082
- }
3083
- async function resolveFirstGitCommit(repoPath, refs) {
3084
- for (const ref of refs) {
3085
- const result = await runSandboxProcess({
3086
- command: "git",
3087
- args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
3088
- timeoutMs: 30_000,
3089
- maxOutputBytes: 1024 * 1024,
3090
- });
3091
- const commitSha = result.stdout.trim().toLowerCase();
3092
- if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
3093
- return commitSha;
3094
- }
3095
- }
3096
- return null;
3097
- }
3098
2971
  function parseOfferEnvelope(value) {
3099
2972
  return parseDispatchEnvelope(value);
3100
2973
  }
@@ -71,6 +71,11 @@ export interface BridgeServiceConfig {
71
71
  * polled while running. Null or absent: no local yield flag.
72
72
  */
73
73
  readonly localYieldFlagPath?: string | null;
74
+ /**
75
+ * Where the running bridge publishes whether it is idle (`bridge.state.json` next to
76
+ * the bridge config), read by `forge-bridge status --idle`. Null or absent: not published.
77
+ */
78
+ readonly bridgeStatePath?: string | null;
74
79
  }
75
80
  export interface BridgeRepoMapping {
76
81
  readonly repoId?: string | null;