@athenaintel/react 0.48.0 → 0.50.0

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 (179) hide show
  1. package/README.md +48 -10
  2. package/dist/agent-runtime/src/call-recap.cjs +319 -0
  3. package/dist/agent-runtime/src/call-recap.cjs.map +1 -0
  4. package/dist/agent-runtime/src/call-recap.d.ts +142 -0
  5. package/dist/agent-runtime/src/call-recap.js +319 -0
  6. package/dist/agent-runtime/src/call-recap.js.map +1 -0
  7. package/dist/agent-runtime/src/chat-outbox-store.cjs +1 -0
  8. package/dist/agent-runtime/src/chat-outbox-store.cjs.map +1 -1
  9. package/dist/agent-runtime/src/chat-outbox-store.d.ts +7 -0
  10. package/dist/agent-runtime/src/chat-outbox-store.js +1 -0
  11. package/dist/agent-runtime/src/chat-outbox-store.js.map +1 -1
  12. package/dist/agent-runtime/src/chat-outbox.cjs +46 -5
  13. package/dist/agent-runtime/src/chat-outbox.cjs.map +1 -1
  14. package/dist/agent-runtime/src/chat-outbox.d.ts +29 -0
  15. package/dist/agent-runtime/src/chat-outbox.js +46 -5
  16. package/dist/agent-runtime/src/chat-outbox.js.map +1 -1
  17. package/dist/agent-runtime/src/conversation-index.cjs.map +1 -1
  18. package/dist/agent-runtime/src/conversation-index.d.ts +7 -0
  19. package/dist/agent-runtime/src/conversation-index.js.map +1 -1
  20. package/dist/agent-runtime/src/conversation-list.cjs +2 -1
  21. package/dist/agent-runtime/src/conversation-list.cjs.map +1 -1
  22. package/dist/agent-runtime/src/conversation-list.d.ts +19 -3
  23. package/dist/agent-runtime/src/conversation-list.js +2 -1
  24. package/dist/agent-runtime/src/conversation-list.js.map +1 -1
  25. package/dist/agent-runtime/src/index.d.ts +6 -5
  26. package/dist/agent-runtime/src/interrupts.cjs +28 -1
  27. package/dist/agent-runtime/src/interrupts.cjs.map +1 -1
  28. package/dist/agent-runtime/src/interrupts.d.ts +21 -1
  29. package/dist/agent-runtime/src/interrupts.js +28 -1
  30. package/dist/agent-runtime/src/interrupts.js.map +1 -1
  31. package/dist/agent-runtime/src/model-context.cjs +3 -2
  32. package/dist/agent-runtime/src/model-context.cjs.map +1 -1
  33. package/dist/agent-runtime/src/model-context.d.ts +6 -1
  34. package/dist/agent-runtime/src/model-context.js +3 -2
  35. package/dist/agent-runtime/src/model-context.js.map +1 -1
  36. package/dist/agent-runtime/src/runtime.d.ts +3 -2
  37. package/dist/agent-runtime/src/send-recovery.cjs +37 -3
  38. package/dist/agent-runtime/src/send-recovery.cjs.map +1 -1
  39. package/dist/agent-runtime/src/send-recovery.d.ts +19 -0
  40. package/dist/agent-runtime/src/send-recovery.js +37 -3
  41. package/dist/agent-runtime/src/send-recovery.js.map +1 -1
  42. package/dist/agent-runtime/src/thread-handoff-flow-machine.d.ts +8 -8
  43. package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +113 -1
  44. package/dist/agent-runtime/src/thread-handoff.d.ts +1 -1
  45. package/dist/agent-runtime/src/use-conversation-list.cjs +3 -2
  46. package/dist/agent-runtime/src/use-conversation-list.cjs.map +1 -1
  47. package/dist/agent-runtime/src/use-conversation-list.d.ts +6 -0
  48. package/dist/agent-runtime/src/use-conversation-list.js +3 -2
  49. package/dist/agent-runtime/src/use-conversation-list.js.map +1 -1
  50. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs +21 -1
  51. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs.map +1 -1
  52. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.d.ts +8 -2
  53. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js +21 -1
  54. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js.map +1 -1
  55. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs +24 -6
  56. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  57. package/dist/agent-runtime/src/use-deep-agent-runtime.d.ts +17 -0
  58. package/dist/agent-runtime/src/use-deep-agent-runtime.js +24 -6
  59. package/dist/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
  60. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +44 -9
  61. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -1
  62. package/dist/agent-runtime/src/use-deep-agent-voice.d.ts +34 -1
  63. package/dist/agent-runtime/src/use-deep-agent-voice.js +44 -9
  64. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -1
  65. package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +8 -2
  66. package/dist/agent-runtime/src/voice-earcon.cjs +139 -0
  67. package/dist/agent-runtime/src/voice-earcon.cjs.map +1 -0
  68. package/dist/agent-runtime/src/voice-earcon.d.ts +38 -0
  69. package/dist/agent-runtime/src/voice-earcon.js +139 -0
  70. package/dist/agent-runtime/src/voice-earcon.js.map +1 -0
  71. package/dist/agent-runtime/src/voice-media.cjs.map +1 -1
  72. package/dist/agent-runtime/src/voice-media.d.ts +14 -0
  73. package/dist/agent-runtime/src/voice-media.js.map +1 -1
  74. package/dist/agent-runtime/src/voice-presentation.cjs +2 -0
  75. package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
  76. package/dist/agent-runtime/src/voice-presentation.js +2 -0
  77. package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
  78. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  79. package/dist/assets/AthenaAssetEmbed.d.ts +11 -5
  80. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  81. package/dist/assets/use-asset-embed.cjs.map +1 -1
  82. package/dist/assets/use-asset-embed.d.ts +12 -5
  83. package/dist/assets/use-asset-embed.js.map +1 -1
  84. package/dist/chat/StatewireApprovalCard.cjs +41 -6
  85. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  86. package/dist/chat/StatewireApprovalCard.d.ts +18 -1
  87. package/dist/chat/StatewireApprovalCard.js +42 -7
  88. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  89. package/dist/chat/StatewireQueuedMessages.cjs +56 -6
  90. package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
  91. package/dist/chat/StatewireQueuedMessages.d.ts +14 -0
  92. package/dist/chat/StatewireQueuedMessages.js +58 -8
  93. package/dist/chat/StatewireQueuedMessages.js.map +1 -1
  94. package/dist/chat/WaitingOnYouBanner.cjs +6 -2
  95. package/dist/chat/WaitingOnYouBanner.cjs.map +1 -1
  96. package/dist/chat/WaitingOnYouBanner.js +7 -3
  97. package/dist/chat/WaitingOnYouBanner.js.map +1 -1
  98. package/dist/chat/chat-voice-controls.cjs +3 -1
  99. package/dist/chat/chat-voice-controls.cjs.map +1 -1
  100. package/dist/chat/chat-voice-controls.d.ts +6 -1
  101. package/dist/chat/chat-voice-controls.js +3 -1
  102. package/dist/chat/chat-voice-controls.js.map +1 -1
  103. package/dist/chat-ui/index.cjs +3 -0
  104. package/dist/chat-ui/index.cjs.map +1 -1
  105. package/dist/chat-ui/index.d.ts +1 -0
  106. package/dist/chat-ui/index.js +3 -0
  107. package/dist/chat-ui/index.js.map +1 -1
  108. package/dist/chat-ui/messages/from-the-call-card.cjs +124 -0
  109. package/dist/chat-ui/messages/from-the-call-card.cjs.map +1 -0
  110. package/dist/chat-ui/messages/from-the-call-card.d.ts +17 -0
  111. package/dist/chat-ui/messages/from-the-call-card.js +124 -0
  112. package/dist/chat-ui/messages/from-the-call-card.js.map +1 -0
  113. package/dist/chat-ui/rich-text/chat-link.cjs +1 -0
  114. package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -1
  115. package/dist/chat-ui/rich-text/chat-link.d.ts +4 -0
  116. package/dist/chat-ui/rich-text/chat-link.js +4 -3
  117. package/dist/chat-ui/rich-text/chat-link.js.map +1 -1
  118. package/dist/chat-ui/rich-text/chat-message-body.cjs +1 -0
  119. package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -1
  120. package/dist/chat-ui/rich-text/chat-message-body.d.ts +12 -0
  121. package/dist/chat-ui/rich-text/chat-message-body.js +2 -1
  122. package/dist/chat-ui/rich-text/chat-message-body.js.map +1 -1
  123. package/dist/chat-ui/thread/chat-thread-shell.cjs +2 -0
  124. package/dist/chat-ui/thread/chat-thread-shell.cjs.map +1 -1
  125. package/dist/chat-ui/thread/chat-thread-shell.js +2 -0
  126. package/dist/chat-ui/thread/chat-thread-shell.js.map +1 -1
  127. package/dist/collab/client.cjs +15 -3
  128. package/dist/collab/client.cjs.map +1 -1
  129. package/dist/collab/client.d.ts +4 -2
  130. package/dist/collab/client.js +16 -4
  131. package/dist/collab/client.js.map +1 -1
  132. package/dist/composer/index.d.ts +1 -1
  133. package/dist/composer/useReadComposerDraft.cjs +26 -7
  134. package/dist/composer/useReadComposerDraft.cjs.map +1 -1
  135. package/dist/composer/useReadComposerDraft.d.ts +23 -1
  136. package/dist/composer/useReadComposerDraft.js +27 -8
  137. package/dist/composer/useReadComposerDraft.js.map +1 -1
  138. package/dist/index.cjs +3 -0
  139. package/dist/index.cjs.map +1 -1
  140. package/dist/index.d.ts +3 -1
  141. package/dist/index.js +4 -1
  142. package/dist/index.js.map +1 -1
  143. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs +190 -0
  144. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs.map +1 -0
  145. package/dist/keryx-http/src/unconfirmed-update-attributions.d.ts +132 -0
  146. package/dist/keryx-http/src/unconfirmed-update-attributions.js +190 -0
  147. package/dist/keryx-http/src/unconfirmed-update-attributions.js.map +1 -0
  148. package/dist/keryx-http/src/update-attributions.cjs +34 -4
  149. package/dist/keryx-http/src/update-attributions.cjs.map +1 -1
  150. package/dist/keryx-http/src/update-attributions.d.ts +36 -4
  151. package/dist/keryx-http/src/update-attributions.js +35 -5
  152. package/dist/keryx-http/src/update-attributions.js.map +1 -1
  153. package/dist/provider/AthenaProvider.cjs +4 -0
  154. package/dist/provider/AthenaProvider.cjs.map +1 -1
  155. package/dist/provider/AthenaProvider.d.ts +11 -1
  156. package/dist/provider/AthenaProvider.js +4 -0
  157. package/dist/provider/AthenaProvider.js.map +1 -1
  158. package/dist/react/package.json.cjs +1 -1
  159. package/dist/react/package.json.js +1 -1
  160. package/dist/threads/api.cjs.map +1 -1
  161. package/dist/threads/api.d.ts +15 -0
  162. package/dist/threads/api.js.map +1 -1
  163. package/dist/threads/conversation-list-fetcher.cjs +13 -5
  164. package/dist/threads/conversation-list-fetcher.cjs.map +1 -1
  165. package/dist/threads/conversation-list-fetcher.d.ts +4 -1
  166. package/dist/threads/conversation-list-fetcher.js +13 -5
  167. package/dist/threads/conversation-list-fetcher.js.map +1 -1
  168. package/dist/threads/statewire-thread-list.cjs +28 -6
  169. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  170. package/dist/threads/statewire-thread-list.d.ts +20 -8
  171. package/dist/threads/statewire-thread-list.js +28 -6
  172. package/dist/threads/statewire-thread-list.js.map +1 -1
  173. package/dist/threads/use-athena-sessions.cjs +27 -5
  174. package/dist/threads/use-athena-sessions.cjs.map +1 -1
  175. package/dist/threads/use-athena-sessions.d.ts +10 -5
  176. package/dist/threads/use-athena-sessions.js +28 -6
  177. package/dist/threads/use-athena-sessions.js.map +1 -1
  178. package/dist/threads/use-rest-conversation-history.d.ts +1 -0
  179. package/package.json +1 -1
@@ -10,7 +10,7 @@ export { pickThreadConfigCustom, type ThreadConfigPatch, } from "./config-mutati
10
10
  export { type ConversationIndexEntry, conversationIndexFingerprint, useConversationIndex, } from "./conversation-index";
11
11
  export { type ConversationListPage, type ConversationSummary, mergeConversationIndexIntoPage, } from "./conversation-list";
12
12
  export { isLegacyThreadReadOnlyRejection, isStatewireChannelTeardown, isStatewireRewindAnchorRejection, statewireRejectionDetailMessage, statewireRejectionPayload, } from "./errors";
13
- export { asHitlApproval, findAbandonedInterrupt, HITL_PENDING_RESUME_GRACE_MS, type HitlApprovalPayload, hitlResumeApprove, hitlResumeReject, interruptResumeDecline, isApprovalCardInterrupt, readAbandonedInputRequests, readInterruptMessage, useApprovalResumeLock, } from "./interrupts";
13
+ export { asHitlApproval, findAbandonedInterrupt, HITL_PENDING_RESUME_GRACE_MS, type HitlApprovalPayload, hitlResumeApprove, hitlResumeReject, interruptResumeDecline, isApprovalCardInterrupt, pendingActionRequests, readAbandonedInputRequests, readInterruptMessage, toolCallIdsAwaitingApproval, useApprovalResumeLock, } from "./interrupts";
14
14
  export { type DeepAgentMessageWindowDeclaration } from "./message-window";
15
15
  export { ATHENA_RUN_MARKER_KEY, isQueuedLaneMessage, } from "./messages";
16
16
  export { isDeepAgentHostState } from "./protocol";
@@ -32,9 +32,10 @@ export { DeepAgentChatOutboxContext, useChatOutboxReachable, useChatOutboxSnapsh
32
32
  export { type DeepAgentConfigWriteResult, isConfigWriteForbiddenRejection, useDeepAgentConfig, } from "./use-deep-agent-config";
33
33
  export { useDeepAgentMessageEditSubmit } from "./use-deep-agent-edit-submit";
34
34
  export { type DeepAgentThreadElement, logUnhandledStatewireError, useDeepAgentRuntime, } from "./use-deep-agent-runtime";
35
- export { describeVoiceFailure, describeVoiceLiveElsewhere, type DeepAgentVoiceSurface, useDeepAgentVoice, type UseDeepAgentVoiceReturn, useVoiceElapsed, useVoiceMovedNotice, VOICE_CONTINUE_BY_VOICE_LABEL, VOICE_MOVE_CALL_HERE_LABEL, VOICE_MOVE_HERE_ACTION, } from "./use-deep-agent-voice";
35
+ export { describeVoiceFailure, describeVoiceLiveElsewhere, type DeepAgentVoiceCallMove, type DeepAgentVoiceSurface, playVoiceMoveEarcon, useDeepAgentVoice, type UseDeepAgentVoiceReturn, useVoiceElapsed, useVoiceMovedNotice, VOICE_CONTINUE_BY_VOICE_LABEL, VOICE_MOVE_CALL_HERE_LABEL, VOICE_MOVE_EARCON_MS, VOICE_MOVE_HERE_ACTION, voiceMoveEarconDataUri, } from "./use-deep-agent-voice";
36
36
  export { useDeepAgentWindowSync } from "./use-deep-agent-window-sync";
37
37
  export { describeVoiceUpdateToolCall, isVoiceDelegationMessage, VOICE_LIVE_TYPED_HINT, VOICE_UPDATE_TOOL_NAME, voiceProvenanceLabel, voiceUpdateStatusLabel, } from "./voice-presentation";
38
+ export { CALL_RECAP_APPROVAL_LABEL, CALL_RECAP_TITLE, type CallRecap, type CallRecapApproval, type CallRecapAsset, type CallRecapItem, type CallRecapLink, type CallRecapMessage, type CallRecapOpenToolCall, type CallRecapPart, callRecapAfter, callRecapHasItems, callRecapItems, isCallUserMessage, mayHaveLiveCall, VOICE_TYPED_ID_PREFIX, } from "./call-recap";
38
39
  export { type ResumeExtras } from "./interrupts";
39
40
  export { resumeValueApproves } from "./interrupts";
40
41
  export { statewireAnswerDescriptors } from "./decision-checks";
@@ -4,12 +4,16 @@ const statewireState = require("./statewire-state.cjs");
4
4
  const AUTO_RETRY_FATES = /* @__PURE__ */ new Set(["lost", "aborted"]);
5
5
  const MAX_AUTO_RETRIES_PER_MESSAGE = 3;
6
6
  const MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1e3;
7
+ const MAX_BEFORE_RETRY_HOLDS = 10;
7
8
  function shouldAutoRetryFailedSend(failure) {
8
9
  return failure !== void 0 && AUTO_RETRY_FATES.has(failure.fate);
9
10
  }
10
11
  function awaitsLostPredecessor(entry) {
11
12
  return entry.sendFailure.fate === "aborted" && entry.sendFailure.predecessorLost === true;
12
13
  }
14
+ function isThenable(value) {
15
+ return typeof value === "object" && value !== null && typeof value.then === "function";
16
+ }
13
17
  function commandMessageId(update) {
14
18
  var _a, _b;
15
19
  const first = (_a = update.params) == null ? void 0 : _a[0];
@@ -28,14 +32,16 @@ function createDeepAgentSendRecovery(options) {
28
32
  const surfacedDeferrals = /* @__PURE__ */ new Set();
29
33
  const inFlight = /* @__PURE__ */ new Set();
30
34
  const deferred = /* @__PURE__ */ new Set();
35
+ const holds = /* @__PURE__ */ new Map();
36
+ let holding = false;
31
37
  const record = (event, data) => {
32
38
  var _a, _b;
33
39
  (_b = (_a = options.diagnostics) == null ? void 0 : _a.call(options)) == null ? void 0 : _b.record(event, data);
34
40
  };
35
41
  const sweep = () => {
36
- var _a;
42
+ var _a, _b;
37
43
  sweepScheduled = false;
38
- if (disposed || !hydrated || !armed) return;
44
+ if (disposed || holding || !hydrated || !armed) return;
39
45
  const lane = options.lane();
40
46
  if (lane === null) return;
41
47
  armed = false;
@@ -75,6 +81,29 @@ function createDeepAgentSendRecovery(options) {
75
81
  if (isLost) lostPredecessorPending = true;
76
82
  continue;
77
83
  }
84
+ let before;
85
+ try {
86
+ before = (_b = options.beforeRetry) == null ? void 0 : _b.call(options, entry.id);
87
+ } catch {
88
+ record("send-recovery/before-retry-failed", { messageId: entry.id });
89
+ }
90
+ if (isThenable(before)) {
91
+ const held = (holds.get(entry.id) ?? 0) + 1;
92
+ if (held <= MAX_BEFORE_RETRY_HOLDS) {
93
+ holds.set(entry.id, held);
94
+ holding = true;
95
+ armed = true;
96
+ record("send-recovery/held", { messageId: entry.id, holds: held });
97
+ const resume = () => {
98
+ holding = false;
99
+ armed = true;
100
+ scheduleSweep();
101
+ };
102
+ before.then(resume, resume);
103
+ return;
104
+ }
105
+ record("send-recovery/held-too-long", { messageId: entry.id });
106
+ }
78
107
  try {
79
108
  lane.retryFailed(entry.id);
80
109
  attempts.set(entry.id, attempt);
@@ -87,12 +116,16 @@ function createDeepAgentSendRecovery(options) {
87
116
  });
88
117
  } catch {
89
118
  record("send-recovery/raced", { messageId: entry.id });
119
+ try {
120
+ if (typeof before === "function") before();
121
+ } catch {
122
+ }
90
123
  }
91
124
  }
92
125
  if (deferred.size > 0) armed = true;
93
126
  };
94
127
  const scheduleSweep = () => {
95
- if (disposed || sweepScheduled || !hydrated || !armed) return;
128
+ if (disposed || sweepScheduled || holding || !hydrated || !armed) return;
96
129
  sweepScheduled = true;
97
130
  schedule(sweep);
98
131
  };
@@ -123,6 +156,7 @@ function createDeepAgentSendRecovery(options) {
123
156
  }
124
157
  };
125
158
  }
159
+ exports.MAX_BEFORE_RETRY_HOLDS = MAX_BEFORE_RETRY_HOLDS;
126
160
  exports.createDeepAgentSendRecovery = createDeepAgentSendRecovery;
127
161
  exports.shouldAutoRetryFailedSend = shouldAutoRetryFailedSend;
128
162
  //# sourceMappingURL=send-recovery.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"send-recovery.cjs","sources":["../../../../agent-runtime/src/send-recovery.ts"],"sourcesContent":["import type {\n StatewireDiagnosticsCommandUpdate,\n StatewireDiagnosticsRecorder,\n} from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated } from './statewire-state';\nimport type { StatewireFailedSendEntry, StatewireFailedSendLane } from './thread-extras';\n\n/**\n * Transport-level send durability for the deep-agent thread (the successor to\n * Olympus' localStorage outbox, #29368 → #31504).\n *\n * The durable journal itself is the statewire session record: every command is\n * persisted through the mounted session storage from `send()` until the server\n * durably admits or judges it, and a reload resends survivors on the SAME lane\n * seq (exactly-once — the server absorbs replayed seqs at or below its\n * watermark). What the record cannot recover on its own is a send the client\n * had to settle without a server verdict — a proven session loss or a record\n * reset settles it `lost`/`aborted` and RETAINS it in the record's failed lane\n * (message-carrying sends only), where the vendor drops it as soon as a\n * canonical snapshot shows the message landed (`failureCovered`).\n *\n * This controller turns that persisted failed lane back into live sends: once\n * the thread snapshot has hydrated (so covered entries are already gone), every\n * failed send the server NEVER judged is re-dispatched through the thread's own\n * `retryFailed` — same client-minted message id, re-anchored against the\n * current thread — which the host dedupes by id (a still-queued id re-places,\n * a durable one rejects `duplicate-id`). Server-judged fates (`rejected`,\n * `failed`, `crashed`, `expired`) are the user's decision and stay in the\n * manual retry/discard affordance.\n *\n * Ordering: an `aborted` send stamped `predecessorLost` was never attempted\n * because an earlier send of the same batch WAS attempted and settled `lost`\n * — it may or may not have run. Re-dispatching the successor first could land\n * it ahead of a predecessor that later turns out to have landed too, so the\n * successor is held until every preceding `lost` predecessor has settled: it\n * was covered by a snapshot, its retry was judged by the server, or the user\n * discarded it.\n */\n\n/** Fates the server never saw: the send died client-side (unmount, stream\n * gone, session lost) and is safe to re-dispatch under its original message\n * id. The complement — rejected/failed/crashed/expired — is server-judged. */\nconst AUTO_RETRY_FATES: ReadonlySet<string> = new Set(['lost', 'aborted']);\n\n/** A failed send is re-dispatched at most this many times per attach; a\n * persistent failure (repeated session losses) stays in the manual lane. */\nconst MAX_AUTO_RETRIES_PER_MESSAGE = 3;\n\n/** Persisted failures older than this stay manual: auto-sending a message the\n * user abandoned a day ago is worse than surfacing it for a decision. Mirrors\n * the retired outbox's retention window. */\nconst MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1000;\n\nexport interface DeepAgentSendRecoveryOptions {\n /**\n * Reads the thread's failed-send lane. `null` while it is unavailable (the\n * client has not mounted yet, or its extras are not a statewire thread) —\n * the controller stays armed and retries on the next state change.\n */\n lane: () => StatewireFailedSendLane | null;\n /**\n * Persisted failure stamps (message id → epoch ms of the original send) for\n * the freshness gate. `null`/absent means no persistence is readable — every\n * lane entry then counts as fresh (an in-memory failed lane can only hold\n * failures from this page session).\n */\n failureStamps?: (() => ReadonlyMap<string, number> | null) | undefined;\n /** Transport lifecycle recorder; read per event so a late-mounted recorder still sees retries. */\n diagnostics?: (() => StatewireDiagnosticsRecorder | undefined) | undefined;\n /** Injectable clock (tests). */\n now?: () => number;\n /** Sweep scheduler; defaults to `queueMicrotask` so a sweep never dispatches\n * from inside a statewire flush or a React render. */\n schedule?: (task: () => void) => void;\n}\n\nexport interface DeepAgentSendRecovery {\n /** Feed every (normalized) statewire state change; hydration arms the mount sweep. */\n observeStateChange(state: unknown): void;\n /** Feed every command-lifecycle update; a never-server-judged settle arms a sweep. */\n observeCommand(update: StatewireDiagnosticsCommandUpdate): void;\n /** Feed client notifications too: failed history can publish after the\n * command settles, without any change to the canonical thread snapshot. */\n observeFailedLaneChange(): void;\n dispose(): void;\n}\n\n/** Whether a settle failure is a client-side death the recovery re-dispatches\n * (the server never judged the command). Exported for host-side telemetry. */\nexport function shouldAutoRetryFailedSend(failure: { fate: string } | undefined): boolean {\n return failure !== undefined && AUTO_RETRY_FATES.has(failure.fate);\n}\n\n/** Whether a failed entry must wait for a lost predecessor to settle first. */\nfunction awaitsLostPredecessor(entry: StatewireFailedSendEntry): boolean {\n return entry.sendFailure.fate === 'aborted' && entry.sendFailure.predecessorLost === true;\n}\n\n/** The client-minted message id a run send carries, off a command update's params. */\nfunction commandMessageId(update: StatewireDiagnosticsCommandUpdate): string | null {\n const first = update.params?.[0] as { message?: { id?: unknown } } | undefined;\n const id = first?.message?.id;\n return typeof id === 'string' ? id : null;\n}\n\nexport function createDeepAgentSendRecovery(\n options: DeepAgentSendRecoveryOptions\n): DeepAgentSendRecovery {\n const now = options.now ?? Date.now;\n const schedule = options.schedule ?? ((task: () => void) => queueMicrotask(task));\n\n let disposed = false;\n let hydrated = false;\n /** Work may exist: set at hydration and on retryable settles, cleared by a\n * sweep that could actually read the lane. */\n let armed = false;\n let sweepScheduled = false;\n /** Retry budget per message id, for this controller's attach lifetime. */\n const attempts = new Map<string, number>();\n /** Message ids already diagnosed as stale/exhausted, so the lane re-scan\n * stays quiet about them. */\n const surfacedSkips = new Set<string>();\n /** Message ids whose deferral behind a lost predecessor was diagnosed once. */\n const surfacedDeferrals = new Set<string>();\n /** Re-dispatched sends still awaiting the server's verdict: a successor\n * stamped `predecessorLost` waits while any of these is pending. */\n const inFlight = new Set<string>();\n /** Successors held back by the last sweep; a non-empty set keeps the\n * controller armed so the next settle or state change re-sweeps. */\n const deferred = new Set<string>();\n\n const record = (event: string, data?: Record<string, unknown>): void => {\n options.diagnostics?.()?.record(event, data);\n };\n\n const sweep = (): void => {\n sweepScheduled = false;\n if (disposed || !hydrated || !armed) return;\n const lane = options.lane();\n // No readable lane yet: stay armed so the next state change re-sweeps.\n if (lane === null) return;\n armed = false;\n deferred.clear();\n const stamps = options.failureStamps?.() ?? null;\n // A `lost` entry earlier in lane order that this sweep leaves unsettled\n // (skipped as stale/exhausted, or re-dispatched and now in flight).\n let lostPredecessorPending = false;\n for (const entry of lane.failed) {\n if (!shouldAutoRetryFailedSend(entry.sendFailure)) continue;\n // Shared retry/discard may still be waiting for the storage lock. The\n // visible lane can keep this entry until then; do not spend another\n // attempt on a send whose previous retry is still awaiting a verdict.\n if (inFlight.has(entry.id)) {\n if (entry.sendFailure.fate === 'lost') lostPredecessorPending = true;\n continue;\n }\n if (awaitsLostPredecessor(entry) && (lostPredecessorPending || inFlight.size > 0)) {\n deferred.add(entry.id);\n if (!surfacedDeferrals.has(entry.id)) {\n surfacedDeferrals.add(entry.id);\n record('send-recovery/deferred', { messageId: entry.id });\n }\n continue;\n }\n const isLost = entry.sendFailure.fate === 'lost';\n const stamp = stamps?.get(entry.id);\n if (stamp !== undefined && now() - stamp > MAX_AUTO_RETRY_AGE_MS) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/stale', { messageId: entry.id, ageMs: Math.round(now() - stamp) });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n const attempt = (attempts.get(entry.id) ?? 0) + 1;\n if (attempt > MAX_AUTO_RETRIES_PER_MESSAGE) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/exhausted', { messageId: entry.id });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n try {\n lane.retryFailed(entry.id);\n attempts.set(entry.id, attempt);\n inFlight.add(entry.id);\n if (isLost) lostPredecessorPending = true;\n record('send-recovery/retry', {\n messageId: entry.id,\n fate: entry.sendFailure.fate,\n attempt,\n });\n } catch {\n // The entry settled or was covered between the lane read and the\n // retry (the vendor drops covered failures against every snapshot);\n // nothing was dispatched.\n record('send-recovery/raced', { messageId: entry.id });\n }\n }\n // Held successors must be revisited once their predecessors settle.\n if (deferred.size > 0) armed = true;\n };\n\n const scheduleSweep = (): void => {\n if (disposed || sweepScheduled || !hydrated || !armed) return;\n sweepScheduled = true;\n schedule(sweep);\n };\n\n return {\n observeStateChange(state) {\n if (disposed) return;\n if (!hydrated && isDeepAgentStateHydrated(state)) {\n // First real snapshot: the vendor's failureCovered pass has had its\n // chance to drop entries whose message actually landed, so whatever\n // remains provably never reached the thread.\n hydrated = true;\n armed = true;\n }\n scheduleSweep();\n },\n observeCommand(update) {\n if (disposed || update.status !== 'settled') return;\n const messageId = commandMessageId(update);\n if (messageId !== null) inFlight.delete(messageId);\n // A never-server-judged settle means new work; any settle while\n // successors are held may be the predecessor they wait on.\n if (!shouldAutoRetryFailedSend(update.failure) && deferred.size === 0) return;\n armed = true;\n scheduleSweep();\n },\n observeFailedLaneChange() {\n if (disposed) return;\n armed = true;\n scheduleSweep();\n },\n dispose() {\n disposed = true;\n },\n };\n}\n"],"names":["isDeepAgentStateHydrated"],"mappings":";;;AA0CA,MAAM,mBAAwC,oBAAI,IAAI,CAAC,QAAQ,SAAS,CAAC;AAIzE,MAAM,+BAA+B;AAKrC,MAAM,wBAAwB,KAAK,KAAK,KAAK;AAsCtC,SAAS,0BAA0B,SAAgD;AACxF,SAAO,YAAY,UAAa,iBAAiB,IAAI,QAAQ,IAAI;AACnE;AAGA,SAAS,sBAAsB,OAA0C;AACvE,SAAO,MAAM,YAAY,SAAS,aAAa,MAAM,YAAY,oBAAoB;AACvF;AAGA,SAAS,iBAAiB,QAA0D;;AAClF,QAAM,SAAQ,YAAO,WAAP,mBAAgB;AAC9B,QAAM,MAAK,oCAAO,YAAP,mBAAgB;AAC3B,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEO,SAAS,4BACd,SACuB;AACvB,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,WAAW,QAAQ,aAAa,CAAC,SAAqB,eAAe,IAAI;AAE/E,MAAI,WAAW;AACf,MAAI,WAAW;AAGf,MAAI,QAAQ;AACZ,MAAI,iBAAiB;AAErB,QAAM,+BAAe,IAAA;AAGrB,QAAM,oCAAoB,IAAA;AAE1B,QAAM,wCAAwB,IAAA;AAG9B,QAAM,+BAAe,IAAA;AAGrB,QAAM,+BAAe,IAAA;AAErB,QAAM,SAAS,CAAC,OAAe,SAAyC;;AACtE,wBAAQ,gBAAR,wDAAyB,OAAO,OAAO;AAAA,EACzC;AAEA,QA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YAAI,OAAQ,0BAAyB;AACrC;AAAA,MACF;AACA,UAAI;AACF,aAAK,YAAY,MAAM,EAAE;AACzB,iBAAS,IAAI,MAAM,IAAI,OAAO;AAC9B,iBAAS,IAAI,MAAM,EAAE;AACrB,YAAI,OAAQ,0BAAyB;AACrC,eAAO,uBAAuB;AAAA,UAC5B,WAAW,MAAM;AAAA,UACjB,MAAM,MAAM,YAAY;AAAA,UACxB;AAAA,QAAA,CACD;AAAA,MACH,QAAQ;AAIN,eAAO,uBAAuB,EAAE,WAAW,MAAM,IAAI;AAAA,MACvD;AAAA,IACF;AAEA,QAAI,SAAS,OAAO,EAAG,SAAQ;AAAA,EACjC;AAEA,QAAM,gBAAgB,MAAY;AAChC,QAAI,YAAY,kBAAkB,CAAC,YAAY,CAAC,MAAO;AACvD,qBAAiB;AACjB,aAAS,KAAK;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,mBAAmB,OAAO;AACxB,UAAI,SAAU;AACd,UAAI,CAAC,YAAYA,wCAAyB,KAAK,GAAG;AAIhD,mBAAW;AACX,gBAAQ;AAAA,MACV;AACA,oBAAA;AAAA,IACF;AAAA,IACA,eAAe,QAAQ;AACrB,UAAI,YAAY,OAAO,WAAW,UAAW;AAC7C,YAAM,YAAY,iBAAiB,MAAM;AACzC,UAAI,cAAc,KAAM,UAAS,OAAO,SAAS;AAGjD,UAAI,CAAC,0BAA0B,OAAO,OAAO,KAAK,SAAS,SAAS,EAAG;AACvE,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,0BAA0B;AACxB,UAAI,SAAU;AACd,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,UAAU;AACR,iBAAW;AAAA,IACb;AAAA,EAAA;AAEJ;;;"}
1
+ {"version":3,"file":"send-recovery.cjs","sources":["../../../../agent-runtime/src/send-recovery.ts"],"sourcesContent":["import type {\n StatewireDiagnosticsCommandUpdate,\n StatewireDiagnosticsRecorder,\n} from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated } from './statewire-state';\nimport type { StatewireFailedSendEntry, StatewireFailedSendLane } from './thread-extras';\n\n/**\n * Transport-level send durability for the deep-agent thread (the successor to\n * Olympus' localStorage outbox, #29368 → #31504).\n *\n * The durable journal itself is the statewire session record: every command is\n * persisted through the mounted session storage from `send()` until the server\n * durably admits or judges it, and a reload resends survivors on the SAME lane\n * seq (exactly-once — the server absorbs replayed seqs at or below its\n * watermark). What the record cannot recover on its own is a send the client\n * had to settle without a server verdict — a proven session loss or a record\n * reset settles it `lost`/`aborted` and RETAINS it in the record's failed lane\n * (message-carrying sends only), where the vendor drops it as soon as a\n * canonical snapshot shows the message landed (`failureCovered`).\n *\n * This controller turns that persisted failed lane back into live sends: once\n * the thread snapshot has hydrated (so covered entries are already gone), every\n * failed send the server NEVER judged is re-dispatched through the thread's own\n * `retryFailed` — same client-minted message id, re-anchored against the\n * current thread — which the host dedupes by id (a still-queued id re-places,\n * a durable one rejects `duplicate-id`). Server-judged fates (`rejected`,\n * `failed`, `crashed`, `expired`) are the user's decision and stay in the\n * manual retry/discard affordance.\n *\n * Ordering: an `aborted` send stamped `predecessorLost` was never attempted\n * because an earlier send of the same batch WAS attempted and settled `lost`\n * — it may or may not have run. Re-dispatching the successor first could land\n * it ahead of a predecessor that later turns out to have landed too, so the\n * successor is held until every preceding `lost` predecessor has settled: it\n * was covered by a snapshot, its retry was judged by the server, or the user\n * discarded it.\n */\n\n/** Fates the server never saw: the send died client-side (unmount, stream\n * gone, session lost) and is safe to re-dispatch under its original message\n * id. The complement — rejected/failed/crashed/expired — is server-judged. */\nconst AUTO_RETRY_FATES: ReadonlySet<string> = new Set(['lost', 'aborted']);\n\n/** A failed send is re-dispatched at most this many times per attach; a\n * persistent failure (repeated session losses) stays in the manual lane. */\nconst MAX_AUTO_RETRIES_PER_MESSAGE = 3;\n\n/** Persisted failures older than this stay manual: auto-sending a message the\n * user abandoned a day ago is worse than surfacing it for a decision. Mirrors\n * the retired outbox's retention window. */\nconst MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** How many times a host may hold one message's retry (`beforeRetry`\n * returning a promise) before the sweep sends it regardless: a hold is the\n * host's own bounded wait, never a reason to keep a message back for good. */\nexport const MAX_BEFORE_RETRY_HOLDS = 10;\n\nexport interface DeepAgentSendRecoveryOptions {\n /**\n * Reads the thread's failed-send lane. `null` while it is unavailable (the\n * client has not mounted yet, or its extras are not a statewire thread) —\n * the controller stays armed and retries on the next state change.\n */\n lane: () => StatewireFailedSendLane | null;\n /**\n * Persisted failure stamps (message id → epoch ms of the original send) for\n * the freshness gate. `null`/absent means no persistence is readable — every\n * lane entry then counts as fresh (an in-memory failed lane can only hold\n * failures from this page session).\n */\n failureStamps?: (() => ReadonlyMap<string, number> | null) | undefined;\n /** Transport lifecycle recorder; read per event so a late-mounted recorder still sees retries. */\n diagnostics?: (() => StatewireDiagnosticsRecorder | undefined) | undefined;\n /** Injectable clock (tests). */\n now?: () => number;\n /** Sweep scheduler; defaults to `queueMicrotask` so a sweep never dispatches\n * from inside a statewire flush or a React render. */\n schedule?: (task: () => void) => void;\n /**\n * Called right before a failed send is dispatched again, with its message\n * id, so a host can put back the per-send context that message was sent\n * with (Olympus stages the agents it named) before its command leaves.\n *\n * Returning a promise holds the retry: the host can't put that context back\n * yet (every send of the conversation rides one ambient context, and a send\n * with another context is still on its way). The sweep then stops at this\n * message, so nothing behind it overtakes it, and asks again once the\n * promise settles; past {@link MAX_BEFORE_RETRY_HOLDS} holds it sends the\n * message regardless. A hook that throws never holds a retry back. A\n * function returned is called when the message does not go after all (the\n * retry raced its leaving the lane), so the host lets go of what it put back.\n */\n beforeRetry?: ((messageId: string) => void | PromiseLike<void> | (() => void)) | undefined;\n}\n\nexport interface DeepAgentSendRecovery {\n /** Feed every (normalized) statewire state change; hydration arms the mount sweep. */\n observeStateChange(state: unknown): void;\n /** Feed every command-lifecycle update; a never-server-judged settle arms a sweep. */\n observeCommand(update: StatewireDiagnosticsCommandUpdate): void;\n /** Feed client notifications too: failed history can publish after the\n * command settles, without any change to the canonical thread snapshot. */\n observeFailedLaneChange(): void;\n dispose(): void;\n}\n\n/** Whether a settle failure is a client-side death the recovery re-dispatches\n * (the server never judged the command). Exported for host-side telemetry. */\nexport function shouldAutoRetryFailedSend(failure: { fate: string } | undefined): boolean {\n return failure !== undefined && AUTO_RETRY_FATES.has(failure.fate);\n}\n\n/** Whether a failed entry must wait for a lost predecessor to settle first. */\nfunction awaitsLostPredecessor(entry: StatewireFailedSendEntry): boolean {\n return entry.sendFailure.fate === 'aborted' && entry.sendFailure.predecessorLost === true;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/** The client-minted message id a run send carries, off a command update's params. */\nfunction commandMessageId(update: StatewireDiagnosticsCommandUpdate): string | null {\n const first = update.params?.[0] as { message?: { id?: unknown } } | undefined;\n const id = first?.message?.id;\n return typeof id === 'string' ? id : null;\n}\n\nexport function createDeepAgentSendRecovery(\n options: DeepAgentSendRecoveryOptions\n): DeepAgentSendRecovery {\n const now = options.now ?? Date.now;\n const schedule = options.schedule ?? ((task: () => void) => queueMicrotask(task));\n\n let disposed = false;\n let hydrated = false;\n /** Work may exist: set at hydration and on retryable settles, cleared by a\n * sweep that could actually read the lane. */\n let armed = false;\n let sweepScheduled = false;\n /** Retry budget per message id, for this controller's attach lifetime. */\n const attempts = new Map<string, number>();\n /** Message ids already diagnosed as stale/exhausted, so the lane re-scan\n * stays quiet about them. */\n const surfacedSkips = new Set<string>();\n /** Message ids whose deferral behind a lost predecessor was diagnosed once. */\n const surfacedDeferrals = new Set<string>();\n /** Re-dispatched sends still awaiting the server's verdict: a successor\n * stamped `predecessorLost` waits while any of these is pending. */\n const inFlight = new Set<string>();\n /** Successors held back by the last sweep; a non-empty set keeps the\n * controller armed so the next settle or state change re-sweeps. */\n const deferred = new Set<string>();\n /** How many times the host held each message's retry (`beforeRetry`'s promise). */\n const holds = new Map<string, number>();\n /** A host's hold in progress: no sweep runs until it settles. */\n let holding = false;\n\n const record = (event: string, data?: Record<string, unknown>): void => {\n options.diagnostics?.()?.record(event, data);\n };\n\n const sweep = (): void => {\n sweepScheduled = false;\n // A host's hold re-sweeps once it settles; until then nothing is retried.\n if (disposed || holding || !hydrated || !armed) return;\n const lane = options.lane();\n // No readable lane yet: stay armed so the next state change re-sweeps.\n if (lane === null) return;\n armed = false;\n deferred.clear();\n const stamps = options.failureStamps?.() ?? null;\n // A `lost` entry earlier in lane order that this sweep leaves unsettled\n // (skipped as stale/exhausted, or re-dispatched and now in flight).\n let lostPredecessorPending = false;\n for (const entry of lane.failed) {\n if (!shouldAutoRetryFailedSend(entry.sendFailure)) continue;\n // Shared retry/discard may still be waiting for the storage lock. The\n // visible lane can keep this entry until then; do not spend another\n // attempt on a send whose previous retry is still awaiting a verdict.\n if (inFlight.has(entry.id)) {\n if (entry.sendFailure.fate === 'lost') lostPredecessorPending = true;\n continue;\n }\n if (awaitsLostPredecessor(entry) && (lostPredecessorPending || inFlight.size > 0)) {\n deferred.add(entry.id);\n if (!surfacedDeferrals.has(entry.id)) {\n surfacedDeferrals.add(entry.id);\n record('send-recovery/deferred', { messageId: entry.id });\n }\n continue;\n }\n const isLost = entry.sendFailure.fate === 'lost';\n const stamp = stamps?.get(entry.id);\n if (stamp !== undefined && now() - stamp > MAX_AUTO_RETRY_AGE_MS) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/stale', { messageId: entry.id, ageMs: Math.round(now() - stamp) });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n const attempt = (attempts.get(entry.id) ?? 0) + 1;\n if (attempt > MAX_AUTO_RETRIES_PER_MESSAGE) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/exhausted', { messageId: entry.id });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n let before: ReturnType<NonNullable<DeepAgentSendRecoveryOptions['beforeRetry']>> | undefined;\n try {\n before = options.beforeRetry?.(entry.id);\n } catch {\n // A host's own context step failing never holds the retry back.\n record('send-recovery/before-retry-failed', { messageId: entry.id });\n }\n if (isThenable(before)) {\n const held = (holds.get(entry.id) ?? 0) + 1;\n if (held <= MAX_BEFORE_RETRY_HOLDS) {\n // The host can't put this message's context back yet: it waits, and\n // so does everything behind it (nothing overtakes it); the sweep asks\n // again once the hold settles.\n holds.set(entry.id, held);\n holding = true;\n armed = true;\n record('send-recovery/held', { messageId: entry.id, holds: held });\n const resume = (): void => {\n holding = false;\n armed = true;\n scheduleSweep();\n };\n before.then(resume, resume);\n return;\n }\n record('send-recovery/held-too-long', { messageId: entry.id });\n }\n try {\n lane.retryFailed(entry.id);\n attempts.set(entry.id, attempt);\n inFlight.add(entry.id);\n if (isLost) lostPredecessorPending = true;\n record('send-recovery/retry', {\n messageId: entry.id,\n fate: entry.sendFailure.fate,\n attempt,\n });\n } catch {\n // The entry settled or was covered between the lane read and the\n // retry (the vendor drops covered failures against every snapshot);\n // nothing was dispatched, so the host lets go of what it put back.\n record('send-recovery/raced', { messageId: entry.id });\n try {\n if (typeof before === 'function') before();\n } catch {\n // The host's own step failing never stops the sweep.\n }\n }\n }\n // Held successors must be revisited once their predecessors settle.\n if (deferred.size > 0) armed = true;\n };\n\n const scheduleSweep = (): void => {\n if (disposed || sweepScheduled || holding || !hydrated || !armed) return;\n sweepScheduled = true;\n schedule(sweep);\n };\n\n return {\n observeStateChange(state) {\n if (disposed) return;\n if (!hydrated && isDeepAgentStateHydrated(state)) {\n // First real snapshot: the vendor's failureCovered pass has had its\n // chance to drop entries whose message actually landed, so whatever\n // remains provably never reached the thread.\n hydrated = true;\n armed = true;\n }\n scheduleSweep();\n },\n observeCommand(update) {\n if (disposed || update.status !== 'settled') return;\n const messageId = commandMessageId(update);\n if (messageId !== null) inFlight.delete(messageId);\n // A never-server-judged settle means new work; any settle while\n // successors are held may be the predecessor they wait on.\n if (!shouldAutoRetryFailedSend(update.failure) && deferred.size === 0) return;\n armed = true;\n scheduleSweep();\n },\n observeFailedLaneChange() {\n if (disposed) return;\n armed = true;\n scheduleSweep();\n },\n dispose() {\n disposed = true;\n },\n };\n}\n"],"names":["isDeepAgentStateHydrated"],"mappings":";;;AA0CA,MAAM,mBAAwC,oBAAI,IAAI,CAAC,QAAQ,SAAS,CAAC;AAIzE,MAAM,+BAA+B;AAKrC,MAAM,wBAAwB,KAAK,KAAK,KAAK;AAKtC,MAAM,yBAAyB;AAqD/B,SAAS,0BAA0B,SAAgD;AACxF,SAAO,YAAY,UAAa,iBAAiB,IAAI,QAAQ,IAAI;AACnE;AAGA,SAAS,sBAAsB,OAA0C;AACvE,SAAO,MAAM,YAAY,SAAS,aAAa,MAAM,YAAY,oBAAoB;AACvF;AAEA,SAAS,WAAW,OAA+C;AACjE,SACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;AAGA,SAAS,iBAAiB,QAA0D;;AAClF,QAAM,SAAQ,YAAO,WAAP,mBAAgB;AAC9B,QAAM,MAAK,oCAAO,YAAP,mBAAgB;AAC3B,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEO,SAAS,4BACd,SACuB;AACvB,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,WAAW,QAAQ,aAAa,CAAC,SAAqB,eAAe,IAAI;AAE/E,MAAI,WAAW;AACf,MAAI,WAAW;AAGf,MAAI,QAAQ;AACZ,MAAI,iBAAiB;AAErB,QAAM,+BAAe,IAAA;AAGrB,QAAM,oCAAoB,IAAA;AAE1B,QAAM,wCAAwB,IAAA;AAG9B,QAAM,+BAAe,IAAA;AAGrB,QAAM,+BAAe,IAAA;AAErB,QAAM,4BAAY,IAAA;AAElB,MAAI,UAAU;AAEd,QAAM,SAAS,CAAC,OAAe,SAAyC;;AACtE,wBAAQ,gBAAR,wDAAyB,OAAO,OAAO;AAAA,EACzC;AAEA,QAAM,QAAQ,MA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,CAAC,YAAYA,wCAAyB,KAAK,GAAG;AAIhD,mBAAW;AACX,gBAAQ;AAAA,MACV;AACA,oBAAA;AAAA,IACF;AAAA,IACA,eAAe,QAAQ;AACrB,UAAI,YAAY,OAAO,WAAW,UAAW;AAC7C,YAAM,YAAY,iBAAiB,MAAM;AACzC,UAAI,cAAc,KAAM,UAAS,OAAO,SAAS;AAGjD,UAAI,CAAC,0BAA0B,OAAO,OAAO,KAAK,SAAS,SAAS,EAAG;AACvE,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,0BAA0B;AACxB,UAAI,SAAU;AACd,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,UAAU;AACR,iBAAW;AAAA,IACb;AAAA,EAAA;AAEJ;;;;"}
@@ -1,5 +1,9 @@
1
1
  import type { StatewireDiagnosticsCommandUpdate, StatewireDiagnosticsRecorder } from './statewire-diagnostics';
2
2
  import type { StatewireFailedSendLane } from './thread-extras';
3
+ /** How many times a host may hold one message's retry (`beforeRetry`
4
+ * returning a promise) before the sweep sends it regardless: a hold is the
5
+ * host's own bounded wait, never a reason to keep a message back for good. */
6
+ export declare const MAX_BEFORE_RETRY_HOLDS = 10;
3
7
  export interface DeepAgentSendRecoveryOptions {
4
8
  /**
5
9
  * Reads the thread's failed-send lane. `null` while it is unavailable (the
@@ -21,6 +25,21 @@ export interface DeepAgentSendRecoveryOptions {
21
25
  /** Sweep scheduler; defaults to `queueMicrotask` so a sweep never dispatches
22
26
  * from inside a statewire flush or a React render. */
23
27
  schedule?: (task: () => void) => void;
28
+ /**
29
+ * Called right before a failed send is dispatched again, with its message
30
+ * id, so a host can put back the per-send context that message was sent
31
+ * with (Olympus stages the agents it named) before its command leaves.
32
+ *
33
+ * Returning a promise holds the retry: the host can't put that context back
34
+ * yet (every send of the conversation rides one ambient context, and a send
35
+ * with another context is still on its way). The sweep then stops at this
36
+ * message, so nothing behind it overtakes it, and asks again once the
37
+ * promise settles; past {@link MAX_BEFORE_RETRY_HOLDS} holds it sends the
38
+ * message regardless. A hook that throws never holds a retry back. A
39
+ * function returned is called when the message does not go after all (the
40
+ * retry raced its leaving the lane), so the host lets go of what it put back.
41
+ */
42
+ beforeRetry?: ((messageId: string) => void | PromiseLike<void> | (() => void)) | undefined;
24
43
  }
25
44
  export interface DeepAgentSendRecovery {
26
45
  /** Feed every (normalized) statewire state change; hydration arms the mount sweep. */
@@ -2,12 +2,16 @@ import { isDeepAgentStateHydrated } from "./statewire-state.js";
2
2
  const AUTO_RETRY_FATES = /* @__PURE__ */ new Set(["lost", "aborted"]);
3
3
  const MAX_AUTO_RETRIES_PER_MESSAGE = 3;
4
4
  const MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1e3;
5
+ const MAX_BEFORE_RETRY_HOLDS = 10;
5
6
  function shouldAutoRetryFailedSend(failure) {
6
7
  return failure !== void 0 && AUTO_RETRY_FATES.has(failure.fate);
7
8
  }
8
9
  function awaitsLostPredecessor(entry) {
9
10
  return entry.sendFailure.fate === "aborted" && entry.sendFailure.predecessorLost === true;
10
11
  }
12
+ function isThenable(value) {
13
+ return typeof value === "object" && value !== null && typeof value.then === "function";
14
+ }
11
15
  function commandMessageId(update) {
12
16
  var _a, _b;
13
17
  const first = (_a = update.params) == null ? void 0 : _a[0];
@@ -26,14 +30,16 @@ function createDeepAgentSendRecovery(options) {
26
30
  const surfacedDeferrals = /* @__PURE__ */ new Set();
27
31
  const inFlight = /* @__PURE__ */ new Set();
28
32
  const deferred = /* @__PURE__ */ new Set();
33
+ const holds = /* @__PURE__ */ new Map();
34
+ let holding = false;
29
35
  const record = (event, data) => {
30
36
  var _a, _b;
31
37
  (_b = (_a = options.diagnostics) == null ? void 0 : _a.call(options)) == null ? void 0 : _b.record(event, data);
32
38
  };
33
39
  const sweep = () => {
34
- var _a;
40
+ var _a, _b;
35
41
  sweepScheduled = false;
36
- if (disposed || !hydrated || !armed) return;
42
+ if (disposed || holding || !hydrated || !armed) return;
37
43
  const lane = options.lane();
38
44
  if (lane === null) return;
39
45
  armed = false;
@@ -73,6 +79,29 @@ function createDeepAgentSendRecovery(options) {
73
79
  if (isLost) lostPredecessorPending = true;
74
80
  continue;
75
81
  }
82
+ let before;
83
+ try {
84
+ before = (_b = options.beforeRetry) == null ? void 0 : _b.call(options, entry.id);
85
+ } catch {
86
+ record("send-recovery/before-retry-failed", { messageId: entry.id });
87
+ }
88
+ if (isThenable(before)) {
89
+ const held = (holds.get(entry.id) ?? 0) + 1;
90
+ if (held <= MAX_BEFORE_RETRY_HOLDS) {
91
+ holds.set(entry.id, held);
92
+ holding = true;
93
+ armed = true;
94
+ record("send-recovery/held", { messageId: entry.id, holds: held });
95
+ const resume = () => {
96
+ holding = false;
97
+ armed = true;
98
+ scheduleSweep();
99
+ };
100
+ before.then(resume, resume);
101
+ return;
102
+ }
103
+ record("send-recovery/held-too-long", { messageId: entry.id });
104
+ }
76
105
  try {
77
106
  lane.retryFailed(entry.id);
78
107
  attempts.set(entry.id, attempt);
@@ -85,12 +114,16 @@ function createDeepAgentSendRecovery(options) {
85
114
  });
86
115
  } catch {
87
116
  record("send-recovery/raced", { messageId: entry.id });
117
+ try {
118
+ if (typeof before === "function") before();
119
+ } catch {
120
+ }
88
121
  }
89
122
  }
90
123
  if (deferred.size > 0) armed = true;
91
124
  };
92
125
  const scheduleSweep = () => {
93
- if (disposed || sweepScheduled || !hydrated || !armed) return;
126
+ if (disposed || sweepScheduled || holding || !hydrated || !armed) return;
94
127
  sweepScheduled = true;
95
128
  schedule(sweep);
96
129
  };
@@ -122,6 +155,7 @@ function createDeepAgentSendRecovery(options) {
122
155
  };
123
156
  }
124
157
  export {
158
+ MAX_BEFORE_RETRY_HOLDS,
125
159
  createDeepAgentSendRecovery,
126
160
  shouldAutoRetryFailedSend
127
161
  };
@@ -1 +1 @@
1
- {"version":3,"file":"send-recovery.js","sources":["../../../../agent-runtime/src/send-recovery.ts"],"sourcesContent":["import type {\n StatewireDiagnosticsCommandUpdate,\n StatewireDiagnosticsRecorder,\n} from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated } from './statewire-state';\nimport type { StatewireFailedSendEntry, StatewireFailedSendLane } from './thread-extras';\n\n/**\n * Transport-level send durability for the deep-agent thread (the successor to\n * Olympus' localStorage outbox, #29368 → #31504).\n *\n * The durable journal itself is the statewire session record: every command is\n * persisted through the mounted session storage from `send()` until the server\n * durably admits or judges it, and a reload resends survivors on the SAME lane\n * seq (exactly-once — the server absorbs replayed seqs at or below its\n * watermark). What the record cannot recover on its own is a send the client\n * had to settle without a server verdict — a proven session loss or a record\n * reset settles it `lost`/`aborted` and RETAINS it in the record's failed lane\n * (message-carrying sends only), where the vendor drops it as soon as a\n * canonical snapshot shows the message landed (`failureCovered`).\n *\n * This controller turns that persisted failed lane back into live sends: once\n * the thread snapshot has hydrated (so covered entries are already gone), every\n * failed send the server NEVER judged is re-dispatched through the thread's own\n * `retryFailed` — same client-minted message id, re-anchored against the\n * current thread — which the host dedupes by id (a still-queued id re-places,\n * a durable one rejects `duplicate-id`). Server-judged fates (`rejected`,\n * `failed`, `crashed`, `expired`) are the user's decision and stay in the\n * manual retry/discard affordance.\n *\n * Ordering: an `aborted` send stamped `predecessorLost` was never attempted\n * because an earlier send of the same batch WAS attempted and settled `lost`\n * — it may or may not have run. Re-dispatching the successor first could land\n * it ahead of a predecessor that later turns out to have landed too, so the\n * successor is held until every preceding `lost` predecessor has settled: it\n * was covered by a snapshot, its retry was judged by the server, or the user\n * discarded it.\n */\n\n/** Fates the server never saw: the send died client-side (unmount, stream\n * gone, session lost) and is safe to re-dispatch under its original message\n * id. The complement — rejected/failed/crashed/expired — is server-judged. */\nconst AUTO_RETRY_FATES: ReadonlySet<string> = new Set(['lost', 'aborted']);\n\n/** A failed send is re-dispatched at most this many times per attach; a\n * persistent failure (repeated session losses) stays in the manual lane. */\nconst MAX_AUTO_RETRIES_PER_MESSAGE = 3;\n\n/** Persisted failures older than this stay manual: auto-sending a message the\n * user abandoned a day ago is worse than surfacing it for a decision. Mirrors\n * the retired outbox's retention window. */\nconst MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1000;\n\nexport interface DeepAgentSendRecoveryOptions {\n /**\n * Reads the thread's failed-send lane. `null` while it is unavailable (the\n * client has not mounted yet, or its extras are not a statewire thread) —\n * the controller stays armed and retries on the next state change.\n */\n lane: () => StatewireFailedSendLane | null;\n /**\n * Persisted failure stamps (message id → epoch ms of the original send) for\n * the freshness gate. `null`/absent means no persistence is readable — every\n * lane entry then counts as fresh (an in-memory failed lane can only hold\n * failures from this page session).\n */\n failureStamps?: (() => ReadonlyMap<string, number> | null) | undefined;\n /** Transport lifecycle recorder; read per event so a late-mounted recorder still sees retries. */\n diagnostics?: (() => StatewireDiagnosticsRecorder | undefined) | undefined;\n /** Injectable clock (tests). */\n now?: () => number;\n /** Sweep scheduler; defaults to `queueMicrotask` so a sweep never dispatches\n * from inside a statewire flush or a React render. */\n schedule?: (task: () => void) => void;\n}\n\nexport interface DeepAgentSendRecovery {\n /** Feed every (normalized) statewire state change; hydration arms the mount sweep. */\n observeStateChange(state: unknown): void;\n /** Feed every command-lifecycle update; a never-server-judged settle arms a sweep. */\n observeCommand(update: StatewireDiagnosticsCommandUpdate): void;\n /** Feed client notifications too: failed history can publish after the\n * command settles, without any change to the canonical thread snapshot. */\n observeFailedLaneChange(): void;\n dispose(): void;\n}\n\n/** Whether a settle failure is a client-side death the recovery re-dispatches\n * (the server never judged the command). Exported for host-side telemetry. */\nexport function shouldAutoRetryFailedSend(failure: { fate: string } | undefined): boolean {\n return failure !== undefined && AUTO_RETRY_FATES.has(failure.fate);\n}\n\n/** Whether a failed entry must wait for a lost predecessor to settle first. */\nfunction awaitsLostPredecessor(entry: StatewireFailedSendEntry): boolean {\n return entry.sendFailure.fate === 'aborted' && entry.sendFailure.predecessorLost === true;\n}\n\n/** The client-minted message id a run send carries, off a command update's params. */\nfunction commandMessageId(update: StatewireDiagnosticsCommandUpdate): string | null {\n const first = update.params?.[0] as { message?: { id?: unknown } } | undefined;\n const id = first?.message?.id;\n return typeof id === 'string' ? id : null;\n}\n\nexport function createDeepAgentSendRecovery(\n options: DeepAgentSendRecoveryOptions\n): DeepAgentSendRecovery {\n const now = options.now ?? Date.now;\n const schedule = options.schedule ?? ((task: () => void) => queueMicrotask(task));\n\n let disposed = false;\n let hydrated = false;\n /** Work may exist: set at hydration and on retryable settles, cleared by a\n * sweep that could actually read the lane. */\n let armed = false;\n let sweepScheduled = false;\n /** Retry budget per message id, for this controller's attach lifetime. */\n const attempts = new Map<string, number>();\n /** Message ids already diagnosed as stale/exhausted, so the lane re-scan\n * stays quiet about them. */\n const surfacedSkips = new Set<string>();\n /** Message ids whose deferral behind a lost predecessor was diagnosed once. */\n const surfacedDeferrals = new Set<string>();\n /** Re-dispatched sends still awaiting the server's verdict: a successor\n * stamped `predecessorLost` waits while any of these is pending. */\n const inFlight = new Set<string>();\n /** Successors held back by the last sweep; a non-empty set keeps the\n * controller armed so the next settle or state change re-sweeps. */\n const deferred = new Set<string>();\n\n const record = (event: string, data?: Record<string, unknown>): void => {\n options.diagnostics?.()?.record(event, data);\n };\n\n const sweep = (): void => {\n sweepScheduled = false;\n if (disposed || !hydrated || !armed) return;\n const lane = options.lane();\n // No readable lane yet: stay armed so the next state change re-sweeps.\n if (lane === null) return;\n armed = false;\n deferred.clear();\n const stamps = options.failureStamps?.() ?? null;\n // A `lost` entry earlier in lane order that this sweep leaves unsettled\n // (skipped as stale/exhausted, or re-dispatched and now in flight).\n let lostPredecessorPending = false;\n for (const entry of lane.failed) {\n if (!shouldAutoRetryFailedSend(entry.sendFailure)) continue;\n // Shared retry/discard may still be waiting for the storage lock. The\n // visible lane can keep this entry until then; do not spend another\n // attempt on a send whose previous retry is still awaiting a verdict.\n if (inFlight.has(entry.id)) {\n if (entry.sendFailure.fate === 'lost') lostPredecessorPending = true;\n continue;\n }\n if (awaitsLostPredecessor(entry) && (lostPredecessorPending || inFlight.size > 0)) {\n deferred.add(entry.id);\n if (!surfacedDeferrals.has(entry.id)) {\n surfacedDeferrals.add(entry.id);\n record('send-recovery/deferred', { messageId: entry.id });\n }\n continue;\n }\n const isLost = entry.sendFailure.fate === 'lost';\n const stamp = stamps?.get(entry.id);\n if (stamp !== undefined && now() - stamp > MAX_AUTO_RETRY_AGE_MS) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/stale', { messageId: entry.id, ageMs: Math.round(now() - stamp) });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n const attempt = (attempts.get(entry.id) ?? 0) + 1;\n if (attempt > MAX_AUTO_RETRIES_PER_MESSAGE) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/exhausted', { messageId: entry.id });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n try {\n lane.retryFailed(entry.id);\n attempts.set(entry.id, attempt);\n inFlight.add(entry.id);\n if (isLost) lostPredecessorPending = true;\n record('send-recovery/retry', {\n messageId: entry.id,\n fate: entry.sendFailure.fate,\n attempt,\n });\n } catch {\n // The entry settled or was covered between the lane read and the\n // retry (the vendor drops covered failures against every snapshot);\n // nothing was dispatched.\n record('send-recovery/raced', { messageId: entry.id });\n }\n }\n // Held successors must be revisited once their predecessors settle.\n if (deferred.size > 0) armed = true;\n };\n\n const scheduleSweep = (): void => {\n if (disposed || sweepScheduled || !hydrated || !armed) return;\n sweepScheduled = true;\n schedule(sweep);\n };\n\n return {\n observeStateChange(state) {\n if (disposed) return;\n if (!hydrated && isDeepAgentStateHydrated(state)) {\n // First real snapshot: the vendor's failureCovered pass has had its\n // chance to drop entries whose message actually landed, so whatever\n // remains provably never reached the thread.\n hydrated = true;\n armed = true;\n }\n scheduleSweep();\n },\n observeCommand(update) {\n if (disposed || update.status !== 'settled') return;\n const messageId = commandMessageId(update);\n if (messageId !== null) inFlight.delete(messageId);\n // A never-server-judged settle means new work; any settle while\n // successors are held may be the predecessor they wait on.\n if (!shouldAutoRetryFailedSend(update.failure) && deferred.size === 0) return;\n armed = true;\n scheduleSweep();\n },\n observeFailedLaneChange() {\n if (disposed) return;\n armed = true;\n scheduleSweep();\n },\n dispose() {\n disposed = true;\n },\n };\n}\n"],"names":[],"mappings":";AA0CA,MAAM,mBAAwC,oBAAI,IAAI,CAAC,QAAQ,SAAS,CAAC;AAIzE,MAAM,+BAA+B;AAKrC,MAAM,wBAAwB,KAAK,KAAK,KAAK;AAsCtC,SAAS,0BAA0B,SAAgD;AACxF,SAAO,YAAY,UAAa,iBAAiB,IAAI,QAAQ,IAAI;AACnE;AAGA,SAAS,sBAAsB,OAA0C;AACvE,SAAO,MAAM,YAAY,SAAS,aAAa,MAAM,YAAY,oBAAoB;AACvF;AAGA,SAAS,iBAAiB,QAA0D;;AAClF,QAAM,SAAQ,YAAO,WAAP,mBAAgB;AAC9B,QAAM,MAAK,oCAAO,YAAP,mBAAgB;AAC3B,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEO,SAAS,4BACd,SACuB;AACvB,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,WAAW,QAAQ,aAAa,CAAC,SAAqB,eAAe,IAAI;AAE/E,MAAI,WAAW;AACf,MAAI,WAAW;AAGf,MAAI,QAAQ;AACZ,MAAI,iBAAiB;AAErB,QAAM,+BAAe,IAAA;AAGrB,QAAM,oCAAoB,IAAA;AAE1B,QAAM,wCAAwB,IAAA;AAG9B,QAAM,+BAAe,IAAA;AAGrB,QAAM,+BAAe,IAAA;AAErB,QAAM,SAAS,CAAC,OAAe,SAAyC;;AACtE,wBAAQ,gBAAR,wDAAyB,OAAO,OAAO;AAAA,EACzC;AAEA,QAAM,QAAQ,MAAY;;AACxB,qBAAiB;AACjB,QAAI,YAAY,CAAC,YAAY,CAAC,MAAO;AACrC,UAAM,OAAO,QAAQ,KAAA;AAErB,QAAI,SAAS,KAAM;AACnB,YAAQ;AACR,aAAS,MAAA;AACT,UAAM,WAAS,aAAQ,kBAAR,qCAA6B;AAG5C,QAAI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AW,MAAM;AAAA,UACjB,MAAM,MAAM,YAAY;AAAA,UACxB;AAAA,QAAA,CACD;AAAA,MACH,QAAQ;AAIN,eAAO,uBAAuB,EAAE,WAAW,MAAM,IAAI;AAAA,MACvD;AAAA,IACF;AAEA,QAAI,SAAS,OAAO,EAAG,SAAQ;AAAA,EACjC;AAEA,QAAM,gBAAgB,MAAY;AAChC,QAAI,YAAY,kBAAkB,CAAC,YAAY,CAAC,MAAO;AACvD,qBAAiB;AACjB,aAAS,KAAK;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,mBAAmB,OAAO;AACxB,UAAI,SAAU;AACd,UAAI,CAAC,YAAY,yBAAyB,KAAK,GAAG;AAIhD,mBAAW;AACX,gBAAQ;AAAA,MACV;AACA,oBAAA;AAAA,IACF;AAAA,IACA,eAAe,QAAQ;AACrB,UAAI,YAAY,OAAO,WAAW,UAAW;AAC7C,YAAM,YAAY,iBAAiB,MAAM;AACzC,UAAI,cAAc,KAAM,UAAS,OAAO,SAAS;AAGjD,UAAI,CAAC,0BAA0B,OAAO,OAAO,KAAK,SAAS,SAAS,EAAG;AACvE,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,0BAA0B;AACxB,UAAI,SAAU;AACd,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,UAAU;AACR,iBAAW;AAAA,IACb;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"send-recovery.js","sources":["../../../../agent-runtime/src/send-recovery.ts"],"sourcesContent":["import type {\n StatewireDiagnosticsCommandUpdate,\n StatewireDiagnosticsRecorder,\n} from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated } from './statewire-state';\nimport type { StatewireFailedSendEntry, StatewireFailedSendLane } from './thread-extras';\n\n/**\n * Transport-level send durability for the deep-agent thread (the successor to\n * Olympus' localStorage outbox, #29368 → #31504).\n *\n * The durable journal itself is the statewire session record: every command is\n * persisted through the mounted session storage from `send()` until the server\n * durably admits or judges it, and a reload resends survivors on the SAME lane\n * seq (exactly-once — the server absorbs replayed seqs at or below its\n * watermark). What the record cannot recover on its own is a send the client\n * had to settle without a server verdict — a proven session loss or a record\n * reset settles it `lost`/`aborted` and RETAINS it in the record's failed lane\n * (message-carrying sends only), where the vendor drops it as soon as a\n * canonical snapshot shows the message landed (`failureCovered`).\n *\n * This controller turns that persisted failed lane back into live sends: once\n * the thread snapshot has hydrated (so covered entries are already gone), every\n * failed send the server NEVER judged is re-dispatched through the thread's own\n * `retryFailed` — same client-minted message id, re-anchored against the\n * current thread — which the host dedupes by id (a still-queued id re-places,\n * a durable one rejects `duplicate-id`). Server-judged fates (`rejected`,\n * `failed`, `crashed`, `expired`) are the user's decision and stay in the\n * manual retry/discard affordance.\n *\n * Ordering: an `aborted` send stamped `predecessorLost` was never attempted\n * because an earlier send of the same batch WAS attempted and settled `lost`\n * — it may or may not have run. Re-dispatching the successor first could land\n * it ahead of a predecessor that later turns out to have landed too, so the\n * successor is held until every preceding `lost` predecessor has settled: it\n * was covered by a snapshot, its retry was judged by the server, or the user\n * discarded it.\n */\n\n/** Fates the server never saw: the send died client-side (unmount, stream\n * gone, session lost) and is safe to re-dispatch under its original message\n * id. The complement — rejected/failed/crashed/expired — is server-judged. */\nconst AUTO_RETRY_FATES: ReadonlySet<string> = new Set(['lost', 'aborted']);\n\n/** A failed send is re-dispatched at most this many times per attach; a\n * persistent failure (repeated session losses) stays in the manual lane. */\nconst MAX_AUTO_RETRIES_PER_MESSAGE = 3;\n\n/** Persisted failures older than this stay manual: auto-sending a message the\n * user abandoned a day ago is worse than surfacing it for a decision. Mirrors\n * the retired outbox's retention window. */\nconst MAX_AUTO_RETRY_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** How many times a host may hold one message's retry (`beforeRetry`\n * returning a promise) before the sweep sends it regardless: a hold is the\n * host's own bounded wait, never a reason to keep a message back for good. */\nexport const MAX_BEFORE_RETRY_HOLDS = 10;\n\nexport interface DeepAgentSendRecoveryOptions {\n /**\n * Reads the thread's failed-send lane. `null` while it is unavailable (the\n * client has not mounted yet, or its extras are not a statewire thread) —\n * the controller stays armed and retries on the next state change.\n */\n lane: () => StatewireFailedSendLane | null;\n /**\n * Persisted failure stamps (message id → epoch ms of the original send) for\n * the freshness gate. `null`/absent means no persistence is readable — every\n * lane entry then counts as fresh (an in-memory failed lane can only hold\n * failures from this page session).\n */\n failureStamps?: (() => ReadonlyMap<string, number> | null) | undefined;\n /** Transport lifecycle recorder; read per event so a late-mounted recorder still sees retries. */\n diagnostics?: (() => StatewireDiagnosticsRecorder | undefined) | undefined;\n /** Injectable clock (tests). */\n now?: () => number;\n /** Sweep scheduler; defaults to `queueMicrotask` so a sweep never dispatches\n * from inside a statewire flush or a React render. */\n schedule?: (task: () => void) => void;\n /**\n * Called right before a failed send is dispatched again, with its message\n * id, so a host can put back the per-send context that message was sent\n * with (Olympus stages the agents it named) before its command leaves.\n *\n * Returning a promise holds the retry: the host can't put that context back\n * yet (every send of the conversation rides one ambient context, and a send\n * with another context is still on its way). The sweep then stops at this\n * message, so nothing behind it overtakes it, and asks again once the\n * promise settles; past {@link MAX_BEFORE_RETRY_HOLDS} holds it sends the\n * message regardless. A hook that throws never holds a retry back. A\n * function returned is called when the message does not go after all (the\n * retry raced its leaving the lane), so the host lets go of what it put back.\n */\n beforeRetry?: ((messageId: string) => void | PromiseLike<void> | (() => void)) | undefined;\n}\n\nexport interface DeepAgentSendRecovery {\n /** Feed every (normalized) statewire state change; hydration arms the mount sweep. */\n observeStateChange(state: unknown): void;\n /** Feed every command-lifecycle update; a never-server-judged settle arms a sweep. */\n observeCommand(update: StatewireDiagnosticsCommandUpdate): void;\n /** Feed client notifications too: failed history can publish after the\n * command settles, without any change to the canonical thread snapshot. */\n observeFailedLaneChange(): void;\n dispose(): void;\n}\n\n/** Whether a settle failure is a client-side death the recovery re-dispatches\n * (the server never judged the command). Exported for host-side telemetry. */\nexport function shouldAutoRetryFailedSend(failure: { fate: string } | undefined): boolean {\n return failure !== undefined && AUTO_RETRY_FATES.has(failure.fate);\n}\n\n/** Whether a failed entry must wait for a lost predecessor to settle first. */\nfunction awaitsLostPredecessor(entry: StatewireFailedSendEntry): boolean {\n return entry.sendFailure.fate === 'aborted' && entry.sendFailure.predecessorLost === true;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\n/** The client-minted message id a run send carries, off a command update's params. */\nfunction commandMessageId(update: StatewireDiagnosticsCommandUpdate): string | null {\n const first = update.params?.[0] as { message?: { id?: unknown } } | undefined;\n const id = first?.message?.id;\n return typeof id === 'string' ? id : null;\n}\n\nexport function createDeepAgentSendRecovery(\n options: DeepAgentSendRecoveryOptions\n): DeepAgentSendRecovery {\n const now = options.now ?? Date.now;\n const schedule = options.schedule ?? ((task: () => void) => queueMicrotask(task));\n\n let disposed = false;\n let hydrated = false;\n /** Work may exist: set at hydration and on retryable settles, cleared by a\n * sweep that could actually read the lane. */\n let armed = false;\n let sweepScheduled = false;\n /** Retry budget per message id, for this controller's attach lifetime. */\n const attempts = new Map<string, number>();\n /** Message ids already diagnosed as stale/exhausted, so the lane re-scan\n * stays quiet about them. */\n const surfacedSkips = new Set<string>();\n /** Message ids whose deferral behind a lost predecessor was diagnosed once. */\n const surfacedDeferrals = new Set<string>();\n /** Re-dispatched sends still awaiting the server's verdict: a successor\n * stamped `predecessorLost` waits while any of these is pending. */\n const inFlight = new Set<string>();\n /** Successors held back by the last sweep; a non-empty set keeps the\n * controller armed so the next settle or state change re-sweeps. */\n const deferred = new Set<string>();\n /** How many times the host held each message's retry (`beforeRetry`'s promise). */\n const holds = new Map<string, number>();\n /** A host's hold in progress: no sweep runs until it settles. */\n let holding = false;\n\n const record = (event: string, data?: Record<string, unknown>): void => {\n options.diagnostics?.()?.record(event, data);\n };\n\n const sweep = (): void => {\n sweepScheduled = false;\n // A host's hold re-sweeps once it settles; until then nothing is retried.\n if (disposed || holding || !hydrated || !armed) return;\n const lane = options.lane();\n // No readable lane yet: stay armed so the next state change re-sweeps.\n if (lane === null) return;\n armed = false;\n deferred.clear();\n const stamps = options.failureStamps?.() ?? null;\n // A `lost` entry earlier in lane order that this sweep leaves unsettled\n // (skipped as stale/exhausted, or re-dispatched and now in flight).\n let lostPredecessorPending = false;\n for (const entry of lane.failed) {\n if (!shouldAutoRetryFailedSend(entry.sendFailure)) continue;\n // Shared retry/discard may still be waiting for the storage lock. The\n // visible lane can keep this entry until then; do not spend another\n // attempt on a send whose previous retry is still awaiting a verdict.\n if (inFlight.has(entry.id)) {\n if (entry.sendFailure.fate === 'lost') lostPredecessorPending = true;\n continue;\n }\n if (awaitsLostPredecessor(entry) && (lostPredecessorPending || inFlight.size > 0)) {\n deferred.add(entry.id);\n if (!surfacedDeferrals.has(entry.id)) {\n surfacedDeferrals.add(entry.id);\n record('send-recovery/deferred', { messageId: entry.id });\n }\n continue;\n }\n const isLost = entry.sendFailure.fate === 'lost';\n const stamp = stamps?.get(entry.id);\n if (stamp !== undefined && now() - stamp > MAX_AUTO_RETRY_AGE_MS) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/stale', { messageId: entry.id, ageMs: Math.round(now() - stamp) });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n const attempt = (attempts.get(entry.id) ?? 0) + 1;\n if (attempt > MAX_AUTO_RETRIES_PER_MESSAGE) {\n if (!surfacedSkips.has(entry.id)) {\n surfacedSkips.add(entry.id);\n record('send-recovery/exhausted', { messageId: entry.id });\n }\n if (isLost) lostPredecessorPending = true;\n continue;\n }\n let before: ReturnType<NonNullable<DeepAgentSendRecoveryOptions['beforeRetry']>> | undefined;\n try {\n before = options.beforeRetry?.(entry.id);\n } catch {\n // A host's own context step failing never holds the retry back.\n record('send-recovery/before-retry-failed', { messageId: entry.id });\n }\n if (isThenable(before)) {\n const held = (holds.get(entry.id) ?? 0) + 1;\n if (held <= MAX_BEFORE_RETRY_HOLDS) {\n // The host can't put this message's context back yet: it waits, and\n // so does everything behind it (nothing overtakes it); the sweep asks\n // again once the hold settles.\n holds.set(entry.id, held);\n holding = true;\n armed = true;\n record('send-recovery/held', { messageId: entry.id, holds: held });\n const resume = (): void => {\n holding = false;\n armed = true;\n scheduleSweep();\n };\n before.then(resume, resume);\n return;\n }\n record('send-recovery/held-too-long', { messageId: entry.id });\n }\n try {\n lane.retryFailed(entry.id);\n attempts.set(entry.id, attempt);\n inFlight.add(entry.id);\n if (isLost) lostPredecessorPending = true;\n record('send-recovery/retry', {\n messageId: entry.id,\n fate: entry.sendFailure.fate,\n attempt,\n });\n } catch {\n // The entry settled or was covered between the lane read and the\n // retry (the vendor drops covered failures against every snapshot);\n // nothing was dispatched, so the host lets go of what it put back.\n record('send-recovery/raced', { messageId: entry.id });\n try {\n if (typeof before === 'function') before();\n } catch {\n // The host's own step failing never stops the sweep.\n }\n }\n }\n // Held successors must be revisited once their predecessors settle.\n if (deferred.size > 0) armed = true;\n };\n\n const scheduleSweep = (): void => {\n if (disposed || sweepScheduled || holding || !hydrated || !armed) return;\n sweepScheduled = true;\n schedule(sweep);\n };\n\n return {\n observeStateChange(state) {\n if (disposed) return;\n if (!hydrated && isDeepAgentStateHydrated(state)) {\n // First real snapshot: the vendor's failureCovered pass has had its\n // chance to drop entries whose message actually landed, so whatever\n // remains provably never reached the thread.\n hydrated = true;\n armed = true;\n }\n scheduleSweep();\n },\n observeCommand(update) {\n if (disposed || update.status !== 'settled') return;\n const messageId = commandMessageId(update);\n if (messageId !== null) inFlight.delete(messageId);\n // A never-server-judged settle means new work; any settle while\n // successors are held may be the predecessor they wait on.\n if (!shouldAutoRetryFailedSend(update.failure) && deferred.size === 0) return;\n armed = true;\n scheduleSweep();\n },\n observeFailedLaneChange() {\n if (disposed) return;\n armed = true;\n scheduleSweep();\n },\n dispose() {\n disposed = true;\n },\n };\n}\n"],"names":[],"mappings":";AA0CA,MAAM,mBAAwC,oBAAI,IAAI,CAAC,QAAQ,SAAS,C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,UAAI,CAAC,0BAA0B,OAAO,OAAO,KAAK,SAAS,SAAS,EAAG;AACvE,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,0BAA0B;AACxB,UAAI,SAAU;AACd,cAAQ;AACR,oBAAA;AAAA,IACF;AAAA,IACA,UAAU;AACR,iBAAW;AAAA,IACb;AAAA,EAAA;AAEJ;"}
@@ -72,19 +72,19 @@ export declare const threadHandoffFlowMachine: import("xstate").StateMachine<Han
72
72
  } | {
73
73
  kind: "office_invitation";
74
74
  host: "excel" | "powerpoint" | "word";
75
+ } | {
76
+ kind: "chrome";
75
77
  } | {
76
78
  kind: "spaces";
77
79
  url: string;
80
+ } | {
81
+ kind: "next";
78
82
  } | {
79
83
  kind: "desktop";
80
84
  scheme_url: string;
81
85
  download_url: string;
82
86
  deployment_url: string;
83
87
  protocol_version: 1;
84
- } | {
85
- kind: "chrome";
86
- } | {
87
- kind: "next";
88
88
  };
89
89
  }, {
90
90
  run: ThreadHandoffRun;
@@ -132,19 +132,19 @@ export declare const threadHandoffFlowMachine: import("xstate").StateMachine<Han
132
132
  } | {
133
133
  kind: "office_invitation";
134
134
  host: "excel" | "powerpoint" | "word";
135
+ } | {
136
+ kind: "chrome";
135
137
  } | {
136
138
  kind: "spaces";
137
139
  url: string;
140
+ } | {
141
+ kind: "next";
138
142
  } | {
139
143
  kind: "desktop";
140
144
  scheme_url: string;
141
145
  download_url: string;
142
146
  deployment_url: string;
143
147
  protocol_version: 1;
144
- } | {
145
- kind: "chrome";
146
- } | {
147
- kind: "next";
148
148
  };
149
149
  }, {
150
150
  run: ThreadHandoffRun;
@@ -94,6 +94,54 @@ export declare const destinationReadinessSchema: z.ZodObject<{
94
94
  marketplace_url: z.ZodOptional<z.ZodNullable<z.ZodString>>;
95
95
  }, z.core.$strip>;
96
96
  export type DestinationReadiness = z.infer<typeof destinationReadinessSchema>;
97
+ /**
98
+ * How recently one of the person's four apps was seen, from a real signal: the desktop app and
99
+ * Chrome by their device tunnel, the phone by its foreground ping (or its push token), Spaces by
100
+ * workspace awareness. `live` is open right now; `recent` within minutes; `seen` longer ago;
101
+ * `not_seen` no evidence; `unknown` no signal to judge by; `unsupported` not in this environment.
102
+ */
103
+ export declare const surfaceLivenessStateSchema: z.ZodEnum<{
104
+ live: "live";
105
+ not_seen: "not_seen";
106
+ recent: "recent";
107
+ seen: "seen";
108
+ unknown: "unknown";
109
+ unsupported: "unsupported";
110
+ }>;
111
+ export type SurfaceLivenessState = z.infer<typeof surfaceLivenessStateSchema>;
112
+ /** The signal a liveness row rests on. */
113
+ export declare const surfaceLivenessBasisSchema: z.ZodEnum<{
114
+ awareness: "awareness";
115
+ device_tunnel: "device_tunnel";
116
+ foreground: "foreground";
117
+ push_token: "push_token";
118
+ }>;
119
+ export type SurfaceLivenessBasis = z.infer<typeof surfaceLivenessBasisSchema>;
120
+ export declare const surfaceLivenessSchema: z.ZodObject<{
121
+ surface: z.ZodEnum<{
122
+ chrome: "chrome";
123
+ desktop: "desktop";
124
+ mobile: "mobile";
125
+ spaces: "spaces";
126
+ }>;
127
+ state: z.ZodEnum<{
128
+ live: "live";
129
+ not_seen: "not_seen";
130
+ recent: "recent";
131
+ seen: "seen";
132
+ unknown: "unknown";
133
+ unsupported: "unsupported";
134
+ }>;
135
+ basis: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
136
+ awareness: "awareness";
137
+ device_tunnel: "device_tunnel";
138
+ foreground: "foreground";
139
+ push_token: "push_token";
140
+ }>>>;
141
+ last_seen_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
142
+ label: z.ZodOptional<z.ZodNullable<z.ZodString>>;
143
+ }, z.core.$strip>;
144
+ export type SurfaceLiveness = z.infer<typeof surfaceLivenessSchema>;
97
145
  export declare const handoffReadinessResponseSchema: z.ZodObject<{
98
146
  environment: z.ZodEnum<{
99
147
  localhost: "localhost";
@@ -122,11 +170,44 @@ export declare const handoffReadinessResponseSchema: z.ZodObject<{
122
170
  supports_office_invitations: z.ZodOptional<z.ZodBoolean>;
123
171
  supports_desktop_source: z.ZodOptional<z.ZodBoolean>;
124
172
  supports_surface_destinations: z.ZodOptional<z.ZodBoolean>;
173
+ supports_surface_liveness: z.ZodOptional<z.ZodBoolean>;
174
+ surfaces: z.ZodCatch<z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodUnknown>, z.ZodTransform<{
175
+ surface: "chrome" | "desktop" | "mobile" | "spaces";
176
+ state: "live" | "not_seen" | "recent" | "seen" | "unknown" | "unsupported";
177
+ basis?: "awareness" | "device_tunnel" | "foreground" | "push_token" | null | undefined;
178
+ last_seen_at?: string | null | undefined;
179
+ label?: string | null | undefined;
180
+ }[], unknown[]>>>>;
125
181
  }, z.core.$strip>;
126
182
  export type HandoffReadinessResponse = z.infer<typeof handoffReadinessResponseSchema>;
127
183
  export declare const supportsDesktopHandoffSource: (readiness: HandoffReadinessResponse | null | undefined) => boolean;
128
184
  /** Whether the server can broker the four-surface destinations; absent means an older agora. */
129
185
  export declare const supportsSurfaceHandoffDestinations: (readiness: HandoffReadinessResponse | null | undefined) => boolean;
186
+ /** Whether the server reports where the person's apps were last seen; absent means an older agora. */
187
+ export declare const supportsSurfaceLiveness: (readiness: HandoffReadinessResponse | null | undefined) => boolean;
188
+ /** Index liveness rows by surface; `null` where the server sent none (or can't report liveness). */
189
+ export declare const surfaceLivenessBySurface: (readiness: HandoffReadinessResponse | null | undefined) => Record<PickupSurface, SurfaceLiveness | null>;
190
+ /** "just now", "4 min ago", "3 hr ago", "yesterday", "5 days ago". */
191
+ export declare const livenessAgo: ({ at, now }: {
192
+ at: number;
193
+ now: number;
194
+ }) => string;
195
+ export type SurfaceLivenessTone = 'live' | 'recent' | 'idle';
196
+ /** What a "Continue on…" row says about where that app was last seen, and how warm it is. */
197
+ export interface SurfaceLivenessPresentation {
198
+ text: string;
199
+ tone: SurfaceLivenessTone;
200
+ }
201
+ /**
202
+ * The one wording every picker shows for a surface's liveness ("Open now on your Mac", "Chrome is
203
+ * running", "Your phone was active 2 min ago"). `null` when there is nothing real to say (no row,
204
+ * an older server, `unknown`, `unsupported`): the row then keeps the text it shows today.
205
+ */
206
+ export declare const presentSurfaceLiveness: ({ surface, liveness, now, }: {
207
+ surface: PickupSurface;
208
+ liveness: SurfaceLiveness | null | undefined;
209
+ now?: number;
210
+ }) => SurfaceLivenessPresentation | null;
130
211
  export declare const threadHandoffViewSchema: z.ZodObject<{
131
212
  handoff_id: z.ZodString;
132
213
  thread_id: z.ZodString;
@@ -368,11 +449,29 @@ export interface CreateThreadHandoffInput {
368
449
  officeLaunchMode?: OfficeLaunchMode;
369
450
  /** An observed workspace precondition, never an authorization grant. */
370
451
  expectedWorkspaceId?: string;
371
- /** The composer's unsent text; the destination prefills it and never sends it. */
452
+ /**
453
+ * The composer's unsent text; the destination prefills it and never sends
454
+ * it. Blank (the composer is empty) clears an open ticket's draft; omitted
455
+ * leaves it. See {@link handoffDraftToCarry}.
456
+ */
372
457
  draft?: string;
373
458
  /** `voice` offers "Continue by voice" on the destination. Omitted means text. */
374
459
  mode?: HandoffMode;
375
460
  }
461
+ /**
462
+ * The draft a create carries, the one rule every source follows. An Office
463
+ * pane never gets one: it neither prefills nor continues by voice. Anywhere
464
+ * else a surface that read its composer sends what it holds, within the
465
+ * server's bound, and a blank composer as `''`: agora reuses an open ticket
466
+ * for the same thread, destination and mode, and an empty draft clears the
467
+ * one that ticket stored, so text the person deleted never comes back at the
468
+ * destination. `undefined` or `null` (the surface could not read a composer)
469
+ * sends none and leaves an open ticket's draft as it was.
470
+ */
471
+ export declare function handoffDraftToCarry({ destination, draft, }: {
472
+ destination: ThreadHandoffDestination;
473
+ draft: string | null | undefined;
474
+ }): string | undefined;
376
475
  /** A phone invites the computer's pane; other sources keep their existing launch. */
377
476
  export declare function resolveOfficeHandoffLaunchMode({ source, destination, officeLaunchMode, }: CreateThreadHandoffInput): OfficeLaunchMode | undefined;
378
477
  /** The same request body for every host's authenticated HTTP adapter. */
@@ -599,6 +698,19 @@ export interface ThreadHandoffTransport {
599
698
  export declare const HANDOFF_DESTINATION_LABELS: Record<HandoffDestination, string>;
600
699
  /** Picker labels for every destination a "Continue on…" row can name. */
601
700
  export declare const THREAD_HANDOFF_DESTINATION_LABELS: Record<ThreadHandoffDestination, string>;
701
+ /**
702
+ * How a landing names the surface a conversation came from ("Continued from …"), and every other
703
+ * "from …" an app says about another (a device's "Athena is using Mail, from your phone").
704
+ */
705
+ export declare const HANDOFF_ORIGIN_LABELS: {
706
+ readonly spaces: 'Spaces';
707
+ readonly mobile: 'your phone';
708
+ readonly chrome: 'Chrome';
709
+ readonly desktop: 'Athena Desktop';
710
+ readonly word: 'Word';
711
+ readonly powerpoint: 'PowerPoint';
712
+ readonly excel: 'Excel';
713
+ };
602
714
  /** "Pick up your conversation from your phone?" — a destination's offer, before any claim. */
603
715
  export declare const pickUpOfferLabel: (source: string) => string;
604
716
  /** "Continued from your phone" — the divider a destination shows where it picked up. */
@@ -1,3 +1,3 @@
1
1
  /** Backward-compatible entrypoint. Use the protocol entrypoint without QR rendering. */
2
- export { type CreateThreadHandoffInput, type CreateThreadHandoffResponse, type DestinationReadiness, HANDOFF_DESTINATIONS, HANDOFF_DESTINATION_LABELS, HANDOFF_URL_PARAM, type HandoffDestination, type HandoffDestinationPresentation, type HandoffEnvironment, HandoffGoneError, type HandoffLaunch, type HandoffOutcome, HandoffPermanentError, type HandoffReadinessResponse, type HandoffReadinessState, type HandoffSource, type HandoffState, type HandoffTransportErrorKind, MOBILE_APP_SCHEME, type MobileHandoffLaunch, type MobileLaunchMode, OFFICE_HANDOFF_DESTINATIONS, type OfficeHandoffDestination, type OfficeHandoffLaunch, type OfficeInvitationLaunch, type OfficeLaunchMode, SERVER_HANDOFF_DESTINATIONS, type ServerHandoffDestination, type ThreadHandoffTransport, type ThreadHandoffView, type WaitForHandoffOutcomeOptions, buildMobileHandoffSchemeUrl, chromeHandoffLaunchSchema, classifyHandoffTransportError, createThreadHandoffResponseSchema, describeHandoffTransportError, destinationReadinessSchema, handoffEnvironmentSchema, handoffHttpError, handoffLaunchSchema, handoffReadinessResponseSchema, handoffReadinessStateSchema, handoffStateSchema, isHandoffGoneError, isHandoffPermanentError, isOfficeHandoffDestination, isRetryableHandoffHttpStatus, isServerHandoffDestination, isTerminalHandoffState, mobileHandoffLaunchSchema, officeHandoffLaunchSchema, officeInvitationLaunchSchema, officeLaunchModeSchema, parseHandoffIdParam, presentHandoffDestination, readinessByDestination, resolveOfficeHandoffLaunchMode, selectMobileLaunchMode, supportsDesktopHandoffSource, threadHandoffCreateBody, threadHandoffViewSchema, waitForHandoffOutcome, type ClaimThreadHandoffResponse, claimThreadHandoffResponseSchema, clampHandoffDraft, continuedFromLabel, pickUpFromLabel, pickUpOfferLabel, type DesktopThreadHandoffLaunch, desktopThreadHandoffLaunchSchema, driverSurfaceForChannel, drivingOnLabel, type HandoffLanding, handoffLandingFromView, isPickupSurface, MAX_HANDOFF_DRAFT_LENGTH, nextHandoffLaunchSchema, parseThreadHandoffCreateResponse, pendingThreadHandoffResponseSchema, pickedUpOnLabel, PICKUP_SURFACES, type PickupSurface, shouldOfferPendingHandoff, SPACES_HANDOFF_URL_PARAM, type SpacesHandoffLaunch, spacesHandoffLaunchSchema, SURFACE_HANDOFF_DESTINATIONS, type SurfaceHandoffDestination, supportsSurfaceHandoffDestinations, THREAD_HANDOFF_DESTINATION_LABELS, THREAD_HANDOFF_DESTINATIONS, threadHandoffClaimBody, threadHandoffCreateRequest, type ThreadHandoffDestination, type ThreadHandoffReceiverTransport, MAX_PENDING_EXCLUDE, pendingExcludeIds, pickupExcludeIds, pendingHandoffPath, type HandoffMode, handoffModeSchema, isVoiceHandoffDestination, } from './thread-handoff-protocol';
2
+ export { type CreateThreadHandoffInput, type CreateThreadHandoffResponse, type DestinationReadiness, HANDOFF_DESTINATIONS, HANDOFF_DESTINATION_LABELS, HANDOFF_URL_PARAM, type HandoffDestination, type HandoffDestinationPresentation, type HandoffEnvironment, HandoffGoneError, type HandoffLaunch, type HandoffOutcome, HandoffPermanentError, type HandoffReadinessResponse, type HandoffReadinessState, type HandoffSource, type HandoffState, type HandoffTransportErrorKind, MOBILE_APP_SCHEME, type MobileHandoffLaunch, type MobileLaunchMode, OFFICE_HANDOFF_DESTINATIONS, type OfficeHandoffDestination, type OfficeHandoffLaunch, type OfficeInvitationLaunch, type OfficeLaunchMode, SERVER_HANDOFF_DESTINATIONS, type ServerHandoffDestination, type ThreadHandoffTransport, type ThreadHandoffView, type WaitForHandoffOutcomeOptions, buildMobileHandoffSchemeUrl, chromeHandoffLaunchSchema, classifyHandoffTransportError, createThreadHandoffResponseSchema, describeHandoffTransportError, destinationReadinessSchema, handoffEnvironmentSchema, handoffHttpError, handoffLaunchSchema, handoffReadinessResponseSchema, handoffReadinessStateSchema, handoffStateSchema, isHandoffGoneError, isHandoffPermanentError, isOfficeHandoffDestination, isRetryableHandoffHttpStatus, isServerHandoffDestination, isTerminalHandoffState, mobileHandoffLaunchSchema, officeHandoffLaunchSchema, officeInvitationLaunchSchema, officeLaunchModeSchema, parseHandoffIdParam, presentHandoffDestination, readinessByDestination, resolveOfficeHandoffLaunchMode, selectMobileLaunchMode, supportsDesktopHandoffSource, threadHandoffCreateBody, threadHandoffViewSchema, waitForHandoffOutcome, type ClaimThreadHandoffResponse, claimThreadHandoffResponseSchema, clampHandoffDraft, handoffDraftToCarry, continuedFromLabel, pickUpFromLabel, pickUpOfferLabel, type DesktopThreadHandoffLaunch, desktopThreadHandoffLaunchSchema, driverSurfaceForChannel, drivingOnLabel, type HandoffLanding, handoffLandingFromView, isPickupSurface, MAX_HANDOFF_DRAFT_LENGTH, nextHandoffLaunchSchema, parseThreadHandoffCreateResponse, pendingThreadHandoffResponseSchema, pickedUpOnLabel, PICKUP_SURFACES, type PickupSurface, shouldOfferPendingHandoff, SPACES_HANDOFF_URL_PARAM, type SpacesHandoffLaunch, spacesHandoffLaunchSchema, SURFACE_HANDOFF_DESTINATIONS, type SurfaceHandoffDestination, supportsSurfaceHandoffDestinations, THREAD_HANDOFF_DESTINATION_LABELS, THREAD_HANDOFF_DESTINATIONS, threadHandoffClaimBody, threadHandoffCreateRequest, type ThreadHandoffDestination, type ThreadHandoffReceiverTransport, MAX_PENDING_EXCLUDE, pendingExcludeIds, pickupExcludeIds, pendingHandoffPath, type HandoffMode, handoffModeSchema, isVoiceHandoffDestination, livenessAgo, presentSurfaceLiveness, type SurfaceLiveness, type SurfaceLivenessBasis, surfaceLivenessBasisSchema, surfaceLivenessBySurface, type SurfaceLivenessPresentation, surfaceLivenessSchema, type SurfaceLivenessState, surfaceLivenessStateSchema, type SurfaceLivenessTone, supportsSurfaceLiveness, } from './thread-handoff-protocol';
3
3
  export { buildHandoffQrSvg } from './thread-handoff-qr';
@@ -7,7 +7,7 @@ const DEFAULT_PAGE_SIZE = 20;
7
7
  const DEFAULT_STALE_TIME_MS = 3e4;
8
8
  const DEFAULT_GC_TIME_MS = 10 * 60 * 1e3;
9
9
  function useConversationList(options) {
10
- var _a, _b, _c;
10
+ var _a, _b, _c, _d;
11
11
  const {
12
12
  filter,
13
13
  pageSize = DEFAULT_PAGE_SIZE,
@@ -133,10 +133,11 @@ function useConversationList(options) {
133
133
  return {
134
134
  conversations,
135
135
  totalCount: ((_b = firstPage.data) == null ? void 0 : _b.totalCount) ?? null,
136
+ homeAgentApplied: ((_c = firstPage.data) == null ? void 0 : _c.homeAgentApplied) === true,
136
137
  isLoading: firstPage.isLoading,
137
138
  isFetching: firstPage.isFetching || history.isFetching,
138
139
  hasResolvedFirstPage: firstPage.data !== void 0,
139
- hasNextPage: hasLoadedHistory ? history.hasNextPage ?? false : ((_c = firstPage.data) == null ? void 0 : _c.hasMore) ?? false,
140
+ hasNextPage: hasLoadedHistory ? history.hasNextPage ?? false : ((_d = firstPage.data) == null ? void 0 : _d.hasMore) ?? false,
140
141
  isFetchingNextPage: history.isFetchingNextPage || !hasLoadedHistory && history.isFetching,
141
142
  isFetchNextPageError: history.isError,
142
143
  fetchNextPage,