@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.17ad6c965e41

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 (159) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +5 -2
  3. package/dist/bridge/bridge-chat-provider-command.js +29 -22
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.service.d.ts +17 -12
  15. package/dist/bridge/bridge.service.js +144 -251
  16. package/dist/bridge/bridge.types.d.ts +5 -0
  17. package/dist/bridge/in-flight-registry.d.ts +62 -0
  18. package/dist/bridge/in-flight-registry.js +207 -0
  19. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  20. package/dist/bridge/readiness-result-outbox.js +20 -0
  21. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  22. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  23. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  24. package/dist/cleanup/cleanup-wip.js +66 -0
  25. package/dist/cleanup/cleanup.service.d.ts +11 -1
  26. package/dist/cleanup/cleanup.service.js +80 -62
  27. package/dist/cleanup/cleanup.types.d.ts +2 -0
  28. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  29. package/dist/cleanup/host-runtime-ledger.js +30 -9
  30. package/dist/cli/cli.help.js +56 -12
  31. package/dist/cli/cli.service.d.ts +3 -10
  32. package/dist/cli/cli.service.js +10 -171
  33. package/dist/cli/idle-status.d.ts +84 -0
  34. package/dist/cli/idle-status.js +181 -0
  35. package/dist/cli/local-config.d.ts +2 -0
  36. package/dist/cli/local-config.js +7 -1
  37. package/dist/cli/provider-cli-detection.d.ts +10 -0
  38. package/dist/cli/provider-cli-detection.js +160 -0
  39. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  40. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  41. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  42. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  43. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  44. package/dist/runtime/attempt-process-supervisor.js +12 -6
  45. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  46. package/dist/runtime/docker-engine-probe.js +7 -0
  47. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  48. package/dist/runtime/dotnet-build-outputs.js +402 -0
  49. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  50. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  51. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  52. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  53. package/dist/runtime/host-load-governor.d.ts +2 -0
  54. package/dist/runtime/host-load-ledger-lock.js +6 -4
  55. package/dist/runtime/host-load-runtime-settings.js +4 -2
  56. package/dist/runtime/host-load-sampler.d.ts +8 -1
  57. package/dist/runtime/host-load-sampler.js +14 -7
  58. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  59. package/dist/runtime/host-runtime-contract.js +29 -1
  60. package/dist/runtime/host-runtime-lease.d.ts +3 -1
  61. package/dist/runtime/host-runtime-lease.js +36 -160
  62. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  63. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  64. package/dist/runtime/managed-command-teardown.js +5 -16
  65. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  66. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  67. package/dist/runtime/runner-settings.d.ts +4 -0
  68. package/dist/runtime/runner-settings.js +22 -0
  69. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  70. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  72. package/dist/sandbox/host-capacity-broker.js +4 -2
  73. package/dist/sandbox/managed-branch.d.ts +13 -0
  74. package/dist/sandbox/managed-branch.js +90 -0
  75. package/dist/sandbox/provider-auth/codex.js +11 -11
  76. package/dist/sandbox/runtime.js +2 -6
  77. package/dist/session/managed-attempt-tools.d.ts +0 -7
  78. package/dist/session/managed-attempt-tools.js +50 -82
  79. package/dist/session/managed-build-coordinator.d.ts +16 -0
  80. package/dist/session/managed-build-coordinator.js +10 -0
  81. package/dist/session/managed-build-receipt.d.ts +5 -0
  82. package/dist/session/managed-build-receipt.js +8 -3
  83. package/dist/session/phase-completion.artifacts.js +2 -1
  84. package/dist/session/phase-completion.d.ts +8 -0
  85. package/dist/session/phase-completion.js +1 -0
  86. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  87. package/dist/session/phase-completion.mcp-args.js +156 -0
  88. package/dist/session/phase-completion.runtime.d.ts +0 -8
  89. package/dist/session/phase-completion.runtime.js +43 -197
  90. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  91. package/dist/session/pre-publication-native-postgres.js +111 -0
  92. package/dist/session/pre-publication-process.js +10 -10
  93. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  94. package/dist/session/pre-publication-step-execution.js +6 -5
  95. package/dist/session/pre-publication-validation.d.ts +7 -3
  96. package/dist/session/pre-publication-validation.js +32 -30
  97. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  98. package/dist/session/provider-cli/claude-background-work.js +4 -3
  99. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  100. package/dist/session/provider-cli/host-build-lock.js +30 -0
  101. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  102. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  103. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  104. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  105. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  107. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  108. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  109. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  110. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  111. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  112. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  113. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  114. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  115. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  116. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  117. package/dist/session/qa-sidecar-validation.js +28 -0
  118. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  119. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  120. package/dist/session/session-redaction.js +31 -181
  121. package/dist/session/session.service.d.ts +2 -0
  122. package/dist/session/session.service.js +69 -64
  123. package/dist/session/session.types.js +1 -1
  124. package/dist/session/sidecar-json-shape.d.ts +31 -0
  125. package/dist/session/sidecar-json-shape.js +217 -0
  126. package/dist/shared/fs/file-identity.d.ts +10 -0
  127. package/dist/shared/fs/file-identity.js +15 -0
  128. package/dist/shared/fs/replace-file.d.ts +7 -0
  129. package/dist/shared/fs/replace-file.js +33 -0
  130. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  131. package/dist/shared/process/host-process-recovery.js +23 -3
  132. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  133. package/dist/shared/process/host-process-supervisor.js +66 -14
  134. package/dist/shared/provider-capabilities.js +9 -1
  135. package/dist/version.d.ts +1 -1
  136. package/dist/version.js +1 -1
  137. package/dist/worktree/orphan-relink.d.ts +19 -0
  138. package/dist/worktree/orphan-relink.js +106 -0
  139. package/dist/worktree/wip-git.d.ts +33 -0
  140. package/dist/worktree/wip-git.js +122 -0
  141. package/dist/worktree/wip-refs.d.ts +62 -0
  142. package/dist/worktree/wip-refs.js +119 -0
  143. package/dist/worktree/wip-restore.d.ts +38 -0
  144. package/dist/worktree/wip-restore.js +190 -0
  145. package/dist/worktree/wip-snapshot.d.ts +50 -0
  146. package/dist/worktree/wip-snapshot.js +268 -0
  147. package/dist/worktree/worktree-inputs.d.ts +8 -0
  148. package/dist/worktree/worktree-inputs.js +134 -0
  149. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  150. package/dist/worktree/worktree-origin-sync.js +127 -0
  151. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  152. package/dist/worktree/worktree-wip-events.js +98 -0
  153. package/dist/worktree/worktree-wip.d.ts +50 -0
  154. package/dist/worktree/worktree-wip.js +185 -0
  155. package/dist/worktree/worktree.base.d.ts +7 -1
  156. package/dist/worktree/worktree.service.d.ts +27 -5
  157. package/dist/worktree/worktree.service.js +110 -181
  158. package/dist/worktree/worktree.types.d.ts +31 -0
  159. package/package.json +1 -1
@@ -15,7 +15,7 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session
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.`);
@@ -894,19 +929,7 @@ export class ForgeBridgeService {
894
929
  return;
895
930
  }
896
931
  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
- });
932
+ this.registerActiveDispatch(dispatch, controller);
910
933
  if (reservationHandoff) {
911
934
  // Promotion is synchronous with active-session registration. A qualified
912
935
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -930,43 +953,10 @@ export class ForgeBridgeService {
930
953
  };
931
954
  await this.invokeAck("DispatchStarted", started);
932
955
  }
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
- }
956
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
957
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
969
958
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
959
+ this.inFlight.notePhase(leaseId, "result_delivery");
970
960
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
971
961
  }
972
962
  catch (error) {
@@ -990,6 +980,77 @@ export class ForgeBridgeService {
990
980
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
991
981
  }
992
982
  }
983
+ registerActiveDispatch(dispatch, controller) {
984
+ this.activeSessions.set(dispatch.lease.id, {
985
+ leaseId: dispatch.lease.id,
986
+ kind: "dispatch",
987
+ fencingToken: dispatch.lease.fencingToken,
988
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
989
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
990
+ leaseExpiresAt: dispatch.lease.expiresAt,
991
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
992
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
993
+ controller
994
+ });
995
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
996
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
997
+ }
998
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
999
+ const leaseId = dispatch.lease.id;
1000
+ return {
1001
+ emit: async (event) => {
1002
+ this.inFlight.notePhase(leaseId, event.eventType);
1003
+ if (event.eventType === "provider_cli_started") {
1004
+ const active = this.activeSessions.get(leaseId);
1005
+ if (active)
1006
+ active.resources = { ...active.resources, buildSlots: 0 };
1007
+ }
1008
+ try {
1009
+ await this.invokeAck("DispatchEvent", {
1010
+ leaseId,
1011
+ fencingToken: dispatch.lease.fencingToken,
1012
+ ...(dispatch.sandbox ? {
1013
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1014
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1015
+ } : {}),
1016
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1017
+ }, {
1018
+ replayCallbackTimeout: true,
1019
+ signal: controller.signal,
1020
+ });
1021
+ }
1022
+ catch (error) {
1023
+ if (isDispatchNoLongerPending(error)) {
1024
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1025
+ return;
1026
+ }
1027
+ throw error;
1028
+ }
1029
+ }
1030
+ };
1031
+ }
1032
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1033
+ async runDispatchOnce(dispatch, sink, signal) {
1034
+ const docker = dispatch.sandbox?.executionMode === "docker";
1035
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1036
+ const startedAt = Date.now();
1037
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1038
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1039
+ try {
1040
+ const result = docker
1041
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1042
+ : await this.sessions.runOnce(dispatch, sink, signal);
1043
+ if (docker) {
1044
+ await this.flushCleanupReports().catch(() => undefined);
1045
+ }
1046
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1047
+ return result;
1048
+ }
1049
+ catch (error) {
1050
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1051
+ throw error;
1052
+ }
1053
+ }
993
1054
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
994
1055
  const sandbox = dispatch.sandbox;
995
1056
  const reservation = handoff.reservation;
@@ -1351,6 +1412,8 @@ export class ForgeBridgeService {
1351
1412
  reservedResources: accepted ? reservedResources : null,
1352
1413
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1353
1414
  };
1415
+ if (accepted)
1416
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1354
1417
  await this.invokeAck("OfferDecision", payload);
1355
1418
  }
1356
1419
  async parseDispatchOrReport(rawDispatch) {
@@ -1464,7 +1527,13 @@ export class ForgeBridgeService {
1464
1527
  acceptedAt: new Date().toISOString(),
1465
1528
  };
1466
1529
  await this.invokeAck("ReadinessAccepted", accepted);
1467
- if (this.activeSessions.size > 0) {
1530
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1531
+ await this.refreshLocalYield().catch(() => undefined);
1532
+ await this.settingsTail;
1533
+ if (this.yieldingOrQueued()) {
1534
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1535
+ }
1536
+ else if (this.activeSessions.size > 0) {
1468
1537
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1469
1538
  }
1470
1539
  else if (!this.sessions.probeHostRuntime) {
@@ -1845,7 +1914,8 @@ export class ForgeBridgeService {
1845
1914
  startSandboxMaintenance() {
1846
1915
  this.stopSandboxMaintenance();
1847
1916
  this.sandboxMaintenanceTimer = setInterval(() => {
1848
- this.runSandboxMaintenance().catch(() => undefined);
1917
+ this.runSandboxMaintenance().catch(error => { if (isBridgeCallbackTimeout(error))
1918
+ logBridgeStatus(`Sandbox maintenance skipped this pass: ${errorMessage(error)}`); });
1849
1919
  }, 60_000);
1850
1920
  this.sandboxMaintenanceTimer.unref?.();
1851
1921
  }
@@ -1885,9 +1955,15 @@ export class ForgeBridgeService {
1885
1955
  const connection = this.connection;
1886
1956
  if (!connection)
1887
1957
  throw new Error("Bridge is not connected.");
1888
- const response = await connection.invoke("AttemptSnapshot", {
1889
- runnerInstanceId: this.config.runnerInstanceId
1890
- });
1958
+ // Bounded so it can't hold the maintenance guard; SignalR can't cancel it, so one unanswered call per connection and transport generation.
1959
+ const pending = { connection, generation: this.transportRecoveryGeneration };
1960
+ if (this.attemptSnapshotPending?.connection === connection && this.attemptSnapshotPending.generation === pending.generation)
1961
+ throw new Error("bridge_callback_timeout: AttemptSnapshot from an earlier pass is still unanswered.");
1962
+ this.attemptSnapshotPending = pending;
1963
+ const invocation = connection.invoke("AttemptSnapshot", { runnerInstanceId: this.config.runnerInstanceId });
1964
+ invocation.finally(() => { if (this.attemptSnapshotPending === pending)
1965
+ this.attemptSnapshotPending = null; }).catch(() => undefined);
1966
+ const response = await waitForCallbackAck(invocation, "AttemptSnapshot", positiveFiniteNumber(this.config.callbackAckTimeoutMs ?? 30_000, 30_000));
1891
1967
  if (!response.accepted) {
1892
1968
  throw new BridgeCallbackRejectedError(response.code ?? null, response.message ?? response.code ?? "Attempt snapshot was rejected.");
1893
1969
  }
@@ -1922,12 +1998,14 @@ export class ForgeBridgeService {
1922
1998
  await this.sendHeartbeatSnapshot();
1923
1999
  }
1924
2000
  async sendHeartbeatSnapshot(signal) {
2001
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1925
2002
  await this.invokeAck("Heartbeat", {
1926
2003
  status: "online",
1927
2004
  capabilities: this.capabilities(),
1928
2005
  version: this.config.version,
1929
2006
  protocolVersion: this.config.protocolVersion
1930
2007
  }, { signal });
2008
+ this.ackYield(reportedYield);
1931
2009
  }
1932
2010
  capabilities() {
1933
2011
  const preflight = this.preflight.current();
@@ -2169,25 +2247,6 @@ export class ForgeBridgeService {
2169
2247
  }
2170
2248
  }
2171
2249
  }
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
2250
  /** The `run` command's exit code after Forge removed the runner. */
2192
2251
  export const bridgeRevokedExitCode = 3;
2193
2252
  export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
@@ -2620,10 +2679,7 @@ function errorMessage(error) {
2620
2679
  return error instanceof Error ? error.message : String(error);
2621
2680
  }
2622
2681
  function formatDelay(ms) {
2623
- if (ms >= 1000 && ms % 1000 === 0) {
2624
- return `${ms / 1000}s`;
2625
- }
2626
- return `${ms}ms`;
2682
+ return ms >= 1000 && ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`;
2627
2683
  }
2628
2684
  async function waitForCallbackAck(callback, methodName, timeoutMs, signal) {
2629
2685
  let timeout = null;
@@ -2894,24 +2950,6 @@ function parseReadinessProbe(value) {
2894
2950
  }
2895
2951
  return request;
2896
2952
  }
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
2953
  function sandboxProviderNetworkFailure(dispatch, config) {
2916
2954
  const sandbox = dispatch.sandbox;
2917
2955
  if (!sandbox || sandbox.networkPolicy.mode !== "offline")
@@ -2950,151 +2988,6 @@ function rejectedOfferReservation(code, message) {
2950
2988
  resources: null,
2951
2989
  };
2952
2990
  }
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
2991
  function parseOfferEnvelope(value) {
3099
2992
  return parseDispatchEnvelope(value);
3100
2993
  }
@@ -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;
@@ -0,0 +1,62 @@
1
+ export type InFlightKind = "offer" | "start" | "dispatch" | "chat_turn" | "readiness_probe" | "reservation" | "session"
2
+ /** The bridge could not read its own ledgers; treated as busy. */
3
+ | "unknown";
4
+ export interface InFlightIds {
5
+ readonly dispatchAttemptId?: string;
6
+ readonly leaseId?: string;
7
+ readonly sessionId?: string;
8
+ readonly cycleRunId?: string;
9
+ readonly workItemId?: string;
10
+ readonly turnId?: string;
11
+ readonly requestId?: string;
12
+ }
13
+ export interface InFlightEntry {
14
+ readonly kind: InFlightKind;
15
+ readonly ids: InFlightIds;
16
+ readonly phase: string;
17
+ /** When this bridge took the work on, or null when the ledger does not record it. */
18
+ readonly since: string | null;
19
+ /** When the current phase began, or null when unknown. */
20
+ readonly phaseSince: string | null;
21
+ }
22
+ export type InFlightSource = () => readonly InFlightEntry[];
23
+ export declare class BridgeInFlightRegistry {
24
+ private readonly now;
25
+ private readonly tracked;
26
+ private readonly sources;
27
+ private readonly listeners;
28
+ private nextKey;
29
+ constructor(now?: () => Date);
30
+ /** Starts tracking one piece of work; returns the key that ends it. */
31
+ begin(kind: InFlightKind, ids: InFlightIds, phase?: string): number;
32
+ end(key: number): void;
33
+ /** Moves every tracked entry for this lease to a new phase. */
34
+ notePhase(leaseId: string, phase: string | null | undefined): void;
35
+ /** Tracks a hub handler for as long as it runs, whether it resolves or throws. */
36
+ track<T>(kind: InFlightKind, raw: unknown, run: () => Promise<T>): Promise<T>;
37
+ addSource(source: InFlightSource): void;
38
+ onChange(listener: () => void): () => void;
39
+ snapshot(): InFlightEntry[];
40
+ get idle(): boolean;
41
+ private changed;
42
+ }
43
+ /** Reads the ids of a hub payload: an Offer/Start envelope, a dispatch packet, a chat turn or a readiness probe. */
44
+ export declare function inFlightIdsFrom(raw: unknown): InFlightIds;
45
+ /** Accepted offers whose Start has not arrived yet. A claimed one is the Start handler's. */
46
+ export declare function reservationInFlightEntries(reservations: ReadonlyMap<string, {
47
+ readonly leaseId: string;
48
+ readonly reservedUntil: string;
49
+ readonly startClaim?: unknown;
50
+ }>, now?: number): InFlightEntry[];
51
+ export declare function sessionInFlightEntries(sessions: ReadonlyMap<string, {
52
+ readonly kind: string;
53
+ readonly dispatchAttemptId: string | null;
54
+ readonly turnId?: string;
55
+ }>): InFlightEntry[];
56
+ export declare function readinessInFlightEntries(probes: ReadonlyMap<string, unknown>): InFlightEntry[];
57
+ /** Whether a value read back from the state file is a complete in-flight entry. */
58
+ export declare function isInFlightEntry(value: unknown): value is InFlightEntry;
59
+ /** A server-supplied label (role, phase) made safe for one log line: plain identifier or "unknown". */
60
+ export declare function safeLogLabel(value: unknown): string;
61
+ /** "attempt=…, lease=…, session=…, cycle=…" for log lines and status output. */
62
+ export declare function describeInFlightIds(ids: InFlightIds): string;