@athenaintel/react 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/README.md +74 -0
  2. package/dist/assets/use-asset-embed.cjs +8 -0
  3. package/dist/assets/use-asset-embed.cjs.map +1 -1
  4. package/dist/assets/use-asset-embed.js +8 -0
  5. package/dist/assets/use-asset-embed.js.map +1 -1
  6. package/dist/chat/StatewireApprovalCard.cjs +22 -4
  7. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  8. package/dist/chat/StatewireApprovalCard.d.ts +14 -0
  9. package/dist/chat/StatewireApprovalCard.js +23 -5
  10. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  11. package/dist/chat/StatewireClientToolBridge.cjs +2 -1
  12. package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
  13. package/dist/chat/StatewireClientToolBridge.js +2 -1
  14. package/dist/chat/StatewireClientToolBridge.js.map +1 -1
  15. package/dist/chat/StatewireQueuedMessages.cjs +2 -1
  16. package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
  17. package/dist/chat/StatewireQueuedMessages.js +2 -1
  18. package/dist/chat/StatewireQueuedMessages.js.map +1 -1
  19. package/dist/chat/athena-citation-links.cjs +17 -1
  20. package/dist/chat/athena-citation-links.cjs.map +1 -1
  21. package/dist/chat/athena-citation-links.js +17 -1
  22. package/dist/chat/athena-citation-links.js.map +1 -1
  23. package/dist/chat/statewire-client-tools.cjs +2 -1
  24. package/dist/chat/statewire-client-tools.cjs.map +1 -1
  25. package/dist/chat/statewire-client-tools.js +2 -1
  26. package/dist/chat/statewire-client-tools.js.map +1 -1
  27. package/dist/chat/super-grouping/SuperGroupingCard.cjs +69 -187
  28. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  29. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +10 -6
  30. package/dist/chat/super-grouping/SuperGroupingCard.js +73 -191
  31. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  32. package/dist/chat/super-grouping/ToolTimeline.cjs +131 -0
  33. package/dist/chat/super-grouping/ToolTimeline.cjs.map +1 -0
  34. package/dist/chat/super-grouping/ToolTimeline.d.ts +16 -0
  35. package/dist/chat/super-grouping/ToolTimeline.js +131 -0
  36. package/dist/chat/super-grouping/ToolTimeline.js.map +1 -0
  37. package/dist/chat/super-grouping/activity-timeline.cjs +14 -8
  38. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  39. package/dist/chat/super-grouping/activity-timeline.d.ts +3 -0
  40. package/dist/chat/super-grouping/activity-timeline.js +14 -8
  41. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  42. package/dist/chat/super-grouping/timeline-step.cjs +65 -0
  43. package/dist/chat/super-grouping/timeline-step.cjs.map +1 -0
  44. package/dist/chat/super-grouping/timeline-step.d.ts +17 -0
  45. package/dist/chat/super-grouping/timeline-step.js +65 -0
  46. package/dist/chat/super-grouping/timeline-step.js.map +1 -0
  47. package/dist/chat/tiptap-text.cjs +8 -8
  48. package/dist/chat/tiptap-text.cjs.map +1 -1
  49. package/dist/chat/use-athena-run-live.cjs +2 -1
  50. package/dist/chat/use-athena-run-live.cjs.map +1 -1
  51. package/dist/chat/use-athena-run-live.js +2 -1
  52. package/dist/chat/use-athena-run-live.js.map +1 -1
  53. package/dist/chat/use-statewire-approval-request.cjs +7 -2
  54. package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
  55. package/dist/chat/use-statewire-approval-request.d.ts +12 -2
  56. package/dist/chat/use-statewire-approval-request.js +8 -3
  57. package/dist/chat/use-statewire-approval-request.js.map +1 -1
  58. package/dist/chat-ui/composer/tiptap-composer.cjs +24 -65
  59. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  60. package/dist/chat-ui/composer/tiptap-composer.js +24 -65
  61. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  62. package/dist/chat-ui/index.cjs +2 -1
  63. package/dist/chat-ui/index.cjs.map +1 -1
  64. package/dist/chat-ui/index.js +2 -1
  65. package/dist/chat-ui/index.js.map +1 -1
  66. package/dist/chat-ui/mentions/mention-chip.cjs +49 -4
  67. package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
  68. package/dist/chat-ui/mentions/mention-chip.d.ts +11 -0
  69. package/dist/chat-ui/mentions/mention-chip.js +50 -5
  70. package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
  71. package/dist/chat-ui/mentions/mention-extension.cjs +18 -6
  72. package/dist/chat-ui/mentions/mention-extension.cjs.map +1 -1
  73. package/dist/chat-ui/mentions/mention-extension.d.ts +2 -0
  74. package/dist/chat-ui/mentions/mention-extension.js +18 -6
  75. package/dist/chat-ui/mentions/mention-extension.js.map +1 -1
  76. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs +1 -1
  77. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs.map +1 -1
  78. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js +1 -1
  79. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js.map +1 -1
  80. package/dist/chat-ui/mentions/suggestions/components/menu-item.cjs +9 -6
  81. package/dist/chat-ui/mentions/suggestions/components/menu-item.cjs.map +1 -1
  82. package/dist/chat-ui/mentions/suggestions/components/menu-item.d.ts +2 -2
  83. package/dist/chat-ui/mentions/suggestions/components/menu-item.js +10 -7
  84. package/dist/chat-ui/mentions/suggestions/components/menu-item.js.map +1 -1
  85. package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs +2 -2
  86. package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs.map +1 -1
  87. package/dist/chat-ui/mentions/suggestions/components/menu-list.d.ts +2 -2
  88. package/dist/chat-ui/mentions/suggestions/components/menu-list.js +2 -2
  89. package/dist/chat-ui/mentions/suggestions/components/menu-list.js.map +1 -1
  90. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +2 -1
  91. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  92. package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +3 -2
  93. package/dist/chat-ui/mentions/suggestions/data/api-client.js +2 -1
  94. package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
  95. package/dist/chat-ui/messages/message-components.cjs +6 -29
  96. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  97. package/dist/chat-ui/messages/message-components.d.ts +1 -13
  98. package/dist/chat-ui/messages/message-components.js +8 -31
  99. package/dist/chat-ui/messages/message-components.js.map +1 -1
  100. package/dist/chat-ui/messages/runtime-message.cjs +3 -2
  101. package/dist/chat-ui/messages/runtime-message.cjs.map +1 -1
  102. package/dist/chat-ui/messages/runtime-message.js +3 -2
  103. package/dist/chat-ui/messages/runtime-message.js.map +1 -1
  104. package/dist/chat-ui/messages/statewire-continue-run.cjs +23 -8
  105. package/dist/chat-ui/messages/statewire-continue-run.cjs.map +1 -1
  106. package/dist/chat-ui/messages/statewire-continue-run.d.ts +14 -4
  107. package/dist/chat-ui/messages/statewire-continue-run.js +23 -8
  108. package/dist/chat-ui/messages/statewire-continue-run.js.map +1 -1
  109. package/dist/chat-ui/messages/user-edit-composer.cjs +2 -1
  110. package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
  111. package/dist/chat-ui/messages/user-edit-composer.js +2 -1
  112. package/dist/chat-ui/messages/user-edit-composer.js.map +1 -1
  113. package/dist/chat-ui/rich-text/chat-message-body.cjs +76 -0
  114. package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -0
  115. package/dist/chat-ui/rich-text/chat-message-body.d.ts +5 -0
  116. package/dist/chat-ui/rich-text/chat-message-body.js +76 -0
  117. package/dist/chat-ui/rich-text/chat-message-body.js.map +1 -0
  118. package/dist/chat-ui/rich-text/chat-node-views.cjs +51 -0
  119. package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -0
  120. package/dist/chat-ui/rich-text/chat-node-views.d.ts +13 -0
  121. package/dist/chat-ui/rich-text/chat-node-views.js +51 -0
  122. package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -0
  123. package/dist/chat-ui/rich-text/chat-text-schema.cjs +70 -0
  124. package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -0
  125. package/dist/chat-ui/rich-text/chat-text-schema.d.ts +7 -0
  126. package/dist/chat-ui/rich-text/chat-text-schema.js +70 -0
  127. package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -0
  128. package/dist/chat-ui/rich-text/dom-output-spec.cjs +83 -0
  129. package/dist/chat-ui/rich-text/dom-output-spec.cjs.map +1 -0
  130. package/dist/chat-ui/rich-text/dom-output-spec.d.ts +11 -0
  131. package/dist/chat-ui/rich-text/dom-output-spec.js +83 -0
  132. package/dist/chat-ui/rich-text/dom-output-spec.js.map +1 -0
  133. package/dist/chat-ui/statewire.cjs +2 -1
  134. package/dist/chat-ui/statewire.cjs.map +1 -1
  135. package/dist/chat-ui/statewire.js +2 -1
  136. package/dist/chat-ui/statewire.js.map +1 -1
  137. package/dist/chat-ui/thread/statewire-history-edge.cjs +2 -1
  138. package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
  139. package/dist/chat-ui/thread/statewire-history-edge.js +2 -1
  140. package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
  141. package/dist/index.cjs +2 -1
  142. package/dist/index.cjs.map +1 -1
  143. package/dist/index.js +2 -1
  144. package/dist/index.js.map +1 -1
  145. package/dist/node_modules/qrcode-generator/dist/qrcode.cjs +32 -0
  146. package/dist/node_modules/qrcode-generator/dist/qrcode.cjs.map +1 -0
  147. package/dist/node_modules/qrcode-generator/dist/qrcode.js +31 -0
  148. package/dist/node_modules/qrcode-generator/dist/qrcode.js.map +1 -0
  149. package/dist/node_modules/zod/v4/classic/errors.cjs +44 -0
  150. package/dist/node_modules/zod/v4/classic/errors.cjs.map +1 -0
  151. package/dist/node_modules/zod/v4/classic/errors.js +44 -0
  152. package/dist/node_modules/zod/v4/classic/errors.js.map +1 -0
  153. package/dist/node_modules/zod/v4/classic/iso.cjs +43 -0
  154. package/dist/node_modules/zod/v4/classic/iso.cjs.map +1 -0
  155. package/dist/node_modules/zod/v4/classic/iso.js +43 -0
  156. package/dist/node_modules/zod/v4/classic/iso.js.map +1 -0
  157. package/dist/node_modules/zod/v4/classic/parse.cjs +29 -0
  158. package/dist/node_modules/zod/v4/classic/parse.cjs.map +1 -0
  159. package/dist/node_modules/zod/v4/classic/parse.js +29 -0
  160. package/dist/node_modules/zod/v4/classic/parse.js.map +1 -0
  161. package/dist/node_modules/zod/v4/classic/schemas.cjs +871 -0
  162. package/dist/node_modules/zod/v4/classic/schemas.cjs.map +1 -0
  163. package/dist/node_modules/zod/v4/classic/schemas.js +871 -0
  164. package/dist/node_modules/zod/v4/classic/schemas.js.map +1 -0
  165. package/dist/node_modules/zod/v4/core/api.cjs +570 -0
  166. package/dist/node_modules/zod/v4/core/api.cjs.map +1 -0
  167. package/dist/node_modules/zod/v4/core/api.js +570 -0
  168. package/dist/node_modules/zod/v4/core/api.js.map +1 -0
  169. package/dist/node_modules/zod/v4/core/checks.cjs +411 -0
  170. package/dist/node_modules/zod/v4/core/checks.cjs.map +1 -0
  171. package/dist/node_modules/zod/v4/core/checks.js +411 -0
  172. package/dist/node_modules/zod/v4/core/checks.js.map +1 -0
  173. package/dist/node_modules/zod/v4/core/core.cjs +77 -0
  174. package/dist/node_modules/zod/v4/core/core.cjs.map +1 -0
  175. package/dist/node_modules/zod/v4/core/core.js +77 -0
  176. package/dist/node_modules/zod/v4/core/core.js.map +1 -0
  177. package/dist/node_modules/zod/v4/core/doc.cjs +38 -0
  178. package/dist/node_modules/zod/v4/core/doc.cjs.map +1 -0
  179. package/dist/node_modules/zod/v4/core/doc.js +38 -0
  180. package/dist/node_modules/zod/v4/core/doc.js.map +1 -0
  181. package/dist/node_modules/zod/v4/core/errors.cjs +76 -0
  182. package/dist/node_modules/zod/v4/core/errors.cjs.map +1 -0
  183. package/dist/node_modules/zod/v4/core/errors.js +76 -0
  184. package/dist/node_modules/zod/v4/core/errors.js.map +1 -0
  185. package/dist/node_modules/zod/v4/core/json-schema-processors.cjs +312 -0
  186. package/dist/node_modules/zod/v4/core/json-schema-processors.cjs.map +1 -0
  187. package/dist/node_modules/zod/v4/core/json-schema-processors.js +312 -0
  188. package/dist/node_modules/zod/v4/core/json-schema-processors.js.map +1 -0
  189. package/dist/node_modules/zod/v4/core/parse.cjs +96 -0
  190. package/dist/node_modules/zod/v4/core/parse.cjs.map +1 -0
  191. package/dist/node_modules/zod/v4/core/parse.js +96 -0
  192. package/dist/node_modules/zod/v4/core/parse.js.map +1 -0
  193. package/dist/node_modules/zod/v4/core/regexes.cjs +86 -0
  194. package/dist/node_modules/zod/v4/core/regexes.cjs.map +1 -0
  195. package/dist/node_modules/zod/v4/core/regexes.js +86 -0
  196. package/dist/node_modules/zod/v4/core/regexes.js.map +1 -0
  197. package/dist/node_modules/zod/v4/core/registries.cjs +52 -0
  198. package/dist/node_modules/zod/v4/core/registries.cjs.map +1 -0
  199. package/dist/node_modules/zod/v4/core/registries.js +52 -0
  200. package/dist/node_modules/zod/v4/core/registries.js.map +1 -0
  201. package/dist/node_modules/zod/v4/core/schemas.cjs +1412 -0
  202. package/dist/node_modules/zod/v4/core/schemas.cjs.map +1 -0
  203. package/dist/node_modules/zod/v4/core/schemas.js +1413 -0
  204. package/dist/node_modules/zod/v4/core/schemas.js.map +1 -0
  205. package/dist/node_modules/zod/v4/core/to-json-schema.cjs +370 -0
  206. package/dist/node_modules/zod/v4/core/to-json-schema.cjs.map +1 -0
  207. package/dist/node_modules/zod/v4/core/to-json-schema.js +370 -0
  208. package/dist/node_modules/zod/v4/core/to-json-schema.js.map +1 -0
  209. package/dist/node_modules/zod/v4/core/util.cjs +444 -0
  210. package/dist/node_modules/zod/v4/core/util.cjs.map +1 -0
  211. package/dist/node_modules/zod/v4/core/util.js +444 -0
  212. package/dist/node_modules/zod/v4/core/util.js.map +1 -0
  213. package/dist/node_modules/zod/v4/core/versions.cjs +9 -0
  214. package/dist/node_modules/zod/v4/core/versions.cjs.map +1 -0
  215. package/dist/node_modules/zod/v4/core/versions.js +9 -0
  216. package/dist/node_modules/zod/v4/core/versions.js.map +1 -0
  217. package/dist/packages/agent-runtime/src/client-tool-bridge.cjs +7 -1
  218. package/dist/packages/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
  219. package/dist/packages/agent-runtime/src/client-tool-bridge.js +7 -1
  220. package/dist/packages/agent-runtime/src/client-tool-bridge.js.map +1 -1
  221. package/dist/packages/agent-runtime/src/conversation-list.cjs +4 -0
  222. package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
  223. package/dist/packages/agent-runtime/src/conversation-list.js +4 -0
  224. package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
  225. package/dist/packages/agent-runtime/src/edit-command.cjs.map +1 -1
  226. package/dist/packages/agent-runtime/src/edit-command.js.map +1 -1
  227. package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +2 -0
  228. package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  229. package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +2 -0
  230. package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  231. package/dist/packages/agent-runtime/src/interrupts.cjs +31 -7
  232. package/dist/packages/agent-runtime/src/interrupts.cjs.map +1 -1
  233. package/dist/packages/agent-runtime/src/interrupts.js +31 -7
  234. package/dist/packages/agent-runtime/src/interrupts.js.map +1 -1
  235. package/dist/packages/agent-runtime/src/messages.cjs +35 -5
  236. package/dist/packages/agent-runtime/src/messages.cjs.map +1 -1
  237. package/dist/packages/agent-runtime/src/messages.js +35 -5
  238. package/dist/packages/agent-runtime/src/messages.js.map +1 -1
  239. package/dist/packages/agent-runtime/src/protocol.cjs +4 -6
  240. package/dist/packages/agent-runtime/src/protocol.cjs.map +1 -1
  241. package/dist/packages/agent-runtime/src/protocol.js +4 -6
  242. package/dist/packages/agent-runtime/src/protocol.js.map +1 -1
  243. package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs +296 -14
  244. package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  245. package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js +293 -11
  246. package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
  247. package/dist/packages/agent-runtime/src/screen-point.cjs +68 -0
  248. package/dist/packages/agent-runtime/src/screen-point.cjs.map +1 -0
  249. package/dist/packages/agent-runtime/src/screen-point.js +68 -0
  250. package/dist/packages/agent-runtime/src/screen-point.js.map +1 -0
  251. package/dist/packages/agent-runtime/src/statewire-transport.cjs +6 -1
  252. package/dist/packages/agent-runtime/src/statewire-transport.cjs.map +1 -1
  253. package/dist/packages/agent-runtime/src/statewire-transport.js +6 -1
  254. package/dist/packages/agent-runtime/src/statewire-transport.js.map +1 -1
  255. package/dist/packages/agent-runtime/src/thread-handoff.cjs +85 -0
  256. package/dist/packages/agent-runtime/src/thread-handoff.cjs.map +1 -0
  257. package/dist/packages/agent-runtime/src/thread-handoff.js +85 -0
  258. package/dist/packages/agent-runtime/src/thread-handoff.js.map +1 -0
  259. package/dist/packages/agent-runtime/src/thread-snapshot-cache.cjs +1 -1
  260. package/dist/packages/agent-runtime/src/thread-snapshot-cache.cjs.map +1 -1
  261. package/dist/packages/agent-runtime/src/thread-snapshot-cache.js +1 -1
  262. package/dist/packages/agent-runtime/src/thread-snapshot-cache.js.map +1 -1
  263. package/dist/packages/agent-runtime/src/tool-metadata.cjs +0 -8
  264. package/dist/packages/agent-runtime/src/tool-metadata.cjs.map +1 -1
  265. package/dist/packages/agent-runtime/src/tool-metadata.js +0 -8
  266. package/dist/packages/agent-runtime/src/tool-metadata.js.map +1 -1
  267. package/dist/packages/agent-runtime/src/use-deep-agent-config.cjs +14 -0
  268. package/dist/packages/agent-runtime/src/use-deep-agent-config.cjs.map +1 -0
  269. package/dist/packages/agent-runtime/src/use-deep-agent-config.js +14 -0
  270. package/dist/packages/agent-runtime/src/use-deep-agent-config.js.map +1 -0
  271. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs +21 -5
  272. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
  273. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js +21 -5
  274. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
  275. package/dist/packages/agent-runtime/src/use-deep-agent-runtime.cjs +13 -3
  276. package/dist/packages/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  277. package/dist/packages/agent-runtime/src/use-deep-agent-runtime.js +14 -4
  278. package/dist/packages/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
  279. package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs +35 -15
  280. package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  281. package/dist/packages/agent-runtime/src/use-deep-agent-thread.js +35 -15
  282. package/dist/packages/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  283. package/dist/packages/agent-runtime/src/voice-presentation.cjs.map +1 -1
  284. package/dist/packages/agent-runtime/src/voice-presentation.js.map +1 -1
  285. package/dist/packages/react/package.json.cjs +1 -1
  286. package/dist/packages/react/package.json.js +1 -1
  287. package/dist/provider/AthenaProvider.cjs +2 -1
  288. package/dist/provider/AthenaProvider.cjs.map +1 -1
  289. package/dist/provider/AthenaProvider.js +2 -1
  290. package/dist/provider/AthenaProvider.js.map +1 -1
  291. package/dist/runtime/statewire-lifecycle.cjs +2 -1
  292. package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
  293. package/dist/runtime/statewire-lifecycle.js +2 -1
  294. package/dist/runtime/statewire-lifecycle.js.map +1 -1
  295. package/dist/runtime/useAthenaStatewireRuntime.cjs +2 -1
  296. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  297. package/dist/runtime/useAthenaStatewireRuntime.js +2 -1
  298. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  299. package/dist/styles.css +1 -1
  300. package/dist/threads/conversation-list-fetcher.cjs +4 -0
  301. package/dist/threads/conversation-list-fetcher.cjs.map +1 -1
  302. package/dist/threads/conversation-list-fetcher.js +4 -0
  303. package/dist/threads/conversation-list-fetcher.js.map +1 -1
  304. package/dist/threads/statewire-thread-list.cjs +2 -1
  305. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  306. package/dist/threads/statewire-thread-list.js +2 -1
  307. package/dist/threads/statewire-thread-list.js.map +1 -1
  308. package/dist/threads/use-rest-conversation-history.cjs +2 -1
  309. package/dist/threads/use-rest-conversation-history.cjs.map +1 -1
  310. package/dist/threads/use-rest-conversation-history.js +2 -1
  311. package/dist/threads/use-rest-conversation-history.js.map +1 -1
  312. package/dist/threads/use-statewire-conversation-history.cjs +2 -1
  313. package/dist/threads/use-statewire-conversation-history.cjs.map +1 -1
  314. package/dist/threads/use-statewire-conversation-history.d.ts +1 -0
  315. package/dist/threads/use-statewire-conversation-history.js +2 -1
  316. package/dist/threads/use-statewire-conversation-history.js.map +1 -1
  317. package/dist/tools/index.cjs +2 -1
  318. package/dist/tools/index.cjs.map +1 -1
  319. package/dist/tools/index.js +2 -1
  320. package/dist/tools/index.js.map +1 -1
  321. package/dist/tools/misc-tool-uis.cjs +2 -1
  322. package/dist/tools/misc-tool-uis.cjs.map +1 -1
  323. package/dist/tools/misc-tool-uis.js +2 -1
  324. package/dist/tools/misc-tool-uis.js.map +1 -1
  325. package/dist/tools/primitives.cjs +2 -1
  326. package/dist/tools/primitives.cjs.map +1 -1
  327. package/dist/tools/primitives.js +2 -1
  328. package/dist/tools/primitives.js.map +1 -1
  329. package/dist/tools/tool-fallback.cjs +2 -1
  330. package/dist/tools/tool-fallback.cjs.map +1 -1
  331. package/dist/tools/tool-fallback.js +2 -1
  332. package/dist/tools/tool-fallback.js.map +1 -1
  333. package/dist/tools/voice-update-tool-ui.cjs +2 -1
  334. package/dist/tools/voice-update-tool-ui.cjs.map +1 -1
  335. package/dist/tools/voice-update-tool-ui.js +2 -1
  336. package/dist/tools/voice-update-tool-ui.js.map +1 -1
  337. package/dist/voice/index.cjs +6 -0
  338. package/dist/voice/index.cjs.map +1 -0
  339. package/dist/voice/index.d.ts +2 -0
  340. package/dist/voice/index.js +6 -0
  341. package/dist/voice/index.js.map +1 -0
  342. package/dist/voice/use-athena-voice-session.cjs +315 -0
  343. package/dist/voice/use-athena-voice-session.cjs.map +1 -0
  344. package/dist/voice/use-athena-voice-session.d.ts +145 -0
  345. package/dist/voice/use-athena-voice-session.js +315 -0
  346. package/dist/voice/use-athena-voice-session.js.map +1 -0
  347. package/package.json +17 -3
@@ -1 +1 @@
1
- {"version":3,"file":"AthenaProvider.js","sources":["../../src/provider/AthenaProvider.tsx"],"sourcesContent":["import { AuiProvider } from '@assistant-ui/react';\nimport {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { Toolkit } from '@assistant-ui/react';\nimport {\n createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n} from '@athenaintel/agent-runtime';\nimport {\n assertHostMintedStatewireMount,\n deriveAthenaAppUrl,\n getAthenaEnvironmentUrls,\n resolveStatewireSyncUrl,\n type AthenaEnvironment,\n} from '../lib/athena-urls';\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { useParentBridge } from '../runtime/auth';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n useAthenaStatewireRuntime,\n useStatewireClientTools,\n} from '../runtime/useAthenaStatewireRuntime';\nimport {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { resolveAgentProp } from '../runtime/statewire-run-config';\nimport { mintThreadId } from '../threads/mint-thread-id';\nimport { AthenaStatewireLifecycleContext } from './statewire-lifecycle-context';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\nimport {\n athenaDiagnostics,\n debugPropToDiagnosticsConfig,\n installAthenaDiagnosticsGlobal,\n type AthenaDiagnosticEvent,\n type AthenaDiagnosticLevel,\n type AthenaDiagnosticsConfig,\n} from '../diagnostics/athena-diagnostics';\nimport type { AthenaSdkError } from '../diagnostics/errors';\nimport { TooltipProvider } from '../ui/tooltip';\nimport { DEFAULT_AUTO_OPEN_TOOLS } from '../tools/auto-open-tools';\nimport { AthenaContext, type AthenaConfig } from './AthenaContext';\nimport type { AthenaProviderConfig } from './config';\nimport type {\n AthenaCitationLinkOptions,\n AthenaLinkClickOptions,\n} from './citation-links';\nimport {\n AthenaStatewireThreadIdContext,\n AthenaThreadIdContext,\n} from '../threads/thread-id-context';\nimport {\n AthenaStatewireThreadListProvider,\n StatewireThreadTitlePoller,\n useAthenaStatewireThreadList,\n} from '../threads/statewire-thread-list';\nimport { useAssetPanelStore } from '../assets/asset-panel-store';\nimport { themeToStyleVars, type AthenaTheme } from '../theme';\nimport { PostHogProvider, type PostHogConfig } from './PostHogProvider';\n\nexport interface AthenaProviderProps {\n children: ReactNode;\n\n /** Preferred structured config for auth and Athena endpoint settings. */\n config?: AthenaProviderConfig;\n\n /** @deprecated Prefer `config.apiKey`. API key for authentication in standalone mode. */\n apiKey?: string;\n\n /** @deprecated Prefer `config.token`. PropelAuth token. If provided, takes priority over apiKey. If omitted, the SDK\n * will automatically listen for a token from the parent window via PostMessage. */\n token?: string | null;\n\n /** Run the thread AS a published collab agent. The only accepted shape is\n * `collab_agent:<asset_id>`: the thread then uses that agent's prompt,\n * tools, and model default, and the caller must have view access to the\n * agent asset. Omit it (or pass a blank string) to run the Athena deep agent.\n *\n * Any other non-blank value throws at render — the statewire host cannot\n * honour named agents, and a selector that is silently dropped would let a\n * misconfigured deployment answer as the wrong agent. */\n agent?: string;\n\n /** Collab-agent channel id — a built-in channel (`email`, `sms`, …) or a\n * user-defined custom channel id from the agent's Channels tab. Selects\n * that channel's configuration overrides and stamps the session's origin.\n * Only meaningful together with a `collab_agent:<asset_id>` `agent`; sent\n * as `collab_channel_id`. An unknown or disabled channel rejects the run\n * with a structured, teaching error. */\n channel?: string;\n\n /** LLM model identifier. Defaults to the deep-agent default model\n * (`DEFAULT_STATEWIRE_MODEL`) — or, when a collab agent is selected, to\n * the model its author configured. */\n model?: string;\n\n /** Backend toolkit IDs to enable (e.g. 'document_toolkit', 'web_search_browse_toolkit'). */\n tools?: string[];\n\n /** Frontend tools that execute in the browser. The agent can invoke these.\n * Merged on top of the SDK's default auto-open tools; entries here take\n * precedence over defaults with the same name. Tools with a local\n * `execute` are declared to the backend as `client_tools` and run through\n * the statewire client-tool bridge. */\n frontendTools?: Toolkit;\n\n /** Disable the SDK's default auto-open behavior for created/touched assets. */\n disableAutoOpen?: boolean;\n\n /** @deprecated Prefer `config.apiUrl`. URL on the Iris host fronting the\n * deployment; its origin derives the statewire sync mount when\n * `statewireSyncUrl` is not set. */\n apiUrl?: string;\n\n /** @deprecated Prefer `config.backendUrl`. URL for the Athena backend API. */\n backendUrl?: string;\n\n /** @deprecated Prefer `config.appUrl`. URL for the Athena frontend app origin. */\n appUrl?: string;\n\n /** @deprecated Prefer `config.environment`. Athena environment preset used when URLs are not explicitly provided. */\n environment?: AthenaEnvironment;\n\n /** Resolve the latest auth token immediately before a request (for\n * expiring clients). Takes priority over `token` when it resolves.\n * Prefer `config.getToken` (see its `force` contract for refused\n * credentials). */\n getToken?: AthenaStatewireTokenGetter;\n\n /** Additional fields merged into runConfig.custom. Prefer\n * `config.extraRunConfig`. */\n extraRunConfig?: Record<string, unknown>;\n\n /** Statewire sync base URL override (the `…/v2/threads` mount). Defaults to\n * the mount a Marathon host mints, then the effective `apiUrl` host +\n * `/v2/threads`. Prefer `config.statewireSyncUrl`. */\n statewireSyncUrl?: string;\n\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n\n /** System prompt override. */\n systemPrompt?: string;\n\n /** Client app identifier for session filtering.\n * Sessions created with this ID can be filtered in the thread list.\n * E.g. \"olympus\", \"athena-app\", or a computer asset ID like \"asset_<uuid>\". */\n appId?: string;\n\n /** Thread ID override. Auto-generated if not provided. */\n threadId?: string;\n\n /** Enable thread list management (sidebar thread switching). */\n enableThreadList?: boolean;\n\n /** Theme configuration. Pass a preset from `themes` or a custom `AthenaTheme` object.\n * Injects CSS variables on a wrapper element — no CSS files needed.\n *\n * @example\n * import { themes } from '@athenaintel/react';\n * <AthenaProvider theme={themes.dark}>\n *\n * @example\n * <AthenaProvider theme={{ primary: '#8b5cf6', radius: '1rem' }}>\n *\n * @example\n * <AthenaProvider theme={{ ...themes.dark, primary: '#22c55e' }}>\n */\n theme?: AthenaTheme;\n\n /** Customize how rendered chat links behave. */\n linkClicks?: AthenaLinkClickOptions;\n\n /** @deprecated Prefer `linkClicks`. Customize how Athena citation links rendered in chat messages behave. */\n citationLinks?: AthenaCitationLinkOptions;\n\n /** PostHog analytics configuration. When omitted or keys are missing, PostHog is silently disabled.\n * Prefer `config.posthog` for structured configuration. */\n posthog?: PostHogConfig;\n\n /** SDK diagnostics.\n *\n * - `true` / a level: echo structured `[AthenaSDK]` events to the console\n * at that level (`true` = 'debug').\n * - An object: full diagnostics config (console level, PostHog timing\n * forwarding, buffer size).\n *\n * Independent of the prop, `localStorage.setItem('athena:debug','debug')`\n * (or `window.__ATHENA_SDK__.diagnostics.enableConsole()`) turns console\n * echo on at runtime without a rebuild. Errors log once even when off. */\n debug?: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig>;\n\n /** Receives every diagnostics event (timings, warnings, errors) — the hook\n * for shipping SDK telemetry to the host app's own pipeline. */\n onDiagnostic?: (event: AthenaDiagnosticEvent) => void;\n\n /** Receives every SDK error as a typed `AthenaSdkError` (stable `code`,\n * `hint`, structured server `detail`). Fires in addition to the UI's own\n * error handling, so integrations never fail silently. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n}\n\nconst resolveTokenOverride = ({\n config,\n token,\n}: {\n config?: AthenaProviderConfig;\n token?: string | null;\n}): string | null | undefined => {\n if (config?.token !== undefined) {\n return config.token;\n }\n return token;\n};\n\nconst useAthenaConfigValue = ({\n backendUrl,\n appUrl,\n apiKey,\n token,\n enabledToolkits,\n linkClicks,\n citationLinks,\n}: {\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n enabledToolkits: string[];\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}): AthenaConfig => {\n const linkClicksRef = useRef(linkClicks);\n linkClicksRef.current = linkClicks;\n const citationLinksRef = useRef(citationLinks);\n citationLinksRef.current = citationLinks;\n // Keep token in a ref so its value can update without invalidating the\n // config object identity. PropelAuth rotates tokens on window focus —\n // if token were a memo dep, every rotation would publish a new config\n // object to context and force every consumer (e.g. AssetIframe) to\n // re-render, causing asset panel flicker.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n\n return useMemo(\n () => ({\n backendUrl,\n appUrl,\n apiKey,\n enabledToolkits,\n get token() {\n return tokenRef.current;\n },\n get linkClicks() {\n return linkClicksRef.current;\n },\n get citationLinks() {\n return citationLinksRef.current;\n },\n }),\n [backendUrl, appUrl, apiKey, enabledToolkits],\n );\n};\n\n// ─── Standalone Mode ──────────────────────────────────────────────────\n\nfunction AthenaStatewireStandalone({\n children,\n syncUrl,\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n threadId: threadIdProp,\n isNewChatOverride,\n snapshotCache,\n toolOutputs,\n linkClicks,\n citationLinks,\n}: {\n children: ReactNode;\n syncUrl: string;\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n model?: string;\n agent?: string;\n channel?: string;\n tools: string[];\n frontendToolIds: string[];\n frontendTools: Toolkit;\n workbench?: string[];\n knowledgeBase?: string[];\n systemPrompt?: string;\n appId?: string;\n extraRunConfig?: Record<string, unknown>;\n threadId?: string;\n /** Overrides the \"new chat\" derivation (thread-list mode mints ids for\n * brand-new chats, which must still load as new). */\n isNewChatOverride?: boolean;\n /** The provider-owned snapshot cache (see `AthenaProvider`). */\n snapshotCache: DeepAgentThreadSnapshotCache;\n /** The provider-owned store of fetched-back cut tool outputs (see `AthenaProvider`). */\n toolOutputs: DeepAgentToolOutputStore;\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}) {\n // Statewire attaches to `${syncUrl}/${threadId}`, so a thread ID must exist\n // up front. An auto-generated ID is by definition a never-started local chat.\n const generatedIdRef = useRef<string | null>(null);\n if (generatedIdRef.current === null) {\n generatedIdRef.current = mintThreadId();\n }\n const threadId = threadIdProp ?? generatedIdRef.current;\n\n const [lifecycle, dispatchLifecycle] = useReducer(\n statewireLifecycleReducer,\n initialStatewireLifecycle,\n );\n\n const aui = useAthenaStatewireRuntime({\n syncUrl,\n threadId,\n isNewChat: isNewChatOverride ?? !threadIdProp,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n frontendToolkit: frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n toolOutputs,\n // The runtime already records every transport error on the diagnostics\n // bus (with the channel-teardown split), so this layer only maps it to\n // the banner notice.\n onError: (error) => {\n const notice = athenaStatewireErrorNotice(error);\n if (notice) dispatchLifecycle({ type: 'error', error: notice });\n },\n onConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'connection', connection });\n },\n onRawConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'raw-connection', reconnect: connection.reconnect });\n },\n });\n\n const clientTools = useStatewireClientTools(frontendTools);\n\n const dismissError = useCallback(\n () => dispatchLifecycle({ type: 'error', error: null }),\n [],\n );\n const lifecycleValue = useMemo<AthenaStatewireLifecycleState>(\n () => ({\n connection: lifecycle.connection,\n error: lifecycle.error,\n reconnect: lifecycle.reconnect,\n dismissError,\n }),\n [lifecycle, dismissError],\n );\n\n const athenaConfig = useAthenaConfigValue({\n backendUrl,\n appUrl,\n apiKey,\n token,\n enabledToolkits: tools,\n linkClicks,\n citationLinks,\n });\n\n return (\n <AuiProvider value={aui}>\n <AthenaContext.Provider value={athenaConfig}>\n <AthenaStatewireThreadIdContext.Provider value={threadId}>\n <AthenaStatewireLifecycleContext.Provider value={lifecycleValue}>\n <DeepAgentConnectionContext.Provider value={lifecycleValue.connection}>\n <StatewireToolOutputsContext.Provider value={toolOutputs}>\n <TooltipProvider>\n <StatewireClientToolBridge tools={clientTools} threadId={threadId} />\n {children}\n </TooltipProvider>\n </StatewireToolOutputsContext.Provider>\n </DeepAgentConnectionContext.Provider>\n </AthenaStatewireLifecycleContext.Provider>\n </AthenaStatewireThreadIdContext.Provider>\n </AthenaContext.Provider>\n </AuiProvider>\n );\n}\n\n// ─── Thread List Mode ─────────────────────────────────────────────────\n\nfunction AthenaStatewireWithThreadList({\n children,\n backendUrl,\n syncUrl,\n appId,\n apiKey,\n token,\n getToken,\n initialThreadId,\n ...standaloneProps\n}: Omit<\n Parameters<typeof AthenaStatewireStandalone>[0],\n 'threadId' | 'isNewChatOverride'\n> & {\n initialThreadId?: string;\n}) {\n return (\n <AthenaStatewireThreadListProvider\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n initialThreadId={initialThreadId}\n >\n <AthenaStatewireActiveThreadHost\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n appId={appId}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n {...standaloneProps}\n >\n {children}\n </AthenaStatewireActiveThreadHost>\n </AthenaStatewireThreadListProvider>\n );\n}\n\nfunction AthenaStatewireActiveThreadHost({\n children,\n ...standaloneProps\n}: Omit<\n Parameters<typeof AthenaStatewireStandalone>[0],\n 'threadId' | 'isNewChatOverride'\n>) {\n const list = useAthenaStatewireThreadList();\n if (!list) return null;\n\n // Keyed by thread id: a switch remounts the statewire session against the\n // new `…/v2/threads/{id}` URL instead of importing history in place. The\n // thread-id context is undefined for a never-started chat, so\n // history-gated UI (e.g. the loading overlay) does not treat an\n // intentionally-empty new chat as pending history.\n return (\n <AthenaThreadIdContext.Provider\n value={list.isNewChat ? undefined : list.activeThreadId}\n >\n <AthenaStatewireStandalone\n key={list.activeThreadId}\n threadId={list.activeThreadId}\n isNewChatOverride={list.isNewChat}\n {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <AssetPanelThreadSync />\n {children}\n </AthenaStatewireStandalone>\n </AthenaThreadIdContext.Provider>\n );\n}\n\n/**\n * Syncs the active thread ID into the asset panel store so that open asset\n * tabs are scoped per-thread automatically.\n *\n * Scoped by the thread list's minted id from creation onward — NOT by\n * `useAthenaThreadManager().activeThreadId`, which is deliberately `null`\n * while a new chat is unpersisted (so URL sync never names it). The minted id\n * is the id the thread persists under, so tabs opened in a brand-new chat\n * stay put when the backend first lists it instead of being left behind in a\n * `null` scope the store never restores.\n */\nfunction AssetPanelThreadSync() {\n const list = useAthenaStatewireThreadList();\n const setCurrentThread = useAssetPanelStore((s) => s.setCurrentThread);\n const activeThreadId = list?.activeThreadId ?? null;\n\n useEffect(() => {\n setCurrentThread(activeThreadId);\n }, [activeThreadId, setCurrentThread]);\n\n return null;\n}\n\n// ─── Main Provider ────────────────────────────────────────────────────\n\nexport function AthenaProvider({\n children,\n config,\n apiKey,\n token: tokenProp,\n agent,\n channel,\n model,\n tools = [],\n frontendTools = {},\n disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n threadId: threadIdProp,\n enableThreadList = false,\n theme,\n linkClicks,\n citationLinks,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\n}: AthenaProviderProps) {\n // Fail loud before any effect, bridge wait, or network call: an `agent`\n // outside the collab_agent namespace can never apply, so a misconfigured\n // deployment must die at first render rather than answer as the wrong agent.\n resolveAgentProp({ agent });\n\n // Diagnostics wiring first, so everything below is observable. Callbacks\n // ride refs: a per-render closure must not re-register the consumer. Each\n // provider registers its OWN consumer (additive, cleaned up on unmount), so\n // two mounted providers never clobber each other's onDiagnostic/onError —\n // only the console/PostHog/buffer settings are global (last writer wins).\n const onDiagnosticRef = useRef(onDiagnostic);\n onDiagnosticRef.current = onDiagnostic;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n useEffect(() => {\n installAthenaDiagnosticsGlobal();\n return athenaDiagnostics.addConsumer({\n onEvent: (event) => onDiagnosticRef.current?.(event),\n onError: (error, event) => onErrorRef.current?.(error, event),\n });\n }, []);\n const debugKey = JSON.stringify(debugPropToDiagnosticsConfig(debug));\n useEffect(() => {\n athenaDiagnostics.configure(debugPropToDiagnosticsConfig(debug));\n // debugKey is the value-stable form of `debug` (consumers pass literals).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [debugKey]);\n const frontendToolNames = useMemo(() => Object.keys(frontendTools), [frontendTools]);\n // Merge SDK auto-open defaults under the consumer's frontendTools. Consumer\n // entries win on name collision; auto-open tool names are NOT added to\n // frontendToolIds (they are already backend-advertised by their toolkits).\n const effectiveFrontendTools = useMemo<Toolkit>(\n () => (disableAutoOpen ? frontendTools : { ...DEFAULT_AUTO_OPEN_TOOLS, ...frontendTools }),\n [disableAutoOpen, frontendTools],\n );\n const themeStyleVars = useMemo(() => theme ? themeToStyleVars(theme) : undefined, [theme]);\n const configuredEnvironment = config?.environment ?? environment;\n const environmentUrls = useMemo(\n () => getAthenaEnvironmentUrls({ environment: configuredEnvironment }),\n [configuredEnvironment],\n );\n const configuredApiKey = config?.apiKey ?? apiKey;\n const configuredToken = resolveTokenOverride({ config, token: tokenProp });\n const configuredApiUrl = config?.apiUrl ?? apiUrl;\n const configuredBackendUrl = config?.backendUrl ?? backendUrl;\n const configuredAppUrl = config?.appUrl ?? appUrl;\n const configuredStatewireSyncUrl = config?.statewireSyncUrl ?? statewireSyncUrl;\n const configuredGetToken = config?.getToken ?? getToken;\n const configuredExtraRunConfig = config?.extraRunConfig ?? extraRunConfig;\n const configuredTrustedParentOrigins = config?.trustedParentOrigins;\n const posthogConfig: PostHogConfig | undefined = config?.posthog ?? posthogProp;\n\n // Statewire is the SDK's only chat transport; the gauge/event stay on the\n // diagnostics contract so dashboards keyed on them keep reading a value.\n useEffect(() => {\n athenaDiagnostics.gauge('sdk.transport', 'statewire');\n athenaDiagnostics.emit('sdk.transport', {\n level: 'debug',\n data: { transport: 'statewire', thread_list: enableThreadList },\n });\n }, [enableThreadList]);\n\n const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n });\n\n // If an AthenaAuthProvider is present above us, use its access token automatically.\n const authContext = useContext(AthenaAuthContext);\n const authProviderToken = authContext?.accessToken ?? null;\n\n // Per-provider snapshot cache: a switch back to a recently-visited thread\n // mounts with its last-known snapshot instead of a loading spinner. Owned\n // here, above the per-thread keyed mount, so it survives switches; cleared\n // when the acting identity changes so a snapshot captured under one account\n // never seeds a mount under another.\n const [snapshotCache] = useState(() => createDeepAgentThreadSnapshotCache());\n // The windowed wire's fetched-back tool outputs, owned alongside the cache\n // for the same reasons: shared across the provider's thread switches (a\n // tool message id is unique across threads), dropped with the identity.\n const [toolOutputs] = useState(() => createDeepAgentToolOutputStore());\n const principal = authContext?.user?.userId ?? '';\n useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n }, [snapshotCache, toolOutputs, principal, configuredApiKey]);\n\n const effectiveToken = configuredToken !== undefined\n ? configuredToken\n : authProviderToken ?? bridge.token;\n // Explicit config wins. A Marathon host mints the statewire mount, the bare\n // Agora base and the app origin outright (`/_athena/auth`, or a trusted\n // parent's `athena-config`); the environment preset is the last resort, and\n // the sync mount derives from the `apiUrl` host when no host minted one.\n const effectiveApiUrl = configuredApiUrl ?? environmentUrls.apiUrl;\n // Published as the bare Agora base: a historical `…/api/assistant-ui` value\n // is trimmed here once rather than by each REST helper.\n const effectiveBackendUrl = getAthenaApiBaseUrl(\n configuredBackendUrl ?? bridge.backendBaseUrl ?? environmentUrls.backendUrl,\n );\n const hostStatewireSyncUrl = configuredStatewireSyncUrl ?? bridge.statewireSyncUrl ?? undefined;\n const effectiveAppUrl = configuredAppUrl\n ?? bridge.appUrl\n ?? deriveAthenaAppUrl({ apiUrl: effectiveApiUrl, backendUrl: effectiveBackendUrl })\n ?? environmentUrls.appUrl;\n\n // Wait for the parent bridge to deliver config/auth before rendering.\n // This prevents the thread list from fetching with wrong URLs or no token.\n // Falls back after a short timeout (2s) if no bridge responds.\n if (!bridge.ready) {\n return null;\n }\n\n // Both throw on an unresolvable configuration instead of falling back to an\n // Athena default — a custom deployment's credentials must never be sent to\n // a host the consumer didn't configure. A host that answered the bridge\n // without minting the statewire mount is that case: its token would\n // otherwise ride the environment preset.\n assertHostMintedStatewireMount({\n hostAnswered: bridge.hostAnswered,\n hostStatewireSyncUrl: bridge.statewireSyncUrl,\n statewireSyncUrl: configuredStatewireSyncUrl,\n apiUrl: configuredApiUrl,\n });\n const effectiveStatewireSyncUrl = resolveStatewireSyncUrl({\n statewireSyncUrl: hostStatewireSyncUrl,\n apiUrl: effectiveApiUrl,\n });\n\n const statewireProps = {\n syncUrl: effectiveStatewireSyncUrl,\n backendUrl: effectiveBackendUrl,\n appUrl: effectiveAppUrl,\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: configuredGetToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds: frontendToolNames,\n frontendTools: effectiveFrontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n linkClicks,\n citationLinks,\n };\n\n const inner: ReactNode = enableThreadList ? (\n <AthenaStatewireWithThreadList {...statewireProps} initialThreadId={threadIdProp}>\n {children}\n </AthenaStatewireWithThreadList>\n ) : (\n <AthenaStatewireStandalone {...statewireProps} threadId={threadIdProp}>\n {children}\n </AthenaStatewireStandalone>\n );\n\n // The .athena-sdk wrapper (display: contents) anchors the SDK's design\n // tokens and scoped preflight from styles.css, so the stylesheet works\n // in hosts without their own Tailwind build. PostHog gracefully no-ops\n // when its config is missing.\n return (\n <div\n className={themeStyleVars ? \"athena-sdk athena-themed\" : \"athena-sdk\"}\n style={themeStyleVars as React.CSSProperties | undefined}\n >\n <PostHogProvider config={posthogConfig}>\n {inner}\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4NA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AACF,MAGiC;AAC/B,OAAI,iCAAQ,WAAU,QAAW;AAC/B,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AACT;AAEA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAQoB;AAClB,QAAM,gBAAgB,OAAO,UAAU;AACvC,gBAAc,UAAU;AACxB,QAAM,mBAAmB,OAAO,aAAa;AAC7C,mBAAiB,UAAU;AAM3B,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAEnB,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,IAAI,QAAQ;AACV,eAAO,SAAS;AAAA,MAClB;AAAA,MACA,IAAI,aAAa;AACf,eAAO,cAAc;AAAA,MACvB;AAAA,MACA,IAAI,gBAAgB;AAClB,eAAO,iBAAiB;AAAA,MAC1B;AAAA,IAAA;AAAA,IAEF,CAAC,YAA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,wBAAwB;AAAA,IACxD,kBAAkB;AAAA,IAClB,QAAQ;AAAA,EAAA,CACT;AAED,QAAM,iBAAiB;AAAA,IACrB,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,QAAM,QAAmB,mBACvB,oBAAC,+BAAA,EAA+B,GAAG,gBAAgB,iBAAiB,cACjE,SAAA,CACH,wBAEC,2BAAA,EAA2B,GAAG,gBAAgB,UAAU,cACtD,UACH;AAOF,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAW,iBAAiB,6BAA6B;AAAA,MACzD,OAAO;AAAA,MAEP,UAAA,oBAAC,iBAAA,EAAgB,QAAQ,eACtB,UAAA,MAAA,CACH;AAAA,IAAA;AAAA,EAAA;AAGN;"}
1
+ {"version":3,"file":"AthenaProvider.js","sources":["../../src/provider/AthenaProvider.tsx"],"sourcesContent":["import { AuiProvider } from '@assistant-ui/react';\nimport {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { Toolkit } from '@assistant-ui/react';\nimport {\n createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n} from '@athenaintel/agent-runtime';\nimport {\n assertHostMintedStatewireMount,\n deriveAthenaAppUrl,\n getAthenaEnvironmentUrls,\n resolveStatewireSyncUrl,\n type AthenaEnvironment,\n} from '../lib/athena-urls';\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { useParentBridge } from '../runtime/auth';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n useAthenaStatewireRuntime,\n useStatewireClientTools,\n} from '../runtime/useAthenaStatewireRuntime';\nimport {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { resolveAgentProp } from '../runtime/statewire-run-config';\nimport { mintThreadId } from '../threads/mint-thread-id';\nimport { AthenaStatewireLifecycleContext } from './statewire-lifecycle-context';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\nimport {\n athenaDiagnostics,\n debugPropToDiagnosticsConfig,\n installAthenaDiagnosticsGlobal,\n type AthenaDiagnosticEvent,\n type AthenaDiagnosticLevel,\n type AthenaDiagnosticsConfig,\n} from '../diagnostics/athena-diagnostics';\nimport type { AthenaSdkError } from '../diagnostics/errors';\nimport { TooltipProvider } from '../ui/tooltip';\nimport { DEFAULT_AUTO_OPEN_TOOLS } from '../tools/auto-open-tools';\nimport { AthenaContext, type AthenaConfig } from './AthenaContext';\nimport type { AthenaProviderConfig } from './config';\nimport type {\n AthenaCitationLinkOptions,\n AthenaLinkClickOptions,\n} from './citation-links';\nimport {\n AthenaStatewireThreadIdContext,\n AthenaThreadIdContext,\n} from '../threads/thread-id-context';\nimport {\n AthenaStatewireThreadListProvider,\n StatewireThreadTitlePoller,\n useAthenaStatewireThreadList,\n} from '../threads/statewire-thread-list';\nimport { useAssetPanelStore } from '../assets/asset-panel-store';\nimport { themeToStyleVars, type AthenaTheme } from '../theme';\nimport { PostHogProvider, type PostHogConfig } from './PostHogProvider';\n\nexport interface AthenaProviderProps {\n children: ReactNode;\n\n /** Preferred structured config for auth and Athena endpoint settings. */\n config?: AthenaProviderConfig;\n\n /** @deprecated Prefer `config.apiKey`. API key for authentication in standalone mode. */\n apiKey?: string;\n\n /** @deprecated Prefer `config.token`. PropelAuth token. If provided, takes priority over apiKey. If omitted, the SDK\n * will automatically listen for a token from the parent window via PostMessage. */\n token?: string | null;\n\n /** Run the thread AS a published collab agent. The only accepted shape is\n * `collab_agent:<asset_id>`: the thread then uses that agent's prompt,\n * tools, and model default, and the caller must have view access to the\n * agent asset. Omit it (or pass a blank string) to run the Athena deep agent.\n *\n * Any other non-blank value throws at render — the statewire host cannot\n * honour named agents, and a selector that is silently dropped would let a\n * misconfigured deployment answer as the wrong agent. */\n agent?: string;\n\n /** Collab-agent channel id — a built-in channel (`email`, `sms`, …) or a\n * user-defined custom channel id from the agent's Channels tab. Selects\n * that channel's configuration overrides and stamps the session's origin.\n * Only meaningful together with a `collab_agent:<asset_id>` `agent`; sent\n * as `collab_channel_id`. An unknown or disabled channel rejects the run\n * with a structured, teaching error. */\n channel?: string;\n\n /** LLM model identifier. Defaults to the deep-agent default model\n * (`DEFAULT_STATEWIRE_MODEL`) — or, when a collab agent is selected, to\n * the model its author configured. */\n model?: string;\n\n /** Backend toolkit IDs to enable (e.g. 'document_toolkit', 'web_search_browse_toolkit'). */\n tools?: string[];\n\n /** Frontend tools that execute in the browser. The agent can invoke these.\n * Merged on top of the SDK's default auto-open tools; entries here take\n * precedence over defaults with the same name. Tools with a local\n * `execute` are declared to the backend as `client_tools` and run through\n * the statewire client-tool bridge. */\n frontendTools?: Toolkit;\n\n /** Disable the SDK's default auto-open behavior for created/touched assets. */\n disableAutoOpen?: boolean;\n\n /** @deprecated Prefer `config.apiUrl`. URL on the Iris host fronting the\n * deployment; its origin derives the statewire sync mount when\n * `statewireSyncUrl` is not set. */\n apiUrl?: string;\n\n /** @deprecated Prefer `config.backendUrl`. URL for the Athena backend API. */\n backendUrl?: string;\n\n /** @deprecated Prefer `config.appUrl`. URL for the Athena frontend app origin. */\n appUrl?: string;\n\n /** @deprecated Prefer `config.environment`. Athena environment preset used when URLs are not explicitly provided. */\n environment?: AthenaEnvironment;\n\n /** Resolve the latest auth token immediately before a request (for\n * expiring clients). Takes priority over `token` when it resolves.\n * Prefer `config.getToken` (see its `force` contract for refused\n * credentials). */\n getToken?: AthenaStatewireTokenGetter;\n\n /** Additional fields merged into runConfig.custom. Prefer\n * `config.extraRunConfig`. */\n extraRunConfig?: Record<string, unknown>;\n\n /** Statewire sync base URL override (the `…/v2/threads` mount). Defaults to\n * the mount a Marathon host mints, then the effective `apiUrl` host +\n * `/v2/threads`. Prefer `config.statewireSyncUrl`. */\n statewireSyncUrl?: string;\n\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n\n /** System prompt override. */\n systemPrompt?: string;\n\n /** Client app identifier for session filtering.\n * Sessions created with this ID can be filtered in the thread list.\n * E.g. \"olympus\", \"athena-app\", or a computer asset ID like \"asset_<uuid>\". */\n appId?: string;\n\n /** Thread ID override. Auto-generated if not provided. */\n threadId?: string;\n\n /** Enable thread list management (sidebar thread switching). */\n enableThreadList?: boolean;\n\n /** Theme configuration. Pass a preset from `themes` or a custom `AthenaTheme` object.\n * Injects CSS variables on a wrapper element — no CSS files needed.\n *\n * @example\n * import { themes } from '@athenaintel/react';\n * <AthenaProvider theme={themes.dark}>\n *\n * @example\n * <AthenaProvider theme={{ primary: '#8b5cf6', radius: '1rem' }}>\n *\n * @example\n * <AthenaProvider theme={{ ...themes.dark, primary: '#22c55e' }}>\n */\n theme?: AthenaTheme;\n\n /** Customize how rendered chat links behave. */\n linkClicks?: AthenaLinkClickOptions;\n\n /** @deprecated Prefer `linkClicks`. Customize how Athena citation links rendered in chat messages behave. */\n citationLinks?: AthenaCitationLinkOptions;\n\n /** PostHog analytics configuration. When omitted or keys are missing, PostHog is silently disabled.\n * Prefer `config.posthog` for structured configuration. */\n posthog?: PostHogConfig;\n\n /** SDK diagnostics.\n *\n * - `true` / a level: echo structured `[AthenaSDK]` events to the console\n * at that level (`true` = 'debug').\n * - An object: full diagnostics config (console level, PostHog timing\n * forwarding, buffer size).\n *\n * Independent of the prop, `localStorage.setItem('athena:debug','debug')`\n * (or `window.__ATHENA_SDK__.diagnostics.enableConsole()`) turns console\n * echo on at runtime without a rebuild. Errors log once even when off. */\n debug?: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig>;\n\n /** Receives every diagnostics event (timings, warnings, errors) — the hook\n * for shipping SDK telemetry to the host app's own pipeline. */\n onDiagnostic?: (event: AthenaDiagnosticEvent) => void;\n\n /** Receives every SDK error as a typed `AthenaSdkError` (stable `code`,\n * `hint`, structured server `detail`). Fires in addition to the UI's own\n * error handling, so integrations never fail silently. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n}\n\nconst resolveTokenOverride = ({\n config,\n token,\n}: {\n config?: AthenaProviderConfig;\n token?: string | null;\n}): string | null | undefined => {\n if (config?.token !== undefined) {\n return config.token;\n }\n return token;\n};\n\nconst useAthenaConfigValue = ({\n backendUrl,\n appUrl,\n apiKey,\n token,\n enabledToolkits,\n linkClicks,\n citationLinks,\n}: {\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n enabledToolkits: string[];\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}): AthenaConfig => {\n const linkClicksRef = useRef(linkClicks);\n linkClicksRef.current = linkClicks;\n const citationLinksRef = useRef(citationLinks);\n citationLinksRef.current = citationLinks;\n // Keep token in a ref so its value can update without invalidating the\n // config object identity. PropelAuth rotates tokens on window focus —\n // if token were a memo dep, every rotation would publish a new config\n // object to context and force every consumer (e.g. AssetIframe) to\n // re-render, causing asset panel flicker.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n\n return useMemo(\n () => ({\n backendUrl,\n appUrl,\n apiKey,\n enabledToolkits,\n get token() {\n return tokenRef.current;\n },\n get linkClicks() {\n return linkClicksRef.current;\n },\n get citationLinks() {\n return citationLinksRef.current;\n },\n }),\n [backendUrl, appUrl, apiKey, enabledToolkits],\n );\n};\n\n// ─── Standalone Mode ──────────────────────────────────────────────────\n\nfunction AthenaStatewireStandalone({\n children,\n syncUrl,\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n threadId: threadIdProp,\n isNewChatOverride,\n snapshotCache,\n toolOutputs,\n linkClicks,\n citationLinks,\n}: {\n children: ReactNode;\n syncUrl: string;\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n model?: string;\n agent?: string;\n channel?: string;\n tools: string[];\n frontendToolIds: string[];\n frontendTools: Toolkit;\n workbench?: string[];\n knowledgeBase?: string[];\n systemPrompt?: string;\n appId?: string;\n extraRunConfig?: Record<string, unknown>;\n threadId?: string;\n /** Overrides the \"new chat\" derivation (thread-list mode mints ids for\n * brand-new chats, which must still load as new). */\n isNewChatOverride?: boolean;\n /** The provider-owned snapshot cache (see `AthenaProvider`). */\n snapshotCache: DeepAgentThreadSnapshotCache;\n /** The provider-owned store of fetched-back cut tool outputs (see `AthenaProvider`). */\n toolOutputs: DeepAgentToolOutputStore;\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}) {\n // Statewire attaches to `${syncUrl}/${threadId}`, so a thread ID must exist\n // up front. An auto-generated ID is by definition a never-started local chat.\n const generatedIdRef = useRef<string | null>(null);\n if (generatedIdRef.current === null) {\n generatedIdRef.current = mintThreadId();\n }\n const threadId = threadIdProp ?? generatedIdRef.current;\n\n const [lifecycle, dispatchLifecycle] = useReducer(\n statewireLifecycleReducer,\n initialStatewireLifecycle,\n );\n\n const aui = useAthenaStatewireRuntime({\n syncUrl,\n threadId,\n isNewChat: isNewChatOverride ?? !threadIdProp,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n frontendToolkit: frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n toolOutputs,\n // The runtime already records every transport error on the diagnostics\n // bus (with the channel-teardown split), so this layer only maps it to\n // the banner notice.\n onError: (error) => {\n const notice = athenaStatewireErrorNotice(error);\n if (notice) dispatchLifecycle({ type: 'error', error: notice });\n },\n onConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'connection', connection });\n },\n onRawConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'raw-connection', reconnect: connection.reconnect });\n },\n });\n\n const clientTools = useStatewireClientTools(frontendTools);\n\n const dismissError = useCallback(\n () => dispatchLifecycle({ type: 'error', error: null }),\n [],\n );\n const lifecycleValue = useMemo<AthenaStatewireLifecycleState>(\n () => ({\n connection: lifecycle.connection,\n error: lifecycle.error,\n reconnect: lifecycle.reconnect,\n dismissError,\n }),\n [lifecycle, dismissError],\n );\n\n const athenaConfig = useAthenaConfigValue({\n backendUrl,\n appUrl,\n apiKey,\n token,\n enabledToolkits: tools,\n linkClicks,\n citationLinks,\n });\n\n return (\n <AuiProvider value={aui}>\n <AthenaContext.Provider value={athenaConfig}>\n <AthenaStatewireThreadIdContext.Provider value={threadId}>\n <AthenaStatewireLifecycleContext.Provider value={lifecycleValue}>\n <DeepAgentConnectionContext.Provider value={lifecycleValue.connection}>\n <StatewireToolOutputsContext.Provider value={toolOutputs}>\n <TooltipProvider>\n <StatewireClientToolBridge tools={clientTools} threadId={threadId} />\n {children}\n </TooltipProvider>\n </StatewireToolOutputsContext.Provider>\n </DeepAgentConnectionContext.Provider>\n </AthenaStatewireLifecycleContext.Provider>\n </AthenaStatewireThreadIdContext.Provider>\n </AthenaContext.Provider>\n </AuiProvider>\n );\n}\n\n// ─── Thread List Mode ─────────────────────────────────────────────────\n\nfunction AthenaStatewireWithThreadList({\n children,\n backendUrl,\n syncUrl,\n appId,\n apiKey,\n token,\n getToken,\n initialThreadId,\n ...standaloneProps\n}: Omit<\n Parameters<typeof AthenaStatewireStandalone>[0],\n 'threadId' | 'isNewChatOverride'\n> & {\n initialThreadId?: string;\n}) {\n return (\n <AthenaStatewireThreadListProvider\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n initialThreadId={initialThreadId}\n >\n <AthenaStatewireActiveThreadHost\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n appId={appId}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n {...standaloneProps}\n >\n {children}\n </AthenaStatewireActiveThreadHost>\n </AthenaStatewireThreadListProvider>\n );\n}\n\nfunction AthenaStatewireActiveThreadHost({\n children,\n ...standaloneProps\n}: Omit<\n Parameters<typeof AthenaStatewireStandalone>[0],\n 'threadId' | 'isNewChatOverride'\n>) {\n const list = useAthenaStatewireThreadList();\n if (!list) return null;\n\n // Keyed by thread id: a switch remounts the statewire session against the\n // new `…/v2/threads/{id}` URL instead of importing history in place. The\n // thread-id context is undefined for a never-started chat, so\n // history-gated UI (e.g. the loading overlay) does not treat an\n // intentionally-empty new chat as pending history.\n return (\n <AthenaThreadIdContext.Provider\n value={list.isNewChat ? undefined : list.activeThreadId}\n >\n <AthenaStatewireStandalone\n key={list.activeThreadId}\n threadId={list.activeThreadId}\n isNewChatOverride={list.isNewChat}\n {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <AssetPanelThreadSync />\n {children}\n </AthenaStatewireStandalone>\n </AthenaThreadIdContext.Provider>\n );\n}\n\n/**\n * Syncs the active thread ID into the asset panel store so that open asset\n * tabs are scoped per-thread automatically.\n *\n * Scoped by the thread list's minted id from creation onward — NOT by\n * `useAthenaThreadManager().activeThreadId`, which is deliberately `null`\n * while a new chat is unpersisted (so URL sync never names it). The minted id\n * is the id the thread persists under, so tabs opened in a brand-new chat\n * stay put when the backend first lists it instead of being left behind in a\n * `null` scope the store never restores.\n */\nfunction AssetPanelThreadSync() {\n const list = useAthenaStatewireThreadList();\n const setCurrentThread = useAssetPanelStore((s) => s.setCurrentThread);\n const activeThreadId = list?.activeThreadId ?? null;\n\n useEffect(() => {\n setCurrentThread(activeThreadId);\n }, [activeThreadId, setCurrentThread]);\n\n return null;\n}\n\n// ─── Main Provider ────────────────────────────────────────────────────\n\nexport function AthenaProvider({\n children,\n config,\n apiKey,\n token: tokenProp,\n agent,\n channel,\n model,\n tools = [],\n frontendTools = {},\n disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n threadId: threadIdProp,\n enableThreadList = false,\n theme,\n linkClicks,\n citationLinks,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\n}: AthenaProviderProps) {\n // Fail loud before any effect, bridge wait, or network call: an `agent`\n // outside the collab_agent namespace can never apply, so a misconfigured\n // deployment must die at first render rather than answer as the wrong agent.\n resolveAgentProp({ agent });\n\n // Diagnostics wiring first, so everything below is observable. Callbacks\n // ride refs: a per-render closure must not re-register the consumer. Each\n // provider registers its OWN consumer (additive, cleaned up on unmount), so\n // two mounted providers never clobber each other's onDiagnostic/onError —\n // only the console/PostHog/buffer settings are global (last writer wins).\n const onDiagnosticRef = useRef(onDiagnostic);\n onDiagnosticRef.current = onDiagnostic;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n useEffect(() => {\n installAthenaDiagnosticsGlobal();\n return athenaDiagnostics.addConsumer({\n onEvent: (event) => onDiagnosticRef.current?.(event),\n onError: (error, event) => onErrorRef.current?.(error, event),\n });\n }, []);\n const debugKey = JSON.stringify(debugPropToDiagnosticsConfig(debug));\n useEffect(() => {\n athenaDiagnostics.configure(debugPropToDiagnosticsConfig(debug));\n // debugKey is the value-stable form of `debug` (consumers pass literals).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [debugKey]);\n const frontendToolNames = useMemo(() => Object.keys(frontendTools), [frontendTools]);\n // Merge SDK auto-open defaults under the consumer's frontendTools. Consumer\n // entries win on name collision; auto-open tool names are NOT added to\n // frontendToolIds (they are already backend-advertised by their toolkits).\n const effectiveFrontendTools = useMemo<Toolkit>(\n () => (disableAutoOpen ? frontendTools : { ...DEFAULT_AUTO_OPEN_TOOLS, ...frontendTools }),\n [disableAutoOpen, frontendTools],\n );\n const themeStyleVars = useMemo(() => theme ? themeToStyleVars(theme) : undefined, [theme]);\n const configuredEnvironment = config?.environment ?? environment;\n const environmentUrls = useMemo(\n () => getAthenaEnvironmentUrls({ environment: configuredEnvironment }),\n [configuredEnvironment],\n );\n const configuredApiKey = config?.apiKey ?? apiKey;\n const configuredToken = resolveTokenOverride({ config, token: tokenProp });\n const configuredApiUrl = config?.apiUrl ?? apiUrl;\n const configuredBackendUrl = config?.backendUrl ?? backendUrl;\n const configuredAppUrl = config?.appUrl ?? appUrl;\n const configuredStatewireSyncUrl = config?.statewireSyncUrl ?? statewireSyncUrl;\n const configuredGetToken = config?.getToken ?? getToken;\n const configuredExtraRunConfig = config?.extraRunConfig ?? extraRunConfig;\n const configuredTrustedParentOrigins = config?.trustedParentOrigins;\n const posthogConfig: PostHogConfig | undefined = config?.posthog ?? posthogProp;\n\n // Statewire is the SDK's only chat transport; the gauge/event stay on the\n // diagnostics contract so dashboards keyed on them keep reading a value.\n useEffect(() => {\n athenaDiagnostics.gauge('sdk.transport', 'statewire');\n athenaDiagnostics.emit('sdk.transport', {\n level: 'debug',\n data: { transport: 'statewire', thread_list: enableThreadList },\n });\n }, [enableThreadList]);\n\n const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n });\n\n // If an AthenaAuthProvider is present above us, use its access token automatically.\n const authContext = useContext(AthenaAuthContext);\n const authProviderToken = authContext?.accessToken ?? null;\n\n // Per-provider snapshot cache: a switch back to a recently-visited thread\n // mounts with its last-known snapshot instead of a loading spinner. Owned\n // here, above the per-thread keyed mount, so it survives switches; cleared\n // when the acting identity changes so a snapshot captured under one account\n // never seeds a mount under another.\n const [snapshotCache] = useState(() => createDeepAgentThreadSnapshotCache());\n // The windowed wire's fetched-back tool outputs, owned alongside the cache\n // for the same reasons: shared across the provider's thread switches (a\n // tool message id is unique across threads), dropped with the identity.\n const [toolOutputs] = useState(() => createDeepAgentToolOutputStore());\n const principal = authContext?.user?.userId ?? '';\n useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n }, [snapshotCache, toolOutputs, principal, configuredApiKey]);\n\n const effectiveToken = configuredToken !== undefined\n ? configuredToken\n : authProviderToken ?? bridge.token;\n // Explicit config wins. A Marathon host mints the statewire mount, the bare\n // Agora base and the app origin outright (`/_athena/auth`, or a trusted\n // parent's `athena-config`); the environment preset is the last resort, and\n // the sync mount derives from the `apiUrl` host when no host minted one.\n const effectiveApiUrl = configuredApiUrl ?? environmentUrls.apiUrl;\n // Published as the bare Agora base: a historical `…/api/assistant-ui` value\n // is trimmed here once rather than by each REST helper.\n const effectiveBackendUrl = getAthenaApiBaseUrl(\n configuredBackendUrl ?? bridge.backendBaseUrl ?? environmentUrls.backendUrl,\n );\n const hostStatewireSyncUrl = configuredStatewireSyncUrl ?? bridge.statewireSyncUrl ?? undefined;\n const effectiveAppUrl = configuredAppUrl\n ?? bridge.appUrl\n ?? deriveAthenaAppUrl({ apiUrl: effectiveApiUrl, backendUrl: effectiveBackendUrl })\n ?? environmentUrls.appUrl;\n\n // Wait for the parent bridge to deliver config/auth before rendering.\n // This prevents the thread list from fetching with wrong URLs or no token.\n // Falls back after a short timeout (2s) if no bridge responds.\n if (!bridge.ready) {\n return null;\n }\n\n // Both throw on an unresolvable configuration instead of falling back to an\n // Athena default — a custom deployment's credentials must never be sent to\n // a host the consumer didn't configure. A host that answered the bridge\n // without minting the statewire mount is that case: its token would\n // otherwise ride the environment preset.\n assertHostMintedStatewireMount({\n hostAnswered: bridge.hostAnswered,\n hostStatewireSyncUrl: bridge.statewireSyncUrl,\n statewireSyncUrl: configuredStatewireSyncUrl,\n apiUrl: configuredApiUrl,\n });\n const effectiveStatewireSyncUrl = resolveStatewireSyncUrl({\n statewireSyncUrl: hostStatewireSyncUrl,\n apiUrl: effectiveApiUrl,\n });\n\n const statewireProps = {\n syncUrl: effectiveStatewireSyncUrl,\n backendUrl: effectiveBackendUrl,\n appUrl: effectiveAppUrl,\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: configuredGetToken,\n model,\n agent,\n channel,\n tools,\n frontendToolIds: frontendToolNames,\n frontendTools: effectiveFrontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n linkClicks,\n citationLinks,\n };\n\n const inner: ReactNode = enableThreadList ? (\n <AthenaStatewireWithThreadList {...statewireProps} initialThreadId={threadIdProp}>\n {children}\n </AthenaStatewireWithThreadList>\n ) : (\n <AthenaStatewireStandalone {...statewireProps} threadId={threadIdProp}>\n {children}\n </AthenaStatewireStandalone>\n );\n\n // The .athena-sdk wrapper (display: contents) anchors the SDK's design\n // tokens and scoped preflight from styles.css, so the stylesheet works\n // in hosts without their own Tailwind build. PostHog gracefully no-ops\n // when its config is missing.\n return (\n <div\n className={themeStyleVars ? \"athena-sdk athena-themed\" : \"athena-sdk\"}\n style={themeStyleVars as React.CSSProperties | undefined}\n >\n <PostHogProvider config={posthogConfig}>\n {inner}\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4NA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AACF,MAGiC;AAC/B,OAAI,iCAAQ,WAAU,QAAW;AAC/B,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AACT;AAEA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAQoB;AAClB,QAAM,gBAAgB,OAAO,UAAU;AACvC,gBAAc,UAAU;AACxB,QAAM,mBAAmB,OAAO,aAAa;AAC7C,mBAAiB,UAAU;AAM3B,QAAM,W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AO,oBAAoB;AACtF,QAAM,kBAAkB,oBACnB,OAAO,UACP,mBAAmB,EAAE,QAAQ,iBAAiB,YAAY,qBAAqB,KAC/E,gBAAgB;AAKrB,MAAI,CAAC,OAAO,OAAO;AACjB,WAAO;AAAA,EACT;AAOA,iCAA+B;AAAA,IAC7B,cAAc,OAAO;AAAA,IACrB,sBAAsB,OAAO;AAAA,IAC7B,kBAAkB;AAAA,IAClB,QAAQ;AAAA,EAAA,CACT;AACD,QAAM,4BAA4B,wBAAwB;AAAA,IACxD,kBAAkB;AAAA,IAClB,QAAQ;AAAA,EAAA,CACT;AAED,QAAM,iBAAiB;AAAA,IACrB,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,QAAM,QAAmB,mBACvB,oBAAC,+BAAA,EAA+B,GAAG,gBAAgB,iBAAiB,cACjE,SAAA,CACH,wBAEC,2BAAA,EAA2B,GAAG,gBAAgB,UAAU,cACtD,UACH;AAOF,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAW,iBAAiB,6BAA6B;AAAA,MACzD,OAAO;AAAA,MAEP,UAAA,oBAAC,iBAAA,EAAgB,QAAQ,eACtB,UAAA,MAAA,CACH;AAAA,IAAA;AAAA,EAAA;AAGN;"}
@@ -11,10 +11,11 @@ require("../packages/agent-runtime/src/statewire-state.cjs");
11
11
  require("../packages/agent-runtime/src/messages.cjs");
12
12
  require("@assistant-ui/react-statewire");
13
13
  require("@assistant-ui/store");
14
- require("@assistant-ui/react-statewire/local-storage");
14
+ require("../packages/agent-runtime/src/quota-safe-local-storage-session.cjs");
15
15
  require("../packages/agent-runtime/src/statewire-attach-observer.cjs");
16
16
  require("../packages/agent-runtime/src/thread-status.cjs");
17
17
  require("@assistant-ui/core");
18
+ require("../packages/agent-runtime/src/thread-handoff.cjs");
18
19
  function athenaStatewireErrorNotice(error) {
19
20
  if (errors.isStatewireChannelTeardown(error)) return null;
20
21
  const rejection = errors.statewireRejectionPayload(error);
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-lifecycle.cjs","sources":["../../src/runtime/statewire-lifecycle.ts"],"sourcesContent":["import {\n isLegacyThreadReadOnlyRejection,\n isStatewireChannelTeardown,\n statewireRejectionDetailMessage,\n statewireRejectionPayload,\n} from '@athenaintel/agent-runtime';\nimport type { DeepAgentConnectionState } from '@athenaintel/agent-runtime';\n\n/** A user-visible notice mapped from a statewire transport error. */\nexport interface AthenaStatewireErrorNotice {\n kind: 'paywall' | 'read-only' | 'command';\n title: string;\n message: string;\n}\n\n/**\n * Map the statewire failure envelope to a concise, actionable notice.\n * Returns null for expected channel teardowns (thread switch, unmount),\n * which must not surface as errors.\n */\nexport function athenaStatewireErrorNotice(\n error: unknown,\n): AthenaStatewireErrorNotice | null {\n if (isStatewireChannelTeardown(error)) return null;\n const rejection = statewireRejectionPayload(error);\n // The server's own detail names the actionable reason; the Error message is\n // generic client-side text like `command rejected (500)`.\n const detail = statewireRejectionDetailMessage(error);\n\n if (rejection?.status === 402) {\n return {\n kind: 'paywall',\n title: 'Usage limit reached',\n message:\n detail ?? 'Athena could not start this run. Review usage or billing to continue.',\n };\n }\n\n // Legacy-thread dispatch fence: an out-of-band run is writing this\n // pre-cutover thread (or its adoption failed). A per-send failure, not a\n // standing state — the server's detail names the actionable reason (wait\n // for the run vs. start a new chat).\n if (isLegacyThreadReadOnlyRejection(error)) {\n return {\n kind: 'read-only',\n title: 'Message was not sent',\n message:\n detail ??\n 'This conversation cannot take new messages right now. Try again shortly, or start a new chat.',\n };\n }\n\n return {\n kind: 'command',\n title: 'Message was not sent',\n message:\n detail ??\n (error instanceof Error && error.message.length > 0\n ? error.message\n : 'The chat runtime rejected the command. Please try again.'),\n };\n}\n\n/** Shared lifecycle state for the statewire transport, provided by\n * `AthenaProvider` in statewire mode and read by the chat banners. */\nexport interface AthenaStatewireLifecycleState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n dismissError: () => void;\n}\n\n/** The provider's reducer state behind {@link AthenaStatewireLifecycleState}. */\nexport interface StatewireLifecycleReducerState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n}\n\nexport type StatewireLifecycleAction =\n | { type: 'connection'; connection: DeepAgentConnectionState | null }\n | { type: 'error'; error: AthenaStatewireErrorNotice | null }\n | { type: 'raw-connection'; reconnect: () => void };\n\nexport const initialStatewireLifecycle: StatewireLifecycleReducerState = {\n connection: null,\n error: null,\n reconnect: null,\n};\n\n/**\n * Folds the runtime's lifecycle observations into the banner state. A healthy\n * channel — connected, or disconnected only because the instance is quiet\n * (`idle`) or the chat has not sent yet (`deferred`) — clears a stale\n * send/transport error: leaving it up tells the user the chat is broken after\n * it has come back.\n */\nexport function statewireLifecycleReducer(\n state: StatewireLifecycleReducerState,\n action: StatewireLifecycleAction,\n): StatewireLifecycleReducerState {\n switch (action.type) {\n case 'connection': {\n const healthy =\n action.connection?.status === 'connected' ||\n action.connection?.status === 'standby';\n return {\n ...state,\n connection: action.connection,\n error: healthy ? null : state.error,\n };\n }\n case 'error':\n return { ...state, error: action.error };\n case 'raw-connection':\n return { ...state, reconnect: action.reconnect };\n }\n}\n"],"names":["isStatewireChannelTeardown","statewireRejectionPayload","statewireRejectionDetailMessage","isLegacyThreadReadOnlyRejection"],"mappings":";;;;;;;;;;;;;;;;;AAoBO,SAAS,2BACd,OACmC;AACnC,MAAIA,OAAAA,2BAA2B,KAAK,EAAG,QAAO;AAC9C,QAAM,YAAYC,OAAAA,0BAA0B,KAAK;AAGjD,QAAM,SAASC,OAAAA,gCAAgC,KAAK;AAEpD,OAAI,uCAAW,YAAW,KAAK;AAC7B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UAAU;AAAA,IAAA;AAAA,EAEhB;AAMA,MAAIC,OAAAA,gCAAgC,KAAK,GAAG;AAC1C,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UACA;AAAA,IAAA;AAAA,EAEN;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SACE,WACC,iBAAiB,SAAS,MAAM,QAAQ,SAAS,IAC9C,MAAM,UACN;AAAA,EAAA;AAEV;AAuBO,MAAM,4BAA4D;AAAA,EACvE,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AACb;AASO,SAAS,0BACd,OACA,QACgC;;AAChC,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK,cAAc;AACjB,YAAM,YACJ,YAAO,eAAP,mBAAmB,YAAW,iBAC9B,YAAO,eAAP,mBAAmB,YAAW;AAChC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,OAAO;AAAA,QACnB,OAAO,UAAU,OAAO,MAAM;AAAA,MAAA;AAAA,IAElC;AAAA,IACA,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,OAAO,MAAA;AAAA,IACnC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,WAAW,OAAO,UAAA;AAAA,EAAU;AAErD;;;;"}
1
+ {"version":3,"file":"statewire-lifecycle.cjs","sources":["../../src/runtime/statewire-lifecycle.ts"],"sourcesContent":["import {\n isLegacyThreadReadOnlyRejection,\n isStatewireChannelTeardown,\n statewireRejectionDetailMessage,\n statewireRejectionPayload,\n} from '@athenaintel/agent-runtime';\nimport type { DeepAgentConnectionState } from '@athenaintel/agent-runtime';\n\n/** A user-visible notice mapped from a statewire transport error. */\nexport interface AthenaStatewireErrorNotice {\n kind: 'paywall' | 'read-only' | 'command';\n title: string;\n message: string;\n}\n\n/**\n * Map the statewire failure envelope to a concise, actionable notice.\n * Returns null for expected channel teardowns (thread switch, unmount),\n * which must not surface as errors.\n */\nexport function athenaStatewireErrorNotice(\n error: unknown,\n): AthenaStatewireErrorNotice | null {\n if (isStatewireChannelTeardown(error)) return null;\n const rejection = statewireRejectionPayload(error);\n // The server's own detail names the actionable reason; the Error message is\n // generic client-side text like `command rejected (500)`.\n const detail = statewireRejectionDetailMessage(error);\n\n if (rejection?.status === 402) {\n return {\n kind: 'paywall',\n title: 'Usage limit reached',\n message:\n detail ?? 'Athena could not start this run. Review usage or billing to continue.',\n };\n }\n\n // Legacy-thread dispatch fence: an out-of-band run is writing this\n // pre-cutover thread (or its adoption failed). A per-send failure, not a\n // standing state — the server's detail names the actionable reason (wait\n // for the run vs. start a new chat).\n if (isLegacyThreadReadOnlyRejection(error)) {\n return {\n kind: 'read-only',\n title: 'Message was not sent',\n message:\n detail ??\n 'This conversation cannot take new messages right now. Try again shortly, or start a new chat.',\n };\n }\n\n return {\n kind: 'command',\n title: 'Message was not sent',\n message:\n detail ??\n (error instanceof Error && error.message.length > 0\n ? error.message\n : 'The chat runtime rejected the command. Please try again.'),\n };\n}\n\n/** Shared lifecycle state for the statewire transport, provided by\n * `AthenaProvider` in statewire mode and read by the chat banners. */\nexport interface AthenaStatewireLifecycleState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n dismissError: () => void;\n}\n\n/** The provider's reducer state behind {@link AthenaStatewireLifecycleState}. */\nexport interface StatewireLifecycleReducerState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n}\n\nexport type StatewireLifecycleAction =\n | { type: 'connection'; connection: DeepAgentConnectionState | null }\n | { type: 'error'; error: AthenaStatewireErrorNotice | null }\n | { type: 'raw-connection'; reconnect: () => void };\n\nexport const initialStatewireLifecycle: StatewireLifecycleReducerState = {\n connection: null,\n error: null,\n reconnect: null,\n};\n\n/**\n * Folds the runtime's lifecycle observations into the banner state. A healthy\n * channel — connected, or disconnected only because the instance is quiet\n * (`idle`) or the chat has not sent yet (`deferred`) — clears a stale\n * send/transport error: leaving it up tells the user the chat is broken after\n * it has come back.\n */\nexport function statewireLifecycleReducer(\n state: StatewireLifecycleReducerState,\n action: StatewireLifecycleAction,\n): StatewireLifecycleReducerState {\n switch (action.type) {\n case 'connection': {\n const healthy =\n action.connection?.status === 'connected' ||\n action.connection?.status === 'standby';\n return {\n ...state,\n connection: action.connection,\n error: healthy ? null : state.error,\n };\n }\n case 'error':\n return { ...state, error: action.error };\n case 'raw-connection':\n return { ...state, reconnect: action.reconnect };\n }\n}\n"],"names":["isStatewireChannelTeardown","statewireRejectionPayload","statewireRejectionDetailMessage","isLegacyThreadReadOnlyRejection"],"mappings":";;;;;;;;;;;;;;;;;;AAoBO,SAAS,2BACd,OACmC;AACnC,MAAIA,OAAAA,2BAA2B,KAAK,EAAG,QAAO;AAC9C,QAAM,YAAYC,OAAAA,0BAA0B,KAAK;AAGjD,QAAM,SAASC,OAAAA,gCAAgC,KAAK;AAEpD,OAAI,uCAAW,YAAW,KAAK;AAC7B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UAAU;AAAA,IAAA;AAAA,EAEhB;AAMA,MAAIC,OAAAA,gCAAgC,KAAK,GAAG;AAC1C,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UACA;AAAA,IAAA;AAAA,EAEN;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SACE,WACC,iBAAiB,SAAS,MAAM,QAAQ,SAAS,IAC9C,MAAM,UACN;AAAA,EAAA;AAEV;AAuBO,MAAM,4BAA4D;AAAA,EACvE,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AACb;AASO,SAAS,0BACd,OACA,QACgC;;AAChC,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK,cAAc;AACjB,YAAM,YACJ,YAAO,eAAP,mBAAmB,YAAW,iBAC9B,YAAO,eAAP,mBAAmB,YAAW;AAChC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,OAAO;AAAA,QACnB,OAAO,UAAU,OAAO,MAAM;AAAA,MAAA;AAAA,IAElC;AAAA,IACA,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,OAAO,MAAA;AAAA,IACnC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,WAAW,OAAO,UAAA;AAAA,EAAU;AAErD;;;;"}
@@ -9,10 +9,11 @@ import "../packages/agent-runtime/src/statewire-state.js";
9
9
  import "../packages/agent-runtime/src/messages.js";
10
10
  import "@assistant-ui/react-statewire";
11
11
  import "@assistant-ui/store";
12
- import "@assistant-ui/react-statewire/local-storage";
12
+ import "../packages/agent-runtime/src/quota-safe-local-storage-session.js";
13
13
  import "../packages/agent-runtime/src/statewire-attach-observer.js";
14
14
  import "../packages/agent-runtime/src/thread-status.js";
15
15
  import "@assistant-ui/core";
16
+ import "../packages/agent-runtime/src/thread-handoff.js";
16
17
  function athenaStatewireErrorNotice(error) {
17
18
  if (isStatewireChannelTeardown(error)) return null;
18
19
  const rejection = statewireRejectionPayload(error);
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-lifecycle.js","sources":["../../src/runtime/statewire-lifecycle.ts"],"sourcesContent":["import {\n isLegacyThreadReadOnlyRejection,\n isStatewireChannelTeardown,\n statewireRejectionDetailMessage,\n statewireRejectionPayload,\n} from '@athenaintel/agent-runtime';\nimport type { DeepAgentConnectionState } from '@athenaintel/agent-runtime';\n\n/** A user-visible notice mapped from a statewire transport error. */\nexport interface AthenaStatewireErrorNotice {\n kind: 'paywall' | 'read-only' | 'command';\n title: string;\n message: string;\n}\n\n/**\n * Map the statewire failure envelope to a concise, actionable notice.\n * Returns null for expected channel teardowns (thread switch, unmount),\n * which must not surface as errors.\n */\nexport function athenaStatewireErrorNotice(\n error: unknown,\n): AthenaStatewireErrorNotice | null {\n if (isStatewireChannelTeardown(error)) return null;\n const rejection = statewireRejectionPayload(error);\n // The server's own detail names the actionable reason; the Error message is\n // generic client-side text like `command rejected (500)`.\n const detail = statewireRejectionDetailMessage(error);\n\n if (rejection?.status === 402) {\n return {\n kind: 'paywall',\n title: 'Usage limit reached',\n message:\n detail ?? 'Athena could not start this run. Review usage or billing to continue.',\n };\n }\n\n // Legacy-thread dispatch fence: an out-of-band run is writing this\n // pre-cutover thread (or its adoption failed). A per-send failure, not a\n // standing state — the server's detail names the actionable reason (wait\n // for the run vs. start a new chat).\n if (isLegacyThreadReadOnlyRejection(error)) {\n return {\n kind: 'read-only',\n title: 'Message was not sent',\n message:\n detail ??\n 'This conversation cannot take new messages right now. Try again shortly, or start a new chat.',\n };\n }\n\n return {\n kind: 'command',\n title: 'Message was not sent',\n message:\n detail ??\n (error instanceof Error && error.message.length > 0\n ? error.message\n : 'The chat runtime rejected the command. Please try again.'),\n };\n}\n\n/** Shared lifecycle state for the statewire transport, provided by\n * `AthenaProvider` in statewire mode and read by the chat banners. */\nexport interface AthenaStatewireLifecycleState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n dismissError: () => void;\n}\n\n/** The provider's reducer state behind {@link AthenaStatewireLifecycleState}. */\nexport interface StatewireLifecycleReducerState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n}\n\nexport type StatewireLifecycleAction =\n | { type: 'connection'; connection: DeepAgentConnectionState | null }\n | { type: 'error'; error: AthenaStatewireErrorNotice | null }\n | { type: 'raw-connection'; reconnect: () => void };\n\nexport const initialStatewireLifecycle: StatewireLifecycleReducerState = {\n connection: null,\n error: null,\n reconnect: null,\n};\n\n/**\n * Folds the runtime's lifecycle observations into the banner state. A healthy\n * channel — connected, or disconnected only because the instance is quiet\n * (`idle`) or the chat has not sent yet (`deferred`) — clears a stale\n * send/transport error: leaving it up tells the user the chat is broken after\n * it has come back.\n */\nexport function statewireLifecycleReducer(\n state: StatewireLifecycleReducerState,\n action: StatewireLifecycleAction,\n): StatewireLifecycleReducerState {\n switch (action.type) {\n case 'connection': {\n const healthy =\n action.connection?.status === 'connected' ||\n action.connection?.status === 'standby';\n return {\n ...state,\n connection: action.connection,\n error: healthy ? null : state.error,\n };\n }\n case 'error':\n return { ...state, error: action.error };\n case 'raw-connection':\n return { ...state, reconnect: action.reconnect };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAoBO,SAAS,2BACd,OACmC;AACnC,MAAI,2BAA2B,KAAK,EAAG,QAAO;AAC9C,QAAM,YAAY,0BAA0B,KAAK;AAGjD,QAAM,SAAS,gCAAgC,KAAK;AAEpD,OAAI,uCAAW,YAAW,KAAK;AAC7B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UAAU;AAAA,IAAA;AAAA,EAEhB;AAMA,MAAI,gCAAgC,KAAK,GAAG;AAC1C,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UACA;AAAA,IAAA;AAAA,EAEN;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SACE,WACC,iBAAiB,SAAS,MAAM,QAAQ,SAAS,IAC9C,MAAM,UACN;AAAA,EAAA;AAEV;AAuBO,MAAM,4BAA4D;AAAA,EACvE,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AACb;AASO,SAAS,0BACd,OACA,QACgC;;AAChC,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK,cAAc;AACjB,YAAM,YACJ,YAAO,eAAP,mBAAmB,YAAW,iBAC9B,YAAO,eAAP,mBAAmB,YAAW;AAChC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,OAAO;AAAA,QACnB,OAAO,UAAU,OAAO,MAAM;AAAA,MAAA;AAAA,IAElC;AAAA,IACA,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,OAAO,MAAA;AAAA,IACnC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,WAAW,OAAO,UAAA;AAAA,EAAU;AAErD;"}
1
+ {"version":3,"file":"statewire-lifecycle.js","sources":["../../src/runtime/statewire-lifecycle.ts"],"sourcesContent":["import {\n isLegacyThreadReadOnlyRejection,\n isStatewireChannelTeardown,\n statewireRejectionDetailMessage,\n statewireRejectionPayload,\n} from '@athenaintel/agent-runtime';\nimport type { DeepAgentConnectionState } from '@athenaintel/agent-runtime';\n\n/** A user-visible notice mapped from a statewire transport error. */\nexport interface AthenaStatewireErrorNotice {\n kind: 'paywall' | 'read-only' | 'command';\n title: string;\n message: string;\n}\n\n/**\n * Map the statewire failure envelope to a concise, actionable notice.\n * Returns null for expected channel teardowns (thread switch, unmount),\n * which must not surface as errors.\n */\nexport function athenaStatewireErrorNotice(\n error: unknown,\n): AthenaStatewireErrorNotice | null {\n if (isStatewireChannelTeardown(error)) return null;\n const rejection = statewireRejectionPayload(error);\n // The server's own detail names the actionable reason; the Error message is\n // generic client-side text like `command rejected (500)`.\n const detail = statewireRejectionDetailMessage(error);\n\n if (rejection?.status === 402) {\n return {\n kind: 'paywall',\n title: 'Usage limit reached',\n message:\n detail ?? 'Athena could not start this run. Review usage or billing to continue.',\n };\n }\n\n // Legacy-thread dispatch fence: an out-of-band run is writing this\n // pre-cutover thread (or its adoption failed). A per-send failure, not a\n // standing state — the server's detail names the actionable reason (wait\n // for the run vs. start a new chat).\n if (isLegacyThreadReadOnlyRejection(error)) {\n return {\n kind: 'read-only',\n title: 'Message was not sent',\n message:\n detail ??\n 'This conversation cannot take new messages right now. Try again shortly, or start a new chat.',\n };\n }\n\n return {\n kind: 'command',\n title: 'Message was not sent',\n message:\n detail ??\n (error instanceof Error && error.message.length > 0\n ? error.message\n : 'The chat runtime rejected the command. Please try again.'),\n };\n}\n\n/** Shared lifecycle state for the statewire transport, provided by\n * `AthenaProvider` in statewire mode and read by the chat banners. */\nexport interface AthenaStatewireLifecycleState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n dismissError: () => void;\n}\n\n/** The provider's reducer state behind {@link AthenaStatewireLifecycleState}. */\nexport interface StatewireLifecycleReducerState {\n connection: DeepAgentConnectionState | null;\n error: AthenaStatewireErrorNotice | null;\n reconnect: (() => void) | null;\n}\n\nexport type StatewireLifecycleAction =\n | { type: 'connection'; connection: DeepAgentConnectionState | null }\n | { type: 'error'; error: AthenaStatewireErrorNotice | null }\n | { type: 'raw-connection'; reconnect: () => void };\n\nexport const initialStatewireLifecycle: StatewireLifecycleReducerState = {\n connection: null,\n error: null,\n reconnect: null,\n};\n\n/**\n * Folds the runtime's lifecycle observations into the banner state. A healthy\n * channel — connected, or disconnected only because the instance is quiet\n * (`idle`) or the chat has not sent yet (`deferred`) — clears a stale\n * send/transport error: leaving it up tells the user the chat is broken after\n * it has come back.\n */\nexport function statewireLifecycleReducer(\n state: StatewireLifecycleReducerState,\n action: StatewireLifecycleAction,\n): StatewireLifecycleReducerState {\n switch (action.type) {\n case 'connection': {\n const healthy =\n action.connection?.status === 'connected' ||\n action.connection?.status === 'standby';\n return {\n ...state,\n connection: action.connection,\n error: healthy ? null : state.error,\n };\n }\n case 'error':\n return { ...state, error: action.error };\n case 'raw-connection':\n return { ...state, reconnect: action.reconnect };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAoBO,SAAS,2BACd,OACmC;AACnC,MAAI,2BAA2B,KAAK,EAAG,QAAO;AAC9C,QAAM,YAAY,0BAA0B,KAAK;AAGjD,QAAM,SAAS,gCAAgC,KAAK;AAEpD,OAAI,uCAAW,YAAW,KAAK;AAC7B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UAAU;AAAA,IAAA;AAAA,EAEhB;AAMA,MAAI,gCAAgC,KAAK,GAAG;AAC1C,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SACE,UACA;AAAA,IAAA;AAAA,EAEN;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SACE,WACC,iBAAiB,SAAS,MAAM,QAAQ,SAAS,IAC9C,MAAM,UACN;AAAA,EAAA;AAEV;AAuBO,MAAM,4BAA4D;AAAA,EACvE,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AACb;AASO,SAAS,0BACd,OACA,QACgC;;AAChC,UAAQ,OAAO,MAAA;AAAA,IACb,KAAK,cAAc;AACjB,YAAM,YACJ,YAAO,eAAP,mBAAmB,YAAW,iBAC9B,YAAO,eAAP,mBAAmB,YAAW;AAChC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,OAAO;AAAA,QACnB,OAAO,UAAU,OAAO,MAAM;AAAA,MAAA;AAAA,IAElC;AAAA,IACA,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,OAAO,MAAA;AAAA,IACnC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,WAAW,OAAO,UAAA;AAAA,EAAU;AAErD;"}
@@ -12,11 +12,12 @@ require("../packages/agent-runtime/src/statewire-state.cjs");
12
12
  require("../packages/agent-runtime/src/messages.cjs");
13
13
  require("@assistant-ui/react-statewire");
14
14
  require("@assistant-ui/store");
15
- require("@assistant-ui/react-statewire/local-storage");
15
+ require("../packages/agent-runtime/src/quota-safe-local-storage-session.cjs");
16
16
  require("../packages/agent-runtime/src/statewire-attach-observer.cjs");
17
17
  require("../packages/agent-runtime/src/thread-status.cjs");
18
18
  const useDeepAgentRuntime = require("../packages/agent-runtime/src/use-deep-agent-runtime.cjs");
19
19
  require("@assistant-ui/core");
20
+ require("../packages/agent-runtime/src/thread-handoff.cjs");
20
21
  const AthenaAuthContext = require("../auth/AthenaAuthContext.cjs");
21
22
  const statewireClientTools = require("../chat/statewire-client-tools.cjs");
22
23
  const athenaDiagnostics = require("../diagnostics/athena-diagnostics.cjs");
@@ -1 +1 @@
1
- {"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The message window every SDK attach declares (`x-athena-deep-agent-window`):\n * the hello carries the transcript's tail plus the `messagesWindow` lane\n * instead of every message — megabytes on long threads, over the 1 MiB frame\n * limit of stock websocket clients. Older pages load from the\n * `StatewireHistoryEdge` row the chat UI mounts above the messages, and cut\n * tool outputs are fetched back for the cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * The message window declared on the attach (see\n * {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). `false` keeps the full\n * snapshot for a host that renders no history loader.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration | false;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Windowed hello (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n useClient: useSdkClient,\n onStateChange: () => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // The runConfig getter is pulled at command-send time through the core's\n // per-render ref, so it reads the latest props — consumers commonly pass\n // fresh array literals per render, which must not thrash the registration\n // (no `key`: the provider registers once per client).\n runConfig: {\n get: () =>\n buildStatewireRunConfig({\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n }),\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","buildStatewireRunConfig","statewireClientToolWireEntries","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AA0EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJC,qBAAAA,iBAAiB,EAAE,OAAO;AAE1B,QAAM,cAAc,wBAAwB,eAAe;AAI3D,QAAM,cAAcC,MAAAA,WAAWC,mCAAiB;AAChD,QAAM,cAAY,gDAAa,SAAb,mBAAmB,WAAU;AAG/C,QAAM,gBAAgBC,MAAAA,OAAwD,IAAI;AAClF,QAAM,kBAAkBA,MAAAA,OAAsB,IAAI;AAClD,MAAI,gBAAgB,YAAY,UAAU;AACxC,oBAAgB,UAAU;AAC1B,kBAAc,UAAUC,kBAAAA,kBAAkB;AAAA,MACxC,oBAAoB,QAAQ;AAAA,MAC5B;AAAA,MACA,EAAE,WAAW,UAAU,aAAa,UAAA;AAAA,IAAU;AAAA,EAElD;AAEA,QAAM,WAAWN,cAAQ,MAAMO,cAAM,EAAE,SAAS,gBAAA,CAAiB,GAAG,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A;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAaC,qBAAAA,+BAA+B,WAAW;AAAA,MAAA,CACxD;AAAA,IAAA;AAAA,IAEL,SAAS,CAAC,UAAU;AAClB,UAAI,CAACC,OAAAA,2BAA2B,KAAK,GAAG;AACtCR,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAS,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
1
+ {"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The message window every SDK attach declares (`x-athena-deep-agent-window`):\n * the hello carries the transcript's tail plus the `messagesWindow` lane\n * instead of every message — megabytes on long threads, over the 1 MiB frame\n * limit of stock websocket clients. Older pages load from the\n * `StatewireHistoryEdge` row the chat UI mounts above the messages, and cut\n * tool outputs are fetched back for the cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * The message window declared on the attach (see\n * {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). `false` keeps the full\n * snapshot for a host that renders no history loader.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration | false;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Windowed hello (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n useClient: useSdkClient,\n onStateChange: () => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // The runConfig getter is pulled at command-send time through the core's\n // per-render ref, so it reads the latest props — consumers commonly pass\n // fresh array literals per render, which must not thrash the registration\n // (no `key`: the provider registers once per client).\n runConfig: {\n get: () =>\n buildStatewireRunConfig({\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n }),\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","buildStatewireRunConfig","statewireClientToolWireEntries","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AA0EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;A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Ac,UAAU;AACxB,gBAAQ,sBAAsB,EAAE,MAAM,EAAE,WAAW,SAAA,GAAY;AAAA,MACjE;AAAA,IACF;AAAA,IACA,oBAAoB,CAAC,eAAe;AAClCL,wBAAAA,kBAAkB,MAAM,yBAAwB,yCAAY,WAAU,IAAI;AAC1E,WAAI,yCAAY,YAAW,WAAW;AACpCA,0BAAAA,kBAAkB,KAAK,wBAAwB;AAAA,UAC7C,OAAO;AAAA,UACP,MAAM;AAAA,YACJ,QAAQ,WAAW;AAAA,YACnB,QAAQ,WAAW;AAAA,YACnB,SAAS,WAAW;AAAA,UAAA;AAAA,QACtB,CACD;AAAA,MACH;AACA,+DAAqB;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,WAAW;AAAA,MACT,KAAK,MACHM,mBAAAA,wBAAwB;AAAA,QACtB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAaC,qBAAAA,+BAA+B,WAAW;AAAA,MAAA,CACxD;AAAA,IAAA;AAAA,IAEL,SAAS,CAAC,UAAU;AAClB,UAAI,CAACC,OAAAA,2BAA2B,KAAK,GAAG;AACtCR,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAS,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
@@ -10,11 +10,12 @@ import "../packages/agent-runtime/src/statewire-state.js";
10
10
  import "../packages/agent-runtime/src/messages.js";
11
11
  import "@assistant-ui/react-statewire";
12
12
  import "@assistant-ui/store";
13
- import "@assistant-ui/react-statewire/local-storage";
13
+ import "../packages/agent-runtime/src/quota-safe-local-storage-session.js";
14
14
  import "../packages/agent-runtime/src/statewire-attach-observer.js";
15
15
  import "../packages/agent-runtime/src/thread-status.js";
16
16
  import { useDeepAgentRuntime, logUnhandledStatewireError } from "../packages/agent-runtime/src/use-deep-agent-runtime.js";
17
17
  import "@assistant-ui/core";
18
+ import "../packages/agent-runtime/src/thread-handoff.js";
18
19
  import { AthenaAuthContext } from "../auth/AthenaAuthContext.js";
19
20
  import { collectStatewireClientTools, statewireClientToolWireEntries } from "../chat/statewire-client-tools.js";
20
21
  import { athenaDiagnostics } from "../diagnostics/athena-diagnostics.js";
@@ -1 +1 @@
1
- {"version":3,"file":"useAthenaStatewireRuntime.js","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The message window every SDK attach declares (`x-athena-deep-agent-window`):\n * the hello carries the transcript's tail plus the `messagesWindow` lane\n * instead of every message — megabytes on long threads, over the 1 MiB frame\n * limit of stock websocket clients. Older pages load from the\n * `StatewireHistoryEdge` row the chat UI mounts above the messages, and cut\n * tool outputs are fetched back for the cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * The message window declared on the attach (see\n * {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). `false` keeps the full\n * snapshot for a host that renders no history loader.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration | false;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Windowed hello (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n useClient: useSdkClient,\n onStateChange: () => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // The runConfig getter is pulled at command-send time through the core's\n // per-render ref, so it reads the latest props — consumers commonly pass\n // fresh array literals per render, which must not thrash the registration\n // (no `key`: the provider registers once per client).\n runConfig: {\n get: () =>\n buildStatewireRunConfig({\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n }),\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4CO,MAAM,4BAA+D;AAAA,EAC1E,MAAM;AACR;AA0EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAO;AAAA,IACL,MAAM,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJ,mBAAiB,EAAE,OAAO;AAE1B,QAAM,cAAc,wBAAwB,eAAe;AAI3D,QAAM,cAAc,WAAW,iBAAiB;AAChD,QAAM,cAAY,gDAAa,SAAb,mBAAmB,WAAU;AAG/C,QAAM,gBAAgB,OAAwD,IAAI;AAClF,QAAM,kBAAkB,OAAsB,IAAI;AAClD,MAAI,gBAAgB,YAAY,UAAU;AACxC,oBAAgB,UAAU;AAC1B,kBAAc,UAAU,kBAAkB;AAAA,MACxC,oBAAoB,QAAQ;AAAA,M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AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,WAAW;AAAA,MACT,KAAK,MACH,wBAAwB;AAAA,QACtB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAa,+BAA+B,WAAW;AAAA,MAAA,CACxD;AAAA,IAAA;AAAA,IAEL,SAAS,CAAC,UAAU;AAClB,UAAI,CAAC,2BAA2B,KAAK,GAAG;AACtC,0BAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACA,iCAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;"}
1
+ {"version":3,"file":"useAthenaStatewireRuntime.js","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The message window every SDK attach declares (`x-athena-deep-agent-window`):\n * the hello carries the transcript's tail plus the `messagesWindow` lane\n * instead of every message — megabytes on long threads, over the 1 MiB frame\n * limit of stock websocket clients. Older pages load from the\n * `StatewireHistoryEdge` row the chat UI mounts above the messages, and cut\n * tool outputs are fetched back for the cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * The message window declared on the attach (see\n * {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). `false` keeps the full\n * snapshot for a host that renders no history loader.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration | false;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Windowed hello (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n useClient: useSdkClient,\n onStateChange: () => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // The runConfig getter is pulled at command-send time through the core's\n // per-render ref, so it reads the latest props — consumers commonly pass\n // fresh array literals per render, which must not thrash the registration\n // (no `key`: the provider registers once per client).\n runConfig: {\n get: () =>\n buildStatewireRunConfig({\n model,\n agent,\n channel,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n }),\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4CO,MAAM,4BAA+D;AAAA,EAC1E,MAAM;AACR;AA0EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAO;AAAA,IACL,MAAM,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJ,mBAAiB,EAAE,OAAO;AAE1B,QAAM,cAAc,wBAAwB,eAAe;AAI3D,QAAM,cAAc,WAAW,iBAAiB;AAChD,QAAM,cAAY,gDAAa,SAAb,mBAAmB,WAAU;AAG/C,QAAM,gB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