@athenaintel/react 0.42.1 → 0.42.2

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 (96) hide show
  1. package/README.md +36 -7
  2. package/dist/agent-runtime/src/index.d.ts +2 -2
  3. package/dist/agent-runtime/src/messages.cjs +38 -7
  4. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  5. package/dist/agent-runtime/src/messages.d.ts +26 -8
  6. package/dist/agent-runtime/src/messages.js +38 -7
  7. package/dist/agent-runtime/src/messages.js.map +1 -1
  8. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs +10 -0
  9. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  10. package/dist/agent-runtime/src/quota-safe-local-storage-session.d.ts +7 -0
  11. package/dist/agent-runtime/src/quota-safe-local-storage-session.js +10 -0
  12. package/dist/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
  13. package/dist/agent-runtime/src/session-lane-scope.cjs +25 -0
  14. package/dist/agent-runtime/src/session-lane-scope.cjs.map +1 -0
  15. package/dist/agent-runtime/src/session-lane-scope.d.ts +59 -0
  16. package/dist/agent-runtime/src/session-lane-scope.js +25 -0
  17. package/dist/agent-runtime/src/session-lane-scope.js.map +1 -0
  18. package/dist/agent-runtime/src/subagent-transcripts.cjs +2 -2
  19. package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
  20. package/dist/agent-runtime/src/subagent-transcripts.d.ts +2 -2
  21. package/dist/agent-runtime/src/subagent-transcripts.js +3 -3
  22. package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
  23. package/dist/agent-runtime/src/tool-names.cjs +4 -0
  24. package/dist/agent-runtime/src/tool-names.cjs.map +1 -1
  25. package/dist/agent-runtime/src/tool-names.d.ts +7 -0
  26. package/dist/agent-runtime/src/tool-names.js +4 -0
  27. package/dist/agent-runtime/src/tool-names.js.map +1 -1
  28. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs +18 -1
  29. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  30. package/dist/agent-runtime/src/use-deep-agent-runtime.d.ts +19 -10
  31. package/dist/agent-runtime/src/use-deep-agent-runtime.js +19 -2
  32. package/dist/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
  33. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +28 -10
  34. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  35. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +35 -3
  36. package/dist/agent-runtime/src/use-deep-agent-thread.js +28 -10
  37. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  38. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +20 -0
  39. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -1
  40. package/dist/agent-runtime/src/use-deep-agent-voice.js +20 -0
  41. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -1
  42. package/dist/agent-runtime/src/voice-presentation.cjs +2 -0
  43. package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
  44. package/dist/agent-runtime/src/voice-presentation.js +2 -0
  45. package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
  46. package/dist/catalog/runtime-catalog.js +1 -1
  47. package/dist/chat/AthenaChat.cjs +125 -103
  48. package/dist/chat/AthenaChat.cjs.map +1 -1
  49. package/dist/chat/AthenaChat.d.ts +9 -0
  50. package/dist/chat/AthenaChat.js +126 -104
  51. package/dist/chat/AthenaChat.js.map +1 -1
  52. package/dist/chat/chat-voice-controls.cjs +128 -0
  53. package/dist/chat/chat-voice-controls.cjs.map +1 -0
  54. package/dist/chat/chat-voice-controls.d.ts +19 -0
  55. package/dist/chat/chat-voice-controls.js +128 -0
  56. package/dist/chat/chat-voice-controls.js.map +1 -0
  57. package/dist/chat/use-statewire-approval-request.js +1 -1
  58. package/dist/chat-ui/composer/tiptap-composer.cjs +42 -22
  59. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  60. package/dist/chat-ui/composer/tiptap-composer.d.ts +1 -0
  61. package/dist/chat-ui/composer/tiptap-composer.js +43 -23
  62. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  63. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +2 -1
  64. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  65. package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +3 -1
  66. package/dist/chat-ui/mentions/suggestions/data/api-client.js +2 -1
  67. package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
  68. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +29 -51
  69. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
  70. package/dist/chat-ui/mentions/use-account-workspace-id.d.ts +2 -2
  71. package/dist/chat-ui/mentions/use-account-workspace-id.js +30 -52
  72. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
  73. package/dist/chat-ui/thread/composer-send-or-stop.cjs +2 -1
  74. package/dist/chat-ui/thread/composer-send-or-stop.cjs.map +1 -1
  75. package/dist/chat-ui/thread/composer-send-or-stop.d.ts +2 -0
  76. package/dist/chat-ui/thread/composer-send-or-stop.js +2 -1
  77. package/dist/chat-ui/thread/composer-send-or-stop.js.map +1 -1
  78. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  79. package/dist/diagnostics/athena-diagnostics.d.ts +1 -1
  80. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  81. package/dist/index.d.ts +1 -1
  82. package/dist/react/package.json.cjs +1 -1
  83. package/dist/react/package.json.js +1 -1
  84. package/dist/runtime/statewire-session-key.cjs.map +1 -1
  85. package/dist/runtime/statewire-session-key.d.ts +8 -5
  86. package/dist/runtime/statewire-session-key.js.map +1 -1
  87. package/dist/runtime/useAthenaStatewireRuntime.cjs +5 -2
  88. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  89. package/dist/runtime/useAthenaStatewireRuntime.js +5 -2
  90. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  91. package/dist/voice/use-chat-voice-enabled.cjs +43 -0
  92. package/dist/voice/use-chat-voice-enabled.cjs.map +1 -0
  93. package/dist/voice/use-chat-voice-enabled.d.ts +9 -0
  94. package/dist/voice/use-chat-voice-enabled.js +43 -0
  95. package/dist/voice/use-chat-voice-enabled.js.map +1 -0
  96. package/package.json +4 -8
@@ -1,59 +1,37 @@
1
- import { useState, useEffect } from "react";
1
+ import { useQuery } from "@tanstack/react-query";
2
+ import { useId } from "react";
3
+ import { useCatalogQueryClient, credentialFingerprint } from "../../catalog/runtime-catalog.js";
2
4
  import { withCredentialRenewal } from "../../runtime/credential-renewal.js";
3
5
  import { fetchAccountIdentity } from "../../threads/api.js";
4
- const workspaceIdRequests = /* @__PURE__ */ new Map();
5
- function loadWorkspaceId(auth) {
6
- if (auth.workspaceId) return Promise.resolve(auth.workspaceId);
7
- const cacheKey = `${auth.backendUrl}|${auth.userId ?? ""}`;
8
- const cached = workspaceIdRequests.get(cacheKey);
9
- if (cached) return cached;
10
- const request = withCredentialRenewal(
11
- async ({ force } = {}) => {
12
- var _a, _b;
13
- return {
14
- token: (force ? await ((_a = auth.renewAccessToken) == null ? void 0 : _a.call(auth)) : await ((_b = auth.getAccessToken) == null ? void 0 : _b.call(auth))) ?? auth.accessToken ?? null,
15
- apiKey: auth.apiKey,
16
- credentials: auth.credentials
17
- };
18
- },
19
- (credential) => fetchAccountIdentity(auth.backendUrl, credential)
20
- ).then((identity) => identity.workspaceId ?? void 0).catch((error) => {
21
- if (workspaceIdRequests.get(cacheKey) === request) {
22
- workspaceIdRequests.delete(cacheKey);
23
- }
24
- throw error;
25
- });
26
- workspaceIdRequests.set(cacheKey, request);
27
- return request;
28
- }
29
6
  function useAccountWorkspaceId(auth) {
30
- const cacheKey = auth ? `${auth.backendUrl}|${auth.userId ?? ""}` : void 0;
31
- const [resolvedWorkspace, setResolvedWorkspace] = useState();
32
- useEffect(() => {
33
- if (!auth || !cacheKey) {
34
- setResolvedWorkspace(void 0);
35
- return void 0;
36
- }
37
- if (auth.workspaceId) {
38
- setResolvedWorkspace({ cacheKey, workspaceId: auth.workspaceId });
39
- return void 0;
40
- }
41
- let cancelled = false;
42
- setResolvedWorkspace(void 0);
43
- loadWorkspaceId(auth).then(
44
- (workspaceId) => {
45
- if (!cancelled) setResolvedWorkspace({ cacheKey, workspaceId });
7
+ const queryClient = useCatalogQueryClient();
8
+ const anonymousScope = useId();
9
+ const principal = (auth == null ? void 0 : auth.apiKey) ? `key:${credentialFingerprint({ credential: auth.apiKey })}` : (auth == null ? void 0 : auth.userId) ?? ((auth == null ? void 0 : auth.accessToken) ? `token:${credentialFingerprint({ credential: auth.accessToken })}` : anonymousScope);
10
+ const query = useQuery(
11
+ {
12
+ queryKey: ["athena-sdk", "account-workspace", auth == null ? void 0 : auth.backendUrl, auth == null ? void 0 : auth.userId, principal],
13
+ queryFn: async ({ signal }) => {
14
+ if (!auth) return null;
15
+ const identity = await withCredentialRenewal(
16
+ async ({ force } = {}) => {
17
+ var _a, _b;
18
+ return {
19
+ token: (force ? await ((_a = auth.renewAccessToken) == null ? void 0 : _a.call(auth)) : await ((_b = auth.getAccessToken) == null ? void 0 : _b.call(auth))) ?? auth.accessToken ?? null,
20
+ apiKey: auth.apiKey,
21
+ credentials: auth.credentials
22
+ };
23
+ },
24
+ (resolved) => fetchAccountIdentity(auth.backendUrl, resolved, { signal })
25
+ );
26
+ return identity.workspaceId ?? null;
46
27
  },
47
- () => {
48
- if (!cancelled) setResolvedWorkspace({ cacheKey, workspaceId: void 0 });
49
- }
50
- );
51
- return () => {
52
- cancelled = true;
53
- };
54
- }, [auth, cacheKey]);
55
- if (auth == null ? void 0 : auth.workspaceId) return auth.workspaceId;
56
- return cacheKey && (resolvedWorkspace == null ? void 0 : resolvedWorkspace.cacheKey) === cacheKey ? resolvedWorkspace.workspaceId : void 0;
28
+ enabled: auth !== null && !auth.workspaceId,
29
+ retry: false,
30
+ staleTime: 6e4
31
+ },
32
+ queryClient
33
+ );
34
+ return (auth == null ? void 0 : auth.workspaceId) ?? query.data ?? void 0;
57
35
  }
58
36
  export {
59
37
  useAccountWorkspaceId
@@ -1 +1 @@
1
- {"version":3,"file":"use-account-workspace-id.js","sources":["../../../src/chat-ui/mentions/use-account-workspace-id.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\nimport { withCredentialRenewal } from \"../../runtime/credential-renewal\";\nimport { fetchAccountIdentity } from \"../../threads/api\";\nimport type { MentionAuthContext } from \"./suggestions/data/api-client\";\n\nconst workspaceIdRequests = new Map<string, Promise<string | undefined>>();\n\nfunction loadWorkspaceId(auth: MentionAuthContext): Promise<string | undefined> {\n if (auth.workspaceId) return Promise.resolve(auth.workspaceId);\n\n const cacheKey = `${auth.backendUrl}|${auth.userId ?? \"\"}`;\n const cached = workspaceIdRequests.get(cacheKey);\n if (cached) return cached;\n\n const request = withCredentialRenewal(\n async ({ force }: { force?: boolean } = {}) => ({\n token: (force ? await auth.renewAccessToken?.() : await auth.getAccessToken?.()) ?? auth.accessToken ?? null,\n apiKey: auth.apiKey,\n credentials: auth.credentials,\n }),\n (credential) => fetchAccountIdentity(auth.backendUrl, credential),\n )\n .then((identity) => identity.workspaceId ?? undefined)\n .catch((error: unknown) => {\n if (workspaceIdRequests.get(cacheKey) === request) {\n workspaceIdRequests.delete(cacheKey);\n }\n throw error;\n });\n\n workspaceIdRequests.set(cacheKey, request);\n return request;\n}\n\nexport function useAccountWorkspaceId(auth: MentionAuthContext | null): string | undefined {\n const cacheKey = auth ? `${auth.backendUrl}|${auth.userId ?? \"\"}` : undefined;\n const [resolvedWorkspace, setResolvedWorkspace] = useState<{\n cacheKey: string;\n workspaceId: string | undefined;\n }>();\n\n useEffect(() => {\n if (!auth || !cacheKey) {\n setResolvedWorkspace(undefined);\n return undefined;\n }\n if (auth.workspaceId) {\n setResolvedWorkspace({ cacheKey, workspaceId: auth.workspaceId });\n return undefined;\n }\n\n let cancelled = false;\n setResolvedWorkspace(undefined);\n loadWorkspaceId(auth).then(\n (workspaceId) => {\n if (!cancelled) setResolvedWorkspace({ cacheKey, workspaceId });\n },\n () => {\n if (!cancelled) setResolvedWorkspace({ cacheKey, workspaceId: undefined });\n },\n );\n\n return () => {\n cancelled = true;\n };\n }, [auth, cacheKey]);\n\n if (auth?.workspaceId) return auth.workspaceId;\n return cacheKey && resolvedWorkspace?.cacheKey === cacheKey ? resolvedWorkspace.workspaceId : undefined;\n}\n\nexport function resetAccountWorkspaceIdForTests(): void {\n workspaceIdRequests.clear();\n}\n"],"names":[],"mappings":";;;AAKA,MAAM,0CAA0B,IAAA;AAEhC,SAAS,gBAAgB,MAAuD;AAC9E,MAAI,KAAK,YAAa,QAAO,QAAQ,QAAQ,KAAK,WAAW;AAE7D,QAAM,WAAW,GAAG,KAAK,UAAU,IAAI,KAAK,UAAU,EAAE;AACxD,QAAM,SAAS,oBAAoB,IAAI,QAAQ;AAC/C,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU;AAAA,IACd,OAAO,EAAE,MAAA,IAA+B,OAAC;;AAAO;AAAA,QAC9C,QAAQ,QAAQ,QAAM,UAAK,qBAAL,iCAA4B,QAAM,UAAK,mBAAL,mCAA4B,KAAK,eAAe;AAAA,QACxG,QAAQ,KAAK;AAAA,QACb,aAAa,KAAK;AAAA,MAAA;AAAA;AAAA,IAEpB,CAAC,eAAe,qBAAqB,KAAK,YAAY,UAAU;AAAA,EAAA,EAE/D,KAAK,CAAC,aAAa,SAAS,eAAe,MAAS,EACpD,MAAM,CAAC,UAAmB;AACzB,QAAI,oBAAoB,IAAI,QAAQ,MAAM,SAAS;AACjD,0BAAoB,OAAO,QAAQ;AAAA,IACrC;AACA,UAAM;AAAA,EACR,CAAC;AAEH,sBAAoB,IAAI,UAAU,OAAO;AACzC,SAAO;AACT;AAEO,SAAS,sBAAsB,MAAqD;AACzF,QAAM,WAAW,OAAO,GAAG,KAAK,UAAU,IAAI,KAAK,UAAU,EAAE,KAAK;AACpE,QAAM,CAAC,mBAAmB,oBAAoB,IAAI,SAAA;AAKlD,YAAU,MAAM;AACd,QAAI,CAAC,QAAQ,CAAC,UAAU;AACtB,2BAAqB,MAAS;AAC9B,aAAO;AAAA,IACT;AACA,QAAI,KAAK,aAAa;AACpB,2BAAqB,EAAE,UAAU,aAAa,KAAK,aAAa;AAChE,aAAO;AAAA,IACT;AAEA,QAAI,YAAY;AAChB,yBAAqB,MAAS;AAC9B,oBAAgB,IAAI,EAAE;AAAA,MACpB,CAAC,gBAAgB;AACf,YAAI,CAAC,UAAW,sBAAqB,EAAE,UAAU,aAAa;AAAA,MAChE;AAAA,MACA,MAAM;AACJ,YAAI,CAAC,UAAW,sBAAqB,EAAE,UAAU,aAAa,QAAW;AAAA,MAC3E;AAAA,IAAA;AAGF,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,MAAI,6BAAM,YAAa,QAAO,KAAK;AACnC,SAAO,aAAY,uDAAmB,cAAa,WAAW,kBAAkB,cAAc;AAChG;"}
1
+ {"version":3,"file":"use-account-workspace-id.js","sources":["../../../src/chat-ui/mentions/use-account-workspace-id.ts"],"sourcesContent":["import { useQuery } from '@tanstack/react-query';\nimport { useId } from 'react';\nimport { credentialFingerprint, useCatalogQueryClient } from '../../catalog/runtime-catalog';\nimport { withCredentialRenewal } from '../../runtime/credential-renewal';\nimport { fetchAccountIdentity } from '../../threads/api';\nimport type { MentionAuthContext } from './suggestions/data/api-client';\n\n/** Account identity uses the host's query cache and never a process-wide user-id map. */\nexport function useAccountWorkspaceId(auth: MentionAuthContext | null): string | undefined {\n const queryClient = useCatalogQueryClient();\n const anonymousScope = useId();\n // A workspace API key wins even when the person is known; a bearer can\n // rotate without changing that person's cache identity.\n const principal = auth?.apiKey\n ? `key:${credentialFingerprint({ credential: auth.apiKey })}`\n : auth?.userId ??\n (auth?.accessToken\n ? `token:${credentialFingerprint({ credential: auth.accessToken })}`\n : anonymousScope);\n const query = useQuery(\n {\n queryKey: ['athena-sdk', 'account-workspace', auth?.backendUrl, auth?.userId, principal],\n queryFn: async ({ signal }) => {\n if (!auth) return null;\n const identity = await withCredentialRenewal(\n async ({ force }: { force?: boolean } = {}) => ({\n token:\n (force ? await auth.renewAccessToken?.() : await auth.getAccessToken?.()) ??\n auth.accessToken ??\n null,\n apiKey: auth.apiKey,\n credentials: auth.credentials,\n }),\n (resolved) => fetchAccountIdentity(auth.backendUrl, resolved, { signal })\n );\n return identity.workspaceId ?? null;\n },\n enabled: auth !== null && !auth.workspaceId,\n retry: false,\n staleTime: 60_000,\n },\n queryClient\n );\n return auth?.workspaceId ?? query.data ?? undefined;\n}\n"],"names":[],"mappings":";;;;;AAQO,SAAS,sBAAsB,MAAqD;AACzF,QAAM,cAAc,sBAAA;AACpB,QAAM,iBAAiB,MAAA;AAGvB,QAAM,aAAY,6BAAM,UACpB,OAAO,sBAAsB,EAAE,YAAY,KAAK,OAAA,CAAQ,CAAC,MACzD,6BAAM,aACL,6BAAM,eACH,SAAS,sBAAsB,EAAE,YAAY,KAAK,YAAA,CAAa,CAAC,KAChE;AACR,QAAM,QAAQ;AAAA,IACZ;AAAA,MACE,UAAU,CAAC,cAAc,qBAAqB,6BAAM,YAAY,6BAAM,QAAQ,SAAS;AAAA,MACvF,SAAS,OAAO,EAAE,aAAa;AAC7B,YAAI,CAAC,KAAM,QAAO;AAClB,cAAM,WAAW,MAAM;AAAA,UACrB,OAAO,EAAE,MAAA,IAA+B,OAAC;;AAAO;AAAA,cAC9C,QACG,QAAQ,QAAM,UAAK,qBAAL,iCAA4B,QAAM,UAAK,mBAAL,mCACjD,KAAK,eACL;AAAA,cACF,QAAQ,KAAK;AAAA,cACb,aAAa,KAAK;AAAA,YAAA;AAAA;AAAA,UAEpB,CAAC,aAAa,qBAAqB,KAAK,YAAY,UAAU,EAAE,QAAQ;AAAA,QAAA;AAE1E,eAAO,SAAS,eAAe;AAAA,MACjC;AAAA,MACA,SAAS,SAAS,QAAQ,CAAC,KAAK;AAAA,MAChC,OAAO;AAAA,MACP,WAAW;AAAA,IAAA;AAAA,IAEb;AAAA,EAAA;AAEF,UAAO,6BAAM,gBAAe,MAAM,QAAQ;AAC5C;"}
@@ -9,6 +9,7 @@ const messageComponents = require("../messages/message-components.cjs");
9
9
  const ComposerSendOrStop = ({
10
10
  composerRef,
11
11
  hasDraft,
12
+ liveVoice = false,
12
13
  disabled = false,
13
14
  sendBlockedReason = null,
14
15
  sendDisabledTitle,
@@ -24,7 +25,7 @@ const ComposerSendOrStop = ({
24
25
  return ((_a = state.optional.thread) == null ? void 0 : _a.isRunning) ?? false;
25
26
  }
26
27
  );
27
- const action = composerAction.resolveComposerAction({ hasDraft, isRunning });
28
+ const action = liveVoice && hasDraft ? "send" : composerAction.resolveComposerAction({ hasDraft, isRunning });
28
29
  const SendButton = (components == null ? void 0 : components.SendButton) ?? messageComponents.ComposerSendButton;
29
30
  const StopButton = (components == null ? void 0 : components.StopButton) ?? messageComponents.ComposerStopButton;
30
31
  const cancelRun = react$1.useCallback(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"composer-send-or-stop.cjs","sources":["../../../src/chat-ui/thread/composer-send-or-stop.tsx"],"sourcesContent":["import { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport { useAui, useAuiState } from \"@assistant-ui/react\";\nimport type { FC, RefObject } from \"react\";\nimport { useCallback } from \"react\";\nimport {\n resolveComposerAction,\n type ComposerAction,\n} from \"../composer/composer-action\";\nimport {\n ComposerSendButton,\n ComposerStopButton,\n type ComposerSendButtonProps,\n type ComposerStopButtonProps,\n} from \"../messages/message-components\";\n\n/**\n * The slice of a composer handle this control needs: something whose draft\n * can be submitted. `TiptapComposerHandle` satisfies it; hosts with their own\n * editor plumbing (the SDK's AthenaChat) expose a compatible handle.\n */\nexport interface ComposerSubmitHandle {\n submit: () => void | Promise<void>;\n}\n\nexport interface ComposerStopControls {\n /**\n * Cancels the active run via the runtime. Returns false when cancellation\n * threw (e.g. the run already settled), so hosts can report whether their\n * own teardown still needs to stop backend work.\n */\n cancelRun: () => boolean;\n}\n\n/**\n * Control renderers, for hosts with their own published theming contract\n * (AthenaChat's `aui-*` class system). Defaults render the shared buttons.\n */\nexport interface ComposerSendOrStopComponents {\n SendButton?: FC<ComposerSendButtonProps>;\n StopButton?: FC<ComposerStopButtonProps>;\n}\n\nexport interface ComposerSendOrStopProps {\n composerRef: RefObject<ComposerSubmitHandle | null>;\n hasDraft: boolean;\n /** Disables both send and stop (e.g. while a conversation restores). */\n disabled?: boolean;\n /**\n * Blocks sending (not stopping) with this reason as the tooltip — e.g. a\n * broken host tunnel that would make tool calls silently fail.\n */\n sendBlockedReason?: string | null;\n /** Tooltip for the send/queue control while `disabled`. */\n sendDisabledTitle?: string;\n /** Tooltip for the stop control while `disabled`. */\n stopDisabledTitle?: string;\n /**\n * Host work to run before the draft submits (per-turn bookkeeping).\n * `action` distinguishes a fresh send from queueing into an active run.\n */\n onBeforeSend?: (context: {\n action: Extract<ComposerAction, \"send\" | \"queue\">;\n }) => void | Promise<void>;\n /**\n * Full custom stop sequence. Hosts that must tear down in-flight host-side\n * work sequence it around `controls.cancelRun()`. Default: cancel the run.\n */\n onStop?: (controls: ComposerStopControls) => void;\n components?: ComposerSendOrStopComponents;\n}\n\n/**\n * The shared send/queue/stop control: sends the composer draft, queues it as\n * a follow-up while a run is in flight, or stops the run when there is\n * nothing to queue.\n */\nexport const ComposerSendOrStop: FC<ComposerSendOrStopProps> = ({\n composerRef,\n hasDraft,\n disabled = false,\n sendBlockedReason = null,\n sendDisabledTitle,\n stopDisabledTitle,\n onBeforeSend,\n onStop,\n components,\n}) => {\n const aui = useAui();\n const isRunning = useAuiState(\n (state) => state.optional.thread?.isRunning ?? false,\n );\n const action = resolveComposerAction({ hasDraft, isRunning });\n const SendButton = components?.SendButton ?? ComposerSendButton;\n const StopButton = components?.StopButton ?? ComposerStopButton;\n\n const cancelRun = useCallback((): boolean => {\n try {\n aui.thread.cancelRun();\n return true;\n } catch (error) {\n athenaDiagnostics.emit(\"composer.cancel.error\", {\n level: \"warn\",\n data: { error: error instanceof Error ? error.message : String(error) },\n });\n return false;\n }\n }, [aui]);\n\n if (action === \"stop\") {\n return (\n <StopButton\n onStop={() => {\n if (onStop) {\n onStop({ cancelRun });\n } else {\n cancelRun();\n }\n }}\n disabled={disabled}\n title={disabled && stopDisabledTitle ? stopDisabledTitle : undefined}\n />\n );\n }\n\n const handleSend = async () => {\n await onBeforeSend?.({ action });\n await composerRef.current?.submit();\n };\n const sendTitle =\n disabled && sendDisabledTitle\n ? sendDisabledTitle\n : (sendBlockedReason ?? undefined);\n return (\n <SendButton\n action={action}\n onSend={() => void handleSend()}\n disabled={disabled || !hasDraft || sendBlockedReason != null}\n title={sendTitle}\n />\n );\n};\n"],"names":["useAui","useAuiState","resolveComposerAction","ComposerSendButton","ComposerStopButton","useCallback","athenaDiagnostics","jsx"],"mappings":";;;;;;;;AA4EO,MAAM,qBAAkD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,MAAMA,MAAAA,OAAA;AACZ,QAAM,YAAYC,MAAAA;AAAAA,IAChB,CAAC,UAAA;;AAAU,0BAAM,SAAS,WAAf,mBAAuB,cAAa;AAAA;AAAA,EAAA;AAEjD,QAAM,SAASC,eAAAA,sBAAsB,EAAE,UAAU,WAAW;AAC5D,QAAM,cAAa,yCAAY,eAAcC,kBAAAA;AAC7C,QAAM,cAAa,yCAAY,eAAcC,kBAAAA;AAE7C,QAAM,YAAYC,QAAAA,YAAY,MAAe;AAC3C,QAAI;AACF,UAAI,OAAO,UAAA;AACX,aAAO;AAAA,IACT,SAAS,OAAO;AACdC,wBAAAA,kBAAkB,KAAK,yBAAyB;AAAA,QAC9C,OAAO;AAAA,QACP,MAAM,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAA;AAAA,MAAE,CACvE;AACD,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AAER,MAAI,WAAW,QAAQ;AACrB,WACEC,2BAAAA;AAAAA,MAAC;AAAA,MAAA;AAAA,QACC,QAAQ,MAAM;AACZ,cAAI,QAAQ;AACV,mBAAO,EAAE,WAAW;AAAA,UACtB,OAAO;AACL,sBAAA;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,QACA,OAAO,YAAY,oBAAoB,oBAAoB;AAAA,MAAA;AAAA,IAAA;AAAA,EAGjE;AAEA,QAAM,aAAa,YAAY;;AAC7B,WAAM,6CAAe,EAAE;AACvB,YAAM,iBAAY,YAAZ,mBAAqB;AAAA,EAC7B;AACA,QAAM,YACJ,YAAY,oBACR,oBACC,qBAAqB;AAC5B,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC;AAAA,MACA,QAAQ,MAAM,KAAK,WAAA;AAAA,MACnB,UAAU,YAAY,CAAC,YAAY,qBAAqB;AAAA,MACxD,OAAO;AAAA,IAAA;AAAA,EAAA;AAGb;;"}
1
+ {"version":3,"file":"composer-send-or-stop.cjs","sources":["../../../src/chat-ui/thread/composer-send-or-stop.tsx"],"sourcesContent":["import { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport { useAui, useAuiState } from \"@assistant-ui/react\";\nimport type { FC, RefObject } from \"react\";\nimport { useCallback } from \"react\";\nimport {\n resolveComposerAction,\n type ComposerAction,\n} from \"../composer/composer-action\";\nimport {\n ComposerSendButton,\n ComposerStopButton,\n type ComposerSendButtonProps,\n type ComposerStopButtonProps,\n} from \"../messages/message-components\";\n\n/**\n * The slice of a composer handle this control needs: something whose draft\n * can be submitted. `TiptapComposerHandle` satisfies it; hosts with their own\n * editor plumbing (the SDK's AthenaChat) expose a compatible handle.\n */\nexport interface ComposerSubmitHandle {\n submit: () => void | Promise<void>;\n}\n\nexport interface ComposerStopControls {\n /**\n * Cancels the active run via the runtime. Returns false when cancellation\n * threw (e.g. the run already settled), so hosts can report whether their\n * own teardown still needs to stop backend work.\n */\n cancelRun: () => boolean;\n}\n\n/**\n * Control renderers, for hosts with their own published theming contract\n * (AthenaChat's `aui-*` class system). Defaults render the shared buttons.\n */\nexport interface ComposerSendOrStopComponents {\n SendButton?: FC<ComposerSendButtonProps>;\n StopButton?: FC<ComposerStopButtonProps>;\n}\n\nexport interface ComposerSendOrStopProps {\n composerRef: RefObject<ComposerSubmitHandle | null>;\n hasDraft: boolean;\n /** A plain draft enters the live voice conversation instead of the run queue. */\n liveVoice?: boolean;\n /** Disables both send and stop (e.g. while a conversation restores). */\n disabled?: boolean;\n /**\n * Blocks sending (not stopping) with this reason as the tooltip — e.g. a\n * broken host tunnel that would make tool calls silently fail.\n */\n sendBlockedReason?: string | null;\n /** Tooltip for the send/queue control while `disabled`. */\n sendDisabledTitle?: string;\n /** Tooltip for the stop control while `disabled`. */\n stopDisabledTitle?: string;\n /**\n * Host work to run before the draft submits (per-turn bookkeeping).\n * `action` distinguishes a fresh send from queueing into an active run.\n */\n onBeforeSend?: (context: {\n action: Extract<ComposerAction, \"send\" | \"queue\">;\n }) => void | Promise<void>;\n /**\n * Full custom stop sequence. Hosts that must tear down in-flight host-side\n * work sequence it around `controls.cancelRun()`. Default: cancel the run.\n */\n onStop?: (controls: ComposerStopControls) => void;\n components?: ComposerSendOrStopComponents;\n}\n\n/**\n * The shared send/queue/stop control: sends the composer draft, queues it as\n * a follow-up while a run is in flight, or stops the run when there is\n * nothing to queue.\n */\nexport const ComposerSendOrStop: FC<ComposerSendOrStopProps> = ({\n composerRef,\n hasDraft,\n liveVoice = false,\n disabled = false,\n sendBlockedReason = null,\n sendDisabledTitle,\n stopDisabledTitle,\n onBeforeSend,\n onStop,\n components,\n}) => {\n const aui = useAui();\n const isRunning = useAuiState(\n (state) => state.optional.thread?.isRunning ?? false,\n );\n const action = liveVoice && hasDraft ? 'send' : resolveComposerAction({ hasDraft, isRunning });\n const SendButton = components?.SendButton ?? ComposerSendButton;\n const StopButton = components?.StopButton ?? ComposerStopButton;\n\n const cancelRun = useCallback((): boolean => {\n try {\n aui.thread.cancelRun();\n return true;\n } catch (error) {\n athenaDiagnostics.emit(\"composer.cancel.error\", {\n level: \"warn\",\n data: { error: error instanceof Error ? error.message : String(error) },\n });\n return false;\n }\n }, [aui]);\n\n if (action === \"stop\") {\n return (\n <StopButton\n onStop={() => {\n if (onStop) {\n onStop({ cancelRun });\n } else {\n cancelRun();\n }\n }}\n disabled={disabled}\n title={disabled && stopDisabledTitle ? stopDisabledTitle : undefined}\n />\n );\n }\n\n const handleSend = async () => {\n await onBeforeSend?.({ action });\n await composerRef.current?.submit();\n };\n const sendTitle =\n disabled && sendDisabledTitle\n ? sendDisabledTitle\n : (sendBlockedReason ?? undefined);\n return (\n <SendButton\n action={action}\n onSend={() => void handleSend()}\n disabled={disabled || !hasDraft || sendBlockedReason != null}\n title={sendTitle}\n />\n );\n};\n"],"names":["useAui","useAuiState","resolveComposerAction","ComposerSendButton","ComposerStopButton","useCallback","athenaDiagnostics","jsx"],"mappings":";;;;;;;;AA8EO,MAAM,qBAAkD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,MAAMA,MAAAA,OAAA;AACZ,QAAM,YAAYC,MAAAA;AAAAA,IAChB,CAAC,UAAA;;AAAU,0BAAM,SAAS,WAAf,mBAAuB,cAAa;AAAA;AAAA,EAAA;AAEjD,QAAM,SAAS,aAAa,WAAW,SAASC,eAAAA,sBAAsB,EAAE,UAAU,WAAW;AAC7F,QAAM,cAAa,yCAAY,eAAcC,kBAAAA;AAC7C,QAAM,cAAa,yCAAY,eAAcC,kBAAAA;AAE7C,QAAM,YAAYC,QAAAA,YAAY,MAAe;AAC3C,QAAI;AACF,UAAI,OAAO,UAAA;AACX,aAAO;AAAA,IACT,SAAS,OAAO;AACdC,wBAAAA,kBAAkB,KAAK,yBAAyB;AAAA,QAC9C,OAAO;AAAA,QACP,MAAM,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAA;AAAA,MAAE,CACvE;AACD,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AAER,MAAI,WAAW,QAAQ;AACrB,WACEC,2BAAAA;AAAAA,MAAC;AAAA,MAAA;AAAA,QACC,QAAQ,MAAM;AACZ,cAAI,QAAQ;AACV,mBAAO,EAAE,WAAW;AAAA,UACtB,OAAO;AACL,sBAAA;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,QACA,OAAO,YAAY,oBAAoB,oBAAoB;AAAA,MAAA;AAAA,IAAA;AAAA,EAGjE;AAEA,QAAM,aAAa,YAAY;;AAC7B,WAAM,6CAAe,EAAE;AACvB,YAAM,iBAAY,YAAZ,mBAAqB;AAAA,EAC7B;AACA,QAAM,YACJ,YAAY,oBACR,oBACC,qBAAqB;AAC5B,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC;AAAA,MACA,QAAQ,MAAM,KAAK,WAAA;AAAA,MACnB,UAAU,YAAY,CAAC,YAAY,qBAAqB;AAAA,MACxD,OAAO;AAAA,IAAA;AAAA,EAAA;AAGb;;"}
@@ -28,6 +28,8 @@ export interface ComposerSendOrStopComponents {
28
28
  export interface ComposerSendOrStopProps {
29
29
  composerRef: RefObject<ComposerSubmitHandle | null>;
30
30
  hasDraft: boolean;
31
+ /** A plain draft enters the live voice conversation instead of the run queue. */
32
+ liveVoice?: boolean;
31
33
  /** Disables both send and stop (e.g. while a conversation restores). */
32
34
  disabled?: boolean;
33
35
  /**
@@ -7,6 +7,7 @@ import { ComposerSendButton, ComposerStopButton } from "../messages/message-comp
7
7
  const ComposerSendOrStop = ({
8
8
  composerRef,
9
9
  hasDraft,
10
+ liveVoice = false,
10
11
  disabled = false,
11
12
  sendBlockedReason = null,
12
13
  sendDisabledTitle,
@@ -22,7 +23,7 @@ const ComposerSendOrStop = ({
22
23
  return ((_a = state.optional.thread) == null ? void 0 : _a.isRunning) ?? false;
23
24
  }
24
25
  );
25
- const action = resolveComposerAction({ hasDraft, isRunning });
26
+ const action = liveVoice && hasDraft ? "send" : resolveComposerAction({ hasDraft, isRunning });
26
27
  const SendButton = (components == null ? void 0 : components.SendButton) ?? ComposerSendButton;
27
28
  const StopButton = (components == null ? void 0 : components.StopButton) ?? ComposerStopButton;
28
29
  const cancelRun = useCallback(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"composer-send-or-stop.js","sources":["../../../src/chat-ui/thread/composer-send-or-stop.tsx"],"sourcesContent":["import { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport { useAui, useAuiState } from \"@assistant-ui/react\";\nimport type { FC, RefObject } from \"react\";\nimport { useCallback } from \"react\";\nimport {\n resolveComposerAction,\n type ComposerAction,\n} from \"../composer/composer-action\";\nimport {\n ComposerSendButton,\n ComposerStopButton,\n type ComposerSendButtonProps,\n type ComposerStopButtonProps,\n} from \"../messages/message-components\";\n\n/**\n * The slice of a composer handle this control needs: something whose draft\n * can be submitted. `TiptapComposerHandle` satisfies it; hosts with their own\n * editor plumbing (the SDK's AthenaChat) expose a compatible handle.\n */\nexport interface ComposerSubmitHandle {\n submit: () => void | Promise<void>;\n}\n\nexport interface ComposerStopControls {\n /**\n * Cancels the active run via the runtime. Returns false when cancellation\n * threw (e.g. the run already settled), so hosts can report whether their\n * own teardown still needs to stop backend work.\n */\n cancelRun: () => boolean;\n}\n\n/**\n * Control renderers, for hosts with their own published theming contract\n * (AthenaChat's `aui-*` class system). Defaults render the shared buttons.\n */\nexport interface ComposerSendOrStopComponents {\n SendButton?: FC<ComposerSendButtonProps>;\n StopButton?: FC<ComposerStopButtonProps>;\n}\n\nexport interface ComposerSendOrStopProps {\n composerRef: RefObject<ComposerSubmitHandle | null>;\n hasDraft: boolean;\n /** Disables both send and stop (e.g. while a conversation restores). */\n disabled?: boolean;\n /**\n * Blocks sending (not stopping) with this reason as the tooltip — e.g. a\n * broken host tunnel that would make tool calls silently fail.\n */\n sendBlockedReason?: string | null;\n /** Tooltip for the send/queue control while `disabled`. */\n sendDisabledTitle?: string;\n /** Tooltip for the stop control while `disabled`. */\n stopDisabledTitle?: string;\n /**\n * Host work to run before the draft submits (per-turn bookkeeping).\n * `action` distinguishes a fresh send from queueing into an active run.\n */\n onBeforeSend?: (context: {\n action: Extract<ComposerAction, \"send\" | \"queue\">;\n }) => void | Promise<void>;\n /**\n * Full custom stop sequence. Hosts that must tear down in-flight host-side\n * work sequence it around `controls.cancelRun()`. Default: cancel the run.\n */\n onStop?: (controls: ComposerStopControls) => void;\n components?: ComposerSendOrStopComponents;\n}\n\n/**\n * The shared send/queue/stop control: sends the composer draft, queues it as\n * a follow-up while a run is in flight, or stops the run when there is\n * nothing to queue.\n */\nexport const ComposerSendOrStop: FC<ComposerSendOrStopProps> = ({\n composerRef,\n hasDraft,\n disabled = false,\n sendBlockedReason = null,\n sendDisabledTitle,\n stopDisabledTitle,\n onBeforeSend,\n onStop,\n components,\n}) => {\n const aui = useAui();\n const isRunning = useAuiState(\n (state) => state.optional.thread?.isRunning ?? false,\n );\n const action = resolveComposerAction({ hasDraft, isRunning });\n const SendButton = components?.SendButton ?? ComposerSendButton;\n const StopButton = components?.StopButton ?? ComposerStopButton;\n\n const cancelRun = useCallback((): boolean => {\n try {\n aui.thread.cancelRun();\n return true;\n } catch (error) {\n athenaDiagnostics.emit(\"composer.cancel.error\", {\n level: \"warn\",\n data: { error: error instanceof Error ? error.message : String(error) },\n });\n return false;\n }\n }, [aui]);\n\n if (action === \"stop\") {\n return (\n <StopButton\n onStop={() => {\n if (onStop) {\n onStop({ cancelRun });\n } else {\n cancelRun();\n }\n }}\n disabled={disabled}\n title={disabled && stopDisabledTitle ? stopDisabledTitle : undefined}\n />\n );\n }\n\n const handleSend = async () => {\n await onBeforeSend?.({ action });\n await composerRef.current?.submit();\n };\n const sendTitle =\n disabled && sendDisabledTitle\n ? sendDisabledTitle\n : (sendBlockedReason ?? undefined);\n return (\n <SendButton\n action={action}\n onSend={() => void handleSend()}\n disabled={disabled || !hasDraft || sendBlockedReason != null}\n title={sendTitle}\n />\n );\n};\n"],"names":[],"mappings":";;;;;;AA4EO,MAAM,qBAAkD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,MAAM,OAAA;AACZ,QAAM,YAAY;AAAA,IAChB,CAAC,UAAA;;AAAU,0BAAM,SAAS,WAAf,mBAAuB,cAAa;AAAA;AAAA,EAAA;AAEjD,QAAM,SAAS,sBAAsB,EAAE,UAAU,WAAW;AAC5D,QAAM,cAAa,yCAAY,eAAc;AAC7C,QAAM,cAAa,yCAAY,eAAc;AAE7C,QAAM,YAAY,YAAY,MAAe;AAC3C,QAAI;AACF,UAAI,OAAO,UAAA;AACX,aAAO;AAAA,IACT,SAAS,OAAO;AACd,wBAAkB,KAAK,yBAAyB;AAAA,QAC9C,OAAO;AAAA,QACP,MAAM,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAA;AAAA,MAAE,CACvE;AACD,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AAER,MAAI,WAAW,QAAQ;AACrB,WACE;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,QAAQ,MAAM;AACZ,cAAI,QAAQ;AACV,mBAAO,EAAE,WAAW;AAAA,UACtB,OAAO;AACL,sBAAA;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,QACA,OAAO,YAAY,oBAAoB,oBAAoB;AAAA,MAAA;AAAA,IAAA;AAAA,EAGjE;AAEA,QAAM,aAAa,YAAY;;AAC7B,WAAM,6CAAe,EAAE;AACvB,YAAM,iBAAY,YAAZ,mBAAqB;AAAA,EAC7B;AACA,QAAM,YACJ,YAAY,oBACR,oBACC,qBAAqB;AAC5B,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC;AAAA,MACA,QAAQ,MAAM,KAAK,WAAA;AAAA,MACnB,UAAU,YAAY,CAAC,YAAY,qBAAqB;AAAA,MACxD,OAAO;AAAA,IAAA;AAAA,EAAA;AAGb;"}
1
+ {"version":3,"file":"composer-send-or-stop.js","sources":["../../../src/chat-ui/thread/composer-send-or-stop.tsx"],"sourcesContent":["import { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport { useAui, useAuiState } from \"@assistant-ui/react\";\nimport type { FC, RefObject } from \"react\";\nimport { useCallback } from \"react\";\nimport {\n resolveComposerAction,\n type ComposerAction,\n} from \"../composer/composer-action\";\nimport {\n ComposerSendButton,\n ComposerStopButton,\n type ComposerSendButtonProps,\n type ComposerStopButtonProps,\n} from \"../messages/message-components\";\n\n/**\n * The slice of a composer handle this control needs: something whose draft\n * can be submitted. `TiptapComposerHandle` satisfies it; hosts with their own\n * editor plumbing (the SDK's AthenaChat) expose a compatible handle.\n */\nexport interface ComposerSubmitHandle {\n submit: () => void | Promise<void>;\n}\n\nexport interface ComposerStopControls {\n /**\n * Cancels the active run via the runtime. Returns false when cancellation\n * threw (e.g. the run already settled), so hosts can report whether their\n * own teardown still needs to stop backend work.\n */\n cancelRun: () => boolean;\n}\n\n/**\n * Control renderers, for hosts with their own published theming contract\n * (AthenaChat's `aui-*` class system). Defaults render the shared buttons.\n */\nexport interface ComposerSendOrStopComponents {\n SendButton?: FC<ComposerSendButtonProps>;\n StopButton?: FC<ComposerStopButtonProps>;\n}\n\nexport interface ComposerSendOrStopProps {\n composerRef: RefObject<ComposerSubmitHandle | null>;\n hasDraft: boolean;\n /** A plain draft enters the live voice conversation instead of the run queue. */\n liveVoice?: boolean;\n /** Disables both send and stop (e.g. while a conversation restores). */\n disabled?: boolean;\n /**\n * Blocks sending (not stopping) with this reason as the tooltip — e.g. a\n * broken host tunnel that would make tool calls silently fail.\n */\n sendBlockedReason?: string | null;\n /** Tooltip for the send/queue control while `disabled`. */\n sendDisabledTitle?: string;\n /** Tooltip for the stop control while `disabled`. */\n stopDisabledTitle?: string;\n /**\n * Host work to run before the draft submits (per-turn bookkeeping).\n * `action` distinguishes a fresh send from queueing into an active run.\n */\n onBeforeSend?: (context: {\n action: Extract<ComposerAction, \"send\" | \"queue\">;\n }) => void | Promise<void>;\n /**\n * Full custom stop sequence. Hosts that must tear down in-flight host-side\n * work sequence it around `controls.cancelRun()`. Default: cancel the run.\n */\n onStop?: (controls: ComposerStopControls) => void;\n components?: ComposerSendOrStopComponents;\n}\n\n/**\n * The shared send/queue/stop control: sends the composer draft, queues it as\n * a follow-up while a run is in flight, or stops the run when there is\n * nothing to queue.\n */\nexport const ComposerSendOrStop: FC<ComposerSendOrStopProps> = ({\n composerRef,\n hasDraft,\n liveVoice = false,\n disabled = false,\n sendBlockedReason = null,\n sendDisabledTitle,\n stopDisabledTitle,\n onBeforeSend,\n onStop,\n components,\n}) => {\n const aui = useAui();\n const isRunning = useAuiState(\n (state) => state.optional.thread?.isRunning ?? false,\n );\n const action = liveVoice && hasDraft ? 'send' : resolveComposerAction({ hasDraft, isRunning });\n const SendButton = components?.SendButton ?? ComposerSendButton;\n const StopButton = components?.StopButton ?? ComposerStopButton;\n\n const cancelRun = useCallback((): boolean => {\n try {\n aui.thread.cancelRun();\n return true;\n } catch (error) {\n athenaDiagnostics.emit(\"composer.cancel.error\", {\n level: \"warn\",\n data: { error: error instanceof Error ? error.message : String(error) },\n });\n return false;\n }\n }, [aui]);\n\n if (action === \"stop\") {\n return (\n <StopButton\n onStop={() => {\n if (onStop) {\n onStop({ cancelRun });\n } else {\n cancelRun();\n }\n }}\n disabled={disabled}\n title={disabled && stopDisabledTitle ? stopDisabledTitle : undefined}\n />\n );\n }\n\n const handleSend = async () => {\n await onBeforeSend?.({ action });\n await composerRef.current?.submit();\n };\n const sendTitle =\n disabled && sendDisabledTitle\n ? sendDisabledTitle\n : (sendBlockedReason ?? undefined);\n return (\n <SendButton\n action={action}\n onSend={() => void handleSend()}\n disabled={disabled || !hasDraft || sendBlockedReason != null}\n title={sendTitle}\n />\n );\n};\n"],"names":[],"mappings":";;;;;;AA8EO,MAAM,qBAAkD,CAAC;AAAA,EAC9D;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,MAAM,OAAA;AACZ,QAAM,YAAY;AAAA,IAChB,CAAC,UAAA;;AAAU,0BAAM,SAAS,WAAf,mBAAuB,cAAa;AAAA;AAAA,EAAA;AAEjD,QAAM,SAAS,aAAa,WAAW,SAAS,sBAAsB,EAAE,UAAU,WAAW;AAC7F,QAAM,cAAa,yCAAY,eAAc;AAC7C,QAAM,cAAa,yCAAY,eAAc;AAE7C,QAAM,YAAY,YAAY,MAAe;AAC3C,QAAI;AACF,UAAI,OAAO,UAAA;AACX,aAAO;AAAA,IACT,SAAS,OAAO;AACd,wBAAkB,KAAK,yBAAyB;AAAA,QAC9C,OAAO;AAAA,QACP,MAAM,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAA;AAAA,MAAE,CACvE;AACD,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AAER,MAAI,WAAW,QAAQ;AACrB,WACE;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,QAAQ,MAAM;AACZ,cAAI,QAAQ;AACV,mBAAO,EAAE,WAAW;AAAA,UACtB,OAAO;AACL,sBAAA;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,QACA,OAAO,YAAY,oBAAoB,oBAAoB;AAAA,MAAA;AAAA,IAAA;AAAA,EAGjE;AAEA,QAAM,aAAa,YAAY;;AAC7B,WAAM,6CAAe,EAAE;AACvB,YAAM,iBAAY,YAAZ,mBAAqB;AAAA,EAC7B;AACA,QAAM,YACJ,YAAY,oBACR,oBACC,qBAAqB;AAC5B,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC;AAAA,MACA,QAAQ,MAAM,KAAK,WAAA;AAAA,MACnB,UAAU,YAAY,CAAC,YAAY,qBAAqB;AAAA,MACxD,OAAO;AAAA,IAAA;AAAA,EAAA;AAGb;"}
@@ -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 // 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,MA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A;AAAA,MAC/B,eAAe,CAAC,QAA+B,YAAY;AACzD,YAAI;AACF,uBAAa,QAAQ,yBAAyB,KAAK;AAAA,QACrD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,MACA,gBAAgB,MAAM;AACpB,YAAI;AACF,uBAAa,WAAW,uBAAuB;AAAA,QACjD,QAAQ;AAAA,QAER;AACA,0BAAkB,UAAU,EAAE,SAAS,MAAA,CAAO;AAAA,MAChD;AAAA,IAAA;AAAA,EACF;AAEJ;AAGO,SAAS,6BACd,OACkC;AAClC,MAAI,UAAU,OAAW,QAAO,CAAA;AAChC,MAAI,UAAU,KAAM,QAAO,EAAE,SAAS,QAAA;AACtC,MAAI,UAAU,MAAO,QAAO,EAAE,SAAS,MAAA;AACvC,MAAI,OAAO,UAAU,SAAU,QAAO,EAAE,SAAS,MAAA;AACjD,SAAO;AACT;;;;;"}
1
+ {"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n | '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;AACA,WAAO,QAAQ,OAAO,QAAQ,SAAS,UAAU;AAAA,EACnD,QA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I,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;;;;;"}
@@ -31,7 +31,7 @@ export type AthenaDiagnosticEventName = 'sdk.init' | 'sdk.transport' | 'sdk.conf
31
31
  /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */
32
32
  | 'statewire.config' | 'run.send' | 'run.first_token' | 'run.done' | 'run.error' | 'composer.attachment.error'
33
33
  /** Files offered while Athena can't be reached were not attached (they could not upload). */
34
- | 'composer.attachment.refused_offline' | 'composer.cancel.error' | 'composer.dictation' | 'composer.handoff' | 'tools.schema.warning' | 'tools.debug' | 'mentions.fetch.error' | 'sdk.error';
34
+ | 'composer.attachment.refused_offline' | 'composer.cancel.error' | 'composer.dictation' | 'composer.handoff' | 'voice.chat' | 'tools.schema.warning' | 'tools.debug' | 'mentions.fetch.error' | 'sdk.error';
35
35
  export interface AthenaDiagnosticEvent {
36
36
  /** Monotonic sequence number within this page. */
37
37
  seq: number;
@@ -1 +1 @@
1
- {"version":3,"file":"athena-diagnostics.js","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n * from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n * until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n * `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n * `performance.mark` / `performance.measure` too, so the browser Performance\n * panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n * prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n * `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n // Provider / configuration\n | 'sdk.init'\n | 'sdk.transport'\n | 'sdk.config.warning'\n // Auth acquisition + lifecycle\n | 'auth.bridge.start'\n | 'auth.bridge.ready'\n | 'auth.bridge.timeout'\n | 'auth.bridge.absent'\n | 'auth.bridge.error'\n | 'auth.bridge.retry'\n | 'auth.bridge.config_rejected'\n | 'auth.token.acquired'\n | 'auth.token.refreshed'\n | 'auth.token.refresh_failed'\n | 'auth.token.stale'\n | 'auth.sso.userinfo.start'\n | 'auth.sso.userinfo.done'\n | 'auth.sso.userinfo.error'\n | 'auth.sso.userinfo.retry'\n // Thread list + history\n | 'threads.list.start'\n | 'threads.list.done'\n | 'threads.list.error'\n | 'threads.list.aborted'\n | 'threads.history.start'\n | 'threads.history.done'\n | 'threads.history.error'\n | 'threads.history.aborted'\n // Statewire transport\n | 'statewire.attach.start'\n | 'statewire.snapshot'\n | 'statewire.connection'\n | 'statewire.parked'\n | 'statewire.error'\n | 'statewire.read_only'\n /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n | 'statewire.config'\n // Runs\n | 'run.send'\n | 'run.first_token'\n | 'run.done'\n | 'run.error'\n // Composer\n | 'composer.attachment.error'\n /** Files offered while Athena can't be reached were not attached (they could not upload). */\n | 'composer.attachment.refused_offline'\n | 'composer.cancel.error'\n | 'composer.dictation'\n | 'composer.handoff'\n // Tool UIs + frontend tools\n | 'tools.schema.warning'\n | 'tools.debug'\n // Mention suggestions\n | 'mentions.fetch.error'\n // Catch-all\n | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n /** Monotonic sequence number within this page. */\n seq: number;\n /** `performance.now()` at emit time (ms since navigation start). */\n t: number;\n /** Wall-clock ISO timestamp, for exports. */\n at: string;\n name: AthenaDiagnosticEventName;\n level: AthenaDiagnosticLevel;\n /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n durationMs?: number;\n /** Structured context. Never contains credentials — see `redact`. */\n data?: Record<string, unknown>;\n /** Present on error-level events. */\n error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n /** Minimum level echoed to the console. `false` disables console output. */\n console: AthenaDiagnosticLevel | false;\n /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n posthog: boolean;\n /** Receives every event (already redacted). */\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n /** Receives every error-level event's `AthenaSdkError`. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n /** Ring-buffer capacity. */\n bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n sdkVersion: string;\n config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n events: AthenaDiagnosticEvent[];\n /** Latest value per gauge (connection status, transport, auth mode, …). */\n gauges: Record<string, unknown>;\n /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n console: false,\n posthog: false,\n bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (REDACT_KEYS.test(key)) {\n out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n if (!raw) return null;\n if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n return raw as AthenaDiagnosticLevel;\n }\n return raw === '1' || raw === 'true' ? 'debug' : null;\n } catch {\n return null;\n }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n private events: AthenaDiagnosticEvent[] = [];\n private listeners = new Set<Listener>();\n private snapshotListeners = new Set<() => void>();\n private seq = 0;\n private gauges: Record<string, unknown> = {};\n private timings: Record<string, number> = {};\n private spans = new Map<string, number>();\n private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n this.config = { ...this.config, ...partial };\n if (this.events.length > this.config.bufferSize) {\n this.events = this.events.slice(-this.config.bufferSize);\n }\n this.invalidate();\n }\n\n getConfig(): AthenaDiagnosticsConfig {\n return this.config;\n }\n\n /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n private consoleLevel(): AthenaDiagnosticLevel | false {\n if (this.config.console !== false) return this.config.console;\n return readLocalDebugLevel() ?? false;\n }\n\n emit(\n name: AthenaDiagnosticEventName,\n options: {\n level?: AthenaDiagnosticLevel;\n data?: Record<string, unknown>;\n durationMs?: number;\n error?: unknown;\n } = {},\n ): AthenaDiagnosticEvent {\n const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n const error =\n options.error === undefined\n ? undefined\n : toAthenaSdkError(options.error, {\n code: 'unknown',\n message: `Unexpected error during ${name}`,\n });\n const event: AthenaDiagnosticEvent = {\n seq: ++this.seq,\n t: Math.round(nowMs() * 10) / 10,\n at: new Date().toISOString(),\n name,\n level,\n ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n ...(options.data && { data: redact(options.data) }),\n ...(error && { error }),\n };\n\n this.events.push(event);\n if (this.events.length > this.config.bufferSize) {\n this.events.splice(0, this.events.length - this.config.bufferSize);\n }\n if (event.durationMs !== undefined) {\n this.timings[name] = event.durationMs;\n }\n this.invalidate();\n\n this.echoToConsole(event);\n this.forwardToPostHog(event);\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch (listenerError) {\n console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n }\n }\n if (this.config.onEvent) {\n try {\n this.config.onEvent(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n }\n }\n if (error && this.config.onError) {\n try {\n this.config.onError(error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n }\n }\n for (const notify of this.snapshotListeners) notify();\n return event;\n }\n\n /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n error(\n name: AthenaDiagnosticEventName,\n error: unknown,\n fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n data?: Record<string, unknown>,\n ): AthenaSdkError {\n const normalized = toAthenaSdkError(error, fallback);\n this.emit(name, { level: 'error', error: normalized, data });\n return normalized;\n }\n\n /**\n * Start a named span. Returns a function that ends it and emits `doneName`\n * with `durationMs` (or `errorName` when passed an error). Also records a\n * `performance.measure` so the span shows in the browser's Performance panel.\n */\n span(\n spanName: string,\n startName: AthenaDiagnosticEventName,\n data?: Record<string, unknown>,\n ): (\n doneName: AthenaDiagnosticEventName,\n doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n ) => number {\n const startedAt = nowMs();\n this.spans.set(spanName, startedAt);\n this.mark(`${spanName}:start`);\n this.emit(startName, { level: 'debug', data });\n return (doneName, doneOptions = {}) => {\n const durationMs = nowMs() - startedAt;\n this.spans.delete(spanName);\n this.mark(`${spanName}:end`);\n this.measure(spanName);\n this.emit(doneName, {\n level: doneOptions.error !== undefined ? 'error' : 'info',\n durationMs,\n data: doneOptions.data,\n error: doneOptions.error,\n });\n return durationMs;\n };\n }\n\n /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n gauge(name: string, value: unknown): void {\n if (this.gauges[name] === value) return;\n this.gauges[name] = value;\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Additive consumer registration: every registered consumer receives every\n * event (and every error), unlike the single `onEvent`/`onError` config\n * slots which are last-writer-wins. `AthenaProvider` registers through this\n * so two mounted providers never clobber each other's callbacks.\n */\n addConsumer(consumer: {\n onEvent?: (event: AthenaDiagnosticEvent) => void;\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n }): () => void {\n return this.subscribe((event) => {\n try {\n consumer.onEvent?.(event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n }\n if (event.error) {\n try {\n consumer.onError?.(event.error, event);\n } catch (callbackError) {\n console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n }\n }\n });\n }\n\n /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n subscribeSnapshot(listener: () => void): () => void {\n this.snapshotListeners.add(listener);\n return () => {\n this.snapshotListeners.delete(listener);\n };\n }\n\n snapshot(): AthenaDiagnosticsSnapshot {\n if (!this.cachedSnapshot) {\n const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n this.cachedSnapshot = {\n sdkVersion: ATHENA_REACT_SDK_VERSION,\n config,\n events: [...this.events],\n gauges: { ...this.gauges },\n timings: { ...this.timings },\n };\n }\n return this.cachedSnapshot;\n }\n\n /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n export(): string {\n return JSON.stringify(\n this.snapshot(),\n (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n 2,\n );\n }\n\n clear(): void {\n this.events = [];\n this.timings = {};\n this.invalidate();\n for (const notify of this.snapshotListeners) notify();\n }\n\n private invalidate(): void {\n this.cachedSnapshot = null;\n }\n\n private mark(name: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n performance.mark(`athena-sdk:${name}`);\n }\n } catch {\n // User Timing is best-effort.\n }\n }\n\n private measure(spanName: string): void {\n try {\n if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n performance.measure(\n `athena-sdk:${spanName}`,\n `athena-sdk:${spanName}:start`,\n `athena-sdk:${spanName}:end`,\n );\n }\n } catch {\n // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n }\n }\n\n private echoToConsole(event: AthenaDiagnosticEvent): void {\n const level = this.consoleLevel();\n if (level === false) {\n // Errors are never silent: with console output off they still log once,\n // compactly, so a broken integration is visible without enabling debug.\n if (event.level === 'error' && event.error) {\n console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n }\n return;\n }\n if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n const method =\n event.level === 'error'\n ? console.error\n : event.level === 'warn'\n ? console.warn\n : event.level === 'debug'\n ? console.debug\n : console.info;\n method(line, payload ?? '');\n }\n\n private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n if (!this.config.posthog) return;\n if (event.durationMs === undefined && event.level !== 'error') return;\n try {\n const client = getPostHogInstance<PosthogCaptureClient>();\n capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n sdk_version: ATHENA_REACT_SDK_VERSION,\n level: event.level,\n ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n ...(event.error && {\n error_code: event.error.code,\n error_message: event.error.message,\n error_status: event.error.status,\n }),\n ...event.data,\n });\n } catch {\n // Analytics must never break the chat.\n }\n }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n if (typeof window === 'undefined') return;\n const globalWindow = window as unknown as Record<string, unknown>;\n const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n globalWindow[GLOBAL_KEY] = {\n ...existing,\n version: ATHENA_REACT_SDK_VERSION,\n diagnostics: {\n snapshot: () => athenaDiagnostics.snapshot(),\n export: () => athenaDiagnostics.export(),\n clear: () => athenaDiagnostics.clear(),\n enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n try {\n localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: level });\n },\n disableConsole: () => {\n try {\n localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n } catch {\n // localStorage may be unavailable.\n }\n athenaDiagnostics.configure({ console: false });\n },\n },\n };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n if (debug === undefined) return {};\n if (debug === true) return { console: 'debug' };\n if (debug === false) return { console: false };\n if (typeof debug === 'string') return { console: debug };\n return debug;\n}\n"],"names":[],"mappings":";;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA0GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,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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 // 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;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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;"}
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export { getPostHogInstance } from './provider/PostHogProvider';
17
17
  export { capturePosthogEvent, capturePosthogException, getPosthogCaptureGate, wrapPosthogClient, } from './lib/posthog/wrap-posthog-client';
18
18
  export { buildCoalescedCaptureProperties, isCriticalPosthogEvent, withCaptureGateBypass, type CaptureGateSnapshot, type CoalescedCapturePayload, } from './lib/posthog/capture-gate';
19
19
  export { AthenaAssistantActionBar, AthenaAssistantMessage, AthenaChat, AthenaReasoningPart, AthenaUserMessage, } from './chat/AthenaChat';
20
- export type { AthenaAssistantActionBarProps, AthenaAssistantMessageProps, AthenaChatComponents, AthenaChatMessagePartComponents, AthenaChatProps, AthenaReasoningPartProps, AthenaUserMessageProps, } from './chat/AthenaChat';
20
+ export type { AthenaAssistantActionBarProps, AthenaAssistantMessageProps, AthenaChatComponents, AthenaChatMessagePartComponents, AthenaChatProps, AthenaChatVoiceOptions, AthenaReasoningPartProps, AthenaUserMessageProps, } from './chat/AthenaChat';
21
21
  export type { WelcomeSuggestion } from './chat/athena-chat-welcome';
22
22
  export { AthenaChatErrorBoundary } from './chat/AthenaChatErrorBoundary';
23
23
  export { type ActivityItem, type ActivityPhase, type ActivityTimelineOptions, type ActivityToolState, buildActivityTimeline, CollapsibleGroup, type CollapsibleGroupProps, countActivityTools, createToolBasedGroupingFunction, DEFAULT_TOOLKIT_THEME, defaultGetToolGroupKey, excludeFinalTextFromGroups, excludePartsFromGroups, type FinalTextPart, type FinalTextSegment, formatWorkDuration, getActivityItemLabel, getActivitySummary, getActivityToolState, getFinalText, getFinalTextParts, getReasoningLabel, type GetToolGroupKey, type GroupablePart, GroupedMessageParts, type GroupedMessagePartsProps, type GroupingFunction, type MessagePartGroup, readTurnTiming, resetRememberedExpansionsForTests, resolveActivityPhase, splitTurnSegments, SuperGroupingCard, type SuperGroupingCardProps, SuperGroupingFinalText, SuperGroupingProvider, SuperGroupingTranscript, type SuperGroupingTranscriptProps, TOOLKIT_THEMES, type ToolGroupKeyOptions, type ToolkitTheme, type TurnSegment, type TurnTiming, useActivityExpansion, workedDurationMs, } from './chat/super-grouping';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const version = "0.42.1";
3
+ const version = "0.42.2";
4
4
  const packageJson = {
5
5
  version
6
6
  };
@@ -1,4 +1,4 @@
1
- const version = "0.42.1";
1
+ const version = "0.42.2";
2
2
  const packageJson = {
3
3
  version
4
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-session-key.cjs","sources":["../../src/runtime/statewire-session-key.ts"],"sourcesContent":["import type { AthenaAuthState } from '../auth/types';\n\n/**\n * Scope of the persisted statewire command lane: the sync host, the signed-in\n * principal, and the thread. A thread id is only meaningful against the\n * backend that minted it, and a shared browser must never resend one user's\n * un-settled commands under the next user's token — so the key carries WHO is\n * signed in as well as where. The principal is a non-secret user id;\n * API-key-only hosts (no auth provider above) share one anonymous scope.\n */\nexport function statewireSessionKey({\n syncUrl,\n principal,\n threadId,\n}: {\n syncUrl: string;\n principal: string;\n threadId: string;\n}): string {\n return `${syncUrl}:${principal || 'anon'}:${threadId}`;\n}\n\n/**\n * The principal a thread's persisted command lane is scoped by\n * ({@link statewireSessionKey}): the signed-in user's id (also while the\n * sign-in provider refreshes and still names them), `''` (the one anonymous\n * scope) with no sign-in provider above or none signed in, and `null` while\n * the sign-in provider is still resolving who is signed in.\n *\n * A lane belongs to one principal for the life of the thread's mount: a\n * session mounted on a stand-in key keeps its client id, clock and journal when\n * the key changes, and leaves that record behind with the same client id, so a\n * later page load resends its journal below the server's watermark for the id\n * (`expired`). The lane therefore stays `pending` while this is `null` (see\n * `useAthenaStatewireRuntime`).\n */\nexport function statewireSessionPrincipal(\n auth: Pick<AthenaAuthState, 'isLoading' | 'user'> | null,\n): string | null {\n const userId = auth?.user?.userId;\n if (userId) return userId;\n return auth?.isLoading ? null : '';\n}\n"],"names":[],"mappings":";;AAUO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,GAIW;AACT,SAAO,GAAG,OAAO,IAAI,aAAa,MAAM,IAAI,QAAQ;AACtD;AAgBO,SAAS,0BACd,MACe;;AACf,QAAM,UAAS,kCAAM,SAAN,mBAAY;AAC3B,MAAI,OAAQ,QAAO;AACnB,UAAO,6BAAM,aAAY,OAAO;AAClC;;;"}
1
+ {"version":3,"file":"statewire-session-key.cjs","sources":["../../src/runtime/statewire-session-key.ts"],"sourcesContent":["import type { AthenaAuthState } from '../auth/types';\n\n/**\n * Scope of the persisted statewire command lane: the sync host, the signed-in\n * principal, and the thread. A thread id is only meaningful against the\n * backend that minted it, and a shared browser must never resend one user's\n * un-settled commands under the next user's token — so the key carries WHO is\n * signed in as well as where. The principal is a non-secret user id;\n * API-key-only hosts (no auth provider above) share one anonymous scope.\n */\nexport function statewireSessionKey({\n syncUrl,\n principal,\n threadId,\n}: {\n syncUrl: string;\n principal: string;\n threadId: string;\n}): string {\n return `${syncUrl}:${principal || 'anon'}:${threadId}`;\n}\n\n/**\n * The principal a thread's persisted command lane is scoped by\n * ({@link statewireSessionKey}): the signed-in user's id (also while the\n * sign-in provider refreshes and still names them), `''` (the one anonymous\n * scope) with no sign-in provider above or none signed in, and `null` while\n * the sign-in provider is still resolving who is signed in.\n *\n * A lane belongs to one principal. When the principal changes under a mounted\n * chat (a provider signs a signed-out person in, or picks up another account),\n * the runtime remounts the conversation on the new principal's lane as a new\n * client: nothing the previous principal queued is sent as the new one, and\n * the previous principal's record stays for their next sign-in. While the\n * provider is still resolving who is signed in, the lane stays `pending`\n * (`null` here) rather than taking a stand-in key, which would make the first\n * sign-in a principal change and a second attach (see\n * `useAthenaStatewireRuntime`).\n */\nexport function statewireSessionPrincipal(\n auth: Pick<AthenaAuthState, 'isLoading' | 'user'> | null,\n): string | null {\n const userId = auth?.user?.userId;\n if (userId) return userId;\n return auth?.isLoading ? null : '';\n}\n"],"names":[],"mappings":";;AAUO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,GAIW;AACT,SAAO,GAAG,OAAO,IAAI,aAAa,MAAM,IAAI,QAAQ;AACtD;AAmBO,SAAS,0BACd,MACe;;AACf,QAAM,UAAS,kCAAM,SAAN,mBAAY;AAC3B,MAAI,OAAQ,QAAO;AACnB,UAAO,6BAAM,aAAY,OAAO;AAClC;;;"}
@@ -19,11 +19,14 @@ export declare function statewireSessionKey({ syncUrl, principal, threadId, }: {
19
19
  * scope) with no sign-in provider above or none signed in, and `null` while
20
20
  * the sign-in provider is still resolving who is signed in.
21
21
  *
22
- * A lane belongs to one principal for the life of the thread's mount: a
23
- * session mounted on a stand-in key keeps its client id, clock and journal when
24
- * the key changes, and leaves that record behind with the same client id, so a
25
- * later page load resends its journal below the server's watermark for the id
26
- * (`expired`). The lane therefore stays `pending` while this is `null` (see
22
+ * A lane belongs to one principal. When the principal changes under a mounted
23
+ * chat (a provider signs a signed-out person in, or picks up another account),
24
+ * the runtime remounts the conversation on the new principal's lane as a new
25
+ * client: nothing the previous principal queued is sent as the new one, and
26
+ * the previous principal's record stays for their next sign-in. While the
27
+ * provider is still resolving who is signed in, the lane stays `pending`
28
+ * (`null` here) rather than taking a stand-in key, which would make the first
29
+ * sign-in a principal change and a second attach (see
27
30
  * `useAthenaStatewireRuntime`).
28
31
  */
29
32
  export declare function statewireSessionPrincipal(auth: Pick<AthenaAuthState, 'isLoading' | 'user'> | null): string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-session-key.js","sources":["../../src/runtime/statewire-session-key.ts"],"sourcesContent":["import type { AthenaAuthState } from '../auth/types';\n\n/**\n * Scope of the persisted statewire command lane: the sync host, the signed-in\n * principal, and the thread. A thread id is only meaningful against the\n * backend that minted it, and a shared browser must never resend one user's\n * un-settled commands under the next user's token — so the key carries WHO is\n * signed in as well as where. The principal is a non-secret user id;\n * API-key-only hosts (no auth provider above) share one anonymous scope.\n */\nexport function statewireSessionKey({\n syncUrl,\n principal,\n threadId,\n}: {\n syncUrl: string;\n principal: string;\n threadId: string;\n}): string {\n return `${syncUrl}:${principal || 'anon'}:${threadId}`;\n}\n\n/**\n * The principal a thread's persisted command lane is scoped by\n * ({@link statewireSessionKey}): the signed-in user's id (also while the\n * sign-in provider refreshes and still names them), `''` (the one anonymous\n * scope) with no sign-in provider above or none signed in, and `null` while\n * the sign-in provider is still resolving who is signed in.\n *\n * A lane belongs to one principal for the life of the thread's mount: a\n * session mounted on a stand-in key keeps its client id, clock and journal when\n * the key changes, and leaves that record behind with the same client id, so a\n * later page load resends its journal below the server's watermark for the id\n * (`expired`). The lane therefore stays `pending` while this is `null` (see\n * `useAthenaStatewireRuntime`).\n */\nexport function statewireSessionPrincipal(\n auth: Pick<AthenaAuthState, 'isLoading' | 'user'> | null,\n): string | null {\n const userId = auth?.user?.userId;\n if (userId) return userId;\n return auth?.isLoading ? null : '';\n}\n"],"names":[],"mappings":"AAUO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,GAIW;AACT,SAAO,GAAG,OAAO,IAAI,aAAa,MAAM,IAAI,QAAQ;AACtD;AAgBO,SAAS,0BACd,MACe;AA5BV;AA6BL,QAAM,UAAS,kCAAM,SAAN,mBAAY;AAC3B,MAAI,OAAQ,QAAO;AACnB,UAAO,6BAAM,aAAY,OAAO;AAClC;"}
1
+ {"version":3,"file":"statewire-session-key.js","sources":["../../src/runtime/statewire-session-key.ts"],"sourcesContent":["import type { AthenaAuthState } from '../auth/types';\n\n/**\n * Scope of the persisted statewire command lane: the sync host, the signed-in\n * principal, and the thread. A thread id is only meaningful against the\n * backend that minted it, and a shared browser must never resend one user's\n * un-settled commands under the next user's token — so the key carries WHO is\n * signed in as well as where. The principal is a non-secret user id;\n * API-key-only hosts (no auth provider above) share one anonymous scope.\n */\nexport function statewireSessionKey({\n syncUrl,\n principal,\n threadId,\n}: {\n syncUrl: string;\n principal: string;\n threadId: string;\n}): string {\n return `${syncUrl}:${principal || 'anon'}:${threadId}`;\n}\n\n/**\n * The principal a thread's persisted command lane is scoped by\n * ({@link statewireSessionKey}): the signed-in user's id (also while the\n * sign-in provider refreshes and still names them), `''` (the one anonymous\n * scope) with no sign-in provider above or none signed in, and `null` while\n * the sign-in provider is still resolving who is signed in.\n *\n * A lane belongs to one principal. When the principal changes under a mounted\n * chat (a provider signs a signed-out person in, or picks up another account),\n * the runtime remounts the conversation on the new principal's lane as a new\n * client: nothing the previous principal queued is sent as the new one, and\n * the previous principal's record stays for their next sign-in. While the\n * provider is still resolving who is signed in, the lane stays `pending`\n * (`null` here) rather than taking a stand-in key, which would make the first\n * sign-in a principal change and a second attach (see\n * `useAthenaStatewireRuntime`).\n */\nexport function statewireSessionPrincipal(\n auth: Pick<AthenaAuthState, 'isLoading' | 'user'> | null,\n): string | null {\n const userId = auth?.user?.userId;\n if (userId) return userId;\n return auth?.isLoading ? null : '';\n}\n"],"names":[],"mappings":"AAUO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,GAIW;AACT,SAAO,GAAG,OAAO,IAAI,aAAa,MAAM,IAAI,QAAQ;AACtD;AAmBO,SAAS,0BACd,MACe;AA/BV;AAgCL,QAAM,UAAS,kCAAM,SAAN,mBAAY;AAC3B,MAAI,OAAQ,QAAO;AACnB,UAAO,6BAAM,aAAY,OAAO;AAClC;"}