@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 0.1.4-dev.deb7f72e7930

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +14 -19
  4. package/dist/bridge/bridge-state-file.d.ts +161 -0
  5. package/dist/bridge/bridge-state-file.js +376 -0
  6. package/dist/bridge/bridge-state-io.d.ts +11 -0
  7. package/dist/bridge/bridge-state-io.js +50 -0
  8. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  9. package/dist/bridge/bridge-state-lock.js +102 -0
  10. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  11. package/dist/bridge/bridge-state-unpublished.js +111 -0
  12. package/dist/bridge/bridge.service.d.ts +16 -12
  13. package/dist/bridge/bridge.service.js +131 -243
  14. package/dist/bridge/bridge.types.d.ts +5 -0
  15. package/dist/bridge/in-flight-registry.d.ts +62 -0
  16. package/dist/bridge/in-flight-registry.js +207 -0
  17. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  18. package/dist/bridge/readiness-result-outbox.js +20 -0
  19. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  20. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  21. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  22. package/dist/cleanup/cleanup-wip.js +66 -0
  23. package/dist/cleanup/cleanup.service.d.ts +11 -1
  24. package/dist/cleanup/cleanup.service.js +80 -62
  25. package/dist/cleanup/cleanup.types.d.ts +2 -0
  26. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  27. package/dist/cleanup/host-runtime-ledger.js +30 -9
  28. package/dist/cli/cli.help.js +56 -12
  29. package/dist/cli/cli.service.d.ts +3 -10
  30. package/dist/cli/cli.service.js +10 -171
  31. package/dist/cli/idle-status.d.ts +84 -0
  32. package/dist/cli/idle-status.js +181 -0
  33. package/dist/cli/local-config.d.ts +2 -0
  34. package/dist/cli/local-config.js +7 -1
  35. package/dist/cli/provider-cli-detection.d.ts +10 -0
  36. package/dist/cli/provider-cli-detection.js +160 -0
  37. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  38. package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
  39. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  40. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  41. package/dist/runtime/docker-engine-probe.js +7 -0
  42. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  43. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  44. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  45. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  46. package/dist/runtime/host-load-governor.d.ts +2 -0
  47. package/dist/runtime/host-load-ledger-lock.js +6 -4
  48. package/dist/runtime/host-load-runtime-settings.js +4 -2
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.js +10 -50
  52. package/dist/runtime/managed-command-teardown.js +5 -16
  53. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  54. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  55. package/dist/runtime/runner-settings.d.ts +4 -0
  56. package/dist/runtime/runner-settings.js +22 -0
  57. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  58. package/dist/sandbox/host-capacity-broker.js +4 -2
  59. package/dist/sandbox/managed-branch.d.ts +13 -0
  60. package/dist/sandbox/managed-branch.js +36 -0
  61. package/dist/sandbox/provider-auth/codex.js +11 -11
  62. package/dist/sandbox/runtime.js +2 -6
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +45 -77
  65. package/dist/session/managed-build-receipt.d.ts +5 -0
  66. package/dist/session/managed-build-receipt.js +8 -3
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +43 -197
  74. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  75. package/dist/session/pre-publication-native-postgres.js +111 -0
  76. package/dist/session/pre-publication-process.js +10 -10
  77. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  78. package/dist/session/pre-publication-step-execution.js +6 -5
  79. package/dist/session/pre-publication-validation.d.ts +7 -3
  80. package/dist/session/pre-publication-validation.js +32 -30
  81. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  82. package/dist/session/provider-cli/claude-background-work.js +4 -3
  83. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  84. package/dist/session/provider-cli/host-build-lock.js +30 -0
  85. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  86. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  87. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  88. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  89. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  90. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  92. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  93. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  95. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  96. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  97. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  98. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  99. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  100. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  101. package/dist/session/qa-sidecar-validation.js +28 -0
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  103. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  104. package/dist/session/session-redaction.js +31 -181
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +62 -56
  107. package/dist/session/session.types.js +1 -1
  108. package/dist/session/sidecar-json-shape.d.ts +31 -0
  109. package/dist/session/sidecar-json-shape.js +217 -0
  110. package/dist/shared/fs/file-identity.d.ts +10 -0
  111. package/dist/shared/fs/file-identity.js +15 -0
  112. package/dist/shared/fs/replace-file.d.ts +7 -0
  113. package/dist/shared/fs/replace-file.js +33 -0
  114. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  115. package/dist/shared/process/host-process-recovery.js +23 -3
  116. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  117. package/dist/shared/process/host-process-supervisor.js +66 -14
  118. package/dist/shared/provider-capabilities.js +9 -1
  119. package/dist/version.d.ts +1 -1
  120. package/dist/version.js +1 -1
  121. package/dist/worktree/wip-git.d.ts +33 -0
  122. package/dist/worktree/wip-git.js +122 -0
  123. package/dist/worktree/wip-refs.d.ts +62 -0
  124. package/dist/worktree/wip-refs.js +119 -0
  125. package/dist/worktree/wip-restore.d.ts +38 -0
  126. package/dist/worktree/wip-restore.js +190 -0
  127. package/dist/worktree/wip-snapshot.d.ts +50 -0
  128. package/dist/worktree/wip-snapshot.js +268 -0
  129. package/dist/worktree/worktree-inputs.d.ts +8 -0
  130. package/dist/worktree/worktree-inputs.js +134 -0
  131. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  132. package/dist/worktree/worktree-origin-sync.js +127 -0
  133. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  134. package/dist/worktree/worktree-wip-events.js +98 -0
  135. package/dist/worktree/worktree-wip.d.ts +49 -0
  136. package/dist/worktree/worktree-wip.js +182 -0
  137. package/dist/worktree/worktree.base.d.ts +7 -1
  138. package/dist/worktree/worktree.service.d.ts +27 -5
  139. package/dist/worktree/worktree.service.js +106 -181
  140. package/dist/worktree/worktree.types.d.ts +31 -0
  141. 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
@@ -76,6 +77,8 @@ export class ForgeBridgeService {
76
77
  activeSessions = new Map();
77
78
  reservations = new Map();
78
79
  activeReadinessProbes = new Map();
80
+ /** Everything a bridge restart would interrupt, published for `forge-bridge status --idle`. */
81
+ inFlight = new BridgeInFlightRegistry();
79
82
  readinessResultOutbox;
80
83
  readinessResultFlush = null;
81
84
  dispatchResultOutbox;
@@ -96,6 +99,9 @@ export class ForgeBridgeService {
96
99
  // and the effective settings computed from both and the host's env bounds.
97
100
  appliedSettingsDocument = null;
98
101
  localYield = false;
102
+ /** The yield Forge last acknowledged in a report (Hello, Heartbeat, SettingsApplied); published as `yielding`. */
103
+ forgeAckedYield = false;
104
+ publishState = () => undefined;
99
105
  effectiveSettings;
100
106
  settingsReport;
101
107
  /** Applies run one at a time; offers wait for every apply queued before them. */
@@ -172,6 +178,11 @@ export class ForgeBridgeService {
172
178
  // With no server document and no local flag these equal today's env/default behaviour.
173
179
  this.effectiveSettings = computeEffectiveRunnerSettings(null, process.env, this.runnerHostDefaults(), false);
174
180
  this.settingsReport = this.effectiveSettings.report;
181
+ this.inFlight.addSource(() => [
182
+ ...reservationInFlightEntries(this.reservations),
183
+ ...sessionInFlightEntries(this.activeSessions),
184
+ ...readinessInFlightEntries(this.activeReadinessProbes),
185
+ ]);
175
186
  }
176
187
  async connectOnce() {
177
188
  if (this.revokedReason !== null) {
@@ -248,14 +259,14 @@ export class ForgeBridgeService {
248
259
  await connection.stop().catch(() => undefined);
249
260
  }
250
261
  });
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));
262
+ connection.onDispatch((dispatch) => this.inFlight.track("dispatch", dispatch, () => this.handleDispatch(dispatch)));
263
+ connection.onChatTurn?.((dispatch) => this.inFlight.track("chat_turn", dispatch, () => this.handleChatTurn(dispatch)));
264
+ connection.onOffer?.((dispatch) => this.inFlight.track("offer", dispatch, () => this.handleOffer(dispatch)));
265
+ connection.onStart?.((dispatch) => this.inFlight.track("start", dispatch, () => this.handleStart(dispatch)));
255
266
  connection.onLeaseUpdate?.((request) => this.handleLeaseUpdate(request));
256
267
  connection.onCancel((request) => this.handleCancel(request));
257
268
  connection.onReap?.((request) => this.handleReap(request));
258
- connection.onReadinessProbe?.((request) => this.handleReadinessProbe(request));
269
+ connection.onReadinessProbe?.((request) => this.inFlight.track("readiness_probe", request, () => this.handleReadinessProbe(request)));
259
270
  connection.onRevoked?.((notice) => this.handleRevoked(notice));
260
271
  connection.onApplySettings?.((document) => this.handleApplySettings(document));
261
272
  await connection.start();
@@ -294,6 +305,7 @@ export class ForgeBridgeService {
294
305
  while (true) {
295
306
  try {
296
307
  const recoveredHostAttempts = await this.recoveredHostAttemptsForHello();
308
+ const reportedYield = this.settingsReport.values.yieldToForeground;
297
309
  const ack = await connection.invoke("Hello", {
298
310
  version: this.config.version,
299
311
  protocolVersion: this.config.protocolVersion,
@@ -306,6 +318,7 @@ export class ForgeBridgeService {
306
318
  throw new BridgeCallbackRejectedError(ack.code ?? null, ack.message ?? ack.code ?? "Hello callback was rejected.");
307
319
  }
308
320
  this.recoveredHostAttempts.clear();
321
+ this.ackYield(reportedYield);
309
322
  logBridgeStatus(`Registered runner ${this.config.runnerId}, instance ${this.config.runnerInstanceId}, build ${this.config.version}, protocol ${this.config.protocolVersion}.`);
310
323
  return;
311
324
  }
@@ -321,6 +334,7 @@ export class ForgeBridgeService {
321
334
  }
322
335
  }
323
336
  async run(signal) {
337
+ const statePublisher = await this.startStatePublisher();
324
338
  let attempt = 0;
325
339
  try {
326
340
  while (!this.stopped && !signal?.aborted) {
@@ -352,11 +366,28 @@ export class ForgeBridgeService {
352
366
  this.abortActiveReadinessProbes(String(signal.reason ?? "bridge stopping"));
353
367
  }
354
368
  await this.stopConnection();
369
+ await statePublisher?.stop();
355
370
  }
356
371
  if (this.revokedReason !== null) {
357
372
  throw new BridgeRevokedError(this.revokedReason);
358
373
  }
359
374
  }
375
+ async startStatePublisher() {
376
+ if (!this.config.bridgeStatePath)
377
+ return null;
378
+ const publisher = new BridgeStatePublisher(this.config.bridgeStatePath, this.config, {
379
+ inFlight: () => this.inFlight.snapshot(),
380
+ // Yield counts once Forge has acknowledged it: until then placement can still pick this runner.
381
+ yielding: () => this.effectiveSettings.yielding && this.forgeAckedYield,
382
+ yieldApplied: () => this.effectiveSettings.yielding,
383
+ connected: () => this.connection !== null && this.transportRecovery === null,
384
+ }, { log: logBridgeStatus });
385
+ this.publishState = () => void publisher.publish();
386
+ this.inFlight.onChange(this.publishState);
387
+ await publisher.start();
388
+ logBridgeStatus(`Publishing idle state to ${this.config.bridgeStatePath} (forge-bridge status --idle).`);
389
+ return publisher;
390
+ }
360
391
  /** The reason Forge gave when it removed this runner, or null while it is paired. */
361
392
  get revoked() {
362
393
  return this.revokedReason;
@@ -492,6 +523,7 @@ export class ForgeBridgeService {
492
523
  this.appliedSettingsDocument = document;
493
524
  this.effectiveSettings = effective;
494
525
  this.settingsReport = report;
526
+ this.publishState();
495
527
  if (change.kind === "server") {
496
528
  logBridgeStatus(`Applied runner settings v${change.document.version}: ${describeRunnerSettings(report)}.`);
497
529
  }
@@ -533,10 +565,12 @@ export class ForgeBridgeService {
533
565
  }
534
566
  return rejected;
535
567
  }
568
+ ackYield(reported) { this.forgeAckedYield = reported; this.publishState(); }
536
569
  /** A failed acknowledgement is not retried here: the next heartbeat carries the same report. */
537
570
  async sendSettingsApplied(report) {
538
571
  try {
539
572
  await this.invokeAck("SettingsApplied", report);
573
+ this.ackYield(report.values.yieldToForeground);
540
574
  }
541
575
  catch (error) {
542
576
  logBridgeStatus(`SettingsApplied for v${report.version ?? "none"} was not acknowledged: ${errorMessage(error)}. The next heartbeat reports it.`);
@@ -894,19 +928,7 @@ export class ForgeBridgeService {
894
928
  return;
895
929
  }
896
930
  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
- });
931
+ this.registerActiveDispatch(dispatch, controller);
910
932
  if (reservationHandoff) {
911
933
  // Promotion is synchronous with active-session registration. A qualified
912
934
  // pre-start Cancel therefore sees either the cancellable reservation or
@@ -930,43 +952,10 @@ export class ForgeBridgeService {
930
952
  };
931
953
  await this.invokeAck("DispatchStarted", started);
932
954
  }
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
- }
955
+ const sink = this.dispatchEventSink(dispatch, controller, redactionSecrets);
956
+ const result = await this.runDispatchOnce(normalized, sink, controller.signal);
969
957
  const redactedResult = redactRunOnceResultPacket(result, redactionSecrets);
958
+ this.inFlight.notePhase(leaseId, "result_delivery");
970
959
  await this.sendResult(dispatch, compactTerminalResult(dispatch, redactedResult));
971
960
  }
972
961
  catch (error) {
@@ -990,6 +979,77 @@ export class ForgeBridgeService {
990
979
  await this.releaseActiveSessionAndRefreshCapacity(leaseId);
991
980
  }
992
981
  }
982
+ registerActiveDispatch(dispatch, controller) {
983
+ this.activeSessions.set(dispatch.lease.id, {
984
+ leaseId: dispatch.lease.id,
985
+ kind: "dispatch",
986
+ fencingToken: dispatch.lease.fencingToken,
987
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
988
+ runnerInstanceId: dispatch.sandbox?.runnerInstanceId ?? null,
989
+ leaseExpiresAt: dispatch.lease.expiresAt,
990
+ sandboxed: dispatch.sandbox?.executionMode === "docker",
991
+ resources: dispatch.sandbox?.executionMode === "docker" ? dispatch.sandbox.requestedResources : zeroSandboxResources(),
992
+ controller
993
+ });
994
+ this.inFlight.notePhase(dispatch.lease.id, "accepted");
995
+ logBridgeStatus(`Dispatch accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}.`);
996
+ }
997
+ dispatchEventSink(dispatch, controller, redactionSecrets) {
998
+ const leaseId = dispatch.lease.id;
999
+ return {
1000
+ emit: async (event) => {
1001
+ this.inFlight.notePhase(leaseId, event.eventType);
1002
+ if (event.eventType === "provider_cli_started") {
1003
+ const active = this.activeSessions.get(leaseId);
1004
+ if (active)
1005
+ active.resources = { ...active.resources, buildSlots: 0 };
1006
+ }
1007
+ try {
1008
+ await this.invokeAck("DispatchEvent", {
1009
+ leaseId,
1010
+ fencingToken: dispatch.lease.fencingToken,
1011
+ ...(dispatch.sandbox ? {
1012
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
1013
+ runnerInstanceId: dispatch.sandbox.runnerInstanceId
1014
+ } : {}),
1015
+ event: redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets)
1016
+ }, {
1017
+ replayCallbackTimeout: true,
1018
+ signal: controller.signal,
1019
+ });
1020
+ }
1021
+ catch (error) {
1022
+ if (isDispatchNoLongerPending(error)) {
1023
+ controller.abort(error instanceof Error ? error.message : "Dispatch is no longer pending.");
1024
+ return;
1025
+ }
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ };
1030
+ }
1031
+ /** Runs the dispatch on the host or in its Docker sandbox, logging start and end with its ids. */
1032
+ async runDispatchOnce(dispatch, sink, signal) {
1033
+ const docker = dispatch.sandbox?.executionMode === "docker";
1034
+ const ids = describeInFlightIds(inFlightIdsFrom(dispatch));
1035
+ const startedAt = Date.now();
1036
+ this.inFlight.notePhase(dispatch.lease.id, "run_once");
1037
+ logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1038
+ try {
1039
+ const result = docker
1040
+ ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1041
+ : await this.sessions.runOnce(dispatch, sink, signal);
1042
+ if (docker) {
1043
+ await this.flushCleanupReports().catch(() => undefined);
1044
+ }
1045
+ logBridgeStatus(`Run-once ended with exit code ${result.exitCode} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}.`);
1046
+ return result;
1047
+ }
1048
+ catch (error) {
1049
+ logBridgeStatus(`Run-once ${signal.aborted ? "cancelled" : "failed"} after ${Math.round((Date.now() - startedAt) / 1000)}s: ${ids}. The terminal result carries the reason.`);
1050
+ throw error;
1051
+ }
1052
+ }
993
1053
  reservedDispatchHandoffIsCurrent(handoff, dispatch) {
994
1054
  const sandbox = dispatch.sandbox;
995
1055
  const reservation = handoff.reservation;
@@ -1351,6 +1411,8 @@ export class ForgeBridgeService {
1351
1411
  reservedResources: accepted ? reservedResources : null,
1352
1412
  sandboxConfigCommitSha: accepted ? sandboxConfigCommitSha : null,
1353
1413
  };
1414
+ if (accepted)
1415
+ logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1354
1416
  await this.invokeAck("OfferDecision", payload);
1355
1417
  }
1356
1418
  async parseDispatchOrReport(rawDispatch) {
@@ -1464,7 +1526,13 @@ export class ForgeBridgeService {
1464
1526
  acceptedAt: new Date().toISOString(),
1465
1527
  };
1466
1528
  await this.invokeAck("ReadinessAccepted", accepted);
1467
- if (this.activeSessions.size > 0) {
1529
+ // While yielding, background readiness waits too; Forge retries a deferred probe.
1530
+ await this.refreshLocalYield().catch(() => undefined);
1531
+ await this.settingsTail;
1532
+ if (this.yieldingOrQueued()) {
1533
+ result = deferredReadinessResult(request, this.config.runnerInstanceId, "The runner yields to foreground use; Forge retries background runtime readiness once yield is off.");
1534
+ }
1535
+ else if (this.activeSessions.size > 0) {
1468
1536
  result = deferredReadinessResult(request, this.config.runnerInstanceId);
1469
1537
  }
1470
1538
  else if (!this.sessions.probeHostRuntime) {
@@ -1922,12 +1990,14 @@ export class ForgeBridgeService {
1922
1990
  await this.sendHeartbeatSnapshot();
1923
1991
  }
1924
1992
  async sendHeartbeatSnapshot(signal) {
1993
+ const reportedYield = this.settingsReport.values.yieldToForeground;
1925
1994
  await this.invokeAck("Heartbeat", {
1926
1995
  status: "online",
1927
1996
  capabilities: this.capabilities(),
1928
1997
  version: this.config.version,
1929
1998
  protocolVersion: this.config.protocolVersion
1930
1999
  }, { signal });
2000
+ this.ackYield(reportedYield);
1931
2001
  }
1932
2002
  capabilities() {
1933
2003
  const preflight = this.preflight.current();
@@ -2169,25 +2239,6 @@ export class ForgeBridgeService {
2169
2239
  }
2170
2240
  }
2171
2241
  }
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
2242
  /** The `run` command's exit code after Forge removed the runner. */
2192
2243
  export const bridgeRevokedExitCode = 3;
2193
2244
  export const bridgeRevokedMessage = "This bridge was removed from Forge. Pair it again with forge-bridge pair.";
@@ -2894,24 +2945,6 @@ function parseReadinessProbe(value) {
2894
2945
  }
2895
2946
  return request;
2896
2947
  }
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
2948
  function sandboxProviderNetworkFailure(dispatch, config) {
2916
2949
  const sandbox = dispatch.sandbox;
2917
2950
  if (!sandbox || sandbox.networkPolicy.mode !== "offline")
@@ -2950,151 +2983,6 @@ function rejectedOfferReservation(code, message) {
2950
2983
  resources: null,
2951
2984
  };
2952
2985
  }
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
2986
  function parseOfferEnvelope(value) {
3099
2987
  return parseDispatchEnvelope(value);
3100
2988
  }
@@ -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;