@bastani/atomic 0.9.85 → 0.9.86

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 (125) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  3. package/dist/builtin/intercom/README.md +10 -9
  4. package/dist/builtin/intercom/broker/away-asks.ts +272 -0
  5. package/dist/builtin/intercom/broker/broker.ts +171 -9
  6. package/dist/builtin/intercom/broker/client.ts +5 -3
  7. package/dist/builtin/intercom/broker/held-reply-targets.ts +5 -0
  8. package/dist/builtin/intercom/broker/multinode-router.ts +16 -7
  9. package/dist/builtin/intercom/broker/paths.ts +5 -0
  10. package/dist/builtin/intercom/broker/pending-question-index.ts +124 -0
  11. package/dist/builtin/intercom/broker/released-asker-replies.ts +39 -0
  12. package/dist/builtin/intercom/broker/send-handler.ts +44 -3
  13. package/dist/builtin/intercom/broker/terminal-questions.ts +2 -0
  14. package/dist/builtin/intercom/index.bundle.mjs +799 -177
  15. package/dist/builtin/intercom/package.json +1 -1
  16. package/dist/builtin/intercom/retry-policy.ts +1 -1
  17. package/dist/builtin/intercom/skills/intercom/SKILL.md +29 -35
  18. package/dist/builtin/intercom/types.ts +7 -2
  19. package/dist/builtin/mcp/package.json +1 -1
  20. package/dist/builtin/subagents/CHANGELOG.md +40 -0
  21. package/dist/builtin/subagents/package.json +1 -1
  22. package/dist/builtin/subagents/skills/subagent/SKILL.md +1 -1
  23. package/dist/builtin/subagents/src/extension/index.bundle.mjs +2765 -2719
  24. package/dist/builtin/web-access/package.json +1 -1
  25. package/dist/builtin/workflows/CHANGELOG.md +24 -0
  26. package/dist/builtin/workflows/package.json +1 -1
  27. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  28. package/dist/builtin/workflows/src/extension/index.bundle.mjs +371 -193
  29. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +358 -181
  30. package/dist/builtin/workflows/src/index.js +356 -183
  31. package/dist/builtin/workflows/src/local-worker-entry.mjs +358 -181
  32. package/dist/builtin/workflows/src/shared/worktree-restore-outcome.d.ts +16 -0
  33. package/dist/builtin/workflows/src/workers/workspace-binding.d.ts +13 -2
  34. package/dist/core/agent-session-methods.d.ts +1 -0
  35. package/dist/core/agent-session-methods.d.ts.map +1 -1
  36. package/dist/core/agent-session-methods.js.map +1 -1
  37. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  38. package/dist/core/agent-session-prompt.js +2 -35
  39. package/dist/core/agent-session-prompt.js.map +1 -1
  40. package/dist/core/agent-session-runtime.d.ts +3 -1
  41. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  42. package/dist/core/agent-session-runtime.js +12 -5
  43. package/dist/core/agent-session-runtime.js.map +1 -1
  44. package/dist/core/agent-session-state.d.ts.map +1 -1
  45. package/dist/core/agent-session-state.js +14 -1
  46. package/dist/core/agent-session-state.js.map +1 -1
  47. package/dist/core/agent-session.d.ts +2 -0
  48. package/dist/core/agent-session.d.ts.map +1 -1
  49. package/dist/core/agent-session.js +3 -1
  50. package/dist/core/agent-session.js.map +1 -1
  51. package/dist/core/resume/index.d.ts +1 -1
  52. package/dist/core/resume/index.d.ts.map +1 -1
  53. package/dist/core/resume/index.js +1 -1
  54. package/dist/core/resume/index.js.map +1 -1
  55. package/dist/core/resume/path-mapping.d.ts +10 -0
  56. package/dist/core/resume/path-mapping.d.ts.map +1 -1
  57. package/dist/core/resume/path-mapping.js +20 -0
  58. package/dist/core/resume/path-mapping.js.map +1 -1
  59. package/dist/core/resume/session-resume.d.ts +5 -0
  60. package/dist/core/resume/session-resume.d.ts.map +1 -1
  61. package/dist/core/resume/session-resume.js +24 -9
  62. package/dist/core/resume/session-resume.js.map +1 -1
  63. package/dist/core/session-worktree-snapshots.d.ts +5 -8
  64. package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
  65. package/dist/core/session-worktree-snapshots.js +34 -99
  66. package/dist/core/session-worktree-snapshots.js.map +1 -1
  67. package/dist/core/skill-catalog.d.ts +11 -0
  68. package/dist/core/skill-catalog.d.ts.map +1 -1
  69. package/dist/core/skill-catalog.js +31 -0
  70. package/dist/core/skill-catalog.js.map +1 -1
  71. package/dist/core/tasks/agent-adapter.d.ts +2 -0
  72. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  73. package/dist/core/tasks/agent-adapter.js +5 -1
  74. package/dist/core/tasks/agent-adapter.js.map +1 -1
  75. package/dist/core/tasks/supervisor.d.ts +17 -0
  76. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  77. package/dist/core/tasks/supervisor.js +12 -6
  78. package/dist/core/tasks/supervisor.js.map +1 -1
  79. package/dist/core/tasks/task-view-source.d.ts +10 -0
  80. package/dist/core/tasks/task-view-source.d.ts.map +1 -1
  81. package/dist/core/tasks/task-view-source.js +24 -1
  82. package/dist/core/tasks/task-view-source.js.map +1 -1
  83. package/dist/core/worktree-snapshot/best-restore.d.ts +45 -0
  84. package/dist/core/worktree-snapshot/best-restore.d.ts.map +1 -0
  85. package/dist/core/worktree-snapshot/best-restore.js +92 -0
  86. package/dist/core/worktree-snapshot/best-restore.js.map +1 -0
  87. package/dist/core/worktree-snapshot/git.d.ts +2 -2
  88. package/dist/core/worktree-snapshot/git.d.ts.map +1 -1
  89. package/dist/core/worktree-snapshot/git.js +2 -5
  90. package/dist/core/worktree-snapshot/git.js.map +1 -1
  91. package/dist/core/worktree-snapshot/index.d.ts +1 -0
  92. package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
  93. package/dist/core/worktree-snapshot/index.js +1 -0
  94. package/dist/core/worktree-snapshot/index.js.map +1 -1
  95. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  96. package/dist/core/worktree-snapshot/restore.js +18 -2
  97. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  98. package/dist/index.d.ts +3 -2
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +1 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/modes/interactive/chat-autocomplete.d.ts +7 -0
  103. package/dist/modes/interactive/chat-autocomplete.d.ts.map +1 -0
  104. package/dist/modes/interactive/chat-autocomplete.js +85 -0
  105. package/dist/modes/interactive/chat-autocomplete.js.map +1 -0
  106. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/task-transcript-page.js +8 -0
  108. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  109. package/dist/modes/interactive/interactive-autocomplete.js +3 -79
  110. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  111. package/dist/modes/interactive/skill-command-autocomplete.d.ts +6 -0
  112. package/dist/modes/interactive/skill-command-autocomplete.d.ts.map +1 -1
  113. package/dist/modes/interactive/skill-command-autocomplete.js +18 -2
  114. package/dist/modes/interactive/skill-command-autocomplete.js.map +1 -1
  115. package/docs/background-tasks.md +1 -1
  116. package/docs/intercom/operations.md +4 -4
  117. package/docs/intercom/reference.md +39 -8
  118. package/docs/intercom.md +26 -9
  119. package/docs/skills.md +3 -1
  120. package/docs/subagents.md +2 -0
  121. package/docs/workflows/api-reference.md +3 -3
  122. package/docs/workflows/operations.md +2 -2
  123. package/docs/worktree-snapshots.md +10 -4
  124. package/npm-shrinkwrap.json +32 -32
  125. package/package.json +3 -3
@@ -34,6 +34,7 @@ import { acquireSocketReplacementLock } from "./socket-replacement-lock.js";
34
34
  import { type BrokerWatchdog, startBrokerWatchdog } from "./watchdog.js";
35
35
  import { retractBrokerStartAnnouncement } from "./start-announcement.js";
36
36
  import {
37
+ getBrokerAwayAsksPath,
37
38
  getBrokerDeliveredMessagesPath,
38
39
  getBrokerPidPath,
39
40
  getBrokerWatchdogLogPath,
@@ -117,6 +118,8 @@ import {
117
118
  } from "./group-membership.js";
118
119
  import { replyToList } from "./list-reply.js";
119
120
  import { type PendingQuestion, PendingQuestionIndex } from "./pending-question-index.js";
121
+ import { AwayAsks } from "./away-asks.js";
122
+ import { TERMINAL_CHILD_ASK_REFUSAL } from "../recipient-purpose.js";
120
123
  import { type ReceiptSender, RecipientReceipts, UNCERTAIN_RECEIPT_REASON } from "./recipient-receipts.js";
121
124
  import { matchStagePathSegments } from "../workflow-stage-path-matching.js";
122
125
  import { DELIVERED_MESSAGE_TTL_MS, RECIPIENT_RECEIPT_TIMEOUT_MS } from "../retry-policy.js";
@@ -232,6 +235,12 @@ type ConnectedSession = BrokerConnectedSession;
232
235
 
233
236
  interface PendingReleasedReplyAck {
234
237
  readonly handoffId: string;
238
+ /** Who the reply is from: the replier, or the recipient that ended, for a failed ask the broker made (#4751). */
239
+ readonly from: SessionInfo;
240
+ /** A failed ask the broker made: no replier waits for its outcome, so the broker keeps it until it is delivered. */
241
+ readonly synthetic?: true;
242
+ /** The reply itself, delivered to the child as an ordinary send when no call of the child waits for it (#4751). */
243
+ readonly message: Message;
235
244
  readonly timer: ReturnType<typeof setTimeout>;
236
245
  readonly socket: net.Socket;
237
246
  readonly attemptId?: string;
@@ -366,6 +375,14 @@ class IntercomBroker {
366
375
  * that does serve one reads what its predecessors recorded, so a retried send is still deduplicated across restarts.
367
376
  */
368
377
  private openDeliveredMessages(): DeliveredMessageCache {
378
+ // #4751: what waits for away sessions is kept with the same lifetime as the delivered-message authority.
379
+ if (this.deliveredMessageCache === undefined) {
380
+ try {
381
+ this.pendingQuestions.useAwayStore(new AwayAsks(getBrokerAwayAsksPath()));
382
+ } catch (error) {
383
+ console.error(`Intercom broker keeps away asks in memory only: ${error instanceof Error ? error.message : String(error)}`);
384
+ }
385
+ }
369
386
  this.deliveredMessageCache ??= new DeliveredMessageCache(
370
387
  DELIVERED_MESSAGE_TTL_MS,
371
388
  DELIVERED_MESSAGE_MAX_ENTRIES,
@@ -381,7 +398,8 @@ class IntercomBroker {
381
398
  private sessionIdReclaim = new SessionIdReclaim();
382
399
  private pendingQuestions = new PendingQuestionIndex();
383
400
  private receipts = new RecipientReceipts<ConnectedSession>();
384
- private releasedAskerReplies = new ReleasedAskerReplies(undefined, undefined, undefined, () => {
401
+ // #4751: an ask has no expiry, so a released asker's route lasts until the child or its owner ends or it is back.
402
+ private releasedAskerReplies = new ReleasedAskerReplies(undefined, Number.POSITIVE_INFINITY, undefined, () => {
385
403
  console.error("Intercom broker released-asker reply route capacity reached; dropped routes are counted in broker_status");
386
404
  });
387
405
  private releasedReplyAcks = new Map<string, PendingReleasedReplyAck>();
@@ -1933,10 +1951,30 @@ class IntercomBroker {
1933
1951
  }
1934
1952
  // Multi-node S5: frames written while registration waited for the presence lease follow `registered`.
1935
1953
  flushHeldWrites(socket, held);
1954
+ // #4751: a session back under its id takes up the asks it sent or was sent before it went away.
1955
+ this.pendingQuestions.restoreDormant(id, rejoined?.registrationReturnAddress, (sessionId) =>
1956
+ this.sessions.has(sessionId),
1957
+ );
1958
+ // What was held for it while it was away (replies, failed asks) is delivered once: a recipient that confirms
1959
+ // saves releases each when saved, and its inbox shows a redelivered copy only once.
1960
+ const returnAddress = rejoined?.registrationReturnAddress;
1961
+ for (const held of this.pendingQuestions.heldForAsker(returnAddress)) {
1962
+ writeMessageIfOpen(socket, { type: "message", from: held.from, message: held.message });
1963
+ if (clientMessage.acknowledgesReceipt !== true)
1964
+ this.pendingQuestions.releaseHeld(held.message.id, returnAddress);
1965
+ }
1936
1966
  // #3760: a restored subagent is back under the capability its owner reserved it with; the sends held
1937
1967
  // for it while it was being restored go out now, once each and in the order they arrived.
1938
1968
  const registered = info.name?.trim();
1939
1969
  if (registered !== undefined && supervisorId !== undefined) {
1970
+ // #4751: a released subagent back under its owner takes up the routes of its pending asks, including one
1971
+ // whose reply is held for it, so their replies reach it as a live asker.
1972
+ for (const question of this.pendingQuestions.takeParkedAskers(registered, supervisorId))
1973
+ this.pendingQuestions.record(id, question.targetSessionId, question.messageId);
1974
+ for (const route of this.releasedAskerReplies.takeChild(registered, supervisorId))
1975
+ this.pendingQuestions.record(id, route.replierSessionId, route.questionId);
1976
+ for (const held of this.pendingQuestions.takeHeldForReleasedChild(registered, supervisorId))
1977
+ writeMessageIfOpen(socket, { type: "message", from: held.from, message: held.message });
1940
1978
  for (const question of this.pendingQuestions.takeParked(registered, supervisorId)) {
1941
1979
  this.pendingQuestions.record(question.senderSessionId, id, question.messageId);
1942
1980
  const asker = this.sessions.get(question.senderSessionId);
@@ -1987,7 +2025,8 @@ class IntercomBroker {
1987
2025
  }
1988
2026
 
1989
2027
  case "unregister": {
1990
- this.disconnectSession(currentId);
2028
+ // #4751: a session that can be resumed is only away; one that cannot has ended.
2029
+ this.disconnectSession(currentId, clientMessage.resumable !== true);
1991
2030
  setId(null);
1992
2031
  this.scheduleShutdownCheck();
1993
2032
  break;
@@ -2173,6 +2212,9 @@ class IntercomBroker {
2173
2212
  for (const child of validation.children) {
2174
2213
  this.reserveReleasedChild(currentId, owner.registrationGroup, child);
2175
2214
  this.releasedAskerReplies.attach(child.childName, currentId);
2215
+ // #4751: a failed ask kept for the child wakes it again, so it is delivered.
2216
+ if (child.wake && this.pendingQuestions.hasHeldForReleasedChild(child.childName, currentId))
2217
+ this.wakeRestoringRecipientOwner({ ownerSessionId: currentId, childName: child.childName });
2176
2218
  this.dispatchHeldSends(this.departedChildren.supersede(currentId, child.childName));
2177
2219
  }
2178
2220
  writeMessageIfOpen(socket, { type: "released_children_ack", requestId: clientMessage.requestId });
@@ -2554,7 +2596,10 @@ class IntercomBroker {
2554
2596
  }
2555
2597
  const pending = this.releasedReplyAcks.get(clientMessage.messageId);
2556
2598
  if (pending?.ownerSessionId === currentId && pending.handoffId === clientMessage.handoffId) {
2557
- this.settleReleasedReply(clientMessage.messageId, clientMessage.accepted ? "accepted" : "refused");
2599
+ this.settleReleasedReply(
2600
+ clientMessage.messageId,
2601
+ clientMessage.accepted ? "accepted" : clientMessage.deliverToChild === true ? "deliver" : "refused",
2602
+ );
2558
2603
  }
2559
2604
  break;
2560
2605
  }
@@ -2562,6 +2607,9 @@ class IntercomBroker {
2562
2607
  case "received": {
2563
2608
  if (typeof clientMessage.messageId !== "string") throw new Error("Invalid received message");
2564
2609
  const recipient = this.sessions.get(currentId);
2610
+ // #4751: only the asker a message is held for, proven by its return address, releases it.
2611
+ if (recipient !== undefined)
2612
+ this.pendingQuestions.releaseHeld(clientMessage.messageId, recipient.registrationReturnAddress);
2565
2613
  if (recipient?.acknowledgesReceipt === true) {
2566
2614
  this.multiNode?.received(recipient, clientMessage.messageId);
2567
2615
  this.receipts.settle(clientMessage.messageId, deliveryTargetIdentity(recipient), recipient);
@@ -2593,6 +2641,7 @@ class IntercomBroker {
2593
2641
  case "presence":
2594
2642
  case "join_group":
2595
2643
  case "leave_group": {
2644
+ const wasTerminal = this.sessions.get(currentId)?.info.replyCapability === "terminal";
2596
2645
  handleBrokerPresence(
2597
2646
  socket,
2598
2647
  clientMessage,
@@ -2602,6 +2651,9 @@ class IntercomBroker {
2602
2651
  this.pendingQuestions,
2603
2652
  );
2604
2653
  const updated = this.sessions.get(currentId);
2654
+ // #4751: a recipient that can no longer answer fails the asks of released subagents waiting for it.
2655
+ if (updated !== undefined && !wasTerminal && updated.info.replyCapability === "terminal")
2656
+ this.failReleasedAsksTo(updated.info, updated.socket, TERMINAL_CHILD_ASK_REFUSAL, "terminal");
2605
2657
  if (updated !== undefined) this.multiNode?.sessionUpdated(updated);
2606
2658
  break;
2607
2659
  }
@@ -2658,12 +2710,28 @@ class IntercomBroker {
2658
2710
  });
2659
2711
  return true;
2660
2712
  }
2713
+ this.handOffReleasedReply(route, from.info, message, socket, attemptId);
2714
+ return true;
2715
+ };
2716
+
2717
+ /** Hand a reply to a released subagent's ask to its owner, which saves it for a waiting call or lets it through. */
2718
+ private handOffReleasedReply(
2719
+ route: ReleasedAskerReplyRoute,
2720
+ from: SessionInfo,
2721
+ message: Message & { readonly replyTo: string },
2722
+ socket: net.Socket,
2723
+ attemptId?: string,
2724
+ synthetic = false,
2725
+ ): void {
2661
2726
  const owner = this.sessions.get(route.ownerSessionId);
2662
2727
  const timer = setTimeout(() => this.settleReleasedReply(message.id, "uncertain"), RECIPIENT_RECEIPT_TIMEOUT_MS);
2663
2728
  timer.unref?.();
2664
2729
  const handoffId = randomUUID();
2665
2730
  const pending: PendingReleasedReplyAck = {
2666
2731
  handoffId,
2732
+ from,
2733
+ ...(synthetic ? { synthetic: true as const } : {}),
2734
+ message,
2667
2735
  timer,
2668
2736
  socket,
2669
2737
  ...(attemptId === undefined ? {} : { attemptId }),
@@ -2680,19 +2748,52 @@ class IntercomBroker {
2680
2748
  childName: route.childName,
2681
2749
  handoffId,
2682
2750
  replyTo: route.questionId,
2683
- from: from.info,
2751
+ from,
2684
2752
  message,
2685
2753
  });
2686
2754
  if (!written) this.settleReleasedReply(message.id, "refused");
2687
- return true;
2688
- };
2755
+ }
2756
+
2757
+ /**
2758
+ * #4751: a recipient that ended, or can no longer answer, fails the asks of released subagents that wait for it: each
2759
+ * gets a failed-ask message through the same owner handoff as a reply.
2760
+ */
2761
+ private failReleasedAsksTo(target: SessionInfo, socket: net.Socket, reason: string, idPrefix: string): void {
2762
+ for (const route of this.releasedAskerReplies.takeForReplier(target.id)) {
2763
+ this.handOffReleasedReply(
2764
+ route,
2765
+ target,
2766
+ {
2767
+ id: `${idPrefix}:${randomUUID()}`,
2768
+ timestamp: Date.now(),
2769
+ replyTo: route.questionId,
2770
+ replyError: reason,
2771
+ content: { text: reason },
2772
+ },
2773
+ socket,
2774
+ undefined,
2775
+ true,
2776
+ );
2777
+ }
2778
+ }
2689
2779
 
2690
- private settleReleasedReply(messageId: string, outcome: "accepted" | "refused" | "uncertain"): void {
2780
+ private settleReleasedReply(messageId: string, outcome: "accepted" | "refused" | "uncertain" | "deliver"): void {
2691
2781
  const pending = this.releasedReplyAcks.get(messageId);
2692
2782
  if (pending === undefined) return;
2693
2783
  clearTimeout(pending.timer);
2694
2784
  this.releasedReplyAcks.delete(messageId);
2695
2785
  const attempt = pending.attemptId === undefined ? {} : { attemptId: pending.attemptId };
2786
+ if (outcome === "deliver" && this.deliverReplyToReleasedChild(pending)) return;
2787
+ if (pending.synthetic === true && outcome !== "accepted") {
2788
+ // #4751: the owner did not save the failed ask; it is kept for the child, which gets it when its owner reserves
2789
+ // or wakes it again and it registers.
2790
+ this.pendingQuestions.holdForReleasedChild(pending.childName, pending.ownerSessionId, {
2791
+ askerSessionId: pending.route.askerSessionId,
2792
+ from: pending.from,
2793
+ message: pending.message,
2794
+ });
2795
+ return;
2796
+ }
2696
2797
  if (outcome === "accepted") {
2697
2798
  this.deliveredMessages.settleQuestion(pending.questionId);
2698
2799
  writeMessageIfOpen(pending.socket, { type: "delivered", messageId, ...attempt });
@@ -2896,6 +2997,50 @@ class IntercomBroker {
2896
2997
  return true;
2897
2998
  };
2898
2999
 
3000
+ /**
3001
+ * #4751: a reply to an ask of a released subagent whose call no longer waits for it is delivered like any other send
3002
+ * to the child: held for it, waking it, and its ask's route comes back with it. False when it cannot be held.
3003
+ */
3004
+ private deliverReplyToReleasedChild(pending: PendingReleasedReplyAck): boolean {
3005
+ const replier = this.sessions.get(pending.route.replierSessionId);
3006
+ if (replier === undefined || replier.socket !== pending.socket) {
3007
+ // A failed ask whose recipient ended: there is no sender to hold a send for, so the child gets the message when
3008
+ // its owner wakes it and it registers again.
3009
+ if (pending.message.replyError === undefined) return false;
3010
+ this.pendingQuestions.holdForReleasedChild(pending.childName, pending.ownerSessionId, {
3011
+ askerSessionId: pending.route.askerSessionId,
3012
+ from: pending.from,
3013
+ message: pending.message,
3014
+ });
3015
+ this.wakeRestoringRecipientOwner({ ownerSessionId: pending.ownerSessionId, childName: pending.childName });
3016
+ return true;
3017
+ }
3018
+ this.pendingQuestions.parkAsker(pending.childName, pending.ownerSessionId, {
3019
+ senderSessionId: pending.route.askerSessionId,
3020
+ targetSessionId: pending.route.replierSessionId,
3021
+ messageId: pending.questionId,
3022
+ });
3023
+ const held = this.holdForRestoringRecipient({
3024
+ socket: pending.socket,
3025
+ from: replier,
3026
+ clientMessage: {
3027
+ type: "send",
3028
+ to: pending.childName,
3029
+ message: pending.message,
3030
+ // The replier's client sent a `send`, which always waits for a held recipient.
3031
+ awaitRestoringRecipient: true,
3032
+ ...(pending.attemptId === undefined ? {} : { attemptId: pending.attemptId }),
3033
+ },
3034
+ target: pending.childName,
3035
+ messageId: pending.message.id,
3036
+ ...(pending.attemptId === undefined ? {} : { attemptId: pending.attemptId }),
3037
+ });
3038
+ // The route stays with the owner, so a reply whose held delivery fails (the child does not wake in time) can be
3039
+ // sent again and wake the child again; the child's inbox shows a reply once however often it arrives.
3040
+ if (held) this.releasedAskerReplies.restore(pending.route, pending.ownerSessionId);
3041
+ return held;
3042
+ }
3043
+
2899
3044
  /** #4639: a subagent whose session is gone: hold the send for its return or its owner's verdict, or refuse it with why. */
2900
3045
  private holdForDepartedChild(held: HeldSend, target: string, from: ConnectedSession, canHold: boolean): boolean {
2901
3046
  const admission = this.departedChildren.admit(target, { id: from.info.id, info: from.info }, held, canHold);
@@ -3052,7 +3197,8 @@ class IntercomBroker {
3052
3197
  this.dispatchHeldSends(this.departedChildren.adoptOrphans(ownerSessionId, owner.registrationReturnAddress));
3053
3198
  }
3054
3199
 
3055
- private disconnectSession(sessionId: string): void {
3200
+ /** `ended`: the session said goodbye, so it is not coming back; otherwise its connection only dropped. */
3201
+ private disconnectSession(sessionId: string, ended = false): void {
3056
3202
  const departed = this.sessions.get(sessionId);
3057
3203
  if (!departed) return;
3058
3204
  // #4642: the sessions a connection hosts leave with it, and a hosted session leaves its host's index.
@@ -3090,6 +3236,10 @@ class IntercomBroker {
3090
3236
  unanswered,
3091
3237
  this.restoringRecipients.releasedOwner(departed.registrationName),
3092
3238
  );
3239
+ } else if (departed.supervisorId === undefined && !ended) {
3240
+ // #4751: an ask has no expiry and survives its asker's restart or release: the route waits for the asker.
3241
+ this.pendingQuestions.keepDormant(unanswered, departed.registrationReturnAddress);
3242
+ this.pendingQuestions.markAwayAsker(sessionId, departed.registrationReturnAddress);
3093
3243
  }
3094
3244
  this.releasedAskerReplies.dropOwner(sessionId);
3095
3245
  for (const [messageId, pending] of [...this.releasedReplyAcks]) {
@@ -3102,7 +3252,19 @@ class IntercomBroker {
3102
3252
  const parked = childName !== undefined && releasedOwner !== undefined && releasedOwner === departed.supervisorId;
3103
3253
  if (parked) {
3104
3254
  this.pendingQuestions.parkTarget(sessionId, childName, releasedOwner);
3255
+ } else if (!ended && departed.supervisorId === undefined && departed.hostedBy === undefined) {
3256
+ // #4751: a recipient whose connection dropped without ending its session may restart; its asks stay pending.
3257
+ this.pendingQuestions.keepDormant(this.pendingQuestions.takeForTarget(sessionId));
3105
3258
  } else {
3259
+ if (ended) {
3260
+ // #4751: an away asker's ask to it fails with a message held until the asker is back; a session that ended
3261
+ // for good is waited for by nothing.
3262
+ const reason = `Session "${departed.info.name ?? sessionId}" ended before replying`;
3263
+ this.pendingQuestions.failDormantForTarget(departed.info, reason, "recipient-ended");
3264
+ this.failReleasedAsksTo(departed.info, departed.socket, reason, "recipient-ended");
3265
+ if (departed.supervisorId === undefined)
3266
+ this.pendingQuestions.dropAway(departed.registrationReturnAddress);
3267
+ }
3106
3268
  this.failParkedQuestions(this.pendingQuestions.takeForTarget(sessionId), departed.info.name);
3107
3269
  }
3108
3270
  // #4639: a subagent that left without being released: hold sends to it until it is back or its owner says why. An
@@ -3173,7 +3335,7 @@ class IntercomBroker {
3173
3335
  }
3174
3336
  this.workflowInvocationClaims.delete(sessionId);
3175
3337
  this.sessions.delete(sessionId);
3176
- this.multiNode?.sessionLeft(departed, parked ? { ownerSessionId: releasedOwner, childName } : undefined);
3338
+ this.multiNode?.sessionLeft(departed, parked ? { ownerSessionId: releasedOwner, childName } : undefined, ended);
3177
3339
  this.sessionIdReclaim.retire(sessionId, departed.registrationReturnAddress);
3178
3340
  if (isAgentRecipient(departed.info)) this.broadcastToMemberships({ type: "session_left", sessionId }, sessionGroups(departed.info), sessionId);
3179
3341
  for (const send of unreserved) this.dispatchSend(send.socket, send.clientMessage, send.senderId);
@@ -1399,7 +1399,8 @@ export class IntercomClient extends EventEmitter {
1399
1399
  throw new Error(`Unknown broker message type: ${brokerMessage.type}`);
1400
1400
  }
1401
1401
  }
1402
- async disconnect(): Promise<void> {
1402
+ /** `resumable`: this session can be resumed later, so the asks it sent or was sent stay pending (#4751). */
1403
+ async disconnect(options: { readonly resumable?: boolean } = {}): Promise<void> {
1403
1404
  // A connect still in progress (or waiting to retry) is cancelled: it closes any socket it opened and never
1404
1405
  // registers (#3904).
1405
1406
  if (this.connectAttempt !== undefined && this._sessionId === null) {
@@ -1435,7 +1436,7 @@ export class IntercomClient extends EventEmitter {
1435
1436
  socket.once("close", onClose);
1436
1437
  socket.once("error", onError);
1437
1438
  try {
1438
- writeMessage(socket, { type: "unregister" });
1439
+ writeMessage(socket, { type: "unregister", ...(options.resumable === true ? { resumable: true as const } : {}) });
1439
1440
  socket.end();
1440
1441
  } catch {
1441
1442
  // Disconnect should still finish even if the unregister write fails.
@@ -1721,7 +1722,7 @@ export class IntercomClient extends EventEmitter {
1721
1722
  return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName });
1722
1723
  }
1723
1724
 
1724
- acknowledgeReleasedChildReply(reply: ReleasedChildReply, accepted: boolean): boolean {
1725
+ acknowledgeReleasedChildReply(reply: ReleasedChildReply, accepted: boolean, deliverToChild = false): boolean {
1725
1726
  if (!this.socket || this.socket.destroyed) return false;
1726
1727
  this.requireBrokerProtocol("released_child_reply_ack");
1727
1728
  writeMessage(this.socket, {
@@ -1729,6 +1730,7 @@ export class IntercomClient extends EventEmitter {
1729
1730
  messageId: reply.message.id,
1730
1731
  handoffId: reply.handoffId,
1731
1732
  accepted,
1733
+ ...(deliverToChild ? { deliverToChild: true as const } : {}),
1732
1734
  });
1733
1735
  return true;
1734
1736
  }
@@ -0,0 +1,5 @@
1
+ /** The `queued` frame's target for a send waiting in the shared outbox for an offline session (decision 1). */
2
+ export const OFFLINE_SESSION_TARGET = "offline session";
3
+
4
+ /** The `queued` frame's target for a reply held for its asker while the asker is closed (#4751). */
5
+ export const HELD_FOR_AWAY_ASKER_TARGET = "held for asker";
@@ -1,3 +1,4 @@
1
+ import { OFFLINE_SESSION_TARGET } from "./held-reply-targets.js";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { hostname } from "node:os";
3
4
  import { normalizeGroup } from "../group.js";
@@ -88,8 +89,7 @@ export { readSharedStorageSetting } from "./shared-storage-setting.js";
88
89
  * recipient. Shorter than the 20 s hold, so a lost `outcome` hint for a held send is noticed before it times out.
89
90
  */
90
91
  export const MULTI_NODE_OUTCOME_POLL_INTERVAL_MS = 5_000;
91
- /** The `queued` frame's target for a send waiting in the shared outbox for an offline session (decision 1). */
92
- export const OFFLINE_SESSION_TARGET = "offline session";
92
+ export { OFFLINE_SESSION_TARGET };
93
93
  /** A send for another node while the shared database cannot be reached (spec §8, "Database unavailable"). */
94
94
  export const SHARED_STORAGE_UNAVAILABLE_REASON =
95
95
  "Session not found on this node, and Intercom could not reach the shared storage database to look for it on other nodes. Try again once the database is available.";
@@ -516,8 +516,11 @@ export class MultiNodeRouter {
516
516
  }
517
517
  }
518
518
 
519
- /** A session left (cleanly or not): it stays known, so sends to it are queued until it returns anywhere. */
520
- sessionLeft(session: BrokerConnectedSession, released?: ReleasedTarget): void {
519
+ /**
520
+ * A session left (cleanly or not): it stays known, so sends to it are queued until it returns anywhere. `ended`: it
521
+ * ended for good; otherwise a top-level session is only away, and its asks, sent and received, stay open (#4751).
522
+ */
523
+ sessionLeft(session: BrokerConnectedSession, released?: ReleasedTarget, ended = true): void {
521
524
  const entry = this.presence.get(session);
522
525
  if (this.closed || entry === undefined) return;
523
526
  this.presence.delete(session);
@@ -544,9 +547,15 @@ export class MultiNodeRouter {
544
547
  for (const inflight of claims) await this.state.outbox.releaseClaim(inflight.claim);
545
548
  // #4386: asks to a released subagent are parked before its presence ends; registering again on any node takes
546
549
  // that presence over first, so its rebinding always finds them.
547
- await this.state.pendingAsks
548
- .pruneSender(sessionId)
549
- .then(() => settleAsksToDeparted(this.state, sessionId, released))
550
+ // #4751: a top-level session that is only away keeps its asks: a reply to it is queued in the outbox like any
551
+ // send to an offline session, and its own recipient may still answer once it is back.
552
+ const away = session.supervisorId === undefined && !ended;
553
+ await (away ? Promise.resolve() : this.state.pendingAsks.pruneSender(sessionId).then(() => undefined))
554
+ .then(() =>
555
+ away
556
+ ? this.state.pendingAsks.takeParked(sessionId).then(() => undefined)
557
+ : settleAsksToDeparted(this.state, sessionId, released),
558
+ )
550
559
  .catch((error: Error) => this.report(error));
551
560
  if (entry.lease !== undefined) {
552
561
  await this.state.leases.release(entry.lease);
@@ -61,6 +61,11 @@ export function getBrokerDeliveredMessagesPath(agentDir: string = getAgentDir())
61
61
  return join(getIntercomDirPath(agentDir), "delivered-messages.sqlite");
62
62
  }
63
63
 
64
+ /** #4751: asks that wait for away sessions, and the replies held for away askers; owner-only. */
65
+ export function getBrokerAwayAsksPath(agentDir: string = getAgentDir()): string {
66
+ return join(getIntercomDirPath(agentDir), "away-asks.sqlite");
67
+ }
68
+
64
69
  /** Owner-only HMAC key paired with durable accepted-operation authority. */
65
70
  export function getBrokerDeliveredMessagesKeyPath(agentDir: string = getAgentDir()): string {
66
71
  return join(getIntercomDirPath(agentDir), "delivered-messages.key");
@@ -1,3 +1,5 @@
1
+ import type { Message, SessionInfo } from "../types.js";
2
+ import { AwayAsks, type HeldAwayMessage } from "./away-asks.js";
1
3
  export interface PendingQuestion {
2
4
  senderSessionId: string;
3
5
  targetSessionId: string;
@@ -7,7 +9,129 @@ export interface PendingQuestion {
7
9
  /** Tracks delivered questions until their reply or either peer's departure. */
8
10
  export class PendingQuestionIndex {
9
11
  private readonly questions = new Map<string, PendingQuestion[]>();
12
+ /**
13
+ * #4751: questions whose asker, or whose recipient, is away (closed without ending its session, or released), and
14
+ * the replies held for an away asker. An ask has no expiry, so these wait for that session to register again.
15
+ */
16
+ private away: AwayAsks | undefined;
17
+
18
+ /** Keep what waits for away sessions in this store (the broker's durable one); in memory until then. */
19
+ useAwayStore(store: AwayAsks): void {
20
+ this.away = store;
21
+ }
22
+
23
+ private awayAsks(): AwayAsks {
24
+ this.away ??= new AwayAsks();
25
+ return this.away;
26
+ }
27
+
28
+ /** Keep questions whose peer is away until it is back. */
29
+ keepDormant(questions: readonly PendingQuestion[], senderReturnAddress?: string): void {
30
+ if (questions.length === 0) return;
31
+ this.awayAsks().keep(questions, senderReturnAddress);
32
+ }
33
+
34
+ /** The asker is away now too: its questions kept for an away recipient wait for it under its return address (#4761). */
35
+ markAwayAsker(senderSessionId: string, senderReturnAddress: string | undefined): void {
36
+ this.away?.markAsker(senderSessionId, senderReturnAddress);
37
+ }
38
+
39
+ /** Whether `replierSessionId` answers the kept question `questionId`, whose asker is away (#4751). */
40
+ hasDormantReply(questionId: string, replierSessionId: string): boolean {
41
+ return this.awayAsks().question(questionId, replierSessionId) !== undefined;
42
+ }
43
+
44
+ /** The kept question `questionId` that `replierSessionId` answers while its asker is away (#4751). */
45
+ dormantReply(
46
+ questionId: string,
47
+ replierSessionId: string,
48
+ ): (PendingQuestion & { readonly senderReturnAddress?: string }) | undefined {
49
+ return this.awayAsks().question(questionId, replierSessionId);
50
+ }
51
+
52
+ /** A session is back under its id: its kept questions route again once both of their peers are connected. */
53
+ restoreDormant(
54
+ sessionId: string,
55
+ returnAddress: string | undefined,
56
+ isConnected: (sessionId: string) => boolean,
57
+ ): PendingQuestion[] {
58
+ const restored = this.awayAsks().restore(sessionId, returnAddress, isConnected);
59
+ for (const question of restored) this.record(question.senderSessionId, question.targetSessionId, question.messageId);
60
+ return restored;
61
+ }
62
+
63
+ /**
64
+ * Kept questions to a recipient that ended or can no longer answer. Their askers are away, so each gets a failed-ask
65
+ * message held until it is back (#4751).
66
+ */
67
+ failDormantForTarget(target: SessionInfo, reason: string, idPrefix: string): void {
68
+ this.awayAsks().failForTarget(target, reason, idPrefix);
69
+ }
70
+
71
+ /** The session ended for good: nothing waits for it any more. */
72
+ dropAway(returnAddress: string | undefined): void {
73
+ this.awayAsks().drop(returnAddress);
74
+ }
75
+
76
+ /** Hold a reply for the away asker of `question`, delivered once when it registers again (#4751). */
77
+ holdForAwayAsker(
78
+ question: PendingQuestion & { readonly senderReturnAddress: string },
79
+ from: SessionInfo,
80
+ message: Message,
81
+ ): void {
82
+ this.awayAsks().hold(question, from, message);
83
+ }
84
+
85
+ /** Whether this reply is already held for its asker. */
86
+ isHeldForAwayAsker(messageId: string, replierSessionId: string): boolean {
87
+ return this.awayAsks().isHeld(messageId, replierSessionId);
88
+ }
89
+
90
+ /** What is held for the asker that proves itself by its return address, in the order it was held. */
91
+ heldForAsker(askerReturnAddress: string | undefined): HeldAwayMessage[] {
92
+ return this.awayAsks().held(askerReturnAddress);
93
+ }
94
+
95
+ /** The verified asker saved a held message. */
96
+ releaseHeld(messageId: string, askerReturnAddress: string | undefined): void {
97
+ this.away?.release(messageId, askerReturnAddress);
98
+ }
99
+
10
100
  private readonly parked = new Map<string, { ownerSessionId: string; questions: PendingQuestion[] }>();
101
+ /** #4751: asks of released subagents whose reply is held for them, by owner and child name. */
102
+ private readonly parkedAskers = new Map<string, PendingQuestion[]>();
103
+
104
+ parkAsker(childName: string, ownerSessionId: string, question: PendingQuestion): void {
105
+ const key = JSON.stringify([ownerSessionId, childName.trim().toLowerCase()]);
106
+ this.parkedAskers.set(key, [...(this.parkedAskers.get(key) ?? []), question]);
107
+ }
108
+
109
+ /** #4751: failed-ask messages for a released subagent whose recipient ended, by owner and child name. */
110
+ private readonly heldForChildren = new Map<string, HeldAwayMessage[]>();
111
+
112
+ holdForReleasedChild(childName: string, ownerSessionId: string, held: HeldAwayMessage): void {
113
+ const key = JSON.stringify([ownerSessionId, childName.trim().toLowerCase()]);
114
+ const list = this.heldForChildren.get(key) ?? [];
115
+ if (!list.some((existing) => existing.message.id === held.message.id)) this.heldForChildren.set(key, [...list, held]);
116
+ }
117
+
118
+ hasHeldForReleasedChild(childName: string, ownerSessionId: string): boolean {
119
+ return (this.heldForChildren.get(JSON.stringify([ownerSessionId, childName.trim().toLowerCase()]))?.length ?? 0) > 0;
120
+ }
121
+
122
+ takeHeldForReleasedChild(childName: string, ownerSessionId: string): HeldAwayMessage[] {
123
+ const key = JSON.stringify([ownerSessionId, childName.trim().toLowerCase()]);
124
+ const held = this.heldForChildren.get(key) ?? [];
125
+ this.heldForChildren.delete(key);
126
+ return held;
127
+ }
128
+
129
+ takeParkedAskers(childName: string, ownerSessionId: string): PendingQuestion[] {
130
+ const key = JSON.stringify([ownerSessionId, childName.trim().toLowerCase()]);
131
+ const questions = this.parkedAskers.get(key) ?? [];
132
+ this.parkedAskers.delete(key);
133
+ return questions;
134
+ }
11
135
 
12
136
  parkTarget(targetSessionId: string, childName: string, ownerSessionId: string): void {
13
137
  const questions = this.takeForTarget(targetSessionId);
@@ -145,6 +145,45 @@ export class ReleasedAskerReplies {
145
145
  if (ownerSessionId !== undefined) addTo(this.byOwner, ownerSessionId, entry);
146
146
  }
147
147
 
148
+ /**
149
+ * #4751: the child is back under its owner's authorization: its kept asks leave this table and take the ordinary
150
+ * reply routes of a live asker again, so a later reply reaches the child itself.
151
+ */
152
+ takeChild(childName: string, ownerSessionId: string): ReleasedAskerReplyRoute[] {
153
+ const taken: ReleasedAskerReplyRoute[] = [];
154
+ for (const entry of [...(this.byChild.get(normalizeReservationTarget(childName)) ?? [])]) {
155
+ if (entry.ownerSessionId !== ownerSessionId) continue;
156
+ taken.push({
157
+ questionId: entry.questionId,
158
+ askerSessionId: entry.askerSessionId,
159
+ childName: entry.childName,
160
+ replierSessionId: entry.replierSessionId,
161
+ ownerSessionId,
162
+ expiresAt: entry.expiresAt,
163
+ });
164
+ this.remove(entry);
165
+ }
166
+ return taken;
167
+ }
168
+
169
+ /** #4751: the replier ended or can no longer answer: its owned routes leave this table, to be failed. */
170
+ takeForReplier(replierSessionId: string): ReleasedAskerReplyRoute[] {
171
+ const taken: ReleasedAskerReplyRoute[] = [];
172
+ for (const entry of [...this.entries]) {
173
+ if (entry.replierSessionId !== replierSessionId || entry.ownerSessionId === undefined) continue;
174
+ taken.push({
175
+ questionId: entry.questionId,
176
+ askerSessionId: entry.askerSessionId,
177
+ childName: entry.childName,
178
+ replierSessionId: entry.replierSessionId,
179
+ ownerSessionId: entry.ownerSessionId,
180
+ expiresAt: entry.expiresAt,
181
+ });
182
+ this.remove(entry);
183
+ }
184
+ return taken;
185
+ }
186
+
148
187
  dropChild(childName: string, ownerSessionId: string): number {
149
188
  let dropped = 0;
150
189
  for (const entry of [...(this.byChild.get(normalizeReservationTarget(childName)) ?? [])]) {