@athenaintel/react 0.55.0 → 0.57.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 (164) hide show
  1. package/README.md +84 -1
  2. package/dist/agent-runtime/src/answer-label.cjs +8 -2
  3. package/dist/agent-runtime/src/answer-label.cjs.map +1 -1
  4. package/dist/agent-runtime/src/answer-label.d.ts +10 -4
  5. package/dist/agent-runtime/src/answer-label.js +8 -2
  6. package/dist/agent-runtime/src/answer-label.js.map +1 -1
  7. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +6 -3
  8. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  9. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +6 -3
  10. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  11. package/dist/agent-runtime/src/edit-command.cjs +40 -19
  12. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  13. package/dist/agent-runtime/src/edit-command.d.ts +2 -0
  14. package/dist/agent-runtime/src/edit-command.js +41 -20
  15. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  16. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +8 -0
  17. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  18. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +9 -0
  19. package/dist/agent-runtime/src/generated/runconfig-contract.js +8 -0
  20. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  21. package/dist/agent-runtime/src/history-store.cjs +426 -0
  22. package/dist/agent-runtime/src/history-store.cjs.map +1 -0
  23. package/dist/agent-runtime/src/history-store.d.ts +282 -0
  24. package/dist/agent-runtime/src/history-store.js +426 -0
  25. package/dist/agent-runtime/src/history-store.js.map +1 -0
  26. package/dist/agent-runtime/src/inbound-channel.cjs +96 -0
  27. package/dist/agent-runtime/src/inbound-channel.cjs.map +1 -0
  28. package/dist/agent-runtime/src/inbound-channel.d.ts +75 -0
  29. package/dist/agent-runtime/src/inbound-channel.js +96 -0
  30. package/dist/agent-runtime/src/inbound-channel.js.map +1 -0
  31. package/dist/agent-runtime/src/index.d.ts +6 -5
  32. package/dist/agent-runtime/src/interrupts.cjs +45 -3
  33. package/dist/agent-runtime/src/interrupts.cjs.map +1 -1
  34. package/dist/agent-runtime/src/interrupts.d.ts +51 -4
  35. package/dist/agent-runtime/src/interrupts.js +46 -4
  36. package/dist/agent-runtime/src/interrupts.js.map +1 -1
  37. package/dist/agent-runtime/src/message-window.cjs +43 -5
  38. package/dist/agent-runtime/src/message-window.cjs.map +1 -1
  39. package/dist/agent-runtime/src/message-window.d.ts +26 -2
  40. package/dist/agent-runtime/src/message-window.js +44 -6
  41. package/dist/agent-runtime/src/message-window.js.map +1 -1
  42. package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
  43. package/dist/agent-runtime/src/offline-status.d.ts +110 -4
  44. package/dist/agent-runtime/src/offline-status.js.map +1 -1
  45. package/dist/agent-runtime/src/runtime.d.ts +1 -0
  46. package/dist/agent-runtime/src/thread-handoff-flow-machine.d.ts +8 -8
  47. package/dist/agent-runtime/src/tool-metadata.cjs +16 -0
  48. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  49. package/dist/agent-runtime/src/tool-metadata.js +16 -0
  50. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  51. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +8 -16
  52. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  53. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +1 -9
  54. package/dist/agent-runtime/src/use-deep-agent-thread.js +9 -17
  55. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  56. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +86 -79
  57. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
  58. package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +2 -27
  59. package/dist/agent-runtime/src/use-deep-agent-window-sync.js +89 -82
  60. package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
  61. package/dist/auth/AthenaSSOProvider.cjs +54 -12
  62. package/dist/auth/AthenaSSOProvider.cjs.map +1 -1
  63. package/dist/auth/AthenaSSOProvider.d.ts +23 -2
  64. package/dist/auth/AthenaSSOProvider.js +54 -12
  65. package/dist/auth/AthenaSSOProvider.js.map +1 -1
  66. package/dist/auth/index.cjs +2 -0
  67. package/dist/auth/index.cjs.map +1 -1
  68. package/dist/auth/index.d.ts +1 -0
  69. package/dist/auth/index.js +2 -0
  70. package/dist/auth/index.js.map +1 -1
  71. package/dist/auth/sign-back-in.cjs +141 -0
  72. package/dist/auth/sign-back-in.cjs.map +1 -0
  73. package/dist/auth/sign-back-in.d.ts +117 -0
  74. package/dist/auth/sign-back-in.js +141 -0
  75. package/dist/auth/sign-back-in.js.map +1 -0
  76. package/dist/chat/AthenaChat.cjs +7 -2
  77. package/dist/chat/AthenaChat.cjs.map +1 -1
  78. package/dist/chat/AthenaChat.js +7 -2
  79. package/dist/chat/AthenaChat.js.map +1 -1
  80. package/dist/chat/StatewireApprovalCard.cjs +6 -2
  81. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  82. package/dist/chat/StatewireApprovalCard.d.ts +8 -1
  83. package/dist/chat/StatewireApprovalCard.js +7 -3
  84. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  85. package/dist/chat/super-grouping/CollapsibleGroup.cjs +1 -1
  86. package/dist/chat/super-grouping/CollapsibleGroup.cjs.map +1 -1
  87. package/dist/chat/super-grouping/CollapsibleGroup.d.ts +6 -5
  88. package/dist/chat/super-grouping/CollapsibleGroup.js +1 -1
  89. package/dist/chat/super-grouping/CollapsibleGroup.js.map +1 -1
  90. package/dist/chat/super-grouping/earlier-steps-button.cjs +5 -6
  91. package/dist/chat/super-grouping/earlier-steps-button.cjs.map +1 -1
  92. package/dist/chat/super-grouping/earlier-steps-button.d.ts +6 -6
  93. package/dist/chat/super-grouping/earlier-steps-button.js +5 -6
  94. package/dist/chat/super-grouping/earlier-steps-button.js.map +1 -1
  95. package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
  96. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  97. package/dist/chat/super-grouping/toolkit-map.js +1 -0
  98. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  99. package/dist/chat/super-grouping/use-turn-steps.cjs +3 -3
  100. package/dist/chat/super-grouping/use-turn-steps.js +1 -1
  101. package/dist/chat-ui/index.cjs +4 -0
  102. package/dist/chat-ui/index.cjs.map +1 -1
  103. package/dist/chat-ui/index.d.ts +1 -0
  104. package/dist/chat-ui/index.js +5 -1
  105. package/dist/chat-ui/index.js.map +1 -1
  106. package/dist/chat-ui/messages/inbound-channel-message.cjs +219 -0
  107. package/dist/chat-ui/messages/inbound-channel-message.cjs.map +1 -0
  108. package/dist/chat-ui/messages/inbound-channel-message.d.ts +60 -0
  109. package/dist/chat-ui/messages/inbound-channel-message.js +219 -0
  110. package/dist/chat-ui/messages/inbound-channel-message.js.map +1 -0
  111. package/dist/chat-ui/messages/inbound-channel-reader.cjs +184 -0
  112. package/dist/chat-ui/messages/inbound-channel-reader.cjs.map +1 -0
  113. package/dist/chat-ui/messages/inbound-channel-reader.d.ts +65 -0
  114. package/dist/chat-ui/messages/inbound-channel-reader.js +184 -0
  115. package/dist/chat-ui/messages/inbound-channel-reader.js.map +1 -0
  116. package/dist/chat-ui/messages/message-components.cjs +18 -14
  117. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  118. package/dist/chat-ui/messages/message-components.d.ts +7 -0
  119. package/dist/chat-ui/messages/message-components.js +19 -15
  120. package/dist/chat-ui/messages/message-components.js.map +1 -1
  121. package/dist/chat-ui/thread/statewire-history-edge.cjs +0 -4
  122. package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
  123. package/dist/chat-ui/thread/statewire-history-edge.d.ts +5 -7
  124. package/dist/chat-ui/thread/statewire-history-edge.js +1 -5
  125. package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
  126. package/dist/composer/sign-back-in-draft.cjs +62 -0
  127. package/dist/composer/sign-back-in-draft.cjs.map +1 -0
  128. package/dist/composer/sign-back-in-draft.d.ts +34 -0
  129. package/dist/composer/sign-back-in-draft.js +62 -0
  130. package/dist/composer/sign-back-in-draft.js.map +1 -0
  131. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  132. package/dist/diagnostics/athena-diagnostics.d.ts +6 -1
  133. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  134. package/dist/index.cjs +8 -0
  135. package/dist/index.cjs.map +1 -1
  136. package/dist/index.d.ts +2 -0
  137. package/dist/index.js +8 -0
  138. package/dist/index.js.map +1 -1
  139. package/dist/provider/AthenaProvider.cjs +60 -14
  140. package/dist/provider/AthenaProvider.cjs.map +1 -1
  141. package/dist/provider/AthenaProvider.js +60 -14
  142. package/dist/provider/AthenaProvider.js.map +1 -1
  143. package/dist/provider/statewire-window-context.cjs.map +1 -1
  144. package/dist/provider/statewire-window-context.d.ts +8 -8
  145. package/dist/provider/statewire-window-context.js.map +1 -1
  146. package/dist/react/package.json.cjs +1 -1
  147. package/dist/react/package.json.js +1 -1
  148. package/dist/runtime/auth.cjs +11 -0
  149. package/dist/runtime/auth.cjs.map +1 -1
  150. package/dist/runtime/auth.d.ts +18 -1
  151. package/dist/runtime/auth.js +11 -0
  152. package/dist/runtime/auth.js.map +1 -1
  153. package/dist/runtime/useAthenaStatewireRuntime.cjs +0 -2
  154. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  155. package/dist/runtime/useAthenaStatewireRuntime.d.ts +5 -5
  156. package/dist/runtime/useAthenaStatewireRuntime.js +0 -2
  157. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  158. package/dist/styles.css +1 -1
  159. package/package.json +1 -1
  160. package/dist/agent-runtime/src/history-pages.cjs +0 -279
  161. package/dist/agent-runtime/src/history-pages.cjs.map +0 -1
  162. package/dist/agent-runtime/src/history-pages.d.ts +0 -252
  163. package/dist/agent-runtime/src/history-pages.js +0 -279
  164. package/dist/agent-runtime/src/history-pages.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-history-edge.js","sources":["../../../src/chat-ui/thread/statewire-history-edge.tsx"],"sourcesContent":["import {\n getExternalStoreMessages,\n type ThreadMessage,\n type ThreadViewportState,\n useAuiState,\n useThreadViewport,\n useThreadViewportStore,\n} from \"@assistant-ui/react\";\nimport {\n type DeepAgentHistoryLoadEvent,\n type DeepAgentHistoryStore,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n useDeepAgentWindowSync,\n} from \"@athenaintel/agent-runtime\";\nimport type { FC } from \"react\";\nimport { Component, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport {\n NO_STATEWIRE_HISTORY,\n StatewireHistoryContext,\n} from \"../../provider/statewire-history-context\";\nimport {\n useStatewireHistoryPages,\n useStatewireToolOutputs,\n} from \"../../provider/statewire-window-context\";\nimport { AthenaStatewireThreadIdContext } from \"../../threads/thread-id-context\";\n\n/** The attribute `ChatThreadShell` stamps on the scroll viewport. */\nexport const THREAD_VIEWPORT_ATTR = \"data-aui-thread-viewport\";\n/** The attribute `ChatThreadShell` stamps on its sticky viewport footer (the composer dock). */\nexport const THREAD_VIEWPORT_FOOTER_ATTR = \"data-aui-thread-viewport-footer\";\n\n/**\n * How far above the viewport the edge row counts as near: the row sits above\n * the first loaded message, so reaching it means the user has scrolled past\n * everything loaded and the next page should already be on its way. Messages\n * this close to the viewport also count as on screen for cut tool outputs.\n */\nexport const HISTORY_EDGE_NEAR_MARGIN_PX = 1500;\n\n/**\n * Cut tool outputs a transcript reads at once. The reads share the session's\n * command lane with everything the person sends, so a long transcript must\n * not queue dozens of them ahead of a message or a Stop.\n */\nexport const HISTORY_EDGE_TOOL_OUTPUT_CONCURRENCY = 2;\n\n/** What assistant-ui's `MessagePrimitive.Root` stamps on every message. */\nconst MESSAGE_SELECTOR = \"[data-message-id]\";\n\nconst NO_MESSAGE_IDS: ReadonlySet<string> = new Set();\n\nfunction sameIds({ a, b }: { a: ReadonlySet<string>; b: ReadonlySet<string> }): boolean {\n if (a.size !== b.size) return false;\n for (const id of a) if (!b.has(id)) return false;\n return true;\n}\n\n/**\n * Which messages sit within {@link HISTORY_EDGE_NEAR_MARGIN_PX} of the\n * viewport, so cut tool outputs are read for what the person can reach. A\n * thread opens at its newest turn; reading every loaded step's output up\n * front sent dozens of reads, each re-rendering the transcript, for steps\n * nobody had scrolled to.\n *\n * `undefined` (every message counts) where nothing can be observed: no\n * viewport around the row, or no `IntersectionObserver`. A message rendered\n * without a `data-message-id` root (a host's own renderer) cannot be observed\n * either, so it counts as before.\n */\nfunction useMessagesNearViewport({\n viewport,\n hasViewport,\n messages,\n}: {\n viewport: HTMLElement | null;\n /** A viewport is (or will be) registered around the row. */\n hasViewport: boolean;\n /** The converted thread: every change may have mounted or remounted a message. */\n messages: readonly ThreadMessage[];\n}): ((messageId: string) => boolean) | undefined {\n const [nearIds, setNearIds] = useState<ReadonlySet<string>>(NO_MESSAGE_IDS);\n const observable = hasViewport && typeof IntersectionObserver !== \"undefined\";\n const trackRef = useRef<(() => void) | null>(null);\n // Every id a rendered element carries, as of the last scan.\n const renderedIdsRef = useRef<ReadonlySet<string>>(NO_MESSAGE_IDS);\n\n useEffect(() => {\n if (!viewport || !observable) return undefined;\n const near = new Set<Element>();\n const observed = new Set<Element>();\n const publish = () => {\n const ids = new Set<string>();\n for (const element of near) {\n const id = element.getAttribute(\"data-message-id\");\n if (id) ids.add(id);\n }\n setNearIds((previous) => (sameIds({ a: previous, b: ids }) ? previous : ids));\n };\n const intersections = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting && entry.target.isConnected) near.add(entry.target);\n else near.delete(entry.target);\n }\n publish();\n },\n { root: viewport, rootMargin: `${HISTORY_EDGE_NEAR_MARGIN_PX}px 0px` },\n );\n // A page that folds into a turn gives it a new id: a host keyed by id\n // remounts the turn's element, a host keyed by row (`ChatThreadShell`)\n // keeps it and the element's id changes. So what is observed follows the\n // rendered elements, not the message list, and the near ids are read off\n // those elements again on every scan.\n const track = () => {\n for (const element of observed) {\n if (element.isConnected) continue;\n intersections.unobserve(element);\n observed.delete(element);\n near.delete(element);\n }\n const rendered = new Set<string>();\n for (const element of viewport.querySelectorAll(MESSAGE_SELECTOR)) {\n const id = element.getAttribute(\"data-message-id\");\n if (id) rendered.add(id);\n if (observed.has(element)) continue;\n observed.add(element);\n intersections.observe(element);\n }\n renderedIdsRef.current = rendered;\n publish();\n };\n trackRef.current = track;\n track();\n return () => {\n trackRef.current = null;\n renderedIdsRef.current = NO_MESSAGE_IDS;\n intersections.disconnect();\n setNearIds(NO_MESSAGE_IDS);\n };\n }, [viewport, observable]);\n\n // A changed message list is the trigger to re-scan: its messages render in\n // the same commit, so their elements are in the DOM by this effect (a\n // query, no layout read).\n useEffect(() => {\n trackRef.current?.();\n }, [messages]);\n\n return useMemo(() => {\n if (!observable) return undefined;\n return (messageId: string) => {\n // Not registered yet: nothing is on screen to read for.\n if (viewport === null) return false;\n return nearIds.has(messageId) || !renderedIdsRef.current.has(messageId);\n };\n }, [nearIds, observable, viewport]);\n}\n\n/** The wire message a converted message was built from first (its oldest source). */\nfunction oldestSourceId(message: ThreadMessage): string | undefined {\n const source = getExternalStoreMessages<{ id?: unknown }>(message)[0];\n return typeof source?.id === \"string\" ? source.id : undefined;\n}\n\n/**\n * Whether older history landed ahead of what was loaded: the old first\n * message now sits further down (a page ahead of it), or the first message's\n * old oldest wire message now follows earlier ones (a page that folded into\n * the first loaded turn). A first message replaced in place — a branch picked\n * on it, an edit — is neither, and a run streaming at the tail never touches\n * the first message.\n */\nfunction prependedOlderHistory({\n previous,\n next,\n}: {\n previous: readonly ThreadMessage[];\n next: readonly ThreadMessage[];\n}): boolean {\n const previousFirst = previous[0];\n const nextFirst = next[0];\n if (previousFirst === undefined || nextFirst === undefined || previousFirst === nextFirst) return false;\n if (previousFirst.id !== nextFirst.id && next.some((message, index) => index > 0 && message.id === previousFirst.id)) {\n return true;\n }\n const previousOldest = oldestSourceId(previousFirst);\n if (previousOldest === undefined || previousOldest === oldestSourceId(nextFirst)) return false;\n return getExternalStoreMessages<{ id?: unknown }>(nextFirst).some(\n (source, index) => index > 0 && source?.id === previousOldest,\n );\n}\n\ninterface KeepReadingPlaceProps {\n viewport: HTMLElement | null;\n threadId: string | null;\n /** The converted thread. */\n messages: readonly ThreadMessage[];\n}\n\n/**\n * Keeps the reader's place when older history lands. Everything a page adds\n * sits above what the person is reading, so their distance from the bottom of\n * the transcript is what must survive. A class for `getSnapshotBeforeUpdate`:\n * the distance is read right before React applies the commit that renders the\n * page — the one moment it is exact, even for a scroll the browser has not\n * reported yet — and restored after it, instantly (never through the\n * viewport's smooth scrolling). Other commits read no layout.\n *\n * The browser's scroll anchoring and assistant-ui's prepend anchor aim at the\n * same position, so whichever ran first leaves this nothing to do; on its own\n * it covers what they miss: a reader at the very top (browsers never anchor\n * at scroll offset 0) and a page that folds into the first loaded turn of a\n * host that keys rows by message id (that message remounts under a new id,\n * taking the browser's anchor node with it; `ChatThreadShell` keeps the row).\n */\nclass KeepReadingPlace extends Component<KeepReadingPlaceProps> {\n getSnapshotBeforeUpdate(previous: Readonly<KeepReadingPlaceProps>): number | null {\n const { viewport, threadId, messages } = this.props;\n if (\n viewport === null ||\n viewport !== previous.viewport ||\n threadId !== previous.threadId ||\n messages === previous.messages ||\n !prependedOlderHistory({ previous: previous.messages, next: messages })\n ) {\n return null;\n }\n return viewport.scrollHeight - viewport.scrollTop;\n }\n\n componentDidUpdate(\n _previous: Readonly<KeepReadingPlaceProps>,\n _state: unknown,\n fromBottom: number | null,\n ): void {\n const { viewport } = this.props;\n if (viewport === null || fromBottom === null) return;\n const top = viewport.scrollHeight - fromBottom;\n if (Math.abs(viewport.scrollTop - top) >= 1) viewport.scrollTo({ top, behavior: \"instant\" });\n }\n\n render(): null {\n return null;\n }\n}\n\nexport interface HistoryEdgeRowProps {\n /** Whether the server holds messages older than the loaded window. */\n hasOlder: boolean;\n /** Whether the next page can be asked for; `false` with `hasOlder` is the connection's loading depth spent. Defaults to `hasOlder`. */\n canLoadOlder?: boolean;\n /** A page of older history is in flight. */\n loading: boolean;\n onLoadOlder: () => void;\n className?: string;\n /** The row element, for the viewport observer. */\n rowRef?: (element: HTMLElement | null) => void;\n}\n\n/**\n * The top edge of the LOADED history: a manual way to load the next page of\n * older messages, and the in-flight state. Renders nothing when the whole\n * transcript is loaded (or the head interest has not resolved).\n */\nexport const HistoryEdgeRow: FC<HistoryEdgeRowProps> = ({\n hasOlder,\n canLoadOlder = hasOlder,\n loading,\n onLoadOlder,\n className,\n rowRef,\n}) => {\n if (!hasOlder) return null;\n return (\n <div\n ref={rowRef}\n data-testid=\"thread-history-edge\"\n className={cn(\n \"mx-auto flex w-full max-w-(--thread-max-width) items-center justify-center py-1 text-xs text-muted-foreground\",\n className,\n )}\n >\n {loading ? (\n <span data-testid=\"thread-history-edge-loading\">Loading earlier messages…</span>\n ) : canLoadOlder ? (\n <button\n type=\"button\"\n data-testid=\"thread-history-edge-load\"\n onClick={onLoadOlder}\n className=\"rounded-lg px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n >\n Load earlier messages\n </button>\n ) : (\n <span data-testid=\"thread-history-edge-limit\">Earlier messages can't be loaded here</span>\n )}\n </div>\n );\n};\n\nexport interface StatewireHistoryEdgeProps {\n /**\n * The thread's tool-output store (the one its converter substitutes from).\n * Defaults to `AthenaProvider`'s; hosts mounting the runtime themselves pass\n * the store they gave `useDeepAgentRuntime({ toolOutputs })`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /**\n * Where older turns are paged by command (`history/page`) from a host that\n * answers it: the store the thread joins (`useDeepAgentThread({\n * historyStore })`). Defaults to `AthenaProvider`'s; `null` keeps interest\n * pages even under the provider. A host that mounts the runtime itself\n * also provides the store through `StatewireHistoryPagesContext` and the\n * control through `TurnStepsControlContext` (`EarlierStepsButton`), so a\n * summarized turn's rows can open its steps.\n */\n historyPages?: DeepAgentHistoryStore | null;\n className?: string;\n /** A page interest resolved (telemetry). */\n onHistoryLoad?: (event: DeepAgentHistoryLoadEvent) => void;\n}\n\n/**\n * The client half of the interest window for a DOM thread — mounted once per\n * thread, inside the scroll viewport above the messages (`ChatThreadShell`'s\n * `beforeMessages` slot):\n *\n * - renders the \"Load earlier messages\" edge row and loads the next page when\n * the row comes near the viewport (scrolling up) or on its button, keeping\n * the reading position when the page lands above the view;\n * - fetches cut tool outputs whole for the cards near the viewport, a few at\n * a time, so they re-render complete through the converter (`toolOutputs`).\n *\n * Inert until the head interest resolves: no row, no reads.\n */\nexport const StatewireHistoryEdge: FC<StatewireHistoryEdgeProps> = ({\n toolOutputs: toolOutputsProp,\n historyPages: historyPagesProp,\n className,\n onHistoryLoad,\n}) => {\n const providerToolOutputs = useStatewireToolOutputs();\n const toolOutputs = toolOutputsProp ?? providerToolOutputs ?? undefined;\n const providerHistoryPages = useStatewireHistoryPages();\n const historyPages =\n historyPagesProp === null ? undefined : (historyPagesProp ?? providerHistoryPages ?? undefined);\n const messages = useAuiState((s) => s.thread.messages);\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const [nearTop, setNearTop] = useState(false);\n const [nearTopEpoch, setNearTopEpoch] = useState(0);\n const nearTopRef = useRef(false);\n const [rowEl, setRowEl] = useState<HTMLElement | null>(null);\n // The scroll viewport the thread registered (assistant-ui's viewport store),\n // known even while the row renders nothing; the row's ancestor otherwise.\n const hasViewportStore = useThreadViewportStore({ optional: true }) !== null;\n const registeredViewport = useThreadViewport({\n optional: true,\n selector: (state: ThreadViewportState) => state.element.viewport,\n });\n const viewport =\n registeredViewport ?? rowEl?.closest<HTMLElement>(`[${THREAD_VIEWPORT_ATTR}]`) ?? null;\n const isMessageMounted = useMessagesNearViewport({\n viewport,\n hasViewport: hasViewportStore || viewport !== null,\n messages,\n });\n const historyStore = useContext(StatewireHistoryContext);\n const { hasOlder, canLoadOlder, loading, loadOlder } = useDeepAgentWindowSync({\n messages,\n toolOutputs,\n nearTop,\n nearTopEpoch,\n isMessageMounted,\n maxConcurrentToolOutputs: HISTORY_EDGE_TOOL_OUTPUT_CONCURRENCY,\n onHistoryLoad,\n historyPages,\n onError: (error, command) => {\n // Leaving the thread settles an in-flight read as lost: lifecycle, not a failure.\n if (error instanceof Error && isStatewireChannelTeardown(error)) return;\n console.warn(`[StatewireHistoryEdge] ${command} failed:`, error);\n },\n });\n\n // Other surfaces of the provider (the workbench's Shell pane) read where the\n // history stands; leaving the thread or unmounting withdraws the report.\n useEffect(() => {\n if (!historyStore || !threadId) return undefined;\n historyStore.set({ threadId, hasOlder, canLoadOlder, loading, loadOlder });\n return undefined;\n }, [historyStore, threadId, hasOlder, canLoadOlder, loading, loadOlder]);\n useEffect(() => {\n if (!historyStore || !threadId) return undefined;\n return () => {\n if (historyStore.get().threadId === threadId) historyStore.set(NO_STATEWIRE_HISTORY);\n };\n }, [historyStore, threadId]);\n\n // The row's own visibility is the near-top level: a level, not an edge, so\n // pages chain while the user stays at the top and stop once the prepended\n // content has pushed the row away again.\n useEffect(() => {\n if (!rowEl || !hasOlder || typeof IntersectionObserver === \"undefined\") return;\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const near = entry.isIntersecting;\n if (nearTopRef.current === near) continue;\n nearTopRef.current = near;\n setNearTop(near);\n if (near) setNearTopEpoch((epoch) => epoch + 1);\n }\n },\n {\n root: viewport,\n rootMargin: `${HISTORY_EDGE_NEAR_MARGIN_PX}px 0px`,\n },\n );\n observer.observe(rowEl);\n return () => {\n observer.disconnect();\n nearTopRef.current = false;\n setNearTop(false);\n };\n }, [rowEl, hasOlder, viewport]);\n\n return (\n <>\n <KeepReadingPlace viewport={viewport} threadId={threadId} messages={messages} />\n <HistoryEdgeRow\n rowRef={setRowEl}\n hasOlder={hasOlder}\n canLo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,qBAAA,UAAA,EACE,UAAA;AAAA,IAAA,oBAAC,kBAAA,EAAiB,UAAoB,UAAoB,SAAA,CAAoB;AAAA,IAC9E;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,QAAQ;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA,aAAa;AAAA,QACb;AAAA,MAAA;AAAA,IAAA;AAAA,EACF,GACF;AAEJ;"}
1
+ {"version":3,"file":"statewire-history-edge.js","sources":["../../../src/chat-ui/thread/statewire-history-edge.tsx"],"sourcesContent":["import {\n getExternalStoreMessages,\n type ThreadMessage,\n type ThreadViewportState,\n useAuiState,\n useThreadViewport,\n useThreadViewportStore,\n} from \"@assistant-ui/react\";\nimport {\n type DeepAgentHistoryLoadEvent,\n type DeepAgentToolOutputStore,\n isStatewireChannelTeardown,\n useDeepAgentWindowSync,\n} from \"@athenaintel/agent-runtime\";\nimport type { FC } from \"react\";\nimport { Component, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport {\n NO_STATEWIRE_HISTORY,\n StatewireHistoryContext,\n} from \"../../provider/statewire-history-context\";\nimport { useStatewireToolOutputs } from \"../../provider/statewire-window-context\";\nimport { AthenaStatewireThreadIdContext } from \"../../threads/thread-id-context\";\n\n/** The attribute `ChatThreadShell` stamps on the scroll viewport. */\nexport const THREAD_VIEWPORT_ATTR = \"data-aui-thread-viewport\";\n/** The attribute `ChatThreadShell` stamps on its sticky viewport footer (the composer dock). */\nexport const THREAD_VIEWPORT_FOOTER_ATTR = \"data-aui-thread-viewport-footer\";\n\n/**\n * How far above the viewport the edge row counts as near: the row sits above\n * the first loaded message, so reaching it means the user has scrolled past\n * everything loaded and the next page should already be on its way. Messages\n * this close to the viewport also count as on screen for cut tool outputs.\n */\nexport const HISTORY_EDGE_NEAR_MARGIN_PX = 1500;\n\n/**\n * Cut tool outputs a transcript reads at once. The reads share the session's\n * command lane with everything the person sends, so a long transcript must\n * not queue dozens of them ahead of a message or a Stop.\n */\nexport const HISTORY_EDGE_TOOL_OUTPUT_CONCURRENCY = 2;\n\n/** What assistant-ui's `MessagePrimitive.Root` stamps on every message. */\nconst MESSAGE_SELECTOR = \"[data-message-id]\";\n\nconst NO_MESSAGE_IDS: ReadonlySet<string> = new Set();\n\nfunction sameIds({ a, b }: { a: ReadonlySet<string>; b: ReadonlySet<string> }): boolean {\n if (a.size !== b.size) return false;\n for (const id of a) if (!b.has(id)) return false;\n return true;\n}\n\n/**\n * Which messages sit within {@link HISTORY_EDGE_NEAR_MARGIN_PX} of the\n * viewport, so cut tool outputs are read for what the person can reach. A\n * thread opens at its newest turn; reading every loaded step's output up\n * front sent dozens of reads, each re-rendering the transcript, for steps\n * nobody had scrolled to.\n *\n * `undefined` (every message counts) where nothing can be observed: no\n * viewport around the row, or no `IntersectionObserver`. A message rendered\n * without a `data-message-id` root (a host's own renderer) cannot be observed\n * either, so it counts as before.\n */\nfunction useMessagesNearViewport({\n viewport,\n hasViewport,\n messages,\n}: {\n viewport: HTMLElement | null;\n /** A viewport is (or will be) registered around the row. */\n hasViewport: boolean;\n /** The converted thread: every change may have mounted or remounted a message. */\n messages: readonly ThreadMessage[];\n}): ((messageId: string) => boolean) | undefined {\n const [nearIds, setNearIds] = useState<ReadonlySet<string>>(NO_MESSAGE_IDS);\n const observable = hasViewport && typeof IntersectionObserver !== \"undefined\";\n const trackRef = useRef<(() => void) | null>(null);\n // Every id a rendered element carries, as of the last scan.\n const renderedIdsRef = useRef<ReadonlySet<string>>(NO_MESSAGE_IDS);\n\n useEffect(() => {\n if (!viewport || !observable) return undefined;\n const near = new Set<Element>();\n const observed = new Set<Element>();\n const publish = () => {\n const ids = new Set<string>();\n for (const element of near) {\n const id = element.getAttribute(\"data-message-id\");\n if (id) ids.add(id);\n }\n setNearIds((previous) => (sameIds({ a: previous, b: ids }) ? previous : ids));\n };\n const intersections = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting && entry.target.isConnected) near.add(entry.target);\n else near.delete(entry.target);\n }\n publish();\n },\n { root: viewport, rootMargin: `${HISTORY_EDGE_NEAR_MARGIN_PX}px 0px` },\n );\n // A page that folds into a turn gives it a new id: a host keyed by id\n // remounts the turn's element, a host keyed by row (`ChatThreadShell`)\n // keeps it and the element's id changes. So what is observed follows the\n // rendered elements, not the message list, and the near ids are read off\n // those elements again on every scan.\n const track = () => {\n for (const element of observed) {\n if (element.isConnected) continue;\n intersections.unobserve(element);\n observed.delete(element);\n near.delete(element);\n }\n const rendered = new Set<string>();\n for (const element of viewport.querySelectorAll(MESSAGE_SELECTOR)) {\n const id = element.getAttribute(\"data-message-id\");\n if (id) rendered.add(id);\n if (observed.has(element)) continue;\n observed.add(element);\n intersections.observe(element);\n }\n renderedIdsRef.current = rendered;\n publish();\n };\n trackRef.current = track;\n track();\n return () => {\n trackRef.current = null;\n renderedIdsRef.current = NO_MESSAGE_IDS;\n intersections.disconnect();\n setNearIds(NO_MESSAGE_IDS);\n };\n }, [viewport, observable]);\n\n // A changed message list is the trigger to re-scan: its messages render in\n // the same commit, so their elements are in the DOM by this effect (a\n // query, no layout read).\n useEffect(() => {\n trackRef.current?.();\n }, [messages]);\n\n return useMemo(() => {\n if (!observable) return undefined;\n return (messageId: string) => {\n // Not registered yet: nothing is on screen to read for.\n if (viewport === null) return false;\n return nearIds.has(messageId) || !renderedIdsRef.current.has(messageId);\n };\n }, [nearIds, observable, viewport]);\n}\n\n/** The wire message a converted message was built from first (its oldest source). */\nfunction oldestSourceId(message: ThreadMessage): string | undefined {\n const source = getExternalStoreMessages<{ id?: unknown }>(message)[0];\n return typeof source?.id === \"string\" ? source.id : undefined;\n}\n\n/**\n * Whether older history landed ahead of what was loaded: the old first\n * message now sits further down (a page ahead of it), or the first message's\n * old oldest wire message now follows earlier ones (a page that folded into\n * the first loaded turn). A first message replaced in place — a branch picked\n * on it, an edit — is neither, and a run streaming at the tail never touches\n * the first message.\n */\nfunction prependedOlderHistory({\n previous,\n next,\n}: {\n previous: readonly ThreadMessage[];\n next: readonly ThreadMessage[];\n}): boolean {\n const previousFirst = previous[0];\n const nextFirst = next[0];\n if (previousFirst === undefined || nextFirst === undefined || previousFirst === nextFirst) return false;\n if (previousFirst.id !== nextFirst.id && next.some((message, index) => index > 0 && message.id === previousFirst.id)) {\n return true;\n }\n const previousOldest = oldestSourceId(previousFirst);\n if (previousOldest === undefined || previousOldest === oldestSourceId(nextFirst)) return false;\n return getExternalStoreMessages<{ id?: unknown }>(nextFirst).some(\n (source, index) => index > 0 && source?.id === previousOldest,\n );\n}\n\ninterface KeepReadingPlaceProps {\n viewport: HTMLElement | null;\n threadId: string | null;\n /** The converted thread. */\n messages: readonly ThreadMessage[];\n}\n\n/**\n * Keeps the reader's place when older history lands. Everything a page adds\n * sits above what the person is reading, so their distance from the bottom of\n * the transcript is what must survive. A class for `getSnapshotBeforeUpdate`:\n * the distance is read right before React applies the commit that renders the\n * page — the one moment it is exact, even for a scroll the browser has not\n * reported yet — and restored after it, instantly (never through the\n * viewport's smooth scrolling). Other commits read no layout.\n *\n * The browser's scroll anchoring and assistant-ui's prepend anchor aim at the\n * same position, so whichever ran first leaves this nothing to do; on its own\n * it covers what they miss: a reader at the very top (browsers never anchor\n * at scroll offset 0) and a page that folds into the first loaded turn of a\n * host that keys rows by message id (that message remounts under a new id,\n * taking the browser's anchor node with it; `ChatThreadShell` keeps the row).\n */\nclass KeepReadingPlace extends Component<KeepReadingPlaceProps> {\n getSnapshotBeforeUpdate(previous: Readonly<KeepReadingPlaceProps>): number | null {\n const { viewport, threadId, messages } = this.props;\n if (\n viewport === null ||\n viewport !== previous.viewport ||\n threadId !== previous.threadId ||\n messages === previous.messages ||\n !prependedOlderHistory({ previous: previous.messages, next: messages })\n ) {\n return null;\n }\n return viewport.scrollHeight - viewport.scrollTop;\n }\n\n componentDidUpdate(\n _previous: Readonly<KeepReadingPlaceProps>,\n _state: unknown,\n fromBottom: number | null,\n ): void {\n const { viewport } = this.props;\n if (viewport === null || fromBottom === null) return;\n const top = viewport.scrollHeight - fromBottom;\n if (Math.abs(viewport.scrollTop - top) >= 1) viewport.scrollTo({ top, behavior: \"instant\" });\n }\n\n render(): null {\n return null;\n }\n}\n\nexport interface HistoryEdgeRowProps {\n /** Whether the server holds messages older than the loaded window. */\n hasOlder: boolean;\n /** Whether the next page can be asked for; `false` with `hasOlder` is the connection's loading depth spent. Defaults to `hasOlder`. */\n canLoadOlder?: boolean;\n /** A page of older history is in flight. */\n loading: boolean;\n onLoadOlder: () => void;\n className?: string;\n /** The row element, for the viewport observer. */\n rowRef?: (element: HTMLElement | null) => void;\n}\n\n/**\n * The top edge of the LOADED history: a manual way to load the next page of\n * older messages, and the in-flight state. Renders nothing when the whole\n * transcript is loaded (or the head interest has not resolved).\n */\nexport const HistoryEdgeRow: FC<HistoryEdgeRowProps> = ({\n hasOlder,\n canLoadOlder = hasOlder,\n loading,\n onLoadOlder,\n className,\n rowRef,\n}) => {\n if (!hasOlder) return null;\n return (\n <div\n ref={rowRef}\n data-testid=\"thread-history-edge\"\n className={cn(\n \"mx-auto flex w-full max-w-(--thread-max-width) items-center justify-center py-1 text-xs text-muted-foreground\",\n className,\n )}\n >\n {loading ? (\n <span data-testid=\"thread-history-edge-loading\">Loading earlier messages…</span>\n ) : canLoadOlder ? (\n <button\n type=\"button\"\n data-testid=\"thread-history-edge-load\"\n onClick={onLoadOlder}\n className=\"rounded-lg px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n >\n Load earlier messages\n </button>\n ) : (\n <span data-testid=\"thread-history-edge-limit\">Earlier messages can't be loaded here</span>\n )}\n </div>\n );\n};\n\nexport interface StatewireHistoryEdgeProps {\n /**\n * The thread's tool-output store (the one its converter substitutes from).\n * Defaults to `AthenaProvider`'s; hosts mounting the runtime themselves pass\n * the store they gave `useDeepAgentRuntime({ toolOutputs })`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /**\n * @deprecated Ignored. Older history pages by command (`history/page`) on\n * every host that serves it, into the conversation's own store, which the\n * thread joins. A host that mounts the runtime itself provides the steps\n * control through `TurnStepsControlContext` (`EarlierStepsButton`), so a\n * summarized turn's rows can open its steps.\n */\n historyPages?: unknown;\n className?: string;\n /** A page interest resolved (telemetry). */\n onHistoryLoad?: (event: DeepAgentHistoryLoadEvent) => void;\n}\n\n/**\n * The client half of the interest window for a DOM thread — mounted once per\n * thread, inside the scroll viewport above the messages (`ChatThreadShell`'s\n * `beforeMessages` slot):\n *\n * - renders the \"Load earlier messages\" edge row and loads the next page when\n * the row comes near the viewport (scrolling up) or on its button, keeping\n * the reading position when the page lands above the view;\n * - fetches cut tool outputs whole for the cards near the viewport, a few at\n * a time, so they re-render complete through the converter (`toolOutputs`).\n *\n * Inert until the head interest resolves: no row, no reads.\n */\nexport const StatewireHistoryEdge: FC<StatewireHistoryEdgeProps> = ({\n toolOutputs: toolOutputsProp,\n className,\n onHistoryLoad,\n}) => {\n const providerToolOutputs = useStatewireToolOutputs();\n const toolOutputs = toolOutputsProp ?? providerToolOutputs ?? undefined;\n const messages = useAuiState((s) => s.thread.messages);\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const [nearTop, setNearTop] = useState(false);\n const [nearTopEpoch, setNearTopEpoch] = useState(0);\n const nearTopRef = useRef(false);\n const [rowEl, setRowEl] = useState<HTMLElement | null>(null);\n // The scroll viewport the thread registered (assistant-ui's viewport store),\n // known even while the row renders nothing; the row's ancestor otherwise.\n const hasViewportStore = useThreadViewportStore({ optional: true }) !== null;\n const registeredViewport = useThreadViewport({\n optional: true,\n selector: (state: ThreadViewportState) => state.element.viewport,\n });\n const viewport =\n registeredViewport ?? rowEl?.closest<HTMLElement>(`[${THREAD_VIEWPORT_ATTR}]`) ?? null;\n const isMessageMounted = useMessagesNearViewport({\n viewport,\n hasViewport: hasViewportStore || viewport !== null,\n messages,\n });\n const historyStore = useContext(StatewireHistoryContext);\n const { hasOlder, canLoadOlder, loading, loadOlder } = useDeepAgentWindowSync({\n messages,\n toolOutputs,\n nearTop,\n nearTopEpoch,\n isMessageMounted,\n maxConcurrentToolOutputs: HISTORY_EDGE_TOOL_OUTPUT_CONCURRENCY,\n onHistoryLoad,\n onError: (error, command) => {\n // Leaving the thread settles an in-flight read as lost: lifecycle, not a failure.\n if (error instanceof Error && isStatewireChannelTeardown(error)) return;\n console.warn(`[StatewireHistoryEdge] ${command} failed:`, error);\n },\n });\n\n // Other surfaces of the provider (the workbench's Shell pane) read where the\n // history stands; leaving the thread or unmounting withdraws the report.\n useEffect(() => {\n if (!historyStore || !threadId) return undefined;\n historyStore.set({ threadId, hasOlder, canLoadOlder, loading, loadOlder });\n return undefined;\n }, [historyStore, threadId, hasOlder, canLoadOlder, loading, loadOlder]);\n useEffect(() => {\n if (!historyStore || !threadId) return undefined;\n return () => {\n if (historyStore.get().threadId === threadId) historyStore.set(NO_STATEWIRE_HISTORY);\n };\n }, [historyStore, threadId]);\n\n // The row's own visibility is the near-top level: a level, not an edge, so\n // pages chain while the user stays at the top and stop once the prepended\n // content has pushed the row away again.\n useEffect(() => {\n if (!rowEl || !hasOlder || typeof IntersectionObserver === \"undefined\") return;\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const near = entry.isIntersecting;\n if (nearTopRef.current === near) continue;\n nearTopRef.current = near;\n setNearTop(near);\n if (near) setNearTopEpoch((epoch) => epoch + 1);\n }\n },\n {\n root: viewport,\n rootMargin: `${HISTORY_EDGE_NEAR_MARGIN_PX}px 0px`,\n },\n );\n observer.observe(rowEl);\n return () => {\n observer.disconnect();\n nearTopRef.current = false;\n setNearTop(false);\n };\n }, [rowEl, hasOlder, viewport]);\n\n return (\n <>\n <KeepReadingPlace viewport={viewport} threadId={threadId} messages={messages} />\n <HistoryEdgeRow\n rowRef={setRowEl}\n hasOlder={hasOlder}\n canLoadOlder={canLoadOlder}\n loading={loading}\n onLoadOlder={loadOlder}\n className={className}\n />\n </>\n );\n};\n"],"names":[],"mappings":";;;;;;;;;AAyBO,MAAM,uBAAu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AAAA,EACF,GACF;AAEJ;"}
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const SIGN_BACK_IN_DRAFT_KEY = "athena:sign-back-in-draft";
4
+ const SIGN_BACK_IN_DRAFT_TTL_MS = 10 * 60 * 1e3;
5
+ function isKeptDraft(value) {
6
+ if (!value || typeof value !== "object") return false;
7
+ const candidate = value;
8
+ return candidate.v === 1 && typeof candidate.principal === "string" && typeof candidate.threadId === "string" && typeof candidate.isNewChat === "boolean" && typeof candidate.text === "string" && typeof candidate.at === "number" && Number.isFinite(candidate.at);
9
+ }
10
+ function forgetKeptDraft() {
11
+ try {
12
+ window.sessionStorage.removeItem(SIGN_BACK_IN_DRAFT_KEY);
13
+ } catch {
14
+ }
15
+ }
16
+ function keepDraftForSignBackIn({
17
+ principal,
18
+ threadId,
19
+ isNewChat,
20
+ text,
21
+ now = Date.now()
22
+ }) {
23
+ if (typeof window === "undefined" || !principal || text.trim() === "") return;
24
+ const kept = { v: 1, principal, threadId, isNewChat, text, at: now };
25
+ try {
26
+ window.sessionStorage.setItem(SIGN_BACK_IN_DRAFT_KEY, JSON.stringify(kept));
27
+ } catch {
28
+ }
29
+ }
30
+ function takeDraftKeptForSignBackIn({
31
+ principal,
32
+ threadId,
33
+ isNewChat,
34
+ now = Date.now()
35
+ }) {
36
+ if (typeof window === "undefined" || !principal) return null;
37
+ let raw;
38
+ try {
39
+ raw = window.sessionStorage.getItem(SIGN_BACK_IN_DRAFT_KEY);
40
+ } catch {
41
+ return null;
42
+ }
43
+ if (raw === null) return null;
44
+ let kept;
45
+ try {
46
+ kept = JSON.parse(raw);
47
+ } catch {
48
+ kept = null;
49
+ }
50
+ if (!isKeptDraft(kept) || kept.principal !== principal || now - kept.at > SIGN_BACK_IN_DRAFT_TTL_MS || kept.at > now + 6e4) {
51
+ forgetKeptDraft();
52
+ return null;
53
+ }
54
+ const sameConversation = kept.isNewChat ? isNewChat : kept.threadId === threadId;
55
+ if (!sameConversation) return null;
56
+ forgetKeptDraft();
57
+ return kept.text;
58
+ }
59
+ exports.SIGN_BACK_IN_DRAFT_TTL_MS = SIGN_BACK_IN_DRAFT_TTL_MS;
60
+ exports.keepDraftForSignBackIn = keepDraftForSignBackIn;
61
+ exports.takeDraftKeptForSignBackIn = takeDraftKeptForSignBackIn;
62
+ //# sourceMappingURL=sign-back-in-draft.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-back-in-draft.cjs","sources":["../../src/composer/sign-back-in-draft.ts"],"sourcesContent":["/**\n * The composer's draft across the SDK's own trip through sign-in\n * (`auth/sign-back-in.ts`). Right before the page leaves, the draft is kept in\n * this tab's `sessionStorage`; when the page returns, it goes back into the\n * same conversation's composer, for the same person, once.\n *\n * Kept only for a known person (a sign-in provider above `AthenaProvider`\n * names them) and for {@link SIGN_BACK_IN_DRAFT_TTL_MS} at most. A draft kept\n * for someone else is deleted unread: whoever signs in next in this tab never\n * sees it.\n */\n\nconst SIGN_BACK_IN_DRAFT_KEY = 'athena:sign-back-in-draft';\n\n/** How long a kept draft waits for the page that returns. */\nexport const SIGN_BACK_IN_DRAFT_TTL_MS = 10 * 60 * 1000;\n\ninterface KeptDraft {\n v: 1;\n principal: string;\n threadId: string;\n /** A conversation not started yet: its id is new on every page, so it matches any new chat. */\n isNewChat: boolean;\n text: string;\n at: number;\n}\n\nfunction isKeptDraft(value: unknown): value is KeptDraft {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as Partial<Record<keyof KeptDraft, unknown>>;\n return (\n candidate.v === 1 &&\n typeof candidate.principal === 'string' &&\n typeof candidate.threadId === 'string' &&\n typeof candidate.isNewChat === 'boolean' &&\n typeof candidate.text === 'string' &&\n typeof candidate.at === 'number' &&\n Number.isFinite(candidate.at)\n );\n}\n\nfunction forgetKeptDraft(): void {\n try {\n window.sessionStorage.removeItem(SIGN_BACK_IN_DRAFT_KEY);\n } catch {\n // Nothing was kept where storage is unavailable.\n }\n}\n\n/** Keeps `text` for the page that returns from sign-in; nothing for an empty draft or an unknown person. */\nexport function keepDraftForSignBackIn({\n principal,\n threadId,\n isNewChat,\n text,\n now = Date.now(),\n}: {\n principal: string;\n threadId: string;\n isNewChat: boolean;\n text: string;\n /** Test seam. */\n now?: number;\n}): void {\n if (typeof window === 'undefined' || !principal || text.trim() === '') return;\n const kept: KeptDraft = { v: 1, principal, threadId, isNewChat, text, at: now };\n try {\n window.sessionStorage.setItem(SIGN_BACK_IN_DRAFT_KEY, JSON.stringify(kept));\n } catch {\n // Storage full or unavailable: the draft goes with the page, as it did before.\n }\n}\n\n/**\n * The draft kept for this person and conversation, read once (it is deleted),\n * or `null`. A draft kept for another conversation waits for that one; one\n * that is stale, unreadable, or kept for someone else is deleted unread.\n */\nexport function takeDraftKeptForSignBackIn({\n principal,\n threadId,\n isNewChat,\n now = Date.now(),\n}: {\n principal: string;\n threadId: string;\n isNewChat: boolean;\n /** Test seam. */\n now?: number;\n}): string | null {\n if (typeof window === 'undefined' || !principal) return null;\n let raw: string | null;\n try {\n raw = window.sessionStorage.getItem(SIGN_BACK_IN_DRAFT_KEY);\n } catch {\n return null;\n }\n if (raw === null) return null;\n let kept: unknown;\n try {\n kept = JSON.parse(raw);\n } catch {\n kept = null;\n }\n if (\n !isKeptDraft(kept) ||\n kept.principal !== principal ||\n now - kept.at > SIGN_BACK_IN_DRAFT_TTL_MS ||\n kept.at > now + 60_000\n ) {\n forgetKeptDraft();\n return null;\n }\n const sameConversation = kept.isNewChat ? isNewChat : kept.threadId === threadId;\n if (!sameConversation) return null;\n forgetKeptDraft();\n return kept.text;\n}\n"],"names":[],"mappings":";;AAYA,MAAM,yBAAyB;AAGxB,MAAM,4BAA4B,KAAK,KAAK;AAYnD,SAAS,YAAY,OAAoC;AACvD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAClB,SACE,UAAU,MAAM,KAChB,OAAO,UAAU,cAAc,YAC/B,OAAO,UAAU,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* The composer's draft across the SDK's own trip through sign-in
3
+ * (`auth/sign-back-in.ts`). Right before the page leaves, the draft is kept in
4
+ * this tab's `sessionStorage`; when the page returns, it goes back into the
5
+ * same conversation's composer, for the same person, once.
6
+ *
7
+ * Kept only for a known person (a sign-in provider above `AthenaProvider`
8
+ * names them) and for {@link SIGN_BACK_IN_DRAFT_TTL_MS} at most. A draft kept
9
+ * for someone else is deleted unread: whoever signs in next in this tab never
10
+ * sees it.
11
+ */
12
+ /** How long a kept draft waits for the page that returns. */
13
+ export declare const SIGN_BACK_IN_DRAFT_TTL_MS: number;
14
+ /** Keeps `text` for the page that returns from sign-in; nothing for an empty draft or an unknown person. */
15
+ export declare function keepDraftForSignBackIn({ principal, threadId, isNewChat, text, now, }: {
16
+ principal: string;
17
+ threadId: string;
18
+ isNewChat: boolean;
19
+ text: string;
20
+ /** Test seam. */
21
+ now?: number;
22
+ }): void;
23
+ /**
24
+ * The draft kept for this person and conversation, read once (it is deleted),
25
+ * or `null`. A draft kept for another conversation waits for that one; one
26
+ * that is stale, unreadable, or kept for someone else is deleted unread.
27
+ */
28
+ export declare function takeDraftKeptForSignBackIn({ principal, threadId, isNewChat, now, }: {
29
+ principal: string;
30
+ threadId: string;
31
+ isNewChat: boolean;
32
+ /** Test seam. */
33
+ now?: number;
34
+ }): string | null;
@@ -0,0 +1,62 @@
1
+ const SIGN_BACK_IN_DRAFT_KEY = "athena:sign-back-in-draft";
2
+ const SIGN_BACK_IN_DRAFT_TTL_MS = 10 * 60 * 1e3;
3
+ function isKeptDraft(value) {
4
+ if (!value || typeof value !== "object") return false;
5
+ const candidate = value;
6
+ return candidate.v === 1 && typeof candidate.principal === "string" && typeof candidate.threadId === "string" && typeof candidate.isNewChat === "boolean" && typeof candidate.text === "string" && typeof candidate.at === "number" && Number.isFinite(candidate.at);
7
+ }
8
+ function forgetKeptDraft() {
9
+ try {
10
+ window.sessionStorage.removeItem(SIGN_BACK_IN_DRAFT_KEY);
11
+ } catch {
12
+ }
13
+ }
14
+ function keepDraftForSignBackIn({
15
+ principal,
16
+ threadId,
17
+ isNewChat,
18
+ text,
19
+ now = Date.now()
20
+ }) {
21
+ if (typeof window === "undefined" || !principal || text.trim() === "") return;
22
+ const kept = { v: 1, principal, threadId, isNewChat, text, at: now };
23
+ try {
24
+ window.sessionStorage.setItem(SIGN_BACK_IN_DRAFT_KEY, JSON.stringify(kept));
25
+ } catch {
26
+ }
27
+ }
28
+ function takeDraftKeptForSignBackIn({
29
+ principal,
30
+ threadId,
31
+ isNewChat,
32
+ now = Date.now()
33
+ }) {
34
+ if (typeof window === "undefined" || !principal) return null;
35
+ let raw;
36
+ try {
37
+ raw = window.sessionStorage.getItem(SIGN_BACK_IN_DRAFT_KEY);
38
+ } catch {
39
+ return null;
40
+ }
41
+ if (raw === null) return null;
42
+ let kept;
43
+ try {
44
+ kept = JSON.parse(raw);
45
+ } catch {
46
+ kept = null;
47
+ }
48
+ if (!isKeptDraft(kept) || kept.principal !== principal || now - kept.at > SIGN_BACK_IN_DRAFT_TTL_MS || kept.at > now + 6e4) {
49
+ forgetKeptDraft();
50
+ return null;
51
+ }
52
+ const sameConversation = kept.isNewChat ? isNewChat : kept.threadId === threadId;
53
+ if (!sameConversation) return null;
54
+ forgetKeptDraft();
55
+ return kept.text;
56
+ }
57
+ export {
58
+ SIGN_BACK_IN_DRAFT_TTL_MS,
59
+ keepDraftForSignBackIn,
60
+ takeDraftKeptForSignBackIn
61
+ };
62
+ //# sourceMappingURL=sign-back-in-draft.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-back-in-draft.js","sources":["../../src/composer/sign-back-in-draft.ts"],"sourcesContent":["/**\n * The composer's draft across the SDK's own trip through sign-in\n * (`auth/sign-back-in.ts`). Right before the page leaves, the draft is kept in\n * this tab's `sessionStorage`; when the page returns, it goes back into the\n * same conversation's composer, for the same person, once.\n *\n * Kept only for a known person (a sign-in provider above `AthenaProvider`\n * names them) and for {@link SIGN_BACK_IN_DRAFT_TTL_MS} at most. A draft kept\n * for someone else is deleted unread: whoever signs in next in this tab never\n * sees it.\n */\n\nconst SIGN_BACK_IN_DRAFT_KEY = 'athena:sign-back-in-draft';\n\n/** How long a kept draft waits for the page that returns. */\nexport const SIGN_BACK_IN_DRAFT_TTL_MS = 10 * 60 * 1000;\n\ninterface KeptDraft {\n v: 1;\n principal: string;\n threadId: string;\n /** A conversation not started yet: its id is new on every page, so it matches any new chat. */\n isNewChat: boolean;\n text: string;\n at: number;\n}\n\nfunction isKeptDraft(value: unknown): value is KeptDraft {\n if (!value || typeof value !== 'object') return false;\n const candidate = value as Partial<Record<keyof KeptDraft, unknown>>;\n return (\n candidate.v === 1 &&\n typeof candidate.principal === 'string' &&\n typeof candidate.threadId === 'string' &&\n typeof candidate.isNewChat === 'boolean' &&\n typeof candidate.text === 'string' &&\n typeof candidate.at === 'number' &&\n Number.isFinite(candidate.at)\n );\n}\n\nfunction forgetKeptDraft(): void {\n try {\n window.sessionStorage.removeItem(SIGN_BACK_IN_DRAFT_KEY);\n } catch {\n // Nothing was kept where storage is unavailable.\n }\n}\n\n/** Keeps `text` for the page that returns from sign-in; nothing for an empty draft or an unknown person. */\nexport function keepDraftForSignBackIn({\n principal,\n threadId,\n isNewChat,\n text,\n now = Date.now(),\n}: {\n principal: string;\n threadId: string;\n isNewChat: boolean;\n text: string;\n /** Test seam. */\n now?: number;\n}): void {\n if (typeof window === 'undefined' || !principal || text.trim() === '') return;\n const kept: KeptDraft = { v: 1, principal, threadId, isNewChat, text, at: now };\n try {\n window.sessionStorage.setItem(SIGN_BACK_IN_DRAFT_KEY, JSON.stringify(kept));\n } catch {\n // Storage full or unavailable: the draft goes with the page, as it did before.\n }\n}\n\n/**\n * The draft kept for this person and conversation, read once (it is deleted),\n * or `null`. A draft kept for another conversation waits for that one; one\n * that is stale, unreadable, or kept for someone else is deleted unread.\n */\nexport function takeDraftKeptForSignBackIn({\n principal,\n threadId,\n isNewChat,\n now = Date.now(),\n}: {\n principal: string;\n threadId: string;\n isNewChat: boolean;\n /** Test seam. */\n now?: number;\n}): string | null {\n if (typeof window === 'undefined' || !principal) return null;\n let raw: string | null;\n try {\n raw = window.sessionStorage.getItem(SIGN_BACK_IN_DRAFT_KEY);\n } catch {\n return null;\n }\n if (raw === null) return null;\n let kept: unknown;\n try {\n kept = JSON.parse(raw);\n } catch {\n kept = null;\n }\n if (\n !isKeptDraft(kept) ||\n kept.principal !== principal ||\n now - kept.at > SIGN_BACK_IN_DRAFT_TTL_MS ||\n kept.at > now + 60_000\n ) {\n forgetKeptDraft();\n return null;\n }\n const sameConversation = kept.isNewChat ? isNewChat : kept.threadId === threadId;\n if (!sameConversation) return null;\n forgetKeptDraft();\n return kept.text;\n}\n"],"names":[],"mappings":"AAYA,MAAM,yBAAyB;AAGxB,MAAM,4BAA4B,KAAK,KAAK;AAYnD,SAAS,YAAY,OAAoC;AACvD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAClB,SACE,UAAU,MAAM,KAChB,OAAO,UAAU,cAAc,YAC/B,OAAO,UAAU,aAAa,YAC9B,OAAO,UAAU,cAAc,aAC/B,OAAO,UAAU,SAAS,YAC1B,OAAO,UAAU,OAAO,YACxB,OAAO,SAAS,UAAU,EAAE;AAEhC;AAEA,SAAS,kBAAwB;AAC/B,MAAI;AACF,WAAO,eAAe,WAAW,sBAAsB;AAAA,EACzD,QAAQ;AAAA,EAER;AACF;AAGO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAM,KAAK,IAAA;AACb,GAOS;AACP,MAAI,OAAO,WAAW,eAAe,CAAC,aAAa,KAAK,KAAA,MAAW,GAAI;AACvE,QAAM,OAAkB,EAAE,GAAG,GAAG,WAAW,UAAU,WAAW,MAAM,IAAI,IAAA;AAC1E,MAAI;AACF,WAAO,eAAe,QAAQ,wBAAwB,KAAK,UAAU,IAAI,CAAC;AAAA,EAC5E,QAAQ;AAAA,EAER;AACF;AAOO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAM,KAAK,IAAA;AACb,GAMkB;AAChB,MAAI,OAAO,WAAW,eAAe,CAAC,UAAW,QAAO;AACxD,MAAI;AACJ,MAAI;AACF,UAAM,OAAO,eAAe,QAAQ,sBAAsB;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,KAAM,QAAO;AACzB,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MACE,CAAC,YAAY,IAAI,KACjB,KAAK,cAAc,aACnB,MAAM,KAAK,KAAK,6BAChB,KAAK,KAAK,MAAM,KAChB;AACA,oBAAA;AACA,WAAO;AAAA,EACT;AACA,QAAM,mBAAmB,KAAK,YAAY,YAAY,KAAK,aAAa;AACxE,MAAI,CAAC,iBAAkB,QAAO;AAC9B,kBAAA;AACA,SAAO,KAAK;AACd;"}
@@ -1 +1 @@
1
- {"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n | 'voice.chat'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":["toAthenaSdkError","ATHENA_REACT_SDK_VERSION","isAthenaSdkError","getPostHogInstance","capturePosthogEvent"],"mappings":";;;;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA2GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5F,OAAO;AACL,UAAI,GAAG,IAAI;AAAA,IACb;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aACpE,YAAY,QACZ,KAAK,IAAA;AACX;AAEA,SAAS,sBAAoD;AAC3D,MAAI;AACF,QAAI,OAAO,iBAAiB,YAAa,QAAO;AAChD,UAAM,MAAM,aAAa,QAAQ,uBAAuB;AACxD,QAAI,CAAC,IAAK,QAAO;AACjB,QAAK,yBAA+C,SAAS,GAAG,GAAG;AACjE,aAAO;AAAA,IACT;A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AM,oBAAoB,IAAI,qBAAA;AAO9B,SAAS,iCAAuC;AACrD,MAAI,OAAO,WAAW,YAAa;AACnC,QAAM,eAAe;AACrB,QAAM,WAAY,aAAa,UAAU,KAAK,CAAA;AAC9C,eAAa,UAAU,IAAI;AAAA,IACzB,GAAG;AAAA,IACH,SAASA,QAAAA;AAAAA,IACT,aAAa;AAAA,MACX,UAAU,MAAM,kBAAkB,SAAA;AAAA,MAClC,QAAQ,MAAM,kBAAkB,OAAA;AAAA,MAChC,OAAO,MAAM,kBAAkB,MAAA;AAAA,MAC/B,eAAe,CAAC,QAA+B,YAAY;AACzD,YAAI;AACF,uBAAa,QAAQ,yBAAyB,KAAK;AAAA,QACrD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,MACA,gBAAgB,MAAM;AACpB,YAAI;AACF,uBAAa,WAAW,uBAAuB;AAAA,QACjD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,IAAA;AAAA,EACF;AAEJ;AAGO,SAAS,6BACd,OACkC;AAClC,MAAI,UAAU,OAAW,QAAO,CAAA;AAChC,MAAI,UAAU,KAAM,QAAO,EAAE,SAAS,QAAA;AACtC,MAAI,UAAU,MAAO,QAAO,EAAE,SAAS,MAAA;AACvC,MAAI,OAAO,UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;;;;;"}
1
+ {"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n /**\n * A session the page held ended (a 401 or 403 on a renewal): `sign_back_in`\n * says whether the page then went through sign-in on its own (`sign-back-in.ts`).\n */\n | 'auth.session.ended'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n | 'voice.chat'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":["toAthenaSdkError","ATHENA_REACT_SDK_VERSION","isAthenaSdkError","getPostHogInstance","capturePosthogEvent"],"mappings":";;;;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAgHA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IA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AI,OAAO,UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;;;;;"}
@@ -27,7 +27,12 @@ export type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];
27
27
  * are part of the public contract: renaming one is a breaking change for
28
28
  * dashboards, so add new ones instead of repurposing.
29
29
  */
30
- export type AthenaDiagnosticEventName = 'sdk.init' | 'sdk.transport' | 'sdk.config.warning' | 'auth.bridge.start' | 'auth.bridge.ready' | 'auth.bridge.timeout' | 'auth.bridge.absent' | 'auth.bridge.error' | 'auth.bridge.retry' | 'auth.bridge.config_rejected' | 'auth.token.acquired' | 'auth.token.refreshed' | 'auth.token.refresh_failed' | 'auth.token.stale' | 'auth.sso.userinfo.start' | 'auth.sso.userinfo.done' | 'auth.sso.userinfo.error' | 'auth.sso.userinfo.retry' | 'threads.list.start' | 'threads.list.done' | 'threads.list.error' | 'threads.list.aborted' | 'threads.history.start' | 'threads.history.done' | 'threads.history.error' | 'threads.history.aborted' | 'statewire.attach.start' | 'statewire.snapshot' | 'statewire.connection' | 'statewire.parked' | 'statewire.error' | 'statewire.read_only'
30
+ export type AthenaDiagnosticEventName = 'sdk.init' | 'sdk.transport' | 'sdk.config.warning' | 'auth.bridge.start' | 'auth.bridge.ready' | 'auth.bridge.timeout' | 'auth.bridge.absent' | 'auth.bridge.error' | 'auth.bridge.retry' | 'auth.bridge.config_rejected' | 'auth.token.acquired' | 'auth.token.refreshed' | 'auth.token.refresh_failed' | 'auth.token.stale' | 'auth.sso.userinfo.start' | 'auth.sso.userinfo.done' | 'auth.sso.userinfo.error' | 'auth.sso.userinfo.retry'
31
+ /**
32
+ * A session the page held ended (a 401 or 403 on a renewal): `sign_back_in`
33
+ * says whether the page then went through sign-in on its own (`sign-back-in.ts`).
34
+ */
35
+ | 'auth.session.ended' | 'threads.list.start' | 'threads.list.done' | 'threads.list.error' | 'threads.list.aborted' | 'threads.history.start' | 'threads.history.done' | 'threads.history.error' | 'threads.history.aborted' | 'statewire.attach.start' | 'statewire.snapshot' | 'statewire.connection' | 'statewire.parked' | 'statewire.error' | 'statewire.read_only'
31
36
  /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */
32
37
  | 'statewire.config' | 'run.send' | 'run.first_token' | 'run.done' | 'run.error' | 'composer.attachment.error'
33
38
  /** Files offered while Athena can't be reached were not attached (they could not upload). */
@@ -1 +1 @@
1
- {"version":3,"file":"athena-diagnostics.js","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n | 'voice.chat'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":[],"mappings":";;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA2GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EAC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;AACpB,YAAI;AACF,uBAAa,WAAW,uBAAuB;AAAA,QACjD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,IAAA;AAAA,EACF;AAEJ;AAGO,SAAS,6BACd,OACkC;AAClC,MAAI,UAAU,OAAW,QAAO,CAAA;AAChC,MAAI,UAAU,KAAM,QAAO,EAAE,SAAS,QAAA;AACtC,MAAI,UAAU,MAAO,QAAO,EAAE,SAAS,MAAA;AACvC,MAAI,OAAO,UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;"}
1
+ {"version":3,"file":"athena-diagnostics.js","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n /**\n * A session the page held ended (a 401 or 403 on a renewal): `sign_back_in`\n * says whether the page then went through sign-in on its own (`sign-back-in.ts`).\n */\n | 'auth.session.ended'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n | 'voice.chat'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console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