@athenaintel/react 0.41.2 → 0.42.1

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 (451) hide show
  1. package/README.md +108 -9
  2. package/dist/agent-runtime/src/asset-attachment.d.ts +98 -0
  3. package/dist/agent-runtime/src/athena-asset-drag.d.ts +32 -0
  4. package/dist/agent-runtime/src/auth-denial.d.ts +29 -0
  5. package/dist/agent-runtime/src/chat-outbox-attachments.cjs +41 -0
  6. package/dist/agent-runtime/src/chat-outbox-attachments.cjs.map +1 -0
  7. package/dist/agent-runtime/src/chat-outbox-attachments.d.ts +38 -0
  8. package/dist/agent-runtime/src/chat-outbox-attachments.js +41 -0
  9. package/dist/agent-runtime/src/chat-outbox-attachments.js.map +1 -0
  10. package/dist/agent-runtime/src/chat-outbox-signals.cjs +63 -0
  11. package/dist/agent-runtime/src/chat-outbox-signals.cjs.map +1 -0
  12. package/dist/agent-runtime/src/chat-outbox-signals.d.ts +12 -0
  13. package/dist/agent-runtime/src/chat-outbox-signals.js +63 -0
  14. package/dist/agent-runtime/src/chat-outbox-signals.js.map +1 -0
  15. package/dist/agent-runtime/src/chat-outbox-store.cjs +509 -0
  16. package/dist/agent-runtime/src/chat-outbox-store.cjs.map +1 -0
  17. package/dist/agent-runtime/src/chat-outbox-store.d.ts +203 -0
  18. package/dist/agent-runtime/src/chat-outbox-store.js +509 -0
  19. package/dist/agent-runtime/src/chat-outbox-store.js.map +1 -0
  20. package/dist/agent-runtime/src/chat-outbox-thread.cjs +136 -0
  21. package/dist/agent-runtime/src/chat-outbox-thread.cjs.map +1 -0
  22. package/dist/agent-runtime/src/chat-outbox-thread.d.ts +118 -0
  23. package/dist/agent-runtime/src/chat-outbox-thread.js +136 -0
  24. package/dist/agent-runtime/src/chat-outbox-thread.js.map +1 -0
  25. package/dist/agent-runtime/src/chat-outbox.cjs +696 -0
  26. package/dist/agent-runtime/src/chat-outbox.cjs.map +1 -0
  27. package/dist/agent-runtime/src/chat-outbox.d.ts +285 -0
  28. package/dist/agent-runtime/src/chat-outbox.js +696 -0
  29. package/dist/agent-runtime/src/chat-outbox.js.map +1 -0
  30. package/dist/agent-runtime/src/chat-socket-reachability.d.ts +45 -0
  31. package/dist/agent-runtime/src/client-tool-bridge.d.ts +152 -0
  32. package/dist/agent-runtime/src/client-tools.d.ts +133 -0
  33. package/dist/agent-runtime/src/composer-markdown.cjs +10 -0
  34. package/dist/agent-runtime/src/composer-markdown.cjs.map +1 -1
  35. package/dist/agent-runtime/src/composer-markdown.d.ts +108 -0
  36. package/dist/agent-runtime/src/composer-markdown.js +10 -0
  37. package/dist/agent-runtime/src/composer-markdown.js.map +1 -1
  38. package/dist/agent-runtime/src/config-mutations.d.ts +51 -0
  39. package/dist/agent-runtime/src/conversation-index.d.ts +110 -0
  40. package/dist/agent-runtime/src/conversation-list.d.ts +343 -0
  41. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +3 -2
  42. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  43. package/dist/agent-runtime/src/deep-agent-transport-recipe.d.ts +166 -0
  44. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +3 -2
  45. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  46. package/dist/agent-runtime/src/desktop-handoff.d.ts +139 -0
  47. package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs +158 -0
  48. package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs.map +1 -0
  49. package/dist/agent-runtime/src/durable-thread-snapshot-cache.d.ts +60 -0
  50. package/dist/agent-runtime/src/durable-thread-snapshot-cache.js +158 -0
  51. package/dist/agent-runtime/src/durable-thread-snapshot-cache.js.map +1 -0
  52. package/dist/agent-runtime/src/edit-command.d.ts +156 -0
  53. package/dist/agent-runtime/src/errors.d.ts +174 -0
  54. package/dist/agent-runtime/src/execute-output.d.ts +31 -0
  55. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +16 -2
  56. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  57. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +202 -0
  58. package/dist/agent-runtime/src/generated/runconfig-contract.js +16 -2
  59. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  60. package/dist/agent-runtime/src/github-wake-event.d.ts +77 -0
  61. package/dist/agent-runtime/src/index.d.ts +74 -0
  62. package/dist/agent-runtime/src/interrupts.cjs +17 -0
  63. package/dist/agent-runtime/src/interrupts.cjs.map +1 -1
  64. package/dist/agent-runtime/src/interrupts.d.ts +348 -0
  65. package/dist/agent-runtime/src/interrupts.js +17 -0
  66. package/dist/agent-runtime/src/interrupts.js.map +1 -1
  67. package/dist/agent-runtime/src/lane-follow.d.ts +121 -0
  68. package/dist/agent-runtime/src/lane-history.cjs +209 -0
  69. package/dist/agent-runtime/src/lane-history.cjs.map +1 -0
  70. package/dist/agent-runtime/src/lane-history.d.ts +175 -0
  71. package/dist/agent-runtime/src/lane-history.js +209 -0
  72. package/dist/agent-runtime/src/lane-history.js.map +1 -0
  73. package/dist/agent-runtime/src/lane-images.d.ts +184 -0
  74. package/dist/agent-runtime/src/message-author.d.ts +43 -0
  75. package/dist/agent-runtime/src/message-text.cjs +15 -0
  76. package/dist/agent-runtime/src/message-text.cjs.map +1 -0
  77. package/dist/agent-runtime/src/message-text.d.ts +47 -0
  78. package/dist/agent-runtime/src/message-text.js +15 -0
  79. package/dist/agent-runtime/src/message-text.js.map +1 -0
  80. package/dist/agent-runtime/src/message-window.cjs +15 -1
  81. package/dist/agent-runtime/src/message-window.cjs.map +1 -1
  82. package/dist/agent-runtime/src/message-window.d.ts +159 -0
  83. package/dist/agent-runtime/src/message-window.js +16 -2
  84. package/dist/agent-runtime/src/message-window.js.map +1 -1
  85. package/dist/agent-runtime/src/messages.cjs +88 -4
  86. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  87. package/dist/agent-runtime/src/messages.d.ts +603 -0
  88. package/dist/agent-runtime/src/messages.js +88 -4
  89. package/dist/agent-runtime/src/messages.js.map +1 -1
  90. package/dist/agent-runtime/src/model-context.d.ts +22 -0
  91. package/dist/agent-runtime/src/offline-status.d.ts +157 -0
  92. package/dist/agent-runtime/src/optimistic-content.d.ts +21 -0
  93. package/dist/agent-runtime/src/protocol.cjs +12 -4
  94. package/dist/agent-runtime/src/protocol.cjs.map +1 -1
  95. package/dist/agent-runtime/src/protocol.d.ts +119 -0
  96. package/dist/agent-runtime/src/protocol.js +13 -5
  97. package/dist/agent-runtime/src/protocol.js.map +1 -1
  98. package/dist/agent-runtime/src/ptc-subcalls.d.ts +51 -0
  99. package/dist/agent-runtime/src/queue.d.ts +138 -0
  100. package/dist/agent-runtime/src/quota-safe-local-storage-session.d.ts +154 -0
  101. package/dist/agent-runtime/src/running-tool-placeholder.cjs +11 -0
  102. package/dist/agent-runtime/src/running-tool-placeholder.cjs.map +1 -0
  103. package/dist/agent-runtime/src/running-tool-placeholder.d.ts +25 -0
  104. package/dist/agent-runtime/src/running-tool-placeholder.js +11 -0
  105. package/dist/agent-runtime/src/running-tool-placeholder.js.map +1 -0
  106. package/dist/agent-runtime/src/runtime-messages.d.ts +104 -0
  107. package/dist/agent-runtime/src/screen-point.d.ts +151 -0
  108. package/dist/agent-runtime/src/sealed-idb.cjs +112 -0
  109. package/dist/agent-runtime/src/sealed-idb.cjs.map +1 -0
  110. package/dist/agent-runtime/src/sealed-idb.d.ts +106 -0
  111. package/dist/agent-runtime/src/sealed-idb.js +112 -0
  112. package/dist/agent-runtime/src/sealed-idb.js.map +1 -0
  113. package/dist/agent-runtime/src/send-recovery.d.ts +40 -0
  114. package/dist/agent-runtime/src/statewire-attach-observer.d.ts +194 -0
  115. package/dist/agent-runtime/src/statewire-diagnostics.d.ts +74 -0
  116. package/dist/agent-runtime/src/statewire-state.d.ts +29 -0
  117. package/dist/agent-runtime/src/statewire-suspended.cjs.map +1 -1
  118. package/dist/agent-runtime/src/statewire-suspended.d.ts +27 -0
  119. package/dist/agent-runtime/src/statewire-suspended.js.map +1 -1
  120. package/dist/agent-runtime/src/statewire-transport.d.ts +40 -0
  121. package/dist/agent-runtime/src/streaming-markdown.d.ts +46 -0
  122. package/dist/agent-runtime/src/subagent-transcripts.cjs +209 -0
  123. package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -0
  124. package/dist/agent-runtime/src/subagent-transcripts.d.ts +71 -0
  125. package/dist/agent-runtime/src/subagent-transcripts.js +209 -0
  126. package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -0
  127. package/dist/agent-runtime/src/subagents.cjs +253 -0
  128. package/dist/agent-runtime/src/subagents.cjs.map +1 -0
  129. package/dist/agent-runtime/src/subagents.d.ts +311 -0
  130. package/dist/agent-runtime/src/subagents.js +253 -0
  131. package/dist/agent-runtime/src/subagents.js.map +1 -0
  132. package/dist/agent-runtime/src/subscription-wake-event.d.ts +111 -0
  133. package/dist/agent-runtime/src/thread-extras.d.ts +43 -0
  134. package/dist/agent-runtime/src/thread-handoff.d.ts +364 -0
  135. package/dist/agent-runtime/src/thread-prewarm-controller.d.ts +76 -0
  136. package/dist/agent-runtime/src/thread-prewarm.d.ts +118 -0
  137. package/dist/agent-runtime/src/thread-snapshot-cache.d.ts +99 -0
  138. package/dist/agent-runtime/src/thread-snapshot-mirror.cjs +329 -0
  139. package/dist/agent-runtime/src/thread-snapshot-mirror.cjs.map +1 -0
  140. package/dist/agent-runtime/src/thread-snapshot-mirror.d.ts +101 -0
  141. package/dist/agent-runtime/src/thread-snapshot-mirror.js +329 -0
  142. package/dist/agent-runtime/src/thread-snapshot-mirror.js.map +1 -0
  143. package/dist/agent-runtime/src/thread-status.d.ts +53 -0
  144. package/dist/agent-runtime/src/tool-metadata.d.ts +146 -0
  145. package/dist/agent-runtime/src/tool-names.cjs +67 -0
  146. package/dist/agent-runtime/src/tool-names.cjs.map +1 -1
  147. package/dist/agent-runtime/src/tool-names.d.ts +60 -0
  148. package/dist/agent-runtime/src/tool-names.js +68 -1
  149. package/dist/agent-runtime/src/tool-names.js.map +1 -1
  150. package/dist/agent-runtime/src/tool-outputs.d.ts +35 -0
  151. package/dist/agent-runtime/src/tool-result.cjs +1 -0
  152. package/dist/agent-runtime/src/tool-result.cjs.map +1 -1
  153. package/dist/agent-runtime/src/tool-result.d.ts +126 -0
  154. package/dist/agent-runtime/src/tool-result.js +1 -0
  155. package/dist/agent-runtime/src/tool-result.js.map +1 -1
  156. package/dist/agent-runtime/src/types.d.ts +159 -0
  157. package/dist/agent-runtime/src/use-conversation-list.d.ts +76 -0
  158. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs +136 -0
  159. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs.map +1 -0
  160. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.d.ts +64 -0
  161. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js +136 -0
  162. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js.map +1 -0
  163. package/dist/agent-runtime/src/use-deep-agent-config.d.ts +169 -0
  164. package/dist/agent-runtime/src/use-deep-agent-edit-submit.cjs +13 -0
  165. package/dist/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
  166. package/dist/agent-runtime/src/use-deep-agent-edit-submit.d.ts +22 -0
  167. package/dist/agent-runtime/src/use-deep-agent-edit-submit.js +13 -0
  168. package/dist/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
  169. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs +20 -2
  170. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  171. package/dist/agent-runtime/src/use-deep-agent-runtime.d.ts +168 -0
  172. package/dist/agent-runtime/src/use-deep-agent-runtime.js +20 -2
  173. package/dist/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
  174. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +12 -4
  175. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  176. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +320 -0
  177. package/dist/agent-runtime/src/use-deep-agent-thread.js +12 -4
  178. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  179. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +999 -0
  180. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -0
  181. package/dist/agent-runtime/src/use-deep-agent-voice.d.ts +409 -0
  182. package/dist/agent-runtime/src/use-deep-agent-voice.js +999 -0
  183. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -0
  184. package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +102 -0
  185. package/dist/agent-runtime/src/use-historical-edit-attachments.d.ts +2 -0
  186. package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +84 -0
  187. package/dist/agent-runtime/src/voice-presentation.d.ts +80 -0
  188. package/dist/agent-runtime/src/voice-turn-grouping.d.ts +28 -0
  189. package/dist/agent-runtime/src/voice-wire-types.d.ts +15 -0
  190. package/dist/agent-runtime/src/withdrawn-turns.d.ts +97 -0
  191. package/dist/chat/AthenaChat.cjs +77 -6
  192. package/dist/chat/AthenaChat.cjs.map +1 -1
  193. package/dist/chat/AthenaChat.js +78 -7
  194. package/dist/chat/AthenaChat.js.map +1 -1
  195. package/dist/chat/StatewireApprovalCard.d.ts +1 -1
  196. package/dist/chat/StatewireClientToolBridge.d.ts +1 -1
  197. package/dist/chat/StatewireQueuedMessages.cjs +11 -4
  198. package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
  199. package/dist/chat/StatewireQueuedMessages.d.ts +1 -1
  200. package/dist/chat/StatewireQueuedMessages.js +11 -4
  201. package/dist/chat/StatewireQueuedMessages.js.map +1 -1
  202. package/dist/chat/chat-outbox-rows.cjs +223 -0
  203. package/dist/chat/chat-outbox-rows.cjs.map +1 -0
  204. package/dist/chat/chat-outbox-rows.d.ts +29 -0
  205. package/dist/chat/chat-outbox-rows.js +223 -0
  206. package/dist/chat/chat-outbox-rows.js.map +1 -0
  207. package/dist/chat/statewire-approval.d.ts +1 -1
  208. package/dist/chat/statewire-client-tools.d.ts +1 -1
  209. package/dist/chat/super-grouping/SuperGroupingCard.cjs +3 -1
  210. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  211. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +7 -1
  212. package/dist/chat/super-grouping/SuperGroupingCard.js +3 -1
  213. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  214. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +7 -2
  215. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
  216. package/dist/chat/super-grouping/SuperGroupingTranscript.d.ts +2 -2
  217. package/dist/chat/super-grouping/SuperGroupingTranscript.js +7 -2
  218. package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
  219. package/dist/chat/super-grouping/activity-timeline.cjs +19 -11
  220. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  221. package/dist/chat/super-grouping/activity-timeline.d.ts +25 -9
  222. package/dist/chat/super-grouping/activity-timeline.js +19 -11
  223. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  224. package/dist/chat/use-statewire-approval-request.cjs +36 -0
  225. package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
  226. package/dist/chat/use-statewire-approval-request.d.ts +49 -1
  227. package/dist/chat/use-statewire-approval-request.js +39 -3
  228. package/dist/chat/use-statewire-approval-request.js.map +1 -1
  229. package/dist/chat-ui/composer/tiptap-composer.cjs +102 -3
  230. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  231. package/dist/chat-ui/composer/tiptap-composer.d.ts +32 -1
  232. package/dist/chat-ui/composer/tiptap-composer.js +103 -4
  233. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  234. package/dist/chat-ui/header/conversation-history-panel.d.ts +1 -1
  235. package/dist/chat-ui/index.d.ts +1 -1
  236. package/dist/chat-ui/messages/message-components.cjs +15 -0
  237. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  238. package/dist/chat-ui/messages/message-components.js +15 -0
  239. package/dist/chat-ui/messages/message-components.js.map +1 -1
  240. package/dist/chat-ui/messages/runtime-message.d.ts +1 -1
  241. package/dist/chat-ui/messages/statewire-continue-run.d.ts +1 -1
  242. package/dist/chat-ui/messages/user-edit-composer.cjs +15 -2
  243. package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
  244. package/dist/chat-ui/messages/user-edit-composer.d.ts +4 -2
  245. package/dist/chat-ui/messages/user-edit-composer.js +15 -2
  246. package/dist/chat-ui/messages/user-edit-composer.js.map +1 -1
  247. package/dist/chat-ui/messages/wake-marker.d.ts +1 -1
  248. package/dist/chat-ui/rich-text/chat-text-schema.cjs +1 -0
  249. package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -1
  250. package/dist/chat-ui/rich-text/chat-text-schema.d.ts +3 -0
  251. package/dist/chat-ui/rich-text/chat-text-schema.js +1 -0
  252. package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -1
  253. package/dist/chat-ui/statewire.cjs +1 -0
  254. package/dist/chat-ui/statewire.cjs.map +1 -1
  255. package/dist/chat-ui/statewire.d.ts +2 -2
  256. package/dist/chat-ui/statewire.js +2 -1
  257. package/dist/chat-ui/thread/statewire-history-edge.d.ts +1 -1
  258. package/dist/composer/AttachmentContext.cjs +8 -4
  259. package/dist/composer/AttachmentContext.cjs.map +1 -1
  260. package/dist/composer/AttachmentContext.d.ts +7 -0
  261. package/dist/composer/AttachmentContext.js +8 -4
  262. package/dist/composer/AttachmentContext.js.map +1 -1
  263. package/dist/composer/build-composed-message.cjs +34 -0
  264. package/dist/composer/build-composed-message.cjs.map +1 -1
  265. package/dist/composer/build-composed-message.d.ts +20 -0
  266. package/dist/composer/build-composed-message.js +35 -1
  267. package/dist/composer/build-composed-message.js.map +1 -1
  268. package/dist/composer/composer-handoff.cjs +39 -2
  269. package/dist/composer/composer-handoff.cjs.map +1 -1
  270. package/dist/composer/composer-handoff.d.ts +28 -3
  271. package/dist/composer/composer-handoff.js +39 -2
  272. package/dist/composer/composer-handoff.js.map +1 -1
  273. package/dist/composer/useAttachFiles.cjs +15 -2
  274. package/dist/composer/useAttachFiles.cjs.map +1 -1
  275. package/dist/composer/useAttachFiles.d.ts +11 -0
  276. package/dist/composer/useAttachFiles.js +15 -2
  277. package/dist/composer/useAttachFiles.js.map +1 -1
  278. package/dist/composer/useSendMessage.cjs.map +1 -1
  279. package/dist/composer/useSendMessage.d.ts +4 -3
  280. package/dist/composer/useSendMessage.js.map +1 -1
  281. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  282. package/dist/diagnostics/athena-diagnostics.d.ts +3 -1
  283. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  284. package/dist/index.cjs +18 -0
  285. package/dist/index.cjs.map +1 -1
  286. package/dist/index.d.ts +15 -6
  287. package/dist/index.js +19 -1
  288. package/dist/index.js.map +1 -1
  289. package/dist/offline/chat-outbox.cjs +57 -0
  290. package/dist/offline/chat-outbox.cjs.map +1 -0
  291. package/dist/offline/chat-outbox.d.ts +80 -0
  292. package/dist/offline/chat-outbox.js +57 -0
  293. package/dist/offline/chat-outbox.js.map +1 -0
  294. package/dist/offline/offline-history.cjs +77 -0
  295. package/dist/offline/offline-history.cjs.map +1 -0
  296. package/dist/offline/offline-history.d.ts +60 -0
  297. package/dist/offline/offline-history.js +77 -0
  298. package/dist/offline/offline-history.js.map +1 -0
  299. package/dist/provider/AthenaProvider.cjs +206 -9
  300. package/dist/provider/AthenaProvider.cjs.map +1 -1
  301. package/dist/provider/AthenaProvider.d.ts +22 -1
  302. package/dist/provider/AthenaProvider.js +207 -10
  303. package/dist/provider/AthenaProvider.js.map +1 -1
  304. package/dist/provider/statewire-window-context.d.ts +1 -1
  305. package/dist/react/package.json.cjs +1 -1
  306. package/dist/react/package.json.js +1 -1
  307. package/dist/references/src/anchors/file-line-range.d.ts +58 -0
  308. package/dist/references/src/anchors/format.d.ts +21 -0
  309. package/dist/references/src/anchors/message-anchors.d.ts +71 -0
  310. package/dist/references/src/anchors/parse.d.ts +8 -0
  311. package/dist/references/src/anchors/registry-contract.d.ts +24 -0
  312. package/dist/references/src/anchors/registry.d.ts +19 -0
  313. package/dist/references/src/anchors/schemas.d.ts +194 -0
  314. package/dist/references/src/anchors/serialize.d.ts +8 -0
  315. package/dist/references/src/anchors/time.d.ts +78 -0
  316. package/dist/references/src/anchors/types.d.ts +474 -0
  317. package/dist/references/src/asset-bounds.d.ts +27 -0
  318. package/dist/references/src/asset-links.d.ts +23 -0
  319. package/dist/references/src/asset-reference.d.ts +16 -0
  320. package/dist/references/src/formats/format-catalog.d.ts +79 -0
  321. package/dist/references/src/formats/markdown/parse-reference-markdown.d.ts +28 -0
  322. package/dist/references/src/formats/markdown/reference-display-name.d.ts +6 -0
  323. package/dist/references/src/formats/object/asset-object.d.ts +9 -0
  324. package/dist/references/src/formats/object/callable-object.d.ts +6 -0
  325. package/dist/references/src/formats/object/decode-reference-object-payload.d.ts +3 -0
  326. package/dist/references/src/formats/object/external-url-object.d.ts +9 -0
  327. package/dist/references/src/formats/object/group-object.d.ts +9 -0
  328. package/dist/references/src/formats/object/navigation-object.d.ts +9 -0
  329. package/dist/references/src/formats/object/parse-reference-object.d.ts +11 -0
  330. package/dist/references/src/formats/object/person-object.d.ts +9 -0
  331. package/dist/references/src/formats/uri/asset-mention-uri.d.ts +9 -0
  332. package/dist/references/src/formats/uri/asset-spaces-url.d.ts +9 -0
  333. package/dist/references/src/formats/uri/callable-mention-uris.d.ts +9 -0
  334. package/dist/references/src/formats/uri/detect-uri-wire.d.ts +9 -0
  335. package/dist/references/src/formats/uri/group-mention-uri.d.ts +12 -0
  336. package/dist/references/src/formats/uri/navigation-spaces-url.d.ts +14 -0
  337. package/dist/references/src/formats/uri/parse-reference-uri.d.ts +20 -0
  338. package/dist/references/src/formats/uri/person-mention-uri.d.ts +9 -0
  339. package/dist/references/src/formats/uri/template-placeholder.d.ts +12 -0
  340. package/dist/references/src/index.d.ts +47 -0
  341. package/dist/references/src/legacy/index.d.ts +14 -0
  342. package/dist/references/src/legacy/pre-reference-asset-url.d.ts +57 -0
  343. package/dist/references/src/legacy/pre-reference-citation-bridge.d.ts +22 -0
  344. package/dist/references/src/legacy/pre-reference-citation.d.ts +138 -0
  345. package/dist/references/src/legacy/pre-reference-external-url.d.ts +31 -0
  346. package/dist/references/src/legacy/pre-reference-format.d.ts +8 -0
  347. package/dist/references/src/legacy/pre-reference-mention.d.ts +27 -0
  348. package/dist/references/src/legacy/pre-reference-object.d.ts +8 -0
  349. package/dist/references/src/legacy/pre-reference-uri.d.ts +12 -0
  350. package/dist/references/src/legacy.d.ts +2 -0
  351. package/dist/references/src/mention-href-patterns.d.ts +19 -0
  352. package/dist/references/src/mention-node/index.d.ts +5 -0
  353. package/dist/references/src/mention-node/mention-node.d.ts +31 -0
  354. package/dist/references/src/mention-node/resolve-node-attrs.d.ts +27 -0
  355. package/dist/references/src/parse-reference.d.ts +23 -0
  356. package/dist/references/src/schemas.d.ts +463 -0
  357. package/dist/references/src/serialize-reference.d.ts +50 -0
  358. package/dist/references/src/sheet-name.d.ts +10 -0
  359. package/dist/references/src/tool-option-schemas.d.ts +597 -0
  360. package/dist/references/src/types.d.ts +125 -0
  361. package/dist/references/src/version-ref.d.ts +30 -0
  362. package/dist/runtime/statewire-lifecycle.d.ts +1 -1
  363. package/dist/runtime/statewire-model-lane.d.ts +1 -1
  364. package/dist/runtime/statewire-server-lane-context.d.ts +1 -1
  365. package/dist/runtime/statewire-session-key.cjs +7 -0
  366. package/dist/runtime/statewire-session-key.cjs.map +1 -1
  367. package/dist/runtime/statewire-session-key.d.ts +16 -0
  368. package/dist/runtime/statewire-session-key.js +8 -1
  369. package/dist/runtime/statewire-session-key.js.map +1 -1
  370. package/dist/runtime/statewire-session-lane.cjs +48 -0
  371. package/dist/runtime/statewire-session-lane.cjs.map +1 -0
  372. package/dist/runtime/statewire-session-lane.d.ts +29 -0
  373. package/dist/runtime/statewire-session-lane.js +48 -0
  374. package/dist/runtime/statewire-session-lane.js.map +1 -0
  375. package/dist/runtime/statewire-thread-config-lane.d.ts +1 -1
  376. package/dist/runtime/useAthenaStatewireRuntime.cjs +16 -5
  377. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  378. package/dist/runtime/useAthenaStatewireRuntime.d.ts +15 -1
  379. package/dist/runtime/useAthenaStatewireRuntime.js +17 -6
  380. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  381. package/dist/styles.css +1 -1
  382. package/dist/threads/api.d.ts +1 -1
  383. package/dist/threads/conversation-list-fetcher.d.ts +1 -1
  384. package/dist/threads/index-triggered-refresh.cjs +164 -0
  385. package/dist/threads/index-triggered-refresh.cjs.map +1 -0
  386. package/dist/threads/index-triggered-refresh.d.ts +70 -0
  387. package/dist/threads/index-triggered-refresh.js +164 -0
  388. package/dist/threads/index-triggered-refresh.js.map +1 -0
  389. package/dist/threads/offline-session-list.cjs +75 -0
  390. package/dist/threads/offline-session-list.cjs.map +1 -0
  391. package/dist/threads/offline-session-list.d.ts +27 -0
  392. package/dist/threads/offline-session-list.js +75 -0
  393. package/dist/threads/offline-session-list.js.map +1 -0
  394. package/dist/threads/pull-request-display.d.ts +1 -1
  395. package/dist/threads/session-list-model.d.ts +1 -1
  396. package/dist/threads/session-list-tab-share.cjs +150 -0
  397. package/dist/threads/session-list-tab-share.cjs.map +1 -0
  398. package/dist/threads/session-list-tab-share.d.ts +73 -0
  399. package/dist/threads/session-list-tab-share.js +150 -0
  400. package/dist/threads/session-list-tab-share.js.map +1 -0
  401. package/dist/threads/session-row-parts.d.ts +1 -1
  402. package/dist/threads/sessions-query.d.ts +1 -1
  403. package/dist/threads/statewire-thread-list.cjs +105 -20
  404. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  405. package/dist/threads/statewire-thread-list.d.ts +31 -3
  406. package/dist/threads/statewire-thread-list.js +107 -22
  407. package/dist/threads/statewire-thread-list.js.map +1 -1
  408. package/dist/threads/thread-prefetcher.d.ts +1 -1
  409. package/dist/threads/use-athena-session-attention.d.ts +1 -1
  410. package/dist/threads/use-athena-sessions.cjs +32 -22
  411. package/dist/threads/use-athena-sessions.cjs.map +1 -1
  412. package/dist/threads/use-athena-sessions.js +33 -23
  413. package/dist/threads/use-athena-sessions.js.map +1 -1
  414. package/dist/threads/use-rest-conversation-history.d.ts +1 -1
  415. package/dist/threads/use-statewire-conversation-history.d.ts +5 -5
  416. package/dist/tiptap-markdown-table/src/markdown-table-serializer.d.ts +56 -0
  417. package/dist/tools/NestedPtcMessages.cjs +14 -9
  418. package/dist/tools/NestedPtcMessages.cjs.map +1 -1
  419. package/dist/tools/NestedPtcMessages.d.ts +9 -0
  420. package/dist/tools/NestedPtcMessages.js +6 -1
  421. package/dist/tools/NestedPtcMessages.js.map +1 -1
  422. package/dist/tools/index.d.ts +1 -1
  423. package/dist/tools/primitives.d.ts +1 -1
  424. package/dist/tools/subagent-task-tool-ui.cjs +494 -0
  425. package/dist/tools/subagent-task-tool-ui.cjs.map +1 -0
  426. package/dist/tools/subagent-task-tool-ui.d.ts +109 -0
  427. package/dist/tools/subagent-task-tool-ui.js +494 -0
  428. package/dist/tools/subagent-task-tool-ui.js.map +1 -0
  429. package/dist/tools/tool-fallback.d.ts +1 -1
  430. package/dist/tools/tool-icons.d.ts +1 -1
  431. package/dist/tools/tool-summary.d.ts +1 -1
  432. package/dist/tools/tool-uis.cjs +4 -0
  433. package/dist/tools/tool-uis.cjs.map +1 -1
  434. package/dist/tools/tool-uis.js +4 -0
  435. package/dist/tools/tool-uis.js.map +1 -1
  436. package/dist/voice/chat.cjs +6 -0
  437. package/dist/voice/chat.cjs.map +1 -0
  438. package/dist/voice/chat.d.ts +2 -0
  439. package/dist/voice/chat.js +6 -0
  440. package/dist/voice/chat.js.map +1 -0
  441. package/dist/voice/livekit-join.cjs +119 -0
  442. package/dist/voice/livekit-join.cjs.map +1 -0
  443. package/dist/voice/livekit-join.d.ts +8 -0
  444. package/dist/voice/livekit-join.js +119 -0
  445. package/dist/voice/livekit-join.js.map +1 -0
  446. package/dist/voice/livekit.cjs +32 -0
  447. package/dist/voice/livekit.cjs.map +1 -0
  448. package/dist/voice/livekit.d.ts +80 -0
  449. package/dist/voice/livekit.js +32 -0
  450. package/dist/voice/livekit.js.map +1 -0
  451. package/package.json +20 -10
@@ -1 +1 @@
1
- {"version":3,"file":"composer-handoff.js","sources":["../../src/composer/composer-handoff.ts"],"sourcesContent":["/**\n * Composer handoff: writes to the chat composer from host UI that lives\n * outside `<AthenaChat>` (a sidebar, an agenda card, a workflow button).\n *\n * Two problems it solves for `useAppendToComposer` / `useSendMessage`:\n *\n * 1. A write before the chat is ready is lost. While the thread list is still\n * resolving the active thread, or the thread's history is still loading,\n * the composer the hooks write to belongs to a mount that is about to be\n * replaced (thread-list mode keys the statewire subtree by thread), and\n * the draft goes with it. The store below lives ABOVE that mount, so a\n * write made too early waits here and the ready mount drains it.\n * 2. A prefilled draft should put the caret after the text so the user can\n * keep typing or dictating. The Tiptap editor mirrors runtime text on a\n * later tick; the `focusOnNextMirror` flag asks it to focus at the end\n * right after that mirror lands, instead of the host guessing a delay.\n *\n * Every queued write is bound to the statewire thread it was made for and\n * drains only into that thread's mount; a thread switch, an identity change\n * or a provider unmount drops what waits with a `composer_write_dropped`\n * error, never into another user's or another thread's composer.\n */\nimport { createContext, useCallback, useContext } from 'react';\nimport { useAuiState } from '@assistant-ui/react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport { useAthenaStatewireThreadList } from '../threads/statewire-thread-list';\n\n/** The slice of the assistant-ui client the handoff writes to. */\nexport interface ComposerTarget {\n composer: {\n getState: () => { text: string };\n setText: (text: string) => void;\n send: (options?: { steer?: boolean }) => unknown;\n };\n}\n\nexport interface ComposerWrite {\n text: string;\n /** Replace the draft instead of appending on a new line. */\n replace: boolean;\n /** Submit right after writing. */\n send: boolean;\n /** Put the caret at the end of the draft once the editor shows it. */\n focus: boolean;\n /** The statewire thread the write was made for; it drains only into that thread's mount. */\n threadId: string | null;\n /** Settled once the write has been applied (and, for `send`, with the send's outcome). */\n resolve?: (outcome: Promise<void> | void) => void;\n /** Settled with `composer_write_dropped` when the write can no longer land. */\n reject?: (error: AthenaSdkError) => void;\n}\n\nexport interface ComposerHandoffStore {\n /** Writes waiting for a ready composer, oldest first. Adjacent plain appends fold together. */\n pending: ComposerWrite[];\n /** Set by a `focus` write; the editor consumes it after mirroring the draft. */\n focusOnNextMirror: boolean;\n /** Registered by the mounted editor: place the caret at the end of the draft. */\n focusEnd: (() => void) | null;\n /** Set by `useFocusComposer` before the editor mounted; the editor consumes it when it does. */\n focusOnMount: boolean;\n}\n\nexport function createComposerHandoffStore(): ComposerHandoffStore {\n return { pending: [], focusOnNextMirror: false, focusEnd: null, focusOnMount: false };\n}\n\nexport const ComposerHandoffContext = createContext<ComposerHandoffStore | null>(null);\n\n/** The provider's handoff store, or null outside `AthenaProvider`. */\nexport function useComposerHandoffStore(): ComposerHandoffStore | null {\n return useContext(ComposerHandoffContext);\n}\n\n/**\n * Puts the caret at the end of the composer's draft and leaves the draft as it is; asked before the\n * editor has mounted, it focuses the editor as it mounts. For a host that shows the chat again and\n * wants typing to land in it (a launcher window a shortcut brings back).\n */\nexport function useFocusComposer(): () => void {\n const store = useComposerHandoffStore();\n return useCallback(() => {\n if (store) focusComposer({ store });\n }, [store]);\n}\n\n/** The caret to the end of the draft now, or, with no editor mounted yet, as one mounts. */\nexport function focusComposer({ store }: { store: ComposerHandoffStore }): void {\n if (store.focusEnd) store.focusEnd();\n else store.focusOnMount = true;\n}\n\n/**\n * Whether a composer write lands now: in thread-list mode the list has\n * resolved which thread is active, and that thread's history has loaded.\n * Until then the composer the hooks write to is the one of a mount that is\n * about to be replaced, and the draft goes with it.\n *\n * Deliberately not the socket status: a never-started chat sits in\n * `standby` until its first send and must still take a prefill.\n */\nexport function useComposerReady(): boolean {\n const list = useAthenaStatewireThreadList();\n const threadLoading = useAuiState((s) => s.optional.thread?.isLoading ?? false);\n return !(list?.isLoading ?? false) && !threadLoading;\n}\n\n/** The draft after `write`: `replace` (or an empty draft) takes the text as is. */\nexport function mergeComposerDraft({\n current,\n write,\n}: {\n current: string;\n write: Pick<ComposerWrite, 'text' | 'replace'>;\n}): string {\n if (write.replace || !current) return write.text;\n return `${current}\\n${write.text}`;\n}\n\n/**\n * Write into the live composer. Returns the send's outcome for a `send`\n * write so callers can await it.\n */\nexport function applyComposerWrite({\n target,\n store,\n write,\n}: {\n target: ComposerTarget;\n store: ComposerHandoffStore | null;\n write: ComposerWrite;\n}): Promise<void> | void {\n const current = target.composer.getState().text ?? '';\n const next = mergeComposerDraft({ current, write });\n target.composer.setText(next);\n if (write.focus && store) {\n // An unchanged draft never re-mirrors, so focus at once; otherwise the\n // editor focuses itself right after it has shown the new text.\n if (next === current) store.focusEnd?.();\n else store.focusOnNextMirror = true;\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'applied', send: write.send, focus: write.focus, chars: next.length },\n });\n if (write.send) {\n return Promise.resolve(target.composer.send({ steer: false })).then(() => undefined);\n }\n return undefined;\n}\n\n/**\n * Hold a write until the composer is ready. Writes keep their order; a plain\n * append folds into a directly preceding plain append for the same thread\n * (one draft, not two), while a replace or a send is kept as its own step so\n * no message is lost and every send settles on its own.\n */\nexport function queueComposerWrite({\n store,\n write,\n}: {\n store: ComposerHandoffStore;\n write: ComposerWrite;\n}): void {\n const last = store.pending[store.pending.length - 1];\n const foldable =\n last !== undefined &&\n !last.send &&\n !write.send &&\n !write.replace &&\n last.threadId === write.threadId &&\n last.resolve === undefined &&\n write.resolve === undefined;\n if (foldable) {\n last.text = mergeComposerDraft({ current: last.text, write });\n last.focus = last.focus || write.focus;\n } else {\n store.pending.push(write);\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'deferred', send: write.send, focus: write.focus, queued: store.pending.length },\n });\n}\n\nfunction dropWrite({ write, reason }: { write: ComposerWrite; reason: string }): void {\n const error = new AthenaSdkError({\n code: 'composer_write_dropped',\n message: `A composer ${write.send ? 'send' : 'draft'} queued before the chat was ready was dropped: ${reason}.`,\n hint: 'Make the write again from the chat that is active now.',\n context: { threadId: write.threadId, send: write.send },\n });\n athenaDiagnostics.emit('composer.handoff', {\n level: 'warn',\n error,\n data: { phase: 'dropped', send: write.send, reason, threadId: write.threadId },\n });\n write.reject?.(error);\n}\n\n/**\n * Deliver the pending writes, in order, into a now-ready composer. A write\n * made for another thread is dropped (rejected), never applied here.\n */\nexport function drainComposerHandoff({\n store,\n target,\n threadId,\n}: {\n store: ComposerHandoffStore;\n target: ComposerTarget;\n /** The statewire thread of the mount that is draining. */\n threadId: string | null;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) {\n if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {\n dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });\n continue;\n }\n const outcome = applyComposerWrite({ target, store, write });\n write.resolve?.(outcome);\n }\n}\n\n/** Drop every pending write (identity changed, provider unmounted). */\nexport function clearComposerHandoff({\n store,\n reason,\n}: {\n store: ComposerHandoffStore;\n reason: string;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) dropWrite({ write, reason });\n}\n"],"names":[],"mappings":";;;;;AAgEO,SAAS,6BAAmD;AACjE,SAAO,EAAE,SAAS,CAAA,GAAI,mBAAmB,OAAO,UAAU,MAAM,cAAc,MAAA;AAChF;AAEO,MAAM,yBAAyB,cAA2C,IAAI;AAG9E,SAAS,0BAAuD;AACrE,SAAO,WAAW,sBAAsB;AAC1C;AAOO,SAAS,mBAA+B;AAC7C,QAAM,QAAQ,wBAAA;AACd,SAAO,YAAY,MAAM;AACvB,QAAI,MAAO,eAAc,EAAE,OAAO;AAAA,EACpC,GAAG,CAAC,KAAK,CAAC;AACZ;AAGO,SAAS,cAAc,EAA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B;AAAA,EACnC;AAAA,EACA;AACF,GAGS;AACP,QAAM,SAAS,MAAM;AACrB,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,UAAU,CAAA;AAChB,aAAW,SAAS,OAAQ,WAAU,EAAE,OAAO,QAAQ;AACzD;"}
1
+ {"version":3,"file":"composer-handoff.js","sources":["../../src/composer/composer-handoff.ts"],"sourcesContent":["/**\n * Composer handoff: writes to the chat composer from host UI that lives\n * outside `<AthenaChat>` (a sidebar, an agenda card, a workflow button).\n *\n * Two problems it solves for `useAppendToComposer` / `useSendMessage`:\n *\n * 1. A write before the chat is ready is lost. While the thread list is still\n * resolving the active thread, or the thread's history is still loading,\n * the composer the hooks write to belongs to a mount that is about to be\n * replaced (thread-list mode keys the statewire subtree by thread), and\n * the draft goes with it. The store below lives ABOVE that mount, so a\n * write made too early waits here and the ready mount drains it.\n * 2. A prefilled draft should put the caret after the text so the user can\n * keep typing or dictating. The Tiptap editor mirrors runtime text on a\n * later tick; the `focusOnNextMirror` flag asks it to focus at the end\n * right after that mirror lands, instead of the host guessing a delay.\n *\n * Every queued write is bound to the statewire thread it was made for and\n * drains only into that thread's mount; a thread switch, an identity change\n * or a provider unmount drops what waits with a `composer_write_dropped`\n * error, never into another user's or another thread's composer.\n */\nimport { createContext, useCallback, useContext } from 'react';\nimport { useAuiState } from '@assistant-ui/react';\nimport type { ChatOutboxAttachment } from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport { useStatewireSessionLanePending } from '../runtime/statewire-session-lane';\nimport { useAthenaStatewireThreadList } from '../threads/statewire-thread-list';\n\n/** The slice of the assistant-ui client the handoff writes to. */\nexport interface ComposerTarget {\n composer: {\n getState: () => { text: string };\n setText: (text: string) => void;\n send: (options?: { steer?: boolean }) => unknown;\n };\n}\n\nexport interface ComposerWrite {\n text: string;\n /** Replace the draft instead of appending on a new line. */\n replace: boolean;\n /** Submit right after writing. */\n send: boolean;\n /** Put the caret at the end of the draft once the editor shows it. */\n focus: boolean;\n /** The statewire thread the write was made for; it drains only into that thread's mount. */\n threadId: string | null;\n /** Settled once the write has been applied (and, for `send`, with the send's outcome). */\n resolve?: (outcome: Promise<void> | void) => void;\n /** Settled with `composer_write_dropped` when the write can no longer land. */\n reject?: (error: AthenaSdkError) => void;\n}\n\nexport interface ComposerHandoffStore {\n /** Writes waiting for a ready composer, oldest first. Adjacent plain appends fold together. */\n pending: ComposerWrite[];\n /** Set by a `focus` write; the editor consumes it after mirroring the draft. */\n focusOnNextMirror: boolean;\n /** Registered by the mounted editor: place the caret at the end of the draft. */\n focusEnd: (() => void) | null;\n /** Set by `useFocusComposer` before the editor mounted; the editor consumes it when it does. */\n focusOnMount: boolean;\n /**\n * Per thread, the attachments of messages the chat outbox gave back to the composer (Cancel, or\n * Edit on one that couldn't be sent): files already in Athena, back in the draft as mentions. A\n * message held again from that draft names those still in it, so the outbox asks Athena about\n * them again before it goes ({@link rememberRestoredAttachments}, {@link takeRestoredAttachments}).\n */\n restoredAttachments?: Map<string, ChatOutboxAttachment[]>;\n}\n\nexport function createComposerHandoffStore(): ComposerHandoffStore {\n return {\n pending: [],\n focusOnNextMirror: false,\n focusEnd: null,\n focusOnMount: false,\n restoredAttachments: new Map(),\n };\n}\n\n/** A held message given back to `threadId`'s composer: remember the attachments it carried. */\nexport function rememberRestoredAttachments({\n store,\n threadId,\n attachments,\n}: {\n store: ComposerHandoffStore;\n threadId: string;\n attachments: readonly ChatOutboxAttachment[];\n}): void {\n if (attachments.length === 0) return;\n store.restoredAttachments ??= new Map();\n const kept = store.restoredAttachments.get(threadId) ?? [];\n const known = new Set(kept.map((attachment) => attachment.assetId));\n store.restoredAttachments.set(threadId, [\n ...kept,\n ...attachments.filter((attachment) => !known.has(attachment.assetId)),\n ]);\n}\n\n/**\n * The remembered attachments of `threadId`'s draft whose mentions it still holds, for the message\n * leaving it now; the composer forgets them all (sent, held again, or removed from the draft).\n */\nexport function takeRestoredAttachments({\n store,\n threadId,\n assetIdsInDraft,\n}: {\n store: ComposerHandoffStore | null;\n threadId: string;\n assetIdsInDraft: ReadonlySet<string>;\n}): ChatOutboxAttachment[] {\n const kept = store?.restoredAttachments?.get(threadId);\n if (!kept) return [];\n store?.restoredAttachments?.delete(threadId);\n return kept.filter((attachment) => assetIdsInDraft.has(attachment.assetId));\n}\n\nexport const ComposerHandoffContext = createContext<ComposerHandoffStore | null>(null);\n\n/** The provider's handoff store, or null outside `AthenaProvider`. */\nexport function useComposerHandoffStore(): ComposerHandoffStore | null {\n return useContext(ComposerHandoffContext);\n}\n\n/**\n * Puts the caret at the end of the composer's draft and leaves the draft as it is; asked before the\n * editor has mounted, it focuses the editor as it mounts. For a host that shows the chat again and\n * wants typing to land in it (a launcher window a shortcut brings back).\n */\nexport function useFocusComposer(): () => void {\n const store = useComposerHandoffStore();\n return useCallback(() => {\n if (store) focusComposer({ store });\n }, [store]);\n}\n\n/** The caret to the end of the draft now, or, with no editor mounted yet, as one mounts. */\nexport function focusComposer({ store }: { store: ComposerHandoffStore }): void {\n if (store.focusEnd) store.focusEnd();\n else store.focusOnMount = true;\n}\n\n/**\n * Whether a composer write lands now: in thread-list mode the list has\n * resolved which thread is active, that thread's history has loaded, and the\n * chat's session lane is known (the sign-in provider above has resolved who is\n * signed in; see `StatewireSessionLane`). Until then the composer the hooks\n * write to is the one of a mount that is about to be replaced, and the draft\n * goes with it, or a send would go into a parked lane that refuses it unsent.\n *\n * Deliberately not the socket status: a never-started chat sits in\n * `standby` until its first send and must still take a prefill.\n */\nexport function useComposerReady(): boolean {\n const list = useAthenaStatewireThreadList();\n const threadLoading = useAuiState((s) => s.optional.thread?.isLoading ?? false);\n const lanePending = useStatewireSessionLanePending();\n return !(list?.isLoading ?? false) && !threadLoading && !lanePending;\n}\n\n/** The draft after `write`: `replace` (or an empty draft) takes the text as is. */\nexport function mergeComposerDraft({\n current,\n write,\n}: {\n current: string;\n write: Pick<ComposerWrite, 'text' | 'replace'>;\n}): string {\n if (write.replace || !current) return write.text;\n return `${current}\\n${write.text}`;\n}\n\n/**\n * Write into the live composer. Returns the send's outcome for a `send`\n * write so callers can await it.\n */\nexport function applyComposerWrite({\n target,\n store,\n write,\n}: {\n target: ComposerTarget;\n store: ComposerHandoffStore | null;\n write: ComposerWrite;\n}): Promise<void> | void {\n const current = target.composer.getState().text ?? '';\n const next = mergeComposerDraft({ current, write });\n target.composer.setText(next);\n if (write.focus && store) {\n // An unchanged draft never re-mirrors, so focus at once; otherwise the\n // editor focuses itself right after it has shown the new text.\n if (next === current) store.focusEnd?.();\n else store.focusOnNextMirror = true;\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'applied', send: write.send, focus: write.focus, chars: next.length },\n });\n if (write.send) {\n return Promise.resolve(target.composer.send({ steer: false })).then(() => undefined);\n }\n return undefined;\n}\n\n/**\n * Hold a write until the composer is ready. Writes keep their order; a plain\n * append folds into a directly preceding plain append for the same thread\n * (one draft, not two), while a replace or a send is kept as its own step so\n * no message is lost and every send settles on its own.\n */\nexport function queueComposerWrite({\n store,\n write,\n}: {\n store: ComposerHandoffStore;\n write: ComposerWrite;\n}): void {\n const last = store.pending[store.pending.length - 1];\n const foldable =\n last !== undefined &&\n !last.send &&\n !write.send &&\n !write.replace &&\n last.threadId === write.threadId &&\n last.resolve === undefined &&\n write.resolve === undefined;\n if (foldable) {\n last.text = mergeComposerDraft({ current: last.text, write });\n last.focus = last.focus || write.focus;\n } else {\n store.pending.push(write);\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'deferred', send: write.send, focus: write.focus, queued: store.pending.length },\n });\n}\n\nfunction dropWrite({ write, reason }: { write: ComposerWrite; reason: string }): void {\n const error = new AthenaSdkError({\n code: 'composer_write_dropped',\n message: `A composer ${write.send ? 'send' : 'draft'} queued before the chat was ready was dropped: ${reason}.`,\n hint: 'Make the write again from the chat that is active now.',\n context: { threadId: write.threadId, send: write.send },\n });\n athenaDiagnostics.emit('composer.handoff', {\n level: 'warn',\n error,\n data: { phase: 'dropped', send: write.send, reason, threadId: write.threadId },\n });\n write.reject?.(error);\n}\n\n/**\n * Deliver the pending writes, in order, into a now-ready composer. A write\n * made for another thread is dropped (rejected), never applied here.\n */\nexport function drainComposerHandoff({\n store,\n target,\n threadId,\n}: {\n store: ComposerHandoffStore;\n target: ComposerTarget;\n /** The statewire thread of the mount that is draining. */\n threadId: string | null;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) {\n if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {\n dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });\n continue;\n }\n const outcome = applyComposerWrite({ target, store, write });\n write.resolve?.(outcome);\n }\n}\n\n/** Drop every pending write (identity changed, provider unmounted). */\nexport function clearComposerHandoff({\n store,\n reason,\n}: {\n store: ComposerHandoffStore;\n reason: string;\n}): void {\n // Another identity, or no provider: the attachments given back belong to drafts that are gone.\n store.restoredAttachments?.clear();\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) dropWrite({ write, reason });\n}\n"],"names":[],"mappings":";;;;;;AAyEO,SAAS,6BAAmD;AACjE,SAAO;AAAA,IACL,SAAS,CAAA;AAAA,IACT,mBAAmB;AAAA,IACnB,UAAU;AAAA,IACV,cAAc;AAAA,IACd,yCAAyB,IAAA;AAAA,EAAI;AAEjC;AAGO,SAAS,4BAA4B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AACF,GAIS;AACP,MAAI,YAAY,WAAW,EAAG;AAC9B,QAAM,wBAAN,MAAM,0CAA4B,IAAA;AAClC,QAAM,OAAO,MAAM,oBAAoB,IAAI,QAAQ,KAAK,CAAA;AACxD,QAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,eAAe,WAAW,OAAO,CAAC;AAClE,QAAM,oBAAoB,IAAI,UAAU;AAAA,IACtC,GAAG;AAAA,IACH,GA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AA;AAAA,EAAK,CACvD;AACD,oBAAkB,KAAK,oBAAoB;AAAA,IACzC,OAAO;AAAA,IACP;AAAA,IACA,MAAM,EAAE,OAAO,WAAW,MAAM,MAAM,MAAM,QAAQ,UAAU,MAAM,SAAA;AAAA,EAAS,CAC9E;AACD,cAAM,WAAN,+BAAe;AACjB;AAMO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AACF,GAKS;;AACP,QAAM,SAAS,MAAM;AACrB,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,UAAU,CAAA;AAChB,aAAW,SAAS,QAAQ;AAC1B,QAAI,MAAM,aAAa,QAAQ,aAAa,QAAQ,MAAM,aAAa,UAAU;AAC/E,gBAAU,EAAE,OAAO,QAAQ,0BAA0B,MAAM,QAAQ,YAAY,QAAQ,aAAA,CAAc;AACrG;AAAA,IACF;AACA,UAAM,UAAU,mBAAmB,EAAE,QAAQ,OAAO,OAAO;AAC3D,gBAAM,YAAN,+BAAgB;AAAA,EAClB;AACF;AAGO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AACF,GAGS;;AAEP,cAAM,wBAAN,mBAA2B;AAC3B,QAAM,SAAS,MAAM;AACrB,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,UAAU,CAAA;AAChB,aAAW,SAAS,OAAQ,WAAU,EAAE,OAAO,QAAQ;AACzD;"}
@@ -4,6 +4,8 @@ const react = require("react");
4
4
  const athenaDiagnostics = require("../diagnostics/athena-diagnostics.cjs");
5
5
  const AttachmentContext = require("./AttachmentContext.cjs");
6
6
  const useFileUpload = require("./useFileUpload.cjs");
7
+ const useDeepAgentChatOutbox = require("../agent-runtime/src/use-deep-agent-chat-outbox.cjs");
8
+ const OFFLINE_FILE_ATTACH_MESSAGE = "Files can't be attached while Athena can't be reached. Messages you send now go out when it's back — attach the file then.";
7
9
  const ATTACH_FAILURE_MESSAGE = {
8
10
  paperclip: "Failed to attach the selected files",
9
11
  drop: "Failed to attach the dropped files",
@@ -11,10 +13,20 @@ const ATTACH_FAILURE_MESSAGE = {
11
13
  };
12
14
  function useAttachFiles() {
13
15
  const { upload, isUploading, error, clearError } = useFileUpload.useFileUpload();
14
- const { addAttachments, setIsUploading } = AttachmentContext.useAttachments();
16
+ const { addAttachments, setIsUploading, setNotice } = AttachmentContext.useAttachments();
17
+ const outbox = useDeepAgentChatOutbox.useDeepAgentChatOutboxContext();
15
18
  const attachFiles = react.useCallback(
16
19
  async (files, source) => {
17
20
  if (files.length === 0) return [];
21
+ if (outbox && !outbox.reachability.get()) {
22
+ setNotice(OFFLINE_FILE_ATTACH_MESSAGE);
23
+ athenaDiagnostics.athenaDiagnostics.emit("composer.attachment.refused_offline", {
24
+ level: "info",
25
+ data: { source, count: files.length }
26
+ });
27
+ return [];
28
+ }
29
+ setNotice(null);
18
30
  setIsUploading(true);
19
31
  try {
20
32
  const assets = await upload([...files]);
@@ -32,9 +44,10 @@ function useAttachFiles() {
32
44
  setIsUploading(false);
33
45
  }
34
46
  },
35
- [addAttachments, setIsUploading, upload]
47
+ [addAttachments, outbox, setIsUploading, setNotice, upload]
36
48
  );
37
49
  return { attachFiles, isUploading, error, clearError };
38
50
  }
51
+ exports.OFFLINE_FILE_ATTACH_MESSAGE = OFFLINE_FILE_ATTACH_MESSAGE;
39
52
  exports.useAttachFiles = useAttachFiles;
40
53
  //# sourceMappingURL=useAttachFiles.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAttachFiles.cjs","sources":["../../src/composer/useAttachFiles.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { useAttachments } from './AttachmentContext';\nimport { useFileUpload, type UploadedAsset } from './useFileUpload';\n\n/** Which intake the files came through — carried on the diagnostics event. */\nexport type AttachFilesSource = 'paperclip' | 'drop' | 'paste';\n\nconst ATTACH_FAILURE_MESSAGE: Record<AttachFilesSource, string> = {\n paperclip: 'Failed to attach the selected files',\n drop: 'Failed to attach the dropped files',\n paste: 'Failed to attach the pasted images',\n};\n\nexport interface UseAttachFilesReturn {\n /**\n * Upload files as Athena assets and add them to the attachment pills.\n * Resolves to the assets attached; a failed upload resolves to `[]` after\n * recording `composer.attachment.error` on the diagnostics bus (and in\n * `error`).\n */\n attachFiles: (files: readonly File[], source: AttachFilesSource) => Promise<UploadedAsset[]>;\n /** This intake's own upload in flight. */\n isUploading: boolean;\n /** Last failure of this intake, for its own affordance. */\n error: string | null;\n clearError: () => void;\n}\n\n/**\n * The one intake path for the attachment pills: the paperclip, the drop zone\n * and the composer's paste all upload through here, so a failure reaches the\n * diagnostics bus the same way and the shared `isUploading` flag — which\n * parks every submit path — is set for exactly the upload's duration.\n */\nexport function useAttachFiles(): UseAttachFilesReturn {\n const { upload, isUploading, error, clearError } = useFileUpload();\n const { addAttachments, setIsUploading } = useAttachments();\n\n const attachFiles = useCallback(\n async (files: readonly File[], source: AttachFilesSource): Promise<UploadedAsset[]> => {\n if (files.length === 0) return [];\n setIsUploading(true);\n try {\n const assets = await upload([...files]);\n if (assets.length > 0) addAttachments(assets);\n return assets;\n } catch (error) {\n athenaDiagnostics.error(\n 'composer.attachment.error',\n error,\n { code: 'attachment_failed', message: ATTACH_FAILURE_MESSAGE[source] },\n { source, count: files.length },\n );\n return [];\n } finally {\n setIsUploading(false);\n }\n },\n [addAttachments, setIsUploading, upload],\n );\n\n return { attachFiles, isUploading, error, clearError };\n}\n"],"names":["useFileUpload","useAttachments","useCallback","error","athenaDiagnostics"],"mappings":";;;;;;AAQA,MAAM,yBAA4D;AAAA,EAChE,WAAW;AAAA,EACX,MAAM;AAAA,EACN,OAAO;AACT;AAuBO,SAAS,iBAAuC;AACrD,QAAM,EAAE,QAAQ,aAAa,OAAO,WAAA,IAAeA,cAAAA,cAAA;AACnD,QAAM,EAAE,gBAAgB,eAAA,IAAmBC,iCAAA;AAE3C,QAAM,cAAcC,MAAAA;AAAAA,IAClB,OAAO,OAAwB,WAAwD;AACrF,UAAI,MAAM,WAAW,EAAG,QAAO,CAAA;AAC/B,qBAAe,IAAI;AACnB,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,CAAC,GAAG,KAAK,CAAC;AACtC,YAAI,OAAO,SAAS,EAAG,gBAAe,MAAM;AAC5C,eAAO;AAAA,MACT,SAASC,QAAO;AACdC,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACAD;AAAAA,UACA,EAAE,MAAM,qBAAqB,SAAS,uBAAuB,MAAM,EAAA;AAAA,UACnE,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO;AAEhC,eAAO,CAAA;AAAA,MACT,UAAA;AACE,uBAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,IACA,CAAC,gBAAgB,gBAAgB,MAAM;AAAA,EAAA;AAGzC,SAAO,EAAE,aAAa,aAAa,OAAO,WAAA;AAC5C;;"}
1
+ {"version":3,"file":"useAttachFiles.cjs","sources":["../../src/composer/useAttachFiles.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useDeepAgentChatOutboxContext } from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { useAttachments } from './AttachmentContext';\nimport { useFileUpload, type UploadedAsset } from './useFileUpload';\n\n/**\n * What the composer says when a file is picked, pasted or dropped while Athena can't be reached\n * (the same words as Olympus's): the upload cannot happen, and a message sent now waits in the chat\n * outbox with only the files that were already uploaded.\n */\nexport const OFFLINE_FILE_ATTACH_MESSAGE =\n \"Files can't be attached while Athena can't be reached. Messages you send now go out when it's back — attach the file then.\";\n\n/** Which intake the files came through — carried on the diagnostics event. */\nexport type AttachFilesSource = 'paperclip' | 'drop' | 'paste';\n\nconst ATTACH_FAILURE_MESSAGE: Record<AttachFilesSource, string> = {\n paperclip: 'Failed to attach the selected files',\n drop: 'Failed to attach the dropped files',\n paste: 'Failed to attach the pasted images',\n};\n\nexport interface UseAttachFilesReturn {\n /**\n * Upload files as Athena assets and add them to the attachment pills.\n * Resolves to the assets attached; a failed upload resolves to `[]` after\n * recording `composer.attachment.error` on the diagnostics bus (and in\n * `error`).\n */\n attachFiles: (files: readonly File[], source: AttachFilesSource) => Promise<UploadedAsset[]>;\n /** This intake's own upload in flight. */\n isUploading: boolean;\n /** Last failure of this intake, for its own affordance. */\n error: string | null;\n clearError: () => void;\n}\n\n/**\n * The one intake path for the attachment pills: the paperclip, the drop zone\n * and the composer's paste all upload through here, so a failure reaches the\n * diagnostics bus the same way and the shared `isUploading` flag — which\n * parks every submit path — is set for exactly the upload's duration.\n *\n * While the chat's outbox (a host's `chatOutbox`) says Athena can't be\n * reached, a file is not attached: its upload could only fail, and a message\n * that waits to be sent carries only files already uploaded. The composer\n * says so (`notice`, {@link OFFLINE_FILE_ATTACH_MESSAGE}).\n */\nexport function useAttachFiles(): UseAttachFilesReturn {\n const { upload, isUploading, error, clearError } = useFileUpload();\n const { addAttachments, setIsUploading, setNotice } = useAttachments();\n const outbox = useDeepAgentChatOutboxContext();\n\n const attachFiles = useCallback(\n async (files: readonly File[], source: AttachFilesSource): Promise<UploadedAsset[]> => {\n if (files.length === 0) return [];\n if (outbox && !outbox.reachability.get()) {\n setNotice(OFFLINE_FILE_ATTACH_MESSAGE);\n athenaDiagnostics.emit('composer.attachment.refused_offline', {\n level: 'info',\n data: { source, count: files.length },\n });\n return [];\n }\n setNotice(null);\n setIsUploading(true);\n try {\n const assets = await upload([...files]);\n if (assets.length > 0) addAttachments(assets);\n return assets;\n } catch (error) {\n athenaDiagnostics.error(\n 'composer.attachment.error',\n error,\n { code: 'attachment_failed', message: ATTACH_FAILURE_MESSAGE[source] },\n { source, count: files.length },\n );\n return [];\n } finally {\n setIsUploading(false);\n }\n },\n [addAttachments, outbox, setIsUploading, setNotice, upload],\n );\n\n return { attachFiles, isUploading, error, clearError };\n}\n"],"names":["useFileUpload","useAttachments","useDeepAgentChatOutboxContext","useCallback","athenaDiagnostics","error"],"mappings":";;;;;;;AAWO,MAAM,8BACX;AAKF,MAAM,yBAA4D;AAAA,EAChE,WAAW;AAAA,EACX,MAAM;AAAA,EACN,OAAO;AACT;AA4BO,SAAS,iBAAuC;AACrD,QAAM,EAAE,QAAQ,aAAa,OAAO,WAAA,IAAeA,cAAAA,cAAA;AACnD,QAAM,EAAE,gBAAgB,gBAAgB,UAAA,IAAcC,kBAAAA,eAAA;AACtD,QAAM,SAASC,uBAAAA,8BAAA;AAEf,QAAM,cAAcC,MAAAA;AAAAA,IAClB,OAAO,OAAwB,WAAwD;AACrF,UAAI,MAAM,WAAW,EAAG,QAAO,CAAA;AAC/B,UAAI,UAAU,CAAC,OAAO,aAAa,OAAO;AACxC,kBAAU,2BAA2B;AACrCC,0BAAAA,kBAAkB,KAAK,uCAAuC;AAAA,UAC5D,OAAO;AAAA,UACP,MAAM,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO,CACrC;AACD,eAAO,CAAA;AAAA,MACT;AACA,gBAAU,IAAI;AACd,qBAAe,IAAI;AACnB,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,CAAC,GAAG,KAAK,CAAC;AACtC,YAAI,OAAO,SAAS,EAAG,gBAAe,MAAM;AAC5C,eAAO;AAAA,MACT,SAASC,QAAO;AACdD,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACAC;AAAAA,UACA,EAAE,MAAM,qBAAqB,SAAS,uBAAuB,MAAM,EAAA;AAAA,UACnE,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO;AAEhC,eAAO,CAAA;AAAA,MACT,UAAA;AACE,uBAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,IACA,CAAC,gBAAgB,QAAQ,gBAAgB,WAAW,MAAM;AAAA,EAAA;AAG5D,SAAO,EAAE,aAAa,aAAa,OAAO,WAAA;AAC5C;;;"}
@@ -1,4 +1,10 @@
1
1
  import { type UploadedAsset } from './useFileUpload';
2
+ /**
3
+ * What the composer says when a file is picked, pasted or dropped while Athena can't be reached
4
+ * (the same words as Olympus's): the upload cannot happen, and a message sent now waits in the chat
5
+ * outbox with only the files that were already uploaded.
6
+ */
7
+ export declare const OFFLINE_FILE_ATTACH_MESSAGE = "Files can't be attached while Athena can't be reached. Messages you send now go out when it's back \u2014 attach the file then.";
2
8
  /** Which intake the files came through — carried on the diagnostics event. */
3
9
  export type AttachFilesSource = 'paperclip' | 'drop' | 'paste';
4
10
  export interface UseAttachFilesReturn {
@@ -20,5 +26,10 @@ export interface UseAttachFilesReturn {
20
26
  * and the composer's paste all upload through here, so a failure reaches the
21
27
  * diagnostics bus the same way and the shared `isUploading` flag — which
22
28
  * parks every submit path — is set for exactly the upload's duration.
29
+ *
30
+ * While the chat's outbox (a host's `chatOutbox`) says Athena can't be
31
+ * reached, a file is not attached: its upload could only fail, and a message
32
+ * that waits to be sent carries only files already uploaded. The composer
33
+ * says so (`notice`, {@link OFFLINE_FILE_ATTACH_MESSAGE}).
23
34
  */
24
35
  export declare function useAttachFiles(): UseAttachFilesReturn;
@@ -2,6 +2,8 @@ import { useCallback } from "react";
2
2
  import { athenaDiagnostics } from "../diagnostics/athena-diagnostics.js";
3
3
  import { useAttachments } from "./AttachmentContext.js";
4
4
  import { useFileUpload } from "./useFileUpload.js";
5
+ import { useDeepAgentChatOutboxContext } from "../agent-runtime/src/use-deep-agent-chat-outbox.js";
6
+ const OFFLINE_FILE_ATTACH_MESSAGE = "Files can't be attached while Athena can't be reached. Messages you send now go out when it's back — attach the file then.";
5
7
  const ATTACH_FAILURE_MESSAGE = {
6
8
  paperclip: "Failed to attach the selected files",
7
9
  drop: "Failed to attach the dropped files",
@@ -9,10 +11,20 @@ const ATTACH_FAILURE_MESSAGE = {
9
11
  };
10
12
  function useAttachFiles() {
11
13
  const { upload, isUploading, error, clearError } = useFileUpload();
12
- const { addAttachments, setIsUploading } = useAttachments();
14
+ const { addAttachments, setIsUploading, setNotice } = useAttachments();
15
+ const outbox = useDeepAgentChatOutboxContext();
13
16
  const attachFiles = useCallback(
14
17
  async (files, source) => {
15
18
  if (files.length === 0) return [];
19
+ if (outbox && !outbox.reachability.get()) {
20
+ setNotice(OFFLINE_FILE_ATTACH_MESSAGE);
21
+ athenaDiagnostics.emit("composer.attachment.refused_offline", {
22
+ level: "info",
23
+ data: { source, count: files.length }
24
+ });
25
+ return [];
26
+ }
27
+ setNotice(null);
16
28
  setIsUploading(true);
17
29
  try {
18
30
  const assets = await upload([...files]);
@@ -30,11 +42,12 @@ function useAttachFiles() {
30
42
  setIsUploading(false);
31
43
  }
32
44
  },
33
- [addAttachments, setIsUploading, upload]
45
+ [addAttachments, outbox, setIsUploading, setNotice, upload]
34
46
  );
35
47
  return { attachFiles, isUploading, error, clearError };
36
48
  }
37
49
  export {
50
+ OFFLINE_FILE_ATTACH_MESSAGE,
38
51
  useAttachFiles
39
52
  };
40
53
  //# sourceMappingURL=useAttachFiles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAttachFiles.js","sources":["../../src/composer/useAttachFiles.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { useAttachments } from './AttachmentContext';\nimport { useFileUpload, type UploadedAsset } from './useFileUpload';\n\n/** Which intake the files came through — carried on the diagnostics event. */\nexport type AttachFilesSource = 'paperclip' | 'drop' | 'paste';\n\nconst ATTACH_FAILURE_MESSAGE: Record<AttachFilesSource, string> = {\n paperclip: 'Failed to attach the selected files',\n drop: 'Failed to attach the dropped files',\n paste: 'Failed to attach the pasted images',\n};\n\nexport interface UseAttachFilesReturn {\n /**\n * Upload files as Athena assets and add them to the attachment pills.\n * Resolves to the assets attached; a failed upload resolves to `[]` after\n * recording `composer.attachment.error` on the diagnostics bus (and in\n * `error`).\n */\n attachFiles: (files: readonly File[], source: AttachFilesSource) => Promise<UploadedAsset[]>;\n /** This intake's own upload in flight. */\n isUploading: boolean;\n /** Last failure of this intake, for its own affordance. */\n error: string | null;\n clearError: () => void;\n}\n\n/**\n * The one intake path for the attachment pills: the paperclip, the drop zone\n * and the composer's paste all upload through here, so a failure reaches the\n * diagnostics bus the same way and the shared `isUploading` flag — which\n * parks every submit path — is set for exactly the upload's duration.\n */\nexport function useAttachFiles(): UseAttachFilesReturn {\n const { upload, isUploading, error, clearError } = useFileUpload();\n const { addAttachments, setIsUploading } = useAttachments();\n\n const attachFiles = useCallback(\n async (files: readonly File[], source: AttachFilesSource): Promise<UploadedAsset[]> => {\n if (files.length === 0) return [];\n setIsUploading(true);\n try {\n const assets = await upload([...files]);\n if (assets.length > 0) addAttachments(assets);\n return assets;\n } catch (error) {\n athenaDiagnostics.error(\n 'composer.attachment.error',\n error,\n { code: 'attachment_failed', message: ATTACH_FAILURE_MESSAGE[source] },\n { source, count: files.length },\n );\n return [];\n } finally {\n setIsUploading(false);\n }\n },\n [addAttachments, setIsUploading, upload],\n );\n\n return { attachFiles, isUploading, error, clearError };\n}\n"],"names":["error"],"mappings":";;;;AAQA,MAAM,yBAA4D;AAAA,EAChE,WAAW;AAAA,EACX,MAAM;AAAA,EACN,OAAO;AACT;AAuBO,SAAS,iBAAuC;AACrD,QAAM,EAAE,QAAQ,aAAa,OAAO,WAAA,IAAe,cAAA;AACnD,QAAM,EAAE,gBAAgB,eAAA,IAAmB,eAAA;AAE3C,QAAM,cAAc;AAAA,IAClB,OAAO,OAAwB,WAAwD;AACrF,UAAI,MAAM,WAAW,EAAG,QAAO,CAAA;AAC/B,qBAAe,IAAI;AACnB,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,CAAC,GAAG,KAAK,CAAC;AACtC,YAAI,OAAO,SAAS,EAAG,gBAAe,MAAM;AAC5C,eAAO;AAAA,MACT,SAASA,QAAO;AACd,0BAAkB;AAAA,UAChB;AAAA,UACAA;AAAAA,UACA,EAAE,MAAM,qBAAqB,SAAS,uBAAuB,MAAM,EAAA;AAAA,UACnE,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO;AAEhC,eAAO,CAAA;AAAA,MACT,UAAA;AACE,uBAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,IACA,CAAC,gBAAgB,gBAAgB,MAAM;AAAA,EAAA;AAGzC,SAAO,EAAE,aAAa,aAAa,OAAO,WAAA;AAC5C;"}
1
+ {"version":3,"file":"useAttachFiles.js","sources":["../../src/composer/useAttachFiles.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useDeepAgentChatOutboxContext } from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { useAttachments } from './AttachmentContext';\nimport { useFileUpload, type UploadedAsset } from './useFileUpload';\n\n/**\n * What the composer says when a file is picked, pasted or dropped while Athena can't be reached\n * (the same words as Olympus's): the upload cannot happen, and a message sent now waits in the chat\n * outbox with only the files that were already uploaded.\n */\nexport const OFFLINE_FILE_ATTACH_MESSAGE =\n \"Files can't be attached while Athena can't be reached. Messages you send now go out when it's back — attach the file then.\";\n\n/** Which intake the files came through — carried on the diagnostics event. */\nexport type AttachFilesSource = 'paperclip' | 'drop' | 'paste';\n\nconst ATTACH_FAILURE_MESSAGE: Record<AttachFilesSource, string> = {\n paperclip: 'Failed to attach the selected files',\n drop: 'Failed to attach the dropped files',\n paste: 'Failed to attach the pasted images',\n};\n\nexport interface UseAttachFilesReturn {\n /**\n * Upload files as Athena assets and add them to the attachment pills.\n * Resolves to the assets attached; a failed upload resolves to `[]` after\n * recording `composer.attachment.error` on the diagnostics bus (and in\n * `error`).\n */\n attachFiles: (files: readonly File[], source: AttachFilesSource) => Promise<UploadedAsset[]>;\n /** This intake's own upload in flight. */\n isUploading: boolean;\n /** Last failure of this intake, for its own affordance. */\n error: string | null;\n clearError: () => void;\n}\n\n/**\n * The one intake path for the attachment pills: the paperclip, the drop zone\n * and the composer's paste all upload through here, so a failure reaches the\n * diagnostics bus the same way and the shared `isUploading` flag — which\n * parks every submit path — is set for exactly the upload's duration.\n *\n * While the chat's outbox (a host's `chatOutbox`) says Athena can't be\n * reached, a file is not attached: its upload could only fail, and a message\n * that waits to be sent carries only files already uploaded. The composer\n * says so (`notice`, {@link OFFLINE_FILE_ATTACH_MESSAGE}).\n */\nexport function useAttachFiles(): UseAttachFilesReturn {\n const { upload, isUploading, error, clearError } = useFileUpload();\n const { addAttachments, setIsUploading, setNotice } = useAttachments();\n const outbox = useDeepAgentChatOutboxContext();\n\n const attachFiles = useCallback(\n async (files: readonly File[], source: AttachFilesSource): Promise<UploadedAsset[]> => {\n if (files.length === 0) return [];\n if (outbox && !outbox.reachability.get()) {\n setNotice(OFFLINE_FILE_ATTACH_MESSAGE);\n athenaDiagnostics.emit('composer.attachment.refused_offline', {\n level: 'info',\n data: { source, count: files.length },\n });\n return [];\n }\n setNotice(null);\n setIsUploading(true);\n try {\n const assets = await upload([...files]);\n if (assets.length > 0) addAttachments(assets);\n return assets;\n } catch (error) {\n athenaDiagnostics.error(\n 'composer.attachment.error',\n error,\n { code: 'attachment_failed', message: ATTACH_FAILURE_MESSAGE[source] },\n { source, count: files.length },\n );\n return [];\n } finally {\n setIsUploading(false);\n }\n },\n [addAttachments, outbox, setIsUploading, setNotice, upload],\n );\n\n return { attachFiles, isUploading, error, clearError };\n}\n"],"names":["error"],"mappings":";;;;;AAWO,MAAM,8BACX;AAKF,MAAM,yBAA4D;AAAA,EAChE,WAAW;AAAA,EACX,MAAM;AAAA,EACN,OAAO;AACT;AA4BO,SAAS,iBAAuC;AACrD,QAAM,EAAE,QAAQ,aAAa,OAAO,WAAA,IAAe,cAAA;AACnD,QAAM,EAAE,gBAAgB,gBAAgB,UAAA,IAAc,eAAA;AACtD,QAAM,SAAS,8BAAA;AAEf,QAAM,cAAc;AAAA,IAClB,OAAO,OAAwB,WAAwD;AACrF,UAAI,MAAM,WAAW,EAAG,QAAO,CAAA;AAC/B,UAAI,UAAU,CAAC,OAAO,aAAa,OAAO;AACxC,kBAAU,2BAA2B;AACrC,0BAAkB,KAAK,uCAAuC;AAAA,UAC5D,OAAO;AAAA,UACP,MAAM,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO,CACrC;AACD,eAAO,CAAA;AAAA,MACT;AACA,gBAAU,IAAI;AACd,qBAAe,IAAI;AACnB,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,CAAC,GAAG,KAAK,CAAC;AACtC,YAAI,OAAO,SAAS,EAAG,gBAAe,MAAM;AAC5C,eAAO;AAAA,MACT,SAASA,QAAO;AACd,0BAAkB;AAAA,UAChB;AAAA,UACAA;AAAAA,UACA,EAAE,MAAM,qBAAqB,SAAS,uBAAuB,MAAM,EAAA;AAAA,UACnE,EAAE,QAAQ,OAAO,MAAM,OAAA;AAAA,QAAO;AAEhC,eAAO,CAAA;AAAA,MACT,UAAA;AACE,uBAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,IACA,CAAC,gBAAgB,QAAQ,gBAAgB,WAAW,MAAM;AAAA,EAAA;AAG5D,SAAO,EAAE,aAAa,aAAa,OAAO,WAAA;AAC5C;"}
@@ -1 +1 @@
1
- {"version":3,"file":"useSendMessage.cjs","sources":["../../src/composer/useSendMessage.ts"],"sourcesContent":["import { useCallback, useContext, useRef } from 'react';\nimport { useAui } from '@assistant-ui/react';\nimport { AthenaStatewireThreadIdContext } from '../threads/thread-id-context';\nimport {\n applyComposerWrite,\n queueComposerWrite,\n useComposerHandoffStore,\n useComposerReady,\n type ComposerWrite,\n} from './composer-handoff';\n\nexport interface SendMessageOptions {\n /**\n * Replace the current composer text before sending.\n * Defaults to `true`.\n */\n replace?: boolean;\n}\n\n/**\n * Hook to programmatically send a user message from anywhere inside AthenaProvider.\n *\n * This is intended for custom workflow buttons, sidebar shortcuts, or other UI\n * that lives outside the AthenaChat thread tree. Unlike `aui.thread().append()`,\n * this uses the provider-scoped composer runtime and does not depend on\n * ThreadPrimitive context.\n *\n * Safe to call at any time: a send made before the chat is ready (the thread\n * list still resolving the active thread, or the thread's history still\n * loading) waits in the provider, in order with any other early sends, and\n * goes out once the composer is ready. The returned promise settles when\n * that send has been dispatched, and rejects with an `AthenaSdkError`\n * (`composer_write_dropped`) if it can no longer land — the user switched\n * threads, the identity changed, or the provider unmounted first.\n *\n * Usage:\n * const sendMessage = useSendMessage();\n * await sendMessage(\"Run the quarterly workflow\");\n * await sendMessage(\"Add this follow-up\", { replace: false });\n */\nexport function useSendMessage() {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n const readyRef = useRef(ready);\n readyRef.current = ready;\n\n return useCallback(\n async (text: string, options?: SendMessageOptions) => {\n if (!text.trim()) return;\n\n const write: ComposerWrite = {\n text,\n replace: options?.replace ?? true,\n send: true,\n focus: false,\n threadId,\n };\n if (store && !readyRef.current) {\n await new Promise<void>((resolve, reject) => {\n write.resolve = (outcome) => {\n Promise.resolve(outcome).then(() => resolve(), reject);\n };\n write.reject = reject;\n queueComposerWrite({ store, write });\n });\n return;\n }\n await applyComposerWrite({ target: aui, store, write });\n },\n [aui, store, threadId],\n );\n}\n"],"names":["useAui","useComposerHandoffStore","useContext","AthenaStatewireThreadIdContext","useComposerReady","useRef","useCallback","queueComposerWrite","applyComposerWrite"],"mappings":";;;;;;AAwCO,SAAS,iBAAiB;AAC/B,QAAM,MAAMA,MAAAA,OAAA;AACZ,QAAM,QAAQC,gBAAAA,wBAAA;AACd,QAAM,WAAWC,QAAAA,WAAWC,8CAA8B;AAC1D,QAAM,QAAQC,gBAAAA,iBAAA;AACd,QAAM,WAAWC,QAAAA,OAAO,KAAK;AAC7B,WAAS,UAAU;AAEnB,SAAOC,QAAAA;AAAAA,IACL,OAAO,MAAc,YAAiC;AACpD,UAAI,CAAC,KAAK,OAAQ;AAElB,YAAM,QAAuB;AAAA,QAC3B;AAAA,QACA,UAAS,mCAAS,YAAW;AAAA,QAC7B,MAAM;AAAA,QACN,OAAO;AAAA,QACP;AAAA,MAAA;AAEF,UAAI,SAAS,CAAC,SAAS,SAAS;AAC9B,cAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,gBAAM,UAAU,CAAC,YAAY;AAC3B,oBAAQ,QAAQ,OAAO,EAAE,KAAK,MAAM,QAAA,GAAW,MAAM;AAAA,UACvD;AACA,gBAAM,SAAS;AACfC,6CAAmB,EAAE,OAAO,OAAO;AAAA,QACrC,CAAC;AACD;AAAA,MACF;AACA,YAAMC,gBAAAA,mBAAmB,EAAE,QAAQ,KAAK,OAAO,OAAO;AAAA,IACxD;AAAA,IACA,CAAC,KAAK,OAAO,QAAQ;AAAA,EAAA;AAEzB;;"}
1
+ {"version":3,"file":"useSendMessage.cjs","sources":["../../src/composer/useSendMessage.ts"],"sourcesContent":["import { useCallback, useContext, useRef } from 'react';\nimport { useAui } from '@assistant-ui/react';\nimport { AthenaStatewireThreadIdContext } from '../threads/thread-id-context';\nimport {\n applyComposerWrite,\n queueComposerWrite,\n useComposerHandoffStore,\n useComposerReady,\n type ComposerWrite,\n} from './composer-handoff';\n\nexport interface SendMessageOptions {\n /**\n * Replace the current composer text before sending.\n * Defaults to `true`.\n */\n replace?: boolean;\n}\n\n/**\n * Hook to programmatically send a user message from anywhere inside AthenaProvider.\n *\n * This is intended for custom workflow buttons, sidebar shortcuts, or other UI\n * that lives outside the AthenaChat thread tree. Unlike `aui.thread().append()`,\n * this uses the provider-scoped composer runtime and does not depend on\n * ThreadPrimitive context.\n *\n * Safe to call at any time: a send made before the chat is ready (the thread\n * list still resolving the active thread, the thread's history still\n * loading, or a sign-in provider above still resolving who is signed in)\n * waits in the provider, in order with any other early sends, and goes out\n * once the composer is ready. The returned promise settles when\n * that send has been dispatched, and rejects with an `AthenaSdkError`\n * (`composer_write_dropped`) if it can no longer land — the user switched\n * threads, the identity changed, or the provider unmounted first.\n *\n * Usage:\n * const sendMessage = useSendMessage();\n * await sendMessage(\"Run the quarterly workflow\");\n * await sendMessage(\"Add this follow-up\", { replace: false });\n */\nexport function useSendMessage() {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n const readyRef = useRef(ready);\n readyRef.current = ready;\n\n return useCallback(\n async (text: string, options?: SendMessageOptions) => {\n if (!text.trim()) return;\n\n const write: ComposerWrite = {\n text,\n replace: options?.replace ?? true,\n send: true,\n focus: false,\n threadId,\n };\n if (store && !readyRef.current) {\n await new Promise<void>((resolve, reject) => {\n write.resolve = (outcome) => {\n Promise.resolve(outcome).then(() => resolve(), reject);\n };\n write.reject = reject;\n queueComposerWrite({ store, write });\n });\n return;\n }\n await applyComposerWrite({ target: aui, store, write });\n },\n [aui, store, threadId],\n );\n}\n"],"names":["useAui","useComposerHandoffStore","useContext","AthenaStatewireThreadIdContext","useComposerReady","useRef","useCallback","queueComposerWrite","applyComposerWrite"],"mappings":";;;;;;AAyCO,SAAS,iBAAiB;AAC/B,QAAM,MAAMA,MAAAA,OAAA;AACZ,QAAM,QAAQC,gBAAAA,wBAAA;AACd,QAAM,WAAWC,QAAAA,WAAWC,8CAA8B;AAC1D,QAAM,QAAQC,gBAAAA,iBAAA;AACd,QAAM,WAAWC,QAAAA,OAAO,KAAK;AAC7B,WAAS,UAAU;AAEnB,SAAOC,QAAAA;AAAAA,IACL,OAAO,MAAc,YAAiC;AACpD,UAAI,CAAC,KAAK,OAAQ;AAElB,YAAM,QAAuB;AAAA,QAC3B;AAAA,QACA,UAAS,mCAAS,YAAW;AAAA,QAC7B,MAAM;AAAA,QACN,OAAO;AAAA,QACP;AAAA,MAAA;AAEF,UAAI,SAAS,CAAC,SAAS,SAAS;AAC9B,cAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,gBAAM,UAAU,CAAC,YAAY;AAC3B,oBAAQ,QAAQ,OAAO,EAAE,KAAK,MAAM,QAAA,GAAW,MAAM;AAAA,UACvD;AACA,gBAAM,SAAS;AACfC,6CAAmB,EAAE,OAAO,OAAO;AAAA,QACrC,CAAC;AACD;AAAA,MACF;AACA,YAAMC,gBAAAA,mBAAmB,EAAE,QAAQ,KAAK,OAAO,OAAO;AAAA,IACxD;AAAA,IACA,CAAC,KAAK,OAAO,QAAQ;AAAA,EAAA;AAEzB;;"}
@@ -14,9 +14,10 @@ export interface SendMessageOptions {
14
14
  * ThreadPrimitive context.
15
15
  *
16
16
  * Safe to call at any time: a send made before the chat is ready (the thread
17
- * list still resolving the active thread, or the thread's history still
18
- * loading) waits in the provider, in order with any other early sends, and
19
- * goes out once the composer is ready. The returned promise settles when
17
+ * list still resolving the active thread, the thread's history still
18
+ * loading, or a sign-in provider above still resolving who is signed in)
19
+ * waits in the provider, in order with any other early sends, and goes out
20
+ * once the composer is ready. The returned promise settles when
20
21
  * that send has been dispatched, and rejects with an `AthenaSdkError`
21
22
  * (`composer_write_dropped`) if it can no longer land — the user switched
22
23
  * threads, the identity changed, or the provider unmounted first.
@@ -1 +1 @@
1
- {"version":3,"file":"useSendMessage.js","sources":["../../src/composer/useSendMessage.ts"],"sourcesContent":["import { useCallback, useContext, useRef } from 'react';\nimport { useAui } from '@assistant-ui/react';\nimport { AthenaStatewireThreadIdContext } from '../threads/thread-id-context';\nimport {\n applyComposerWrite,\n queueComposerWrite,\n useComposerHandoffStore,\n useComposerReady,\n type ComposerWrite,\n} from './composer-handoff';\n\nexport interface SendMessageOptions {\n /**\n * Replace the current composer text before sending.\n * Defaults to `true`.\n */\n replace?: boolean;\n}\n\n/**\n * Hook to programmatically send a user message from anywhere inside AthenaProvider.\n *\n * This is intended for custom workflow buttons, sidebar shortcuts, or other UI\n * that lives outside the AthenaChat thread tree. Unlike `aui.thread().append()`,\n * this uses the provider-scoped composer runtime and does not depend on\n * ThreadPrimitive context.\n *\n * Safe to call at any time: a send made before the chat is ready (the thread\n * list still resolving the active thread, or the thread's history still\n * loading) waits in the provider, in order with any other early sends, and\n * goes out once the composer is ready. The returned promise settles when\n * that send has been dispatched, and rejects with an `AthenaSdkError`\n * (`composer_write_dropped`) if it can no longer land — the user switched\n * threads, the identity changed, or the provider unmounted first.\n *\n * Usage:\n * const sendMessage = useSendMessage();\n * await sendMessage(\"Run the quarterly workflow\");\n * await sendMessage(\"Add this follow-up\", { replace: false });\n */\nexport function useSendMessage() {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n const readyRef = useRef(ready);\n readyRef.current = ready;\n\n return useCallback(\n async (text: string, options?: SendMessageOptions) => {\n if (!text.trim()) return;\n\n const write: ComposerWrite = {\n text,\n replace: options?.replace ?? true,\n send: true,\n focus: false,\n threadId,\n };\n if (store && !readyRef.current) {\n await new Promise<void>((resolve, reject) => {\n write.resolve = (outcome) => {\n Promise.resolve(outcome).then(() => resolve(), reject);\n };\n write.reject = reject;\n queueComposerWrite({ store, write });\n });\n return;\n }\n await applyComposerWrite({ target: aui, store, write });\n },\n [aui, store, threadId],\n );\n}\n"],"names":[],"mappings":";;;;AAwCO,SAAS,iBAAiB;AAC/B,QAAM,MAAM,OAAA;AACZ,QAAM,QAAQ,wBAAA;AACd,QAAM,WAAW,WAAW,8BAA8B;AAC1D,QAAM,QAAQ,iBAAA;AACd,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAEnB,SAAO;AAAA,IACL,OAAO,MAAc,YAAiC;AACpD,UAAI,CAAC,KAAK,OAAQ;AAElB,YAAM,QAAuB;AAAA,QAC3B;AAAA,QACA,UAAS,mCAAS,YAAW;AAAA,QAC7B,MAAM;AAAA,QACN,OAAO;AAAA,QACP;AAAA,MAAA;AAEF,UAAI,SAAS,CAAC,SAAS,SAAS;AAC9B,cAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,gBAAM,UAAU,CAAC,YAAY;AAC3B,oBAAQ,QAAQ,OAAO,EAAE,KAAK,MAAM,QAAA,GAAW,MAAM;AAAA,UACvD;AACA,gBAAM,SAAS;AACf,6BAAmB,EAAE,OAAO,OAAO;AAAA,QACrC,CAAC;AACD;AAAA,MACF;AACA,YAAM,mBAAmB,EAAE,QAAQ,KAAK,OAAO,OAAO;AAAA,IACxD;AAAA,IACA,CAAC,KAAK,OAAO,QAAQ;AAAA,EAAA;AAEzB;"}
1
+ {"version":3,"file":"useSendMessage.js","sources":["../../src/composer/useSendMessage.ts"],"sourcesContent":["import { useCallback, useContext, useRef } from 'react';\nimport { useAui } from '@assistant-ui/react';\nimport { AthenaStatewireThreadIdContext } from '../threads/thread-id-context';\nimport {\n applyComposerWrite,\n queueComposerWrite,\n useComposerHandoffStore,\n useComposerReady,\n type ComposerWrite,\n} from './composer-handoff';\n\nexport interface SendMessageOptions {\n /**\n * Replace the current composer text before sending.\n * Defaults to `true`.\n */\n replace?: boolean;\n}\n\n/**\n * Hook to programmatically send a user message from anywhere inside AthenaProvider.\n *\n * This is intended for custom workflow buttons, sidebar shortcuts, or other UI\n * that lives outside the AthenaChat thread tree. Unlike `aui.thread().append()`,\n * this uses the provider-scoped composer runtime and does not depend on\n * ThreadPrimitive context.\n *\n * Safe to call at any time: a send made before the chat is ready (the thread\n * list still resolving the active thread, the thread's history still\n * loading, or a sign-in provider above still resolving who is signed in)\n * waits in the provider, in order with any other early sends, and goes out\n * once the composer is ready. The returned promise settles when\n * that send has been dispatched, and rejects with an `AthenaSdkError`\n * (`composer_write_dropped`) if it can no longer land — the user switched\n * threads, the identity changed, or the provider unmounted first.\n *\n * Usage:\n * const sendMessage = useSendMessage();\n * await sendMessage(\"Run the quarterly workflow\");\n * await sendMessage(\"Add this follow-up\", { replace: false });\n */\nexport function useSendMessage() {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n const readyRef = useRef(ready);\n readyRef.current = ready;\n\n return useCallback(\n async (text: string, options?: SendMessageOptions) => {\n if (!text.trim()) return;\n\n const write: ComposerWrite = {\n text,\n replace: options?.replace ?? true,\n send: true,\n focus: false,\n threadId,\n };\n if (store && !readyRef.current) {\n await new Promise<void>((resolve, reject) => {\n write.resolve = (outcome) => {\n Promise.resolve(outcome).then(() => resolve(), reject);\n };\n write.reject = reject;\n queueComposerWrite({ store, write });\n });\n return;\n }\n await applyComposerWrite({ target: aui, store, write });\n },\n [aui, store, threadId],\n );\n}\n"],"names":[],"mappings":";;;;AAyCO,SAAS,iBAAiB;AAC/B,QAAM,MAAM,OAAA;AACZ,QAAM,QAAQ,wBAAA;AACd,QAAM,WAAW,WAAW,8BAA8B;AAC1D,QAAM,QAAQ,iBAAA;AACd,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAEnB,SAAO;AAAA,IACL,OAAO,MAAc,YAAiC;AACpD,UAAI,CAAC,KAAK,OAAQ;AAElB,YAAM,QAAuB;AAAA,QAC3B;AAAA,QACA,UAAS,mCAAS,YAAW;AAAA,QAC7B,MAAM;AAAA,QACN,OAAO;AAAA,QACP;AAAA,MAAA;AAEF,UAAI,SAAS,CAAC,SAAS,SAAS;AAC9B,cAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,gBAAM,UAAU,CAAC,YAAY;AAC3B,oBAAQ,QAAQ,OAAO,EAAE,KAAK,MAAM,QAAA,GAAW,MAAM;AAAA,UACvD;AACA,gBAAM,SAAS;AACf,6BAAmB,EAAE,OAAO,OAAO;AAAA,QACrC,CAAC;AACD;AAAA,MACF;AACA,YAAM,mBAAmB,EAAE,QAAQ,KAAK,OAAO,OAAO;AAAA,IACxD;AAAA,IACA,CAAC,KAAK,OAAO,QAAQ;AAAA,EAAA;AAEzB;"}
@@ -1 +1 @@
1
- {"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":["toAthenaSdkError","ATHENA_REACT_SDK_VERSION","isAthenaSdkError","getPostHogInstance","capturePosthogEvent"],"mappings":";;;;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAwGA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5F,OAAO;AACL,UAAI,GAAG,IAAI;AAAA,IACb;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aACpE,YAAY,QACZ,KAAK,IAAA;AACX;AAEA,SAAS,sBAAoD;AAC3D,MAAI;AACF,QAAI,OAAO,iBAAiB,YAAa,QAAO;AAChD,UAAM,MAAM,aAAa,QAA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AA,QAAA;AAAA,QAE5B,GAAG,MAAM;AAAA,MAAA,CACV;AAAA,IACH,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEO,MAAM,oBAAoB,IAAI,qBAAA;AAO9B,SAAS,iCAAuC;AACrD,MAAI,OAAO,WAAW,YAAa;AACnC,QAAM,eAAe;AACrB,QAAM,WAAY,aAAa,UAAU,KAAK,CAAA;AAC9C,eAAa,UAAU,IAAI;AAAA,IACzB,GAAG;AAAA,IACH,SAASA,QAAAA;AAAAA,IACT,aAAa;AAAA,MACX,UAAU,MAAM,kBAAkB,SAAA;AAAA,MAClC,QAAQ,MAAM,kBAAkB,OAAA;AAAA,MAChC,OAAO,MAAM,kBAAkB,MAAA;AAAA,MAC/B,eAAe,CAAC,QAA+B,YAAY;AACzD,YAAI;AACF,uBAAa,QAAQ,yBAAyB,KAAK;AAAA,QACrD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,MACA,gBAAgB,MAAM;AACpB,YAAI;AACF,uBAAa,WAAW,uBAAuB;AAAA,QACjD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,IAAA;AAAA,EACF;AAEJ;AAGO,SAAS,6BACd,OACkC;AAClC,MAAI,UAAU,OAAW,QAAO,CAAA;AAChC,MAAI,UAAU,KAAM,QAAO,EAAE,SAAS,QAAA;AACtC,MAAI,UAAU,MAAO,QAAO,EAAE,SAAS,MAAA;AACvC,MAAI,OAAO,UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;;;;;"}
1
+ {"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":["toAthenaSdkError","ATHENA_REACT_SDK_VERSION","isAthenaSdkError","getPostHogInstance","capturePosthogEvent"],"mappings":";;;;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA0GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5F,OAAO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UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;;;;;"}
@@ -29,7 +29,9 @@ export type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];
29
29
  */
30
30
  export type AthenaDiagnosticEventName = 'sdk.init' | 'sdk.transport' | 'sdk.config.warning' | 'auth.bridge.start' | 'auth.bridge.ready' | 'auth.bridge.timeout' | 'auth.bridge.absent' | 'auth.bridge.error' | 'auth.bridge.retry' | 'auth.bridge.config_rejected' | 'auth.token.acquired' | 'auth.token.refreshed' | 'auth.token.refresh_failed' | 'auth.token.stale' | 'auth.sso.userinfo.start' | 'auth.sso.userinfo.done' | 'auth.sso.userinfo.error' | 'auth.sso.userinfo.retry' | 'threads.list.start' | 'threads.list.done' | 'threads.list.error' | 'threads.list.aborted' | 'threads.history.start' | 'threads.history.done' | 'threads.history.error' | 'threads.history.aborted' | 'statewire.attach.start' | 'statewire.snapshot' | 'statewire.connection' | 'statewire.parked' | 'statewire.error' | 'statewire.read_only'
31
31
  /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */
32
- | 'statewire.config' | 'run.send' | 'run.first_token' | 'run.done' | 'run.error' | 'composer.attachment.error' | 'composer.cancel.error' | 'composer.dictation' | 'composer.handoff' | 'tools.schema.warning' | 'tools.debug' | 'mentions.fetch.error' | 'sdk.error';
32
+ | 'statewire.config' | 'run.send' | 'run.first_token' | 'run.done' | 'run.error' | 'composer.attachment.error'
33
+ /** Files offered while Athena can't be reached were not attached (they could not upload). */
34
+ | 'composer.attachment.refused_offline' | 'composer.cancel.error' | 'composer.dictation' | 'composer.handoff' | 'tools.schema.warning' | 'tools.debug' | 'mentions.fetch.error' | 'sdk.error';
33
35
  export interface AthenaDiagnosticEvent {
34
36
  /** Monotonic sequence number within this page. */
35
37
  seq: number;
@@ -1 +1 @@
1
- {"version":3,"file":"athena-diagnostics.js","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":[],"mappings":";;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAwGA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5F,OAAO;AACL,UAAI,GAAG,I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ics.js","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":[],"mappings":";;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA0GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAA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