@bastani/atomic 0.9.89-alpha.1 → 0.9.89

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 (153) hide show
  1. package/CHANGELOG.md +289 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +31 -0
  3. package/dist/builtin/intercom/broker/broker-instance.ts +15 -1
  4. package/dist/builtin/intercom/broker/broker.ts +25 -8
  5. package/dist/builtin/intercom/broker/client.ts +29 -14
  6. package/dist/builtin/intercom/broker/multinode-router.ts +193 -52
  7. package/dist/builtin/intercom/broker/multinode-state-store.ts +6 -2
  8. package/dist/builtin/intercom/broker/restoring-recipients.ts +5 -0
  9. package/dist/builtin/intercom/broker/sql-outbox-store.ts +3 -2
  10. package/dist/builtin/intercom/index.bundle.mjs +19 -12
  11. package/dist/builtin/intercom/package.json +1 -1
  12. package/dist/builtin/intercom/types.ts +6 -2
  13. package/dist/builtin/mcp/package.json +1 -1
  14. package/dist/builtin/subagents/CHANGELOG.md +45 -0
  15. package/dist/builtin/subagents/package.json +1 -1
  16. package/dist/builtin/subagents/src/extension/index.bundle.mjs +17 -6
  17. package/dist/builtin/web-access/CHANGELOG.md +11 -0
  18. package/dist/builtin/web-access/package.json +1 -1
  19. package/dist/builtin/workflows/CHANGELOG.md +106 -0
  20. package/dist/builtin/workflows/package.json +1 -1
  21. package/dist/builtin/workflows/src/extension/index.bundle.mjs +310 -344
  22. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +99 -17
  23. package/dist/builtin/workflows/src/index.js +99 -17
  24. package/dist/builtin/workflows/src/local-worker-entry.mjs +99 -17
  25. package/dist/cli/storage-command.js +8 -0
  26. package/dist/cli/storage-command.js.map +1 -1
  27. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  28. package/dist/core/auth-storage-backends.js +1 -0
  29. package/dist/core/auth-storage-backends.js.map +1 -1
  30. package/dist/core/keybindings.d.ts +8 -0
  31. package/dist/core/keybindings.d.ts.map +1 -1
  32. package/dist/core/keybindings.js +4 -0
  33. package/dist/core/keybindings.js.map +1 -1
  34. package/dist/core/process-start-token.d.ts.map +1 -1
  35. package/dist/core/process-start-token.js +8 -1
  36. package/dist/core/process-start-token.js.map +1 -1
  37. package/dist/core/resume/blueprint/build-lock.d.ts.map +1 -1
  38. package/dist/core/resume/blueprint/build-lock.js +2 -1
  39. package/dist/core/resume/blueprint/build-lock.js.map +1 -1
  40. package/dist/core/storage/errors.d.ts +4 -2
  41. package/dist/core/storage/errors.d.ts.map +1 -1
  42. package/dist/core/storage/errors.js +6 -1
  43. package/dist/core/storage/errors.js.map +1 -1
  44. package/dist/core/tasks/completion.d.ts +5 -0
  45. package/dist/core/tasks/completion.d.ts.map +1 -1
  46. package/dist/core/tasks/completion.js +13 -0
  47. package/dist/core/tasks/completion.js.map +1 -1
  48. package/dist/core/tools/shell-task-render.d.ts +1 -2
  49. package/dist/core/tools/shell-task-render.d.ts.map +1 -1
  50. package/dist/core/tools/shell-task-render.js +3 -7
  51. package/dist/core/tools/shell-task-render.js.map +1 -1
  52. package/dist/core/tools/windows-directory-security.d.ts.map +1 -1
  53. package/dist/core/tools/windows-directory-security.js +3 -11
  54. package/dist/core/tools/windows-directory-security.js.map +1 -1
  55. package/dist/core/worktree-snapshot/capture.d.ts.map +1 -1
  56. package/dist/core/worktree-snapshot/capture.js +25 -1
  57. package/dist/core/worktree-snapshot/capture.js.map +1 -1
  58. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  59. package/dist/core/worktree-snapshot/restore.js +38 -9
  60. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  61. package/dist/index.d.ts +2 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +2 -1
  64. package/dist/index.js.map +1 -1
  65. package/dist/modes/interactive/components/agent-panel.d.ts +5 -0
  66. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  67. package/dist/modes/interactive/components/agent-panel.js +13 -0
  68. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  69. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  70. package/dist/modes/interactive/components/chat-transcript.js +5 -2
  71. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  72. package/dist/modes/interactive/components/custom-message.js +1 -1
  73. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  74. package/dist/modes/interactive/components/heartbeat-block.d.ts +34 -0
  75. package/dist/modes/interactive/components/heartbeat-block.d.ts.map +1 -0
  76. package/dist/modes/interactive/components/heartbeat-block.js +50 -0
  77. package/dist/modes/interactive/components/heartbeat-block.js.map +1 -0
  78. package/dist/modes/interactive/components/input-label.d.ts.map +1 -1
  79. package/dist/modes/interactive/components/input-label.js +8 -3
  80. package/dist/modes/interactive/components/input-label.js.map +1 -1
  81. package/dist/modes/interactive/components/main-composer-keys.d.ts.map +1 -1
  82. package/dist/modes/interactive/components/main-composer-keys.js +3 -7
  83. package/dist/modes/interactive/components/main-composer-keys.js.map +1 -1
  84. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  85. package/dist/modes/interactive/components/mermaid.js +13 -7
  86. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  87. package/dist/modes/interactive/components/notice-line.d.ts +10 -2
  88. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  89. package/dist/modes/interactive/components/notice-line.js +13 -3
  90. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  91. package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -1
  92. package/dist/modes/interactive/components/provider-brand.js +3 -0
  93. package/dist/modes/interactive/components/provider-brand.js.map +1 -1
  94. package/dist/modes/interactive/components/task-heartbeat-message.d.ts +9 -4
  95. package/dist/modes/interactive/components/task-heartbeat-message.d.ts.map +1 -1
  96. package/dist/modes/interactive/components/task-heartbeat-message.js +33 -27
  97. package/dist/modes/interactive/components/task-heartbeat-message.js.map +1 -1
  98. package/dist/modes/interactive/components/task-inspector.d.ts +16 -0
  99. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  100. package/dist/modes/interactive/components/task-inspector.js +95 -4
  101. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  102. package/dist/modes/interactive/components/task-list.d.ts +5 -1
  103. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  104. package/dist/modes/interactive/components/task-list.js +20 -3
  105. package/dist/modes/interactive/components/task-list.js.map +1 -1
  106. package/dist/modes/interactive/components/task-transcript-page.d.ts +1 -1
  107. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  108. package/dist/modes/interactive/components/task-transcript-page.js +10 -7
  109. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  110. package/dist/modes/interactive/interactive-startup.js +1 -2
  111. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  112. package/dist/modes/interactive/theme/color-utils.d.ts +29 -1
  113. package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
  114. package/dist/modes/interactive/theme/color-utils.js +81 -7
  115. package/dist/modes/interactive/theme/color-utils.js.map +1 -1
  116. package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
  117. package/dist/modes/interactive/theme/global-theme.js +3 -0
  118. package/dist/modes/interactive/theme/global-theme.js.map +1 -1
  119. package/dist/modes/interactive/theme/theme-class.d.ts +22 -2
  120. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  121. package/dist/modes/interactive/theme/theme-class.js +64 -18
  122. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  123. package/dist/modes/interactive/theme/theme.d.ts +1 -0
  124. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  125. package/dist/modes/interactive/theme/theme.js +1 -0
  126. package/dist/modes/interactive/theme/theme.js.map +1 -1
  127. package/dist/utils/clipboard-image.d.ts.map +1 -1
  128. package/dist/utils/clipboard-image.js +2 -0
  129. package/dist/utils/clipboard-image.js.map +1 -1
  130. package/dist/utils/clipboard.d.ts.map +1 -1
  131. package/dist/utils/clipboard.js +2 -1
  132. package/dist/utils/clipboard.js.map +1 -1
  133. package/dist/utils/tools-manager.d.ts +6 -0
  134. package/dist/utils/tools-manager.d.ts.map +1 -1
  135. package/dist/utils/tools-manager.js +170 -15
  136. package/dist/utils/tools-manager.js.map +1 -1
  137. package/dist/utils/windows-powershell.d.ts +9 -0
  138. package/dist/utils/windows-powershell.d.ts.map +1 -0
  139. package/dist/utils/windows-powershell.js +16 -0
  140. package/dist/utils/windows-powershell.js.map +1 -0
  141. package/docs/background-tasks.md +6 -6
  142. package/docs/getting-started/installation.md +4 -2
  143. package/docs/keybindings.md +3 -0
  144. package/docs/storage.md +24 -5
  145. package/docs/subagents.md +1 -1
  146. package/docs/themes/reference.md +7 -0
  147. package/docs/tui/reference.md +1 -1
  148. package/docs/windows.md +1 -1
  149. package/docs/workflows/api-reference.md +9 -1
  150. package/docs/workflows/operations.md +1 -1
  151. package/npm-shrinkwrap.json +49 -49
  152. package/package.json +6 -6
  153. package/schemas/keybindings.schema.json +4 -0
@@ -2548,7 +2548,7 @@ class IntercomBroker {
2548
2548
  });
2549
2549
  break;
2550
2550
  }
2551
- this.reserveRestoringRecipient(
2551
+ const published = this.reserveRestoringRecipient(
2552
2552
  clientMessage.capability,
2553
2553
  currentId,
2554
2554
  childName,
@@ -2560,7 +2560,12 @@ class IntercomBroker {
2560
2560
  },
2561
2561
  );
2562
2562
  this.dispatchHeldSends(this.departedChildren.supersede(currentId, childName));
2563
- writeMessageIfOpen(socket, { type: "restoring_recipient_ack", requestId: clientMessage.requestId });
2563
+ // #5352: acknowledged once senders on other brokers can find the reservation (bounded by the router).
2564
+ const requestId = clientMessage.requestId;
2565
+ // `published: false`: reserved here, and written for other brokers once the shared database takes it.
2566
+ void published.then((visible) =>
2567
+ writeMessageIfOpen(socket, { type: "restoring_recipient_ack", requestId, ...(visible ? {} : { published: false }) }),
2568
+ );
2564
2569
  break;
2565
2570
  }
2566
2571
 
@@ -2650,8 +2655,9 @@ class IntercomBroker {
2650
2655
  writeMessageIfOpen(socket, { type: "released_children_ack", requestId: clientMessage.requestId, refusal });
2651
2656
  break;
2652
2657
  }
2658
+ const published: Promise<boolean>[] = [];
2653
2659
  for (const child of validation.children) {
2654
- this.reserveReleasedChild(currentId, owner.registrationGroup, child);
2660
+ published.push(this.reserveReleasedChild(currentId, owner.registrationGroup, child));
2655
2661
  this.releasedAskerReplies.attach(child.childName, currentId);
2656
2662
  // #4751: a failed ask kept for the child wakes it again, so it is delivered.
2657
2663
  if (
@@ -2662,7 +2668,15 @@ class IntercomBroker {
2662
2668
  this.wakeRestoringRecipientOwner({ ownerSessionId: currentId, childName: child.childName });
2663
2669
  this.dispatchHeldSends(this.departedChildren.supersede(currentId, child.childName));
2664
2670
  }
2665
- writeMessageIfOpen(socket, { type: "released_children_ack", requestId: clientMessage.requestId });
2671
+ // #5352: acknowledged once senders on other brokers can find the reservations (bounded by the router).
2672
+ const requestId = clientMessage.requestId;
2673
+ void Promise.all(published).then((visible) =>
2674
+ writeMessageIfOpen(socket, {
2675
+ type: "released_children_ack",
2676
+ requestId,
2677
+ ...(visible.every(Boolean) ? {} : { published: false }),
2678
+ }),
2679
+ );
2666
2680
  break;
2667
2681
  }
2668
2682
 
@@ -3433,6 +3447,7 @@ class IntercomBroker {
3433
3447
  },
3434
3448
  dispatch: (socket, clientMessage, senderId) => this.dispatchSend(socket, clientMessage, senderId),
3435
3449
  revokeReleasedReservation: (key, ownerSessionId) => this.revokeReleasedReservation(key, ownerSessionId),
3450
+ holdsReservation: (key, ownerSessionId) => this.restoringRecipients.holds(key, ownerSessionId),
3436
3451
  },
3437
3452
  });
3438
3453
  } catch (error) {
@@ -3596,17 +3611,19 @@ class IntercomBroker {
3596
3611
  group: string,
3597
3612
  aliases: readonly string[],
3598
3613
  options: { readonly dormant: boolean; readonly wake?: boolean; readonly replaceAliases?: true; readonly holdMs?: number },
3599
- ): void {
3614
+ ): Promise<boolean> {
3600
3615
  const wake = this.restoringRecipients.reserve(key, ownerSessionId, childName, group, aliases, options);
3601
- this.multiNode?.restoringReserved(key, ownerSessionId, childName, group, aliases, options.dormant, {
3616
+ const published = this.multiNode?.restoringReserved(key, ownerSessionId, childName, group, aliases, options.dormant, {
3602
3617
  wake: options.wake === true,
3603
3618
  ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
3604
3619
  });
3605
3620
  if (wake !== undefined) this.wakeRestoringRecipientOwner(wake);
3621
+ return published ?? Promise.resolve(true);
3606
3622
  }
3607
3623
 
3608
- private reserveReleasedChild(ownerSessionId: string, ownerGroup: string, child: ParsedReleasedChild): void {
3609
- this.reserveRestoringRecipient(
3624
+ /** Resolves true once senders on other brokers can find the reservation, false while its write is retried. */
3625
+ private reserveReleasedChild(ownerSessionId: string, ownerGroup: string, child: ParsedReleasedChild): Promise<boolean> {
3626
+ return this.reserveRestoringRecipient(
3610
3627
  releasedReservationKey(child.childName),
3611
3628
  ownerSessionId,
3612
3629
  child.childName,
@@ -534,7 +534,10 @@ export class IntercomClient extends EventEmitter {
534
534
  resolve: (authorization: SupervisorAuthorization) => void;
535
535
  reject: (error: Error) => void;
536
536
  }>();
537
- private pendingRestoringRecipientRequests = new Map<string, { resolve(): void; reject(error: Error): void }>();
537
+ private pendingRestoringRecipientRequests = new Map<
538
+ string,
539
+ { resolve(published?: boolean): void; reject(error: Error): void }
540
+ >();
538
541
  private pendingHostedSessionRequests = new Map<
539
542
  string,
540
543
  { resolve(sessions: readonly HostedSessionAssignment[]): void; reject(error: Error): void }
@@ -1317,27 +1320,35 @@ export class IntercomClient extends EventEmitter {
1317
1320
  break;
1318
1321
  }
1319
1322
  case "released_children_ack": {
1320
- const { requestId, refusal } = brokerMessage;
1323
+ const { requestId, refusal, published } = brokerMessage;
1321
1324
  const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
1322
- if (typeof requestId !== "string" || (refusal !== undefined && parsed === undefined)) {
1325
+ if (
1326
+ typeof requestId !== "string" ||
1327
+ (refusal !== undefined && parsed === undefined) ||
1328
+ (published !== undefined && typeof published !== "boolean")
1329
+ ) {
1323
1330
  throw new Error("Invalid released_children_ack message");
1324
1331
  }
1325
1332
  const pending = this.pendingRestoringRecipientRequests.get(requestId);
1326
1333
  if (!pending) return;
1327
1334
  this.pendingRestoringRecipientRequests.delete(requestId);
1328
- if (parsed === undefined) pending.resolve();
1335
+ if (parsed === undefined) pending.resolve(published !== false);
1329
1336
  else pending.reject(releasedChildErrorFor(parsed));
1330
1337
  break;
1331
1338
  }
1332
1339
  case "restoring_recipient_ack": {
1333
- const { requestId, error } = brokerMessage;
1334
- if (typeof requestId !== "string" || (error !== undefined && typeof error !== "string")) {
1340
+ const { requestId, error, published } = brokerMessage;
1341
+ if (
1342
+ typeof requestId !== "string" ||
1343
+ (error !== undefined && typeof error !== "string") ||
1344
+ (published !== undefined && typeof published !== "boolean")
1345
+ ) {
1335
1346
  throw new Error("Invalid restoring_recipient_ack message");
1336
1347
  }
1337
1348
  const pending = this.pendingRestoringRecipientRequests.get(requestId);
1338
1349
  if (!pending) return;
1339
1350
  this.pendingRestoringRecipientRequests.delete(requestId);
1340
- if (error === undefined) pending.resolve();
1351
+ if (error === undefined) pending.resolve(published !== false);
1341
1352
  else pending.reject(new Error(error));
1342
1353
  break;
1343
1354
  }
@@ -1751,12 +1762,14 @@ export class IntercomClient extends EventEmitter {
1751
1762
  * #3760: hold sends to the child that `capability` (issued to this session by `authorizeSupervisorChild`)
1752
1763
  * names, and to its `aliases`, until the child registers with that capability. Calling again adds aliases.
1753
1764
  * A `dormant` hold keeps the child addressable until the supervisor that restores it takes the hold over.
1765
+ * #5352: with multi-node routing, `published` is false when the hold is in force on this broker but brokers on other
1766
+ * hosts could not find it yet: the broker keeps publishing it until it can, or until the hold ends.
1754
1767
  */
1755
- reserveRestoringRecipient(
1768
+ async reserveRestoringRecipient(
1756
1769
  capability: string,
1757
1770
  options: { group?: string; aliases?: readonly string[]; dormant?: boolean; holdMs?: number } = {},
1758
- ): Promise<void> {
1759
- return this.restoringRecipientRequest({
1771
+ ): Promise<{ readonly published: boolean }> {
1772
+ const published = await this.restoringRecipientRequest({
1760
1773
  type: "reserve_restoring_recipient",
1761
1774
  capability,
1762
1775
  ...(options.group === undefined ? {} : { group: options.group }),
@@ -1764,6 +1777,7 @@ export class IntercomClient extends EventEmitter {
1764
1777
  ...(options.dormant === true ? { dormant: true } : {}),
1765
1778
  ...(options.holdMs === undefined ? {} : { holdMs: options.holdMs }),
1766
1779
  });
1780
+ return { published };
1767
1781
  }
1768
1782
 
1769
1783
  /**
@@ -1778,7 +1792,7 @@ export class IntercomClient extends EventEmitter {
1778
1792
  capability,
1779
1793
  ...(gone === undefined ? {} : { gone }),
1780
1794
  ...(refusal === undefined ? {} : { refusal }),
1781
- });
1795
+ }).then(() => undefined);
1782
1796
  }
1783
1797
 
1784
1798
  /**
@@ -1864,7 +1878,7 @@ export class IntercomClient extends EventEmitter {
1864
1878
  } catch (error) {
1865
1879
  return Promise.reject(toError(error));
1866
1880
  }
1867
- return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName });
1881
+ return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName }).then(() => undefined);
1868
1882
  }
1869
1883
 
1870
1884
  acknowledgeReleasedChildReply(reply: ReleasedChildReply, accepted: boolean, deliverToChild = false): boolean {
@@ -1979,7 +1993,8 @@ export class IntercomClient extends EventEmitter {
1979
1993
  });
1980
1994
  }
1981
1995
 
1982
- private restoringRecipientRequest(frame: Record<string, unknown>): Promise<void> {
1996
+ /** Resolves false when the broker reserved with `published: false` (#5352), true for every other success. */
1997
+ private restoringRecipientRequest(frame: Record<string, unknown>): Promise<boolean> {
1983
1998
  let socket: net.Socket;
1984
1999
  try {
1985
2000
  socket = this.requireActiveSocket();
@@ -1993,7 +2008,7 @@ export class IntercomClient extends EventEmitter {
1993
2008
  void this.requestTimeout(socket, new Error("Restoring-recipient request timeout")).then(reject);
1994
2009
  }, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
1995
2010
  this.pendingRestoringRecipientRequests.set(requestId, {
1996
- resolve: () => { clearTimeout(timeout); resolve(); },
2011
+ resolve: (published = true) => { clearTimeout(timeout); resolve(published); },
1997
2012
  reject: (error) => { clearTimeout(timeout); reject(error); },
1998
2013
  });
1999
2014
  try {
@@ -152,6 +152,12 @@ export const SESSION_ID_CLAIM_BOUND_MS = 2_500;
152
152
  * locally, with the local accepted-delivery cache as its duplicate protection.
153
153
  */
154
154
  export const LOCAL_RETRY_LOOKUP_BOUND_MS = 300;
155
+ /**
156
+ * The longest a reservation's acknowledgement waits for the shared database to record it, so a sender on another broker
157
+ * that learns of the child after the acknowledgement finds it held. The client's reserve request gives up after 5 s; past
158
+ * this bound the reservation is still written when the database answers.
159
+ */
160
+ export const RESERVATION_PUBLISH_BOUND_MS = 2_500;
155
161
  /** The longest `list` waits for other nodes' sessions; the client's list request gives up after 5 s. */
156
162
  const REMOTE_SESSIONS_BOUND_MS = 2_000;
157
163
  const MAX_SUPERSEDED_HOPS = 8;
@@ -225,6 +231,11 @@ export interface MultiNodeHost {
225
231
  /** Route a held send again as its sender, exactly like a new send (local delivery or the outbox). */
226
232
  dispatch(socket: BrokerConnectedSession["socket"], clientMessage: SendClientMessage, senderId: string): void;
227
233
  revokeReleasedReservation(reservationKey: string, ownerSessionId: string): void;
234
+ /**
235
+ * #5352: whether this broker still holds the reservation the owner made under `capability` (its capability or
236
+ * released-child key): false once it was released, taken by its child, or replaced by a newer reservation of the child.
237
+ */
238
+ holdsReservation(capability: string, ownerSessionId: string): boolean;
228
239
  }
229
240
 
230
241
  export interface MultiNodeRouterOptions {
@@ -364,6 +375,24 @@ interface MirroredReservation {
364
375
  * handed on when the child consumes it (#4488).
365
376
  */
366
377
  readonly superseded?: readonly string[];
378
+ /** #5352: what was written, to write it again if a stale retry of an older reservation of the child ends it. */
379
+ readonly publication?: UnpublishedReservation;
380
+ }
381
+
382
+ /**
383
+ * A reservation made here that the shared database does not hold yet: its write failed, or has not answered. It is
384
+ * written again at each renewal until it lands, or until it is released, consumed or made again (#5352).
385
+ */
386
+ interface UnpublishedReservation {
387
+ readonly capability: string;
388
+ readonly ownerSessionId: string;
389
+ /** The owner's connection when it reserved: a reservation it no longer holds is not written. */
390
+ readonly owner: BrokerConnectedSession | undefined;
391
+ readonly childName: string;
392
+ readonly group: string;
393
+ readonly aliases: readonly string[];
394
+ readonly dormant: boolean;
395
+ readonly options: ReservationOptions;
367
396
  }
368
397
 
369
398
  /** How a mirrored reservation differs from a plain restoring one. */
@@ -474,6 +503,11 @@ export class MultiNodeRouter {
474
503
  this.fail(request, "Pending question route does not authorize this public reply");
475
504
  return;
476
505
  }
506
+ this.refuseRouteUnavailable(request);
507
+ }
508
+
509
+ /** #4997: refuse a reply as retryable (`route_unavailable`): a route that would authorize it may be unreachable. */
510
+ private refuseRouteUnavailable(request: RemoteSendRequest): void {
477
511
  this.host.write(request.socket, {
478
512
  type: "delivery_failed",
479
513
  messageId: request.message.id,
@@ -500,6 +534,9 @@ export class MultiNodeRouter {
500
534
  private readonly mirrored = new Map<string, MirroredReservation>();
501
535
  /** Reservations with a backup-poll wake check queued or running: one each while the store stalls, not a backlog. */
502
536
  private readonly pendingWakeChecks = new Set<string>();
537
+ /** #5352: reservations made here whose shared write has not landed, by reservation key. */
538
+ private readonly unpublished = new Map<string, UnpublishedReservation>();
539
+ private readonly pendingPublishRetries = new Set<string>();
503
540
  private readonly heldIdentities = new Set<string>();
504
541
  private readonly scanning = new Map<string, { rescan: boolean }>();
505
542
  private readonly serials = new Map<string, Promise<void>>();
@@ -1283,6 +1320,11 @@ export class MultiNodeRouter {
1283
1320
  // ---------------------------------------------------------------------------------------------------------
1284
1321
  // Restoring reservations (§5.7): mirror this broker's reservations so senders on any host hold their sends.
1285
1322
 
1323
+ /**
1324
+ * Resolves true once other brokers can find the reservation, or false when its shared write failed or did not answer
1325
+ * within `RESERVATION_PUBLISH_BOUND_MS`: the reservation then holds sends on this broker, and the write is retried at
1326
+ * each renewal until it lands or the reservation ends.
1327
+ */
1286
1328
  restoringReserved(
1287
1329
  capability: string,
1288
1330
  ownerSessionId: string,
@@ -1291,60 +1333,127 @@ export class MultiNodeRouter {
1291
1333
  aliases: readonly string[],
1292
1334
  dormant: boolean,
1293
1335
  options: ReservationOptions = {},
1294
- ): void {
1295
- if (this.closed) return;
1336
+ ): Promise<boolean> {
1337
+ if (this.closed) return Promise.resolve(true);
1296
1338
  const reservationKey = reservationKeyFor(capability);
1297
- const owner = this.host.sessions.get(ownerSessionId);
1298
- const wake = options.wake === true;
1299
- this.serial(`reservation:${reservationKey}`, async () => {
1300
- const previous = this.mirrored.get(reservationKey);
1301
- const reserved = await this.state.reservations.reserve({
1302
- reservationKey,
1303
- ownerSessionId,
1304
- ownerBrokerId: this.brokerId,
1305
- childName,
1306
- childTarget: normalizeTarget(childName),
1307
- aliases: aliases.map(normalizeTarget).filter((alias) => alias.length > 0),
1308
- group,
1309
- dormant,
1310
- wake,
1311
- ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
1312
- staleAfterMs: BROKER_LEASE_STALE_AFTER_MS,
1313
- });
1314
- if (reserved.status === "not-owner") {
1315
- this.host.revokeReleasedReservation(reservationKey, ownerSessionId);
1316
- return;
1317
- }
1318
- if (reserved.status !== "reserved") return;
1319
- // The owner left (or its id was taken over) while the reserve was being written: its departure scanned the
1320
- // mirrors before this one existed, so end the reservation here instead of renewing it for a gone owner.
1321
- if (this.host.sessions.get(ownerSessionId) !== owner) {
1322
- await this.state.reservations.release(reserved.lease);
1323
- await this.wakeHeldOrigins(reservationKey);
1324
- return;
1325
- }
1326
- const woken =
1327
- wake && previous?.woken === true && previous.lease.fencingToken === reserved.lease.fencingToken;
1328
- const superseded = new Set(
1329
- previous?.lease.fencingToken === reserved.lease.fencingToken ? previous.superseded : undefined,
1330
- );
1331
- for (const key of reserved.superseded) {
1332
- superseded.add(key);
1333
- for (const earlier of this.mirrored.get(key)?.superseded ?? []) superseded.add(earlier);
1334
- }
1335
- this.mirrored.set(reservationKey, {
1336
- lease: reserved.lease,
1337
- wake,
1338
- aliases,
1339
- group,
1340
- ...(woken ? { woken } : {}),
1341
- ...(superseded.size > 0 ? { superseded: [...superseded] } : {}),
1342
- ...(isReleasedReservationKey(capability) ? {} : { capability }),
1339
+ const pending: UnpublishedReservation = {
1340
+ capability,
1341
+ ownerSessionId,
1342
+ owner: this.host.sessions.get(ownerSessionId),
1343
+ childName,
1344
+ group,
1345
+ aliases,
1346
+ dormant,
1347
+ options,
1348
+ };
1349
+ this.unpublished.set(reservationKey, pending);
1350
+ this.serial(`reservation:${reservationKey}`, () => this.publishReservation(reservationKey, pending, false));
1351
+ // #5352: the owner is acknowledged once other brokers can find the reservation, so a sender that learns of the
1352
+ // child afterwards is held rather than told it is not found. A database that does not answer is waited for only
1353
+ // up to `RESERVATION_PUBLISH_BOUND_MS`.
1354
+ const written = this.serials.get(`reservation:${reservationKey}`) ?? Promise.resolve();
1355
+ return new Promise<boolean>((resolve) => {
1356
+ const settle = () => resolve(this.unpublished.get(reservationKey) !== pending);
1357
+ const bound = setTimeout(settle, RESERVATION_PUBLISH_BOUND_MS);
1358
+ bound.unref?.();
1359
+ void written.finally(() => {
1360
+ clearTimeout(bound);
1361
+ settle();
1343
1362
  });
1344
- await this.wakeWaitingChild(reservationKey);
1345
1363
  });
1346
1364
  }
1347
1365
 
1366
+ /**
1367
+ * Write a reservation made here to the shared database. It stays unpublished, for the renewal to write again, only
1368
+ * while the write fails. The first write runs in its key's order, so a release or departure after it ends what it
1369
+ * wrote; a `retry` writes nothing once the reservation was released, consumed, replaced or made again, or its owner
1370
+ * left, and ends what it wrote when that happened while it was writing.
1371
+ */
1372
+ private async publishReservation(reservationKey: string, pending: UnpublishedReservation, retry: boolean): Promise<void> {
1373
+ const { capability, ownerSessionId, owner, childName, group, aliases, dormant, options } = pending;
1374
+ if (
1375
+ retry &&
1376
+ (this.unpublished.get(reservationKey) !== pending ||
1377
+ this.host.sessions.get(ownerSessionId) !== owner ||
1378
+ !this.host.holdsReservation(capability, ownerSessionId))
1379
+ ) {
1380
+ if (this.unpublished.get(reservationKey) === pending) this.unpublished.delete(reservationKey);
1381
+ return;
1382
+ }
1383
+ const settled = () => {
1384
+ if (this.unpublished.get(reservationKey) === pending) this.unpublished.delete(reservationKey);
1385
+ };
1386
+ const wake = options.wake === true;
1387
+ const previous = this.mirrored.get(reservationKey);
1388
+ const reserved = await this.state.reservations.reserve({
1389
+ reservationKey,
1390
+ ownerSessionId,
1391
+ ownerBrokerId: this.brokerId,
1392
+ childName,
1393
+ childTarget: normalizeTarget(childName),
1394
+ aliases: aliases.map(normalizeTarget).filter((alias) => alias.length > 0),
1395
+ group,
1396
+ dormant,
1397
+ wake,
1398
+ ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
1399
+ staleAfterMs: BROKER_LEASE_STALE_AFTER_MS,
1400
+ });
1401
+ settled();
1402
+ if (reserved.status === "not-owner") {
1403
+ this.host.revokeReleasedReservation(reservationKey, ownerSessionId);
1404
+ return;
1405
+ }
1406
+ if (reserved.status !== "reserved") return;
1407
+ // The owner left (or its id was taken over) while the reserve was being written: its departure scanned the
1408
+ // mirrors before this one existed, so end the reservation here instead of renewing it for a gone owner. A retry
1409
+ // likewise ends what it wrote for a reservation its child took, or a newer one replaced, meanwhile: those ran
1410
+ // outside this key's order.
1411
+ if (
1412
+ this.host.sessions.get(ownerSessionId) !== owner ||
1413
+ (retry && !this.host.holdsReservation(capability, ownerSessionId))
1414
+ ) {
1415
+ await this.state.reservations.release(reserved.lease);
1416
+ await this.wakeHeldOrigins(reservationKey);
1417
+ if (retry) this.republishSuperseded(reserved.superseded);
1418
+ return;
1419
+ }
1420
+ const woken =
1421
+ wake && previous?.woken === true && previous.lease.fencingToken === reserved.lease.fencingToken;
1422
+ const superseded = new Set(
1423
+ previous?.lease.fencingToken === reserved.lease.fencingToken ? previous.superseded : undefined,
1424
+ );
1425
+ for (const key of reserved.superseded) {
1426
+ superseded.add(key);
1427
+ for (const earlier of this.mirrored.get(key)?.superseded ?? []) superseded.add(earlier);
1428
+ }
1429
+ this.mirrored.set(reservationKey, {
1430
+ lease: reserved.lease,
1431
+ wake,
1432
+ aliases,
1433
+ group,
1434
+ ...(woken ? { woken } : {}),
1435
+ ...(superseded.size > 0 ? { superseded: [...superseded] } : {}),
1436
+ ...(isReleasedReservationKey(capability) ? {} : { capability }),
1437
+ publication: pending,
1438
+ });
1439
+ await this.wakeWaitingChild(reservationKey);
1440
+ }
1441
+
1442
+ /**
1443
+ * #5352: a stale retry ended the newer reservations of its child that it superseded as it wrote: the ones this broker
1444
+ * still holds are written again, in their keys' order.
1445
+ */
1446
+ private republishSuperseded(keys: readonly string[]): void {
1447
+ for (const key of keys) {
1448
+ const publication = this.mirrored.get(key)?.publication;
1449
+ if (publication === undefined || !this.host.holdsReservation(publication.capability, publication.ownerSessionId))
1450
+ continue;
1451
+ this.mirrored.delete(key);
1452
+ this.unpublished.set(key, publication);
1453
+ this.serial(`reservation:${key}`, () => this.publishReservation(key, publication, true));
1454
+ }
1455
+ }
1456
+
1348
1457
  /**
1349
1458
  * #4401: ask the owner to wake a released child it reserved here while sends wait for it, once per reservation.
1350
1459
  * Derived from the shared state on every reserve and backup poll, so a broker that restarted, or a new owner
@@ -1420,6 +1529,8 @@ export class MultiNodeRouter {
1420
1529
  restoringReleased(capability: string, ownerSessionId: string, gone?: string, refusal?: string): void {
1421
1530
  if (this.closed) return;
1422
1531
  const reservationKey = reservationKeyFor(capability);
1532
+ // #5352: a reservation whose write has not landed is not written after its release.
1533
+ if (this.unpublished.get(reservationKey)?.ownerSessionId === ownerSessionId) this.unpublished.delete(reservationKey);
1423
1534
  // Behind the reserve on the same key: a release while the reserve is still being written ends what it wrote.
1424
1535
  this.serial(`reservation:${reservationKey}`, async () => {
1425
1536
  // #4386: asks parked for a released subagent its owner no longer holds end here, as its local ones do; #4992:
@@ -1444,6 +1555,8 @@ export class MultiNodeRouter {
1444
1555
  ? undefined
1445
1556
  : releasedReservationKey(consumed.childName);
1446
1557
  if (reservationKey === undefined) return;
1558
+ // #5352: the child took its reservation; one whose write has not landed is not written now.
1559
+ this.unpublished.delete(reservationKey);
1447
1560
  const result = await this.state.reservations.consume(
1448
1561
  reservationKey,
1449
1562
  consumed.childName === undefined
@@ -1646,8 +1759,21 @@ export class MultiNodeRouter {
1646
1759
  if (this.host.deliveredMessages.lookupForTarget(request.message.id, request.signature, deliveryTargetIdentity(target)) !== "miss")
1647
1760
  return false;
1648
1761
  const asker = { sessionId: target.info.id, identity: deliveryTargetIdentity(target) };
1649
- if (!(await this.routeMayBeElsewhere(request, asker.sessionId, asker.identity).catch(() => false))) return false;
1650
- await this.refuseUnauthorizedReply(request, asker);
1762
+ const elsewhere = this.routeMayBeElsewhere(request, asker.sessionId, asker.identity).catch(() => false);
1763
+ // A shared database that stops answering leaves the reply undecided: it is refused as retryable, once, within the
1764
+ // bound, so neither it nor the sender's later replies wait on that database for good. It authorizes nothing.
1765
+ let bound: ReturnType<typeof setTimeout> | undefined;
1766
+ const expired = new Promise<"expired">((resolve) => {
1767
+ bound = setTimeout(() => resolve("expired"), PRESENCE_REGISTRATION_BOUND_MS);
1768
+ bound.unref?.();
1769
+ });
1770
+ try {
1771
+ const decided = await Promise.race([elsewhere, expired]);
1772
+ if (decided === false) return false;
1773
+ } finally {
1774
+ clearTimeout(bound);
1775
+ }
1776
+ this.refuseRouteUnavailable(request);
1651
1777
  return true;
1652
1778
  }
1653
1779
 
@@ -1928,6 +2054,9 @@ export class MultiNodeRouter {
1928
2054
  if (existing === "expired") {
1929
2055
  lookup.catch((error: Error) => this.report(error));
1930
2056
  await this.adoptSharedRouteWithin(request, target);
2057
+ // #4997: a reply whose ask's route may be on a broker that is down is refused as retryable here too, not by
2058
+ // the local path's final refusal just because the outbox lookup was slow.
2059
+ if (await this.routeUnreachable(request, target)) return;
1931
2060
  request.notFound();
1932
2061
  return;
1933
2062
  }
@@ -2538,7 +2667,11 @@ export class MultiNodeRouter {
2538
2667
  for (const { row, claim } of claimed.rows) {
2539
2668
  const session = this.localSessionFor(identity);
2540
2669
  if (session === undefined) {
2541
- await this.state.outbox.releaseClaim(claim);
2670
+ // The recipient left while the claim was on its way to the database: the row was never written to it, so it
2671
+ // goes back as never claimed. Its sender's broker then still queues it for the recipient's return
2672
+ // (`positionIfRecipientLeft`), instead of reporting the send uncertain once its receipt wait ends.
2673
+ const released = await this.state.outbox.releaseClaim(claim, { unwritten: true });
2674
+ if (released.status === "released") await this.wakeOrigin(row);
2542
2675
  continue;
2543
2676
  }
2544
2677
  if (row.frame.type === "released_child_reply") {
@@ -2985,6 +3118,14 @@ export class MultiNodeRouter {
2985
3118
  const renewed = await this.state.reservations.renew(mirror.lease);
2986
3119
  if (renewed.status !== "renewed" && this.mirrored.get(key) === mirror) this.mirrored.delete(key);
2987
3120
  }
3121
+ // #5352: a reservation whose write failed or did not answer is written again, in order behind its key's steps.
3122
+ for (const [key, pending] of this.unpublished) {
3123
+ if (this.pendingPublishRetries.has(key)) continue;
3124
+ this.pendingPublishRetries.add(key);
3125
+ this.serial(`reservation:${key}`, () =>
3126
+ this.publishReservation(key, pending, true).finally(() => this.pendingPublishRetries.delete(key)),
3127
+ );
3128
+ }
2988
3129
  for (const identity of [...this.heldIdentities]) this.scanIdentity(identity);
2989
3130
  }
2990
3131
 
@@ -279,8 +279,12 @@ export interface OutboxStore {
279
279
  * waiting. Optional: a store without it never extends a sender's wait.
280
280
  */
281
281
  reportSaving?(claim: OutboxClaim): Promise<OutboxRenewClaimResult>;
282
- /** Return the row to `queued`, for example when its recipient disconnected before acknowledging. */
283
- releaseClaim(claim: OutboxClaim): Promise<OutboxReleaseClaimResult>;
282
+ /**
283
+ * Return the row to `queued`, for example when its recipient disconnected before acknowledging. `unwritten`: the
284
+ * claim never wrote the row to any recipient (it left before), so the attempt is not counted and the row reads as
285
+ * never claimed, as it was before this claim.
286
+ */
287
+ releaseClaim(claim: OutboxClaim, options?: { readonly unwritten?: boolean }): Promise<OutboxReleaseClaimResult>;
284
288
  /**
285
289
  * #5038: return every row `claimantId` holds to `queued`, as its own `releaseClaim` would, so a dead broker's
286
290
  * claims stop holding its recipients' queues until they go stale. Resolves to the number of rows released.
@@ -269,6 +269,11 @@ export class RestoringRecipients {
269
269
  };
270
270
  }
271
271
 
272
+ /** #5352: whether `ownerSessionId` still holds the reservation under `key` here (not released, taken or replaced). */
273
+ holds(key: string, ownerSessionId: string): boolean {
274
+ return this.reservations.get(key)?.ownerSessionId === ownerSessionId;
275
+ }
276
+
272
277
  releasedOwner(childName: string): string | undefined {
273
278
  return this.reservations.get(releasedReservationKey(childName))?.ownerSessionId;
274
279
  }
@@ -286,11 +286,12 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
286
286
  });
287
287
  },
288
288
 
289
- releaseClaim(claim) {
289
+ releaseClaim(claim, options) {
290
+ const attempts = options?.unwritten === true ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
290
291
  return withClaim(claim, async (executor) => {
291
292
  await executor.run(
292
293
  `UPDATE ${table} SET state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL,
293
- saving_at = NULL
294
+ saving_at = NULL${attempts}
294
295
  WHERE message_id = ?`,
295
296
  claim.messageId,
296
297
  );