@athenaintel/react 0.22.1 → 0.22.3

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 (36) hide show
  1. package/README.md +16 -8
  2. package/dist/chat/AthenaChat.cjs +16 -6
  3. package/dist/chat/AthenaChat.cjs.map +1 -1
  4. package/dist/chat/AthenaChat.js +15 -5
  5. package/dist/chat/AthenaChat.js.map +1 -1
  6. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs +0 -1
  7. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs.map +1 -1
  8. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js +0 -1
  9. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js.map +1 -1
  10. package/dist/chat-ui/messages/message-components.cjs +1 -0
  11. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  12. package/dist/chat-ui/messages/message-components.d.ts +7 -0
  13. package/dist/chat-ui/messages/message-components.js +1 -0
  14. package/dist/chat-ui/messages/message-components.js.map +1 -1
  15. package/dist/packages/agent-runtime/src/tool-metadata.cjs +0 -14
  16. package/dist/packages/agent-runtime/src/tool-metadata.cjs.map +1 -1
  17. package/dist/packages/agent-runtime/src/tool-metadata.js +0 -14
  18. package/dist/packages/agent-runtime/src/tool-metadata.js.map +1 -1
  19. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs +79 -28
  20. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
  21. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js +81 -30
  22. package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
  23. package/dist/packages/react/package.json.cjs +1 -1
  24. package/dist/packages/react/package.json.js +1 -1
  25. package/dist/styles.css +1 -1
  26. package/dist/toolkits/index.cjs +0 -7
  27. package/dist/toolkits/index.cjs.map +1 -1
  28. package/dist/toolkits/index.d.ts +0 -2
  29. package/dist/toolkits/index.js +0 -7
  30. package/dist/toolkits/index.js.map +1 -1
  31. package/dist/voice/use-athena-voice-session.cjs +1 -1
  32. package/dist/voice/use-athena-voice-session.cjs.map +1 -1
  33. package/dist/voice/use-athena-voice-session.d.ts +30 -31
  34. package/dist/voice/use-athena-voice-session.js +1 -1
  35. package/dist/voice/use-athena-voice-session.js.map +1 -1
  36. package/package.json +1 -1
@@ -23,8 +23,6 @@ const Toolkits = {
23
23
  COMPUTER_ASSET: "computer_asset_toolkit",
24
24
  /** Web browser automation. */
25
25
  BROWSER: "browser_toolkit",
26
- /** Virtual machine management. */
27
- VM: "vm_toolkit",
28
26
  /** Jupyter notebook execution. */
29
27
  NOTEBOOK: "notebook_toolkit",
30
28
  /** Presentation slide editing. */
@@ -127,11 +125,6 @@ const TOOLKIT_DISPLAY_INFO = {
127
125
  description: "Control a web browser.",
128
126
  icon: "Globe"
129
127
  },
130
- [Toolkits.VM]: {
131
- name: "Virtual Machine",
132
- description: "Manage virtual machine environments.",
133
- icon: "Server"
134
- },
135
128
  [Toolkits.NOTEBOOK]: {
136
129
  name: "Notebook",
137
130
  description: "Run Jupyter notebook workflows.",
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/toolkits/index.ts"],"sourcesContent":["/**\n * Backend toolkit IDs.\n *\n * Pass these to the `tools` prop on `<AthenaProvider>` to enable backend toolkits.\n *\n * @example\n * import { Toolkits } from '@athenaintel/react';\n *\n * <AthenaProvider tools={[Toolkits.DOCUMENT, Toolkits.SPREADSHEET, Toolkits.WEB_SEARCH]}>\n */\nexport const Toolkits = {\n /** Web search and page browsing. */\n WEB_SEARCH: 'web_search_browse_toolkit',\n /** SQL query execution. */\n SQL: 'sql_toolkit',\n /** Azure Blob Storage catalog file operations. */\n AZURE_BLOB_STORAGE: 'azure_blob_storage_toolkit',\n /** Document comments and collaboration. */\n COMMENTS: 'comments_toolkit',\n /** Visual canvas creation. */\n CANVAS: 'canvas_toolkit',\n /** PostgreSQL database management. */\n DATABASE: 'database_toolkit',\n /** Asset collections management. */\n COLLECTIONS: 'collections_toolkit',\n /** Charts, dashboards, and figures. */\n VISUALIZATIONS: 'visualizations_toolkit',\n /** Custom UI creation. */\n USER_INTERFACE: 'user_interface_toolkit',\n /** Agent Operating Procedures. */\n AOP: 'aop_toolkit',\n /** Ephemeral compute environments. */\n COMPUTER_ASSET: 'computer_asset_toolkit',\n /** Web browser automation. */\n BROWSER: 'browser_toolkit',\n /** Virtual machine management. */\n VM: 'vm_toolkit',\n /** Jupyter notebook execution. */\n NOTEBOOK: 'notebook_toolkit',\n /** Presentation slide editing. */\n PRESENTATION: 'presentation_toolkit',\n /** PowerPoint presentation creation from templates. */\n POWERPOINT: 'powerpoint_deck_toolkit',\n /** PowerPoint presentation creation from templates (pptx-studio). */\n PRESENTATION_PPTX_STUDIO: 'presentation_pptx_studio_toolkit',\n /** Workspace file management (Olympus Drive). */\n DRIVE: 'olympus_drive_toolkit',\n /** Python code execution. */\n PYTHON: 'python_toolkit',\n /** Multi-account email and calendar (Gmail + Outlook). */\n EMAIL: 'unified_email_toolkit',\n /** Legacy email and calendar operations. */\n EMAIL_CALENDAR: 'email_calendar_toolkit',\n /** Spreadsheet operations. */\n SPREADSHEET: 'spreadsheet_toolkit',\n /** Athena document editing. */\n DOCUMENT: 'document_toolkit',\n /** Word document backend operations. */\n WORD_DOCUMENT: 'word_document_be_toolkit',\n /** Go-To-Market management. */\n GTM: 'gtm_toolkit',\n /** Marketing campaign management. */\n MARKETING: 'marketing_toolkit',\n /** FDE implementations and workflows. */\n FDE: 'fde_toolkit',\n /** SharePoint / Google Drive / workspace file access. */\n EXTERNAL_DRIVE: 'external_drive_toolkit',\n /** Reusable playbooks and prompts. */\n PLAYBOOK: 'playbook_toolkit',\n /** Local Chrome browser control via tunnel. */\n DEVICE_TUNNEL: 'device_tunnel_toolkit',\n /** Project management. */\n PROJECTS: 'projects_toolkit',\n /** Task Studio script execution. */\n TASK_STUDIO: 'task_studio_toolkit',\n /** User memory and preferences. */\n PREFERENCES: 'preferences_toolkit',\n} as const;\n\n/** A toolkit ID string. */\nexport type ToolkitId = (typeof Toolkits)[keyof typeof Toolkits];\n\nexport interface ToolkitDisplayInfo {\n id: string;\n name: string;\n description?: string;\n icon?: string;\n}\n\nconst TOOLKIT_DISPLAY_INFO: Record<string, Omit<ToolkitDisplayInfo, 'id'>> = {\n [Toolkits.WEB_SEARCH]: {\n name: 'Web Search',\n description: 'Search the web and inspect pages.',\n icon: 'Globe',\n },\n [Toolkits.SQL]: {\n name: 'SQL',\n description: 'Run structured SQL queries.',\n icon: 'Database',\n },\n [Toolkits.AZURE_BLOB_STORAGE]: {\n name: 'Azure Blob Storage',\n description: 'List, read, and upload Azure Blob Storage catalog files.',\n icon: 'Cloud',\n },\n [Toolkits.COMMENTS]: {\n name: 'Comments',\n description: 'Work with document comments and reviews.',\n icon: 'MessageSquare',\n },\n [Toolkits.CANVAS]: {\n name: 'Canvas',\n description: 'Create and edit visual canvases.',\n icon: 'LayoutGrid',\n },\n [Toolkits.DATABASE]: {\n name: 'Database',\n description: 'Inspect and manage database assets.',\n icon: 'Database',\n },\n [Toolkits.COLLECTIONS]: {\n name: 'Collections',\n description: 'Manage asset collections.',\n icon: 'Boxes',\n },\n [Toolkits.VISUALIZATIONS]: {\n name: 'Visualizations',\n description: 'Create charts, dashboards, and figures.',\n icon: 'ChartBar',\n },\n [Toolkits.USER_INTERFACE]: {\n name: 'User Interface',\n description: 'Build custom user interfaces.',\n icon: 'PanelTop',\n },\n [Toolkits.AOP]: {\n name: 'AOP',\n description: 'Run Agent Operating Procedures.',\n icon: 'Workflow',\n },\n [Toolkits.COMPUTER_ASSET]: {\n name: 'Computer Asset',\n description: 'Provision and operate computer assets.',\n icon: 'Monitor',\n },\n [Toolkits.BROWSER]: {\n name: 'Browser',\n description: 'Control a web browser.',\n icon: 'Globe',\n },\n [Toolkits.VM]: {\n name: 'Virtual Machine',\n description: 'Manage virtual machine environments.',\n icon: 'Server',\n },\n [Toolkits.NOTEBOOK]: {\n name: 'Notebook',\n description: 'Run Jupyter notebook workflows.',\n icon: 'BookOpen',\n },\n [Toolkits.PRESENTATION]: {\n name: 'Presentation',\n description: 'Edit presentation slides.',\n icon: 'Presentation',\n },\n [Toolkits.POWERPOINT]: {\n name: 'PowerPoint',\n description: 'Create PowerPoint decks from templates.',\n icon: 'Presentation',\n },\n [Toolkits.PRESENTATION_PPTX_STUDIO]: {\n name: 'Presentation',\n description: 'Create PowerPoint presentations from templates (pptx-studio).',\n icon: 'Presentation',\n },\n [Toolkits.DRIVE]: {\n name: 'Olympus Drive',\n description: 'Find and manage workspace files.',\n icon: 'Folder',\n },\n [Toolkits.PYTHON]: {\n name: 'Python',\n description: 'Run Python analysis and automation.',\n icon: 'Code2',\n },\n [Toolkits.EMAIL]: {\n name: 'Email',\n description: 'Work across connected email and calendar accounts.',\n icon: 'Mail',\n },\n [Toolkits.EMAIL_CALENDAR]: {\n name: 'Email & Calendar',\n description: 'Use email and calendar operations.',\n icon: 'Calendar',\n },\n [Toolkits.SPREADSHEET]: {\n name: 'Spreadsheet',\n description: 'Create and edit spreadsheets.',\n icon: 'Table2',\n },\n [Toolkits.DOCUMENT]: {\n name: 'Document',\n description: 'Create and edit Athena documents.',\n icon: 'FileText',\n },\n [Toolkits.WORD_DOCUMENT]: {\n name: 'Word Document',\n description: 'Create and edit Word documents.',\n icon: 'FileText',\n },\n [Toolkits.GTM]: {\n name: 'Go-To-Market',\n description: 'Manage go-to-market workflows.',\n icon: 'BriefcaseBusiness',\n },\n [Toolkits.MARKETING]: {\n name: 'Marketing',\n description: 'Manage marketing campaigns.',\n icon: 'Megaphone',\n },\n [Toolkits.FDE]: {\n name: 'FDE',\n description: 'Build FDE implementations and workflows.',\n icon: 'Workflow',\n },\n [Toolkits.EXTERNAL_DRIVE]: {\n name: 'External Drive',\n description: 'Access SharePoint, Google Drive, and other files.',\n icon: 'HardDrive',\n },\n [Toolkits.PLAYBOOK]: {\n name: 'Playbook',\n description: 'Use reusable playbooks and prompts.',\n icon: 'BookOpen',\n },\n [Toolkits.DEVICE_TUNNEL]: {\n name: 'Device Tunnel',\n description: 'Control a local browser through a tunnel.',\n icon: 'Cable',\n },\n [Toolkits.PROJECTS]: {\n name: 'Projects',\n description: 'Manage project work.',\n icon: 'FolderKanban',\n },\n [Toolkits.TASK_STUDIO]: {\n name: 'Task Studio',\n description: 'Run Task Studio scripts.',\n icon: 'Terminal',\n },\n [Toolkits.PREFERENCES]: {\n name: 'Preferences',\n description: 'Use memory and preference tools.',\n icon: 'Settings',\n },\n semantic_model_toolkit: {\n name: 'Semantic Model',\n description: 'Query semantic models and generate analytics.',\n icon: 'ChartBar',\n },\n semantic_model_dev_toolkit: {\n name: 'Semantic Model Development',\n description: 'Create, validate, and deploy semantic model YAML.',\n icon: 'Database',\n },\n};\n\nconst humanizeToolkitId = (id: string): string => {\n const trimmed = id.trim();\n if (!trimmed) {\n return 'Toolkit';\n }\n\n const withoutSuffix = trimmed.replace(/_toolkit$/, '');\n return withoutSuffix\n .split(/[_-]+/)\n .filter(Boolean)\n .map((word) => {\n if (word.length <= 3) {\n return word.toUpperCase();\n }\n return `${word.charAt(0).toUpperCase()}${word.slice(1)}`;\n })\n .join(' ');\n};\n\nexport const getToolkitDisplayInfo = (id: string): ToolkitDisplayInfo => {\n const info = TOOLKIT_DISPLAY_INFO[id];\n\n return {\n id,\n name: info?.name ?? humanizeToolkitId(id),\n description: info?.description,\n icon: info?.icon ?? 'Package',\n };\n};\n"],"names":[],"mappings":"AAUO,MAAM,WAAW;AAAA;AAAA,EAEtB,YAAY;AAAA;AAAA,EAEZ,KAAK;AAAA;AAAA,EAEL,oBAAoB;AAAA;AAAA,EAEpB,UAAU;AAAA;AAAA,EAEV,QAAQ;AAAA;AAAA,EAER,UAAU;AAAA;AAAA,EAEV,aAAa;AAAA;AAAA,EAEb,gBAAgB;AAAA;AAAA,EAEhB,gBAAgB;AAAA;AAAA,EAEhB,KAAK;AAAA;AAAA,EAEL,g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AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,CAAC,SAAS,WAAW,GAAG;AAAA,IACtB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,wBAAwB;AAAA,IACtB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,4BAA4B;AAAA,IAC1B,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAEV;AAEA,MAAM,oBAAoB,CAAC,OAAuB;AAChD,QAAM,UAAU,GAAG,KAAA;AACnB,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,gBAAgB,QAAQ,QAAQ,aAAa,EAAE;AACrD,SAAO,cACJ,MAAM,OAAO,EACb,OAAO,OAAO,EACd,IAAI,CAAC,SAAS;AACb,QAAI,KAAK,UAAU,GAAG;AACpB,aAAO,KAAK,YAAA;AAAA,IACd;AACA,WAAO,GAAG,KAAK,OAAO,CAAC,EAAE,YAAA,CAAa,GAAG,KAAK,MAAM,CAAC,CAAC;AAAA,EACxD,CAAC,EACA,KAAK,GAAG;AACb;AAEO,MAAM,wBAAwB,CAAC,OAAmC;AACvE,QAAM,OAAO,qBAAqB,EAAE;AAEpC,SAAO;AAAA,IACL;AAAA,IACA,OAAM,6BAAM,SAAQ,kBAAkB,EAAE;AAAA,IACxC,aAAa,6BAAM;AAAA,IACnB,OAAM,6BAAM,SAAQ;AAAA,EAAA;AAExB;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/toolkits/index.ts"],"sourcesContent":["/**\n * Backend toolkit IDs.\n *\n * Pass these to the `tools` prop on `<AthenaProvider>` to enable backend toolkits.\n *\n * @example\n * import { Toolkits } from '@athenaintel/react';\n *\n * <AthenaProvider tools={[Toolkits.DOCUMENT, Toolkits.SPREADSHEET, Toolkits.WEB_SEARCH]}>\n */\nexport const Toolkits = {\n /** Web search and page browsing. */\n WEB_SEARCH: 'web_search_browse_toolkit',\n /** SQL query execution. */\n SQL: 'sql_toolkit',\n /** Azure Blob Storage catalog file operations. */\n AZURE_BLOB_STORAGE: 'azure_blob_storage_toolkit',\n /** Document comments and collaboration. */\n COMMENTS: 'comments_toolkit',\n /** Visual canvas creation. */\n CANVAS: 'canvas_toolkit',\n /** PostgreSQL database management. */\n DATABASE: 'database_toolkit',\n /** Asset collections management. */\n COLLECTIONS: 'collections_toolkit',\n /** Charts, dashboards, and figures. */\n VISUALIZATIONS: 'visualizations_toolkit',\n /** Custom UI creation. */\n USER_INTERFACE: 'user_interface_toolkit',\n /** Agent Operating Procedures. */\n AOP: 'aop_toolkit',\n /** Ephemeral compute environments. */\n COMPUTER_ASSET: 'computer_asset_toolkit',\n /** Web browser automation. */\n BROWSER: 'browser_toolkit',\n /** Jupyter notebook execution. */\n NOTEBOOK: 'notebook_toolkit',\n /** Presentation slide editing. */\n PRESENTATION: 'presentation_toolkit',\n /** PowerPoint presentation creation from templates. */\n POWERPOINT: 'powerpoint_deck_toolkit',\n /** PowerPoint presentation creation from templates (pptx-studio). */\n PRESENTATION_PPTX_STUDIO: 'presentation_pptx_studio_toolkit',\n /** Workspace file management (Olympus Drive). */\n DRIVE: 'olympus_drive_toolkit',\n /** Python code execution. */\n PYTHON: 'python_toolkit',\n /** Multi-account email and calendar (Gmail + Outlook). */\n EMAIL: 'unified_email_toolkit',\n /** Legacy email and calendar operations. */\n EMAIL_CALENDAR: 'email_calendar_toolkit',\n /** Spreadsheet operations. */\n SPREADSHEET: 'spreadsheet_toolkit',\n /** Athena document editing. */\n DOCUMENT: 'document_toolkit',\n /** Word document backend operations. */\n WORD_DOCUMENT: 'word_document_be_toolkit',\n /** Go-To-Market management. */\n GTM: 'gtm_toolkit',\n /** Marketing campaign management. */\n MARKETING: 'marketing_toolkit',\n /** FDE implementations and workflows. */\n FDE: 'fde_toolkit',\n /** SharePoint / Google Drive / workspace file access. */\n EXTERNAL_DRIVE: 'external_drive_toolkit',\n /** Reusable playbooks and prompts. */\n PLAYBOOK: 'playbook_toolkit',\n /** Local Chrome browser control via tunnel. */\n DEVICE_TUNNEL: 'device_tunnel_toolkit',\n /** Project management. */\n PROJECTS: 'projects_toolkit',\n /** Task Studio script execution. */\n TASK_STUDIO: 'task_studio_toolkit',\n /** User memory and preferences. */\n PREFERENCES: 'preferences_toolkit',\n} as const;\n\n/** A toolkit ID string. */\nexport type ToolkitId = (typeof Toolkits)[keyof typeof Toolkits];\n\nexport interface ToolkitDisplayInfo {\n id: string;\n name: string;\n description?: string;\n icon?: string;\n}\n\nconst TOOLKIT_DISPLAY_INFO: Record<string, Omit<ToolkitDisplayInfo, 'id'>> = {\n [Toolkits.WEB_SEARCH]: {\n name: 'Web Search',\n description: 'Search the web and inspect pages.',\n icon: 'Globe',\n },\n [Toolkits.SQL]: {\n name: 'SQL',\n description: 'Run structured SQL queries.',\n icon: 'Database',\n },\n [Toolkits.AZURE_BLOB_STORAGE]: {\n name: 'Azure Blob Storage',\n description: 'List, read, and upload Azure Blob Storage catalog files.',\n icon: 'Cloud',\n },\n [Toolkits.COMMENTS]: {\n name: 'Comments',\n description: 'Work with document comments and reviews.',\n icon: 'MessageSquare',\n },\n [Toolkits.CANVAS]: {\n name: 'Canvas',\n description: 'Create and edit visual canvases.',\n icon: 'LayoutGrid',\n },\n [Toolkits.DATABASE]: {\n name: 'Database',\n description: 'Inspect and manage database assets.',\n icon: 'Database',\n },\n [Toolkits.COLLECTIONS]: {\n name: 'Collections',\n description: 'Manage asset collections.',\n icon: 'Boxes',\n },\n [Toolkits.VISUALIZATIONS]: {\n name: 'Visualizations',\n description: 'Create charts, dashboards, and figures.',\n icon: 'ChartBar',\n },\n [Toolkits.USER_INTERFACE]: {\n name: 'User Interface',\n description: 'Build custom user interfaces.',\n icon: 'PanelTop',\n },\n [Toolkits.AOP]: {\n name: 'AOP',\n description: 'Run Agent Operating Procedures.',\n icon: 'Workflow',\n },\n [Toolkits.COMPUTER_ASSET]: {\n name: 'Computer Asset',\n description: 'Provision and operate computer assets.',\n icon: 'Monitor',\n },\n [Toolkits.BROWSER]: {\n name: 'Browser',\n description: 'Control a web browser.',\n icon: 'Globe',\n },\n [Toolkits.NOTEBOOK]: {\n name: 'Notebook',\n description: 'Run Jupyter notebook workflows.',\n icon: 'BookOpen',\n },\n [Toolkits.PRESENTATION]: {\n name: 'Presentation',\n description: 'Edit presentation slides.',\n icon: 'Presentation',\n },\n [Toolkits.POWERPOINT]: {\n name: 'PowerPoint',\n description: 'Create PowerPoint decks from templates.',\n icon: 'Presentation',\n },\n [Toolkits.PRESENTATION_PPTX_STUDIO]: {\n name: 'Presentation',\n description: 'Create PowerPoint presentations from templates (pptx-studio).',\n icon: 'Presentation',\n },\n [Toolkits.DRIVE]: {\n name: 'Olympus Drive',\n description: 'Find and manage workspace files.',\n icon: 'Folder',\n },\n [Toolkits.PYTHON]: {\n name: 'Python',\n description: 'Run Python analysis and automation.',\n icon: 'Code2',\n },\n [Toolkits.EMAIL]: {\n name: 'Email',\n description: 'Work across connected email and calendar accounts.',\n icon: 'Mail',\n },\n [Toolkits.EMAIL_CALENDAR]: {\n name: 'Email & Calendar',\n description: 'Use email and calendar operations.',\n icon: 'Calendar',\n },\n [Toolkits.SPREADSHEET]: {\n name: 'Spreadsheet',\n description: 'Create and edit spreadsheets.',\n icon: 'Table2',\n },\n [Toolkits.DOCUMENT]: {\n name: 'Document',\n description: 'Create and edit Athena documents.',\n icon: 'FileText',\n },\n [Toolkits.WORD_DOCUMENT]: {\n name: 'Word Document',\n description: 'Create and edit Word documents.',\n icon: 'FileText',\n },\n [Toolkits.GTM]: {\n name: 'Go-To-Market',\n description: 'Manage go-to-market workflows.',\n icon: 'BriefcaseBusiness',\n },\n [Toolkits.MARKETING]: {\n name: 'Marketing',\n description: 'Manage marketing campaigns.',\n icon: 'Megaphone',\n },\n [Toolkits.FDE]: {\n name: 'FDE',\n description: 'Build FDE implementations and workflows.',\n icon: 'Workflow',\n },\n [Toolkits.EXTERNAL_DRIVE]: {\n name: 'External Drive',\n description: 'Access SharePoint, Google Drive, and other files.',\n icon: 'HardDrive',\n },\n [Toolkits.PLAYBOOK]: {\n name: 'Playbook',\n description: 'Use reusable playbooks and prompts.',\n icon: 'BookOpen',\n },\n [Toolkits.DEVICE_TUNNEL]: {\n name: 'Device Tunnel',\n description: 'Control a local browser through a tunnel.',\n icon: 'Cable',\n },\n [Toolkits.PROJECTS]: {\n name: 'Projects',\n description: 'Manage project work.',\n icon: 'FolderKanban',\n },\n [Toolkits.TASK_STUDIO]: {\n name: 'Task Studio',\n description: 'Run Task Studio scripts.',\n icon: 'Terminal',\n },\n [Toolkits.PREFERENCES]: {\n name: 'Preferences',\n description: 'Use memory and preference tools.',\n icon: 'Settings',\n },\n semantic_model_toolkit: {\n name: 'Semantic Model',\n description: 'Query semantic models and generate analytics.',\n icon: 'ChartBar',\n },\n semantic_model_dev_toolkit: {\n name: 'Semantic Model Development',\n description: 'Create, validate, and deploy semantic model YAML.',\n icon: 'Database',\n },\n};\n\nconst humanizeToolkitId = (id: string): string => {\n const trimmed = id.trim();\n if (!trimmed) {\n return 'Toolkit';\n }\n\n const withoutSuffix = trimmed.replace(/_toolkit$/, '');\n return withoutSuffix\n .split(/[_-]+/)\n .filter(Boolean)\n .map((word) => {\n if (word.length <= 3) {\n return word.toUpperCase();\n }\n return `${word.charAt(0).toUpperCase()}${word.slice(1)}`;\n })\n .join(' ');\n};\n\nexport const getToolkitDisplayInfo = (id: string): ToolkitDisplayInfo => {\n const info = TOOLKIT_DISPLAY_INFO[id];\n\n return {\n id,\n name: info?.name ?? humanizeToolkitId(id),\n description: info?.description,\n icon: info?.icon ?? 'Package',\n };\n};\n"],"names":[],"mappings":"AAUO,MAAM,WAAW;AAAA;AAAA,EAEtB,YAAY;AAAA;AAAA,EAEZ,KAAK;AAAA;AAAA,EAEL,oBAAoB;AAAA;AAAA,EAEpB,UAAU;AAAA;AAAA,EAEV,QAAQ;AAAA;AAAA,EAER,UAAU;AAAA;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IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,CAAC,SAAS,WAAW,GAAG;AAAA,IACtB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,wBAAwB;AAAA,IACtB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAAA,EAER,4BAA4B;AAAA,IAC1B,MAAM;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,EAAA;AAEV;AAEA,MAAM,oBAAoB,CAAC,OAAuB;AAChD,QAAM,UAAU,GAAG,KAAA;AACnB,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,gBAAgB,QAAQ,QAAQ,aAAa,EAAE;AACrD,SAAO,cACJ,MAAM,OAAO,EACb,OAAO,OAAO,EACd,IAAI,CAAC,SAAS;AACb,QAAI,KAAK,UAAU,GAAG;AACpB,aAAO,KAAK,YAAA;AAAA,IACd;AACA,WAAO,GAAG,KAAK,OAAO,CAAC,EAAE,YAAA,CAAa,GAAG,KAAK,MAAM,CAAC,CAAC;AAAA,EACxD,CAAC,EACA,KAAK,GAAG;AACb;AAEO,MAAM,wBAAwB,CAAC,OAAmC;AACvE,QAAM,OAAO,qBAAqB,EAAE;AAEpC,SAAO;AAAA,IACL;AAAA,IACA,OAAM,6BAAM,SAAQ,kBAAkB,EAAE;AAAA,IACxC,aAAa,6BAAM;AAAA,IACnB,OAAM,6BAAM,SAAQ;AAAA,EAAA;AAExB;"}
@@ -33,7 +33,7 @@ const createAthenaVoiceSession = async ({
33
33
  if (!response.ok) {
34
34
  const detail = await response.text().catch(() => "");
35
35
  throw new Error(
36
- `Orpheus create-session failed (${response.status})${detail ? `: ${detail}` : ""}`
36
+ `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ""}`
37
37
  );
38
38
  }
39
39
  return await response.json();
@@ -1 +1 @@
1
- {"version":3,"file":"use-athena-voice-session.cjs","sources":["../../src/voice/use-athena-voice-session.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n Room,\n RoomEvent,\n Track,\n type Participant,\n type RemoteTrack,\n type TranscriptionSegment,\n} from 'livekit-client';\nimport { useParentBridge, type ParentBridgeState } from '../runtime/auth';\n\n/**\n * LiveKit connection details for one Athena voice session. This is the shape\n * Orpheus returns from `POST /api/orpheus/create-session`; the hook only reads\n * these fields, so any server that proxies that call can hand it straight back.\n */\nexport interface AthenaVoiceSessionCredentials {\n /** LiveKit signalling URL (`wss://…`). */\n server_url: string;\n /** Short-lived LiveKit participant JWT scoped to `room_name`. */\n token: string;\n room_name?: string;\n /**\n * Athena session asset the voice run is persisted into. Use it with\n * `GET /api/v0/sessions/{asset_id}/download` to retrieve the transcript\n * after the call.\n */\n asset_id?: string;\n}\n\nexport type AthenaVoiceSessionStatus =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'ended'\n | 'error';\n\nexport type AthenaVoiceSpeaker = 'user' | 'agent';\n\n/** One committed (final) transcription segment from either side of the call. */\nexport interface AthenaVoiceTranscriptTurn {\n id: string;\n speaker: AthenaVoiceSpeaker;\n text: string;\n /** Segment start, in ms since the LiveKit room's epoch. */\n startTime: number;\n endTime: number;\n language: string;\n}\n\n/**\n * A voice tool the Orpheus worker can run for the agent. These are voice tool\n * names, not the chat `Toolkits` ids: `'web_search_browse_toolkit'` is not a\n * voice tool, `'web_search'` is. Only these names are accepted.\n *\n * The worker also has tools that call back into the client over LiveKit RPC\n * (`write_to_clipboard`, `replace_current_selection`, `open_in_olympus`,\n * `open_asset`, `get_screen_contents`). This hook registers no RPC handlers,\n * so they are not part of its contract.\n */\nexport type AthenaVoiceToolId =\n /** Web search (Exa). */\n | 'web_search'\n /** Legacy alias of `web_search`; prefer `web_search`. */\n | 'search_web'\n /** Fetch and read one URL. */\n | 'browse'\n /** The workspace knowledge base (Ragie), where configured. */\n | 'search_knowledge_base'\n /** Same knowledge base, thorough long-running retrieval. */\n | 'search_knowledge_base_lr'\n /** Read Athena assets by id, as the viewer. */\n | 'read_full_asset'\n /** Search the viewer's Athena assets. */\n | 'search_assets'\n /** Hand a question to the general agent and speak its answer. */\n | 'ask_agent'\n /** Save a note for the user (a stub on the worker today). */\n | 'save_note'\n /** Current date and time, Eastern. */\n | 'get_current_time_est';\n\n/**\n * Orpheus agent configuration for a session the hook creates itself (see\n * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of\n * `POST /api/orpheus/create-session`; every field is optional and falls back\n * to the server default.\n */\nexport interface AthenaVoiceSessionConfig {\n /** Persona / instructions for the voice agent. */\n system_prompt?: string;\n /** Realtime provider, e.g. `'openai'` or `'google'`. */\n provider?: string;\n /** Provider model id, e.g. `'gpt-realtime-2'`. */\n model?: string;\n /** Provider voice id, e.g. `'marin'` (OpenAI) or `'Aoede'` (Google). */\n voice?: string;\n temperature?: number;\n /** BCP-47 language tag; default `'en'`. */\n language?: string;\n /**\n * Voice tools the agent may call. Omit it for the server's default set\n * (`web_search`, `search_knowledge_base`, `ask_agent`, …); pass `[]` for a\n * pure conversation with no tool calls.\n */\n enabled_tools?: AthenaVoiceToolId[];\n /** IANA timezone of the speaker, e.g. `'America/New_York'`. */\n timezone?: string;\n}\n\nexport interface UseAthenaVoiceSessionOptions {\n /**\n * Creates the LiveKit session. Omit it when the app is served from a\n * Marathon computer-asset URL: the hook then calls\n * `POST {backendBaseUrl}/api/orpheus/create-session` itself with the\n * viewer's bearer token from `/_athena/auth`, so the session is created as\n * — and shows up in the sessions of — whoever is using the app.\n *\n * Works for workspace members and external SSO viewers alike: the scoped\n * `athview_` viewer credential is authorized for the Orpheus route and\n * `agents/general/invoke` the same way it is for `/api/v0/sessions`.\n *\n * Supply it when the app runs anywhere else (standalone, custom auth): it\n * should run on the caller's own server so the Athena API key never reaches\n * the browser. The hook only reads the returned credentials.\n *\n * Decide once: switching between supplying and omitting it across renders\n * of the same component is not supported.\n */\n createSession?: (\n signal: AbortSignal,\n ) => Promise<AthenaVoiceSessionCredentials>;\n /**\n * Agent configuration for sessions the hook creates itself. Ignored when\n * `createSession` is supplied.\n */\n session?: AthenaVoiceSessionConfig;\n /** Called once per committed transcript turn, in arrival order. */\n onTranscript?: (turn: AthenaVoiceTranscriptTurn) => void;\n /** Called with interim (non-final) transcript text as it streams in. */\n onInterimTranscript?: (speaker: AthenaVoiceSpeaker, text: string) => void;\n onError?: (error: Error) => void;\n /**\n * Where to play the agent's audio. Defaults to a detached `<audio>` element\n * the hook creates and removes itself.\n */\n audioElement?: HTMLMediaElement | null;\n /** Enable the microphone as soon as the room connects. Default `true`. */\n autoEnableMicrophone?: boolean;\n /** @internal Overrides `new Room()`; used by tests. */\n createRoom?: () => Room;\n /** @internal Overrides `useParentBridge()`; used by tests. */\n useBridge?: () => ParentBridgeState;\n}\n\nexport interface UseAthenaVoiceSessionReturn {\n status: AthenaVoiceSessionStatus;\n /** True between `start()` resolving the session and the room connecting. */\n isConnecting: boolean;\n isConnected: boolean;\n /** Who is speaking right now, or `null` when the room is quiet. */\n activeSpeaker: AthenaVoiceSpeaker | null;\n isMuted: boolean;\n /** Committed transcript turns so far, in arrival order. */\n transcript: AthenaVoiceTranscriptTurn[];\n /** Athena session asset id, once the session has been created. */\n sessionId: string | null;\n roomName: string | null;\n error: Error | null;\n /** Creates a session and joins the room. No-op while a session is live. */\n start: () => Promise<void>;\n /** Leaves the room and stops local tracks. Safe to call at any time. */\n stop: () => Promise<void>;\n mute: () => Promise<void>;\n unmute: () => Promise<void>;\n /** Clears `transcript`; does not affect the live session. */\n clearTranscript: () => void;\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst NO_BRIDGE: ParentBridgeState = {\n token: null,\n statewireSyncUrl: null,\n backendBaseUrl: null,\n appUrl: null,\n hostAnswered: false,\n ready: true,\n};\n// Stands in for `useParentBridge` when the caller creates sessions itself, so\n// the hook never fetches `/_athena/auth` it would not use.\nconst useNoBridge = (): ParentBridgeState => NO_BRIDGE;\n\nconst NO_VIEWER_TOKEN_MESSAGE =\n 'useAthenaVoiceSession: no Athena viewer token. Either serve the app from ' +\n 'a Marathon computer-asset URL (which mints one via /_athena/auth) or pass ' +\n '`createSession` to create the session through your own server.';\n\n/**\n * `POST /api/orpheus/create-session` as the current viewer. Exported so apps\n * with their own bridge state (or a server proxy holding a user bearer) can\n * reuse the exact request the hook makes.\n */\nexport const createAthenaVoiceSession = async ({\n backendBaseUrl,\n token,\n session = {},\n signal,\n}: {\n /** Bare Agora API base, e.g. `https://api.athenaintel.com`. */\n backendBaseUrl: string;\n /** Bearer token for the user the session belongs to. */\n token: string;\n session?: AthenaVoiceSessionConfig;\n signal?: AbortSignal;\n}): Promise<AthenaVoiceSessionCredentials> => {\n const url: string = `${backendBaseUrl.replace(/\\/+$/, '')}/api/orpheus/create-session`;\n const response: Response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(session),\n signal,\n });\n if (!response.ok) {\n const detail: string = await response.text().catch(() => '');\n throw new Error(\n `Orpheus create-session failed (${response.status})${detail ? `: ${detail}` : ''}`,\n );\n }\n return (await response.json()) as AthenaVoiceSessionCredentials;\n};\n\nconst speakerOf = (\n participant: Participant | undefined,\n room: Room,\n): AthenaVoiceSpeaker =>\n participant !== undefined &&\n participant.identity === room.localParticipant.identity\n ? 'user'\n : 'agent';\n\n/**\n * Runs one Athena voice session (Orpheus agent over LiveKit) from React.\n *\n * Owns the whole browser-side lifecycle the Orpheus API leaves to the caller:\n * creating the session through the app's own server, joining the LiveKit room,\n * publishing the microphone, playing the agent's audio, tracking who is\n * speaking, committing transcript turns from LiveKit transcription events, and\n * tearing everything down on `stop()` or unmount. A second `start()` while a\n * session is live (or still connecting) is ignored, so React StrictMode's\n * double-invoked effects cannot dispatch two agents into one room.\n */\nexport const useAthenaVoiceSession = (\n options: UseAthenaVoiceSessionOptions = {},\n): UseAthenaVoiceSessionReturn => {\n const {\n createSession,\n session,\n onTranscript,\n onInterimTranscript,\n onError,\n audioElement,\n autoEnableMicrophone = true,\n createRoom,\n useBridge = createSession ? useNoBridge : useParentBridge,\n } = options;\n\n // Viewer identity minted by Marathon (`/_athena/auth`) or the Olympus iframe\n // bridge. Only consulted when the caller did not supply `createSession`.\n const bridge: ParentBridgeState = useBridge();\n const bridgeRef = useRef<ParentBridgeState>(bridge);\n bridgeRef.current = bridge;\n const bridgeReadyWaitersRef = useRef<Array<() => void>>([]);\n useEffect(() => {\n if (!bridge.ready) return;\n const waiters: Array<() => void> = bridgeReadyWaitersRef.current;\n bridgeReadyWaitersRef.current = [];\n for (const resolve of waiters) resolve();\n }, [bridge.ready]);\n\n const sessionRef = useRef<AthenaVoiceSessionConfig | undefined>(session);\n sessionRef.current = session;\n\n const createSessionAsViewer = useCallback(\n async (signal: AbortSignal): Promise<AthenaVoiceSessionCredentials> => {\n if (!bridgeRef.current.ready) {\n await new Promise<void>((resolve) => {\n bridgeReadyWaitersRef.current.push(resolve);\n signal.addEventListener('abort', () => resolve(), { once: true });\n });\n if (signal.aborted) throw new Error('aborted');\n }\n const { token, backendBaseUrl } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n return createAthenaVoiceSession({\n backendBaseUrl,\n token,\n session: sessionRef.current,\n signal,\n });\n },\n [],\n );\n\n const [status, setStatus] = useState<AthenaVoiceSessionStatus>('idle');\n const [activeSpeaker, setActiveSpeaker] = useState<AthenaVoiceSpeaker | null>(\n null,\n );\n const [isMuted, setIsMuted] = useState<boolean>(false);\n const [transcript, setTranscript] = useState<AthenaVoiceTranscriptTurn[]>([]);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [roomName, setRoomName] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Latest callbacks without re-subscribing room listeners on every render.\n const callbacksRef = useRef({\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n });\n callbacksRef.current = {\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n };\n\n const roomRef = useRef<Room | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const attachedElementsRef = useRef<HTMLMediaElement[]>([]);\n const ownedAudioRef = useRef<HTMLMediaElement | null>(null);\n const committedSegmentIdsRef = useRef<Set<string>>(new Set());\n // Guards `start()` against re-entry from the moment it is called, before any\n // state update lands — a StrictMode double effect fires both calls\n // synchronously in the same tick.\n const startingRef = useRef<boolean>(false);\n\n const fail = useCallback((cause: unknown) => {\n const err: Error = toError(cause);\n setError(err);\n setStatus('error');\n callbacksRef.current.onError?.(err);\n }, []);\n\n const detachAudio = useCallback(() => {\n for (const element of attachedElementsRef.current) {\n element.srcObject = null;\n if (element === ownedAudioRef.current) element.remove();\n }\n attachedElementsRef.current = [];\n ownedAudioRef.current = null;\n }, []);\n\n const teardown = useCallback(async () => {\n abortRef.current?.abort();\n abortRef.current = null;\n const room: Room | null = roomRef.current;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n if (room) {\n room.removeAllListeners();\n await room.disconnect(true);\n }\n }, [detachAudio]);\n\n const stop = useCallback(async () => {\n const hadRoom: boolean =\n roomRef.current !== null || abortRef.current !== null;\n await teardown();\n setActiveSpeaker(null);\n if (hadRoom) setStatus('ended');\n }, [teardown]);\n\n const attachTrack = useCallback(\n (track: RemoteTrack) => {\n if (track.kind !== Track.Kind.Audio) return;\n if (audioElement) {\n track.attach(audioElement);\n attachedElementsRef.current.push(audioElement);\n return;\n }\n const element: HTMLMediaElement = track.attach();\n element.setAttribute('data-athena-voice-audio', '');\n document.body.appendChild(element);\n ownedAudioRef.current = element;\n attachedElementsRef.current.push(element);\n },\n [audioElement],\n );\n\n const handleTranscription = useCallback(\n (\n segments: TranscriptionSegment[],\n participant: Participant | undefined,\n room: Room,\n ) => {\n const speaker: AthenaVoiceSpeaker = speakerOf(participant, room);\n const committed: AthenaVoiceTranscriptTurn[] = [];\n for (const segment of segments) {\n if (!segment.final) {\n callbacksRef.current.onInterimTranscript?.(speaker, segment.text);\n continue;\n }\n if (committedSegmentIdsRef.current.has(segment.id)) continue;\n committedSegmentIdsRef.current.add(segment.id);\n committed.push({\n id: segment.id,\n speaker,\n text: segment.text,\n startTime: segment.startTime,\n endTime: segment.endTime,\n language: segment.language,\n });\n }\n if (committed.length === 0) return;\n setTranscript((previous) => [...previous, ...committed]);\n for (const turn of committed) callbacksRef.current.onTranscript?.(turn);\n },\n [],\n );\n\n const start = useCallback(async () => {\n if (startingRef.current || roomRef.current) return;\n startingRef.current = true;\n setError(null);\n setSessionId(null);\n setRoomName(null);\n setStatus('connecting');\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n let credentials: AthenaVoiceSessionCredentials;\n try {\n credentials = await callbacksRef.current.createSession(controller.signal);\n } catch (cause) {\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n fail(cause);\n return;\n }\n if (controller.signal.aborted) return;\n\n setSessionId(credentials.asset_id ?? null);\n setRoomName(credentials.room_name ?? null);\n\n const room: Room = createRoom ? createRoom() : new Room();\n roomRef.current = room;\n\n room\n .on(RoomEvent.TrackSubscribed, attachTrack)\n .on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const first: Participant | undefined = speakers[0];\n setActiveSpeaker(first ? speakerOf(first, room) : null);\n })\n .on(RoomEvent.TranscriptionReceived, (segments, participant) =>\n handleTranscription(segments, participant, room),\n )\n .on(RoomEvent.Reconnecting, () => setStatus('reconnecting'))\n .on(RoomEvent.Reconnected, () => setStatus('connected'))\n .on(RoomEvent.Disconnected, () => {\n if (roomRef.current !== room) return;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n setActiveSpeaker(null);\n setStatus('ended');\n })\n .on(RoomEvent.MediaDevicesError, fail);\n\n try {\n await room.connect(credentials.server_url, credentials.token);\n if (controller.signal.aborted) return;\n if (autoEnableMicrophone) {\n await room.localParticipant.setMicrophoneEnabled(true);\n setIsMuted(false);\n } else {\n setIsMuted(true);\n }\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n setStatus('connected');\n } catch (cause) {\n if (controller.signal.aborted) return;\n await teardown();\n fail(cause);\n }\n }, [\n attachTrack,\n autoEnableMicrophone,\n createRoom,\n detachAudio,\n fail,\n handleTranscription,\n teardown,\n ]);\n\n const setMicrophone = useCallback(async (enabled: boolean) => {\n const room: Room | null = roomRef.current;\n if (!room) return;\n await room.localParticipant.setMicrophoneEnabled(enabled);\n setIsMuted(!enabled);\n }, []);\n const mute = useCallback(() => setMicrophone(false), [setMicrophone]);\n const unmute = useCallback(() => setMicrophone(true), [setMicrophone]);\n\n const clearTranscript = useCallback(() => {\n committedSegmentIdsRef.current.clear();\n setTranscript([]);\n }, []);\n\n // Unmount teardown is deferred one tick so StrictMode's synchronous\n // unmount/remount of the same instance does not abort an in-flight\n // `createSession` (which would dispatch a second Orpheus agent on remount).\n const unmountTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n if (unmountTimerRef.current !== null) {\n clearTimeout(unmountTimerRef.current);\n unmountTimerRef.current = null;\n }\n return () => {\n unmountTimerRef.current = setTimeout(() => {\n unmountTimerRef.current = null;\n void teardown();\n }, 0);\n };\n }, [teardown]);\n\n return useMemo<UseAthenaVoiceSessionReturn>(\n () => ({\n status,\n isConnecting: status === 'connecting',\n isConnected: status === 'connected' || status === 'reconnecting',\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n }),\n [\n status,\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n ],\n );\n};\n"],"names":["useParentBridge","useRef","useEffect","useCallback","useState","Track","Room","RoomEvent","useMemo"],"mappings":";;;;;AAoLA,MAAM,UAAU,CAAC,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,C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OAAO;AAAA,MACL;AAAA,MACA,cAAc,WAAW;AAAA,MACzB,aAAa,WAAW,eAAe,WAAW;AAAA,MAClD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;;;"}
1
+ {"version":3,"file":"use-athena-voice-session.cjs","sources":["../../src/voice/use-athena-voice-session.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n Room,\n RoomEvent,\n Track,\n type Participant,\n type RemoteTrack,\n type TranscriptionSegment,\n} from 'livekit-client';\nimport { useParentBridge, type ParentBridgeState } from '../runtime/auth';\n\n/**\n * Realtime connection details for one Athena voice session. This is the shape\n * the Athena voice session endpoint returns; the hook only reads these\n * fields, so any server that proxies that call can hand it straight back.\n */\nexport interface AthenaVoiceSessionCredentials {\n /** Realtime signalling URL (`wss://…`). */\n server_url: string;\n /** Short-lived participant JWT scoped to `room_name`. */\n token: string;\n room_name?: string;\n /**\n * Athena session asset the voice run is persisted into. Use it with\n * `GET /api/v0/sessions/{asset_id}/download` to retrieve the transcript\n * after the call.\n */\n asset_id?: string;\n}\n\nexport type AthenaVoiceSessionStatus =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'ended'\n | 'error';\n\nexport type AthenaVoiceSpeaker = 'user' | 'agent';\n\n/** One committed (final) transcription segment from either side of the call. */\nexport interface AthenaVoiceTranscriptTurn {\n id: string;\n speaker: AthenaVoiceSpeaker;\n text: string;\n /** Segment start, in ms since the room's epoch. */\n startTime: number;\n endTime: number;\n language: string;\n}\n\n/**\n * A voice tool the Athena voice agent can run. These are voice tool\n * names, not the chat `Toolkits` ids: `'web_search_browse_toolkit'` is not a\n * voice tool, `'web_search'` is. Only these names are accepted.\n *\n * The agent also has tools that call back into the client over room RPC\n * (clipboard, selection, screen contents, opening assets). This hook registers\n * no RPC handlers, so they are not part of its contract.\n */\nexport type AthenaVoiceToolId =\n /** Web search. */\n | 'web_search'\n /** Legacy alias of `web_search`; prefer `web_search`. */\n | 'search_web'\n /** Fetch and read one URL. */\n | 'browse'\n /** The workspace knowledge base, where configured. */\n | 'search_knowledge_base'\n /** Same knowledge base, thorough long-running retrieval. */\n | 'search_knowledge_base_lr'\n /** Read Athena assets by id, as the viewer. */\n | 'read_full_asset'\n /** Search the viewer's Athena assets. */\n | 'search_assets'\n /** Hand a question to the general agent and speak its answer. */\n | 'ask_agent'\n /** Save a note for the user (a stub on the worker today). */\n | 'save_note'\n /** Current date and time, Eastern. */\n | 'get_current_time_est';\n\n/**\n * Voice agent configuration for a session the hook creates itself (see\n * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of the Athena\n * voice session endpoint; every field is optional and falls back to the\n * server default.\n */\nexport interface AthenaVoiceSessionConfig {\n /** Persona / instructions for the voice agent. */\n system_prompt?: string;\n /** Realtime provider, e.g. `'openai'` or `'google'`. */\n provider?: string;\n /** Provider model id, e.g. `'gpt-realtime-2'`. */\n model?: string;\n /** Provider voice id, e.g. `'marin'` (OpenAI) or `'Aoede'` (Google). */\n voice?: string;\n temperature?: number;\n /** BCP-47 language tag; default `'en'`. */\n language?: string;\n /**\n * Voice tools the agent may call. Omit it for the server's default set\n * (`web_search`, `search_knowledge_base`, `ask_agent`, …); pass `[]` for a\n * pure conversation with no tool calls.\n */\n enabled_tools?: AthenaVoiceToolId[];\n /** IANA timezone of the speaker, e.g. `'America/New_York'`. */\n timezone?: string;\n}\n\nexport interface UseAthenaVoiceSessionOptions {\n /**\n * Creates the voice session. Omit it when the app is served from a\n * Marathon computer-asset URL: the hook then calls the Athena voice session\n * endpoint itself with the viewer's bearer token from `/_athena/auth`, so\n * the session is created as — and shows up in the sessions of — whoever is\n * using the app.\n *\n * Works for workspace members and external SSO viewers alike: the scoped\n * `athview_` viewer credential is authorized for the voice session route and\n * `agents/general/invoke` the same way it is for `/api/v0/sessions`.\n *\n * Supply it when the app runs anywhere else (standalone, custom auth): it\n * should run on the caller's own server so the Athena API key never reaches\n * the browser. The hook only reads the returned credentials.\n *\n * Decide once: switching between supplying and omitting it across renders\n * of the same component is not supported.\n */\n createSession?: (\n signal: AbortSignal,\n ) => Promise<AthenaVoiceSessionCredentials>;\n /**\n * Agent configuration for sessions the hook creates itself. Ignored when\n * `createSession` is supplied.\n */\n session?: AthenaVoiceSessionConfig;\n /** Called once per committed transcript turn, in arrival order. */\n onTranscript?: (turn: AthenaVoiceTranscriptTurn) => void;\n /** Called with interim (non-final) transcript text as it streams in. */\n onInterimTranscript?: (speaker: AthenaVoiceSpeaker, text: string) => void;\n onError?: (error: Error) => void;\n /**\n * Where to play the agent's audio. Defaults to a detached `<audio>` element\n * the hook creates and removes itself.\n */\n audioElement?: HTMLMediaElement | null;\n /** Enable the microphone as soon as the room connects. Default `true`. */\n autoEnableMicrophone?: boolean;\n /** @internal Overrides `new Room()`; used by tests. */\n createRoom?: () => Room;\n /** @internal Overrides `useParentBridge()`; used by tests. */\n useBridge?: () => ParentBridgeState;\n}\n\nexport interface UseAthenaVoiceSessionReturn {\n status: AthenaVoiceSessionStatus;\n /** True between `start()` resolving the session and the room connecting. */\n isConnecting: boolean;\n isConnected: boolean;\n /** Who is speaking right now, or `null` when the room is quiet. */\n activeSpeaker: AthenaVoiceSpeaker | null;\n isMuted: boolean;\n /** Committed transcript turns so far, in arrival order. */\n transcript: AthenaVoiceTranscriptTurn[];\n /** Athena session asset id, once the session has been created. */\n sessionId: string | null;\n roomName: string | null;\n error: Error | null;\n /** Creates a session and joins the room. No-op while a session is live. */\n start: () => Promise<void>;\n /** Leaves the room and stops local tracks. Safe to call at any time. */\n stop: () => Promise<void>;\n mute: () => Promise<void>;\n unmute: () => Promise<void>;\n /** Clears `transcript`; does not affect the live session. */\n clearTranscript: () => void;\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst NO_BRIDGE: ParentBridgeState = {\n token: null,\n statewireSyncUrl: null,\n backendBaseUrl: null,\n appUrl: null,\n hostAnswered: false,\n ready: true,\n};\n// Stands in for `useParentBridge` when the caller creates sessions itself, so\n// the hook never fetches `/_athena/auth` it would not use.\nconst useNoBridge = (): ParentBridgeState => NO_BRIDGE;\n\nconst NO_VIEWER_TOKEN_MESSAGE =\n 'useAthenaVoiceSession: no Athena viewer token. Either serve the app from ' +\n 'a Marathon computer-asset URL (which mints one via /_athena/auth) or pass ' +\n '`createSession` to create the session through your own server.';\n\n/**\n * Creates an Athena voice session as the current viewer. Exported so apps with\n * their own bridge state (or a server proxy holding a user bearer) can reuse\n * the exact request the hook makes.\n */\nexport const createAthenaVoiceSession = async ({\n backendBaseUrl,\n token,\n session = {},\n signal,\n}: {\n /** Bare Athena API base, e.g. `https://api.athenaintel.com`. */\n backendBaseUrl: string;\n /** Bearer token for the user the session belongs to. */\n token: string;\n session?: AthenaVoiceSessionConfig;\n signal?: AbortSignal;\n}): Promise<AthenaVoiceSessionCredentials> => {\n const url: string = `${backendBaseUrl.replace(/\\/+$/, '')}/api/orpheus/create-session`;\n const response: Response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(session),\n signal,\n });\n if (!response.ok) {\n const detail: string = await response.text().catch(() => '');\n throw new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n );\n }\n return (await response.json()) as AthenaVoiceSessionCredentials;\n};\n\nconst speakerOf = (\n participant: Participant | undefined,\n room: Room,\n): AthenaVoiceSpeaker =>\n participant !== undefined &&\n participant.identity === room.localParticipant.identity\n ? 'user'\n : 'agent';\n\n/**\n * Runs one Athena voice session from React.\n *\n * Owns the whole browser-side lifecycle the voice API leaves to the caller:\n * creating the session through the app's own server, joining the room,\n * publishing the microphone, playing the agent's audio, tracking who is\n * speaking, committing transcript turns from room transcription events, and\n * tearing everything down on `stop()` or unmount. A second `start()` while a\n * session is live (or still connecting) is ignored, so React StrictMode's\n * double-invoked effects cannot dispatch two agents into one room.\n */\nexport const useAthenaVoiceSession = (\n options: UseAthenaVoiceSessionOptions = {},\n): UseAthenaVoiceSessionReturn => {\n const {\n createSession,\n session,\n onTranscript,\n onInterimTranscript,\n onError,\n audioElement,\n autoEnableMicrophone = true,\n createRoom,\n useBridge = createSession ? useNoBridge : useParentBridge,\n } = options;\n\n // Viewer identity minted by Marathon (`/_athena/auth`) or the Athena app\n // iframe bridge. Only consulted when the caller did not supply `createSession`.\n const bridge: ParentBridgeState = useBridge();\n const bridgeRef = useRef<ParentBridgeState>(bridge);\n bridgeRef.current = bridge;\n const bridgeReadyWaitersRef = useRef<Array<() => void>>([]);\n useEffect(() => {\n if (!bridge.ready) return;\n const waiters: Array<() => void> = bridgeReadyWaitersRef.current;\n bridgeReadyWaitersRef.current = [];\n for (const resolve of waiters) resolve();\n }, [bridge.ready]);\n\n const sessionRef = useRef<AthenaVoiceSessionConfig | undefined>(session);\n sessionRef.current = session;\n\n const createSessionAsViewer = useCallback(\n async (signal: AbortSignal): Promise<AthenaVoiceSessionCredentials> => {\n if (!bridgeRef.current.ready) {\n await new Promise<void>((resolve) => {\n bridgeReadyWaitersRef.current.push(resolve);\n signal.addEventListener('abort', () => resolve(), { once: true });\n });\n if (signal.aborted) throw new Error('aborted');\n }\n const { token, backendBaseUrl } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n return createAthenaVoiceSession({\n backendBaseUrl,\n token,\n session: sessionRef.current,\n signal,\n });\n },\n [],\n );\n\n const [status, setStatus] = useState<AthenaVoiceSessionStatus>('idle');\n const [activeSpeaker, setActiveSpeaker] = useState<AthenaVoiceSpeaker | null>(\n null,\n );\n const [isMuted, setIsMuted] = useState<boolean>(false);\n const [transcript, setTranscript] = useState<AthenaVoiceTranscriptTurn[]>([]);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [roomName, setRoomName] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Latest callbacks without re-subscribing room listeners on every render.\n const callbacksRef = useRef({\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n });\n callbacksRef.current = {\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n };\n\n const roomRef = useRef<Room | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const attachedElementsRef = useRef<HTMLMediaElement[]>([]);\n const ownedAudioRef = useRef<HTMLMediaElement | null>(null);\n const committedSegmentIdsRef = useRef<Set<string>>(new Set());\n // Guards `start()` against re-entry from the moment it is called, before any\n // state update lands — a StrictMode double effect fires both calls\n // synchronously in the same tick.\n const startingRef = useRef<boolean>(false);\n\n const fail = useCallback((cause: unknown) => {\n const err: Error = toError(cause);\n setError(err);\n setStatus('error');\n callbacksRef.current.onError?.(err);\n }, []);\n\n const detachAudio = useCallback(() => {\n for (const element of attachedElementsRef.current) {\n element.srcObject = null;\n if (element === ownedAudioRef.current) element.remove();\n }\n attachedElementsRef.current = [];\n ownedAudioRef.current = null;\n }, []);\n\n const teardown = useCallback(async () => {\n abortRef.current?.abort();\n abortRef.current = null;\n const room: Room | null = roomRef.current;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n if (room) {\n room.removeAllListeners();\n await room.disconnect(true);\n }\n }, [detachAudio]);\n\n const stop = useCallback(async () => {\n const hadRoom: boolean =\n roomRef.current !== null || abortRef.current !== null;\n await teardown();\n setActiveSpeaker(null);\n if (hadRoom) setStatus('ended');\n }, [teardown]);\n\n const attachTrack = useCallback(\n (track: RemoteTrack) => {\n if (track.kind !== Track.Kind.Audio) return;\n if (audioElement) {\n track.attach(audioElement);\n attachedElementsRef.current.push(audioElement);\n return;\n }\n const element: HTMLMediaElement = track.attach();\n element.setAttribute('data-athena-voice-audio', '');\n document.body.appendChild(element);\n ownedAudioRef.current = element;\n attachedElementsRef.current.push(element);\n },\n [audioElement],\n );\n\n const handleTranscription = useCallback(\n (\n segments: TranscriptionSegment[],\n participant: Participant | undefined,\n room: Room,\n ) => {\n const speaker: AthenaVoiceSpeaker = speakerOf(participant, room);\n const committed: AthenaVoiceTranscriptTurn[] = [];\n for (const segment of segments) {\n if (!segment.final) {\n callbacksRef.current.onInterimTranscript?.(speaker, segment.text);\n continue;\n }\n if (committedSegmentIdsRef.current.has(segment.id)) continue;\n committedSegmentIdsRef.current.add(segment.id);\n committed.push({\n id: segment.id,\n speaker,\n text: segment.text,\n startTime: segment.startTime,\n endTime: segment.endTime,\n language: segment.language,\n });\n }\n if (committed.length === 0) return;\n setTranscript((previous) => [...previous, ...committed]);\n for (const turn of committed) callbacksRef.current.onTranscript?.(turn);\n },\n [],\n );\n\n const start = useCallback(async () => {\n if (startingRef.current || roomRef.current) return;\n startingRef.current = true;\n setError(null);\n setSessionId(null);\n setRoomName(null);\n setStatus('connecting');\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n let credentials: AthenaVoiceSessionCredentials;\n try {\n credentials = await callbacksRef.current.createSession(controller.signal);\n } catch (cause) {\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n fail(cause);\n return;\n }\n if (controller.signal.aborted) return;\n\n setSessionId(credentials.asset_id ?? null);\n setRoomName(credentials.room_name ?? null);\n\n const room: Room = createRoom ? createRoom() : new Room();\n roomRef.current = room;\n\n room\n .on(RoomEvent.TrackSubscribed, attachTrack)\n .on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const first: Participant | undefined = speakers[0];\n setActiveSpeaker(first ? speakerOf(first, room) : null);\n })\n .on(RoomEvent.TranscriptionReceived, (segments, participant) =>\n handleTranscription(segments, participant, room),\n )\n .on(RoomEvent.Reconnecting, () => setStatus('reconnecting'))\n .on(RoomEvent.Reconnected, () => setStatus('connected'))\n .on(RoomEvent.Disconnected, () => {\n if (roomRef.current !== room) return;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n setActiveSpeaker(null);\n setStatus('ended');\n })\n .on(RoomEvent.MediaDevicesError, fail);\n\n try {\n await room.connect(credentials.server_url, credentials.token);\n if (controller.signal.aborted) return;\n if (autoEnableMicrophone) {\n await room.localParticipant.setMicrophoneEnabled(true);\n setIsMuted(false);\n } else {\n setIsMuted(true);\n }\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n setStatus('connected');\n } catch (cause) {\n if (controller.signal.aborted) return;\n await teardown();\n fail(cause);\n }\n }, [\n attachTrack,\n autoEnableMicrophone,\n createRoom,\n detachAudio,\n fail,\n handleTranscription,\n teardown,\n ]);\n\n const setMicrophone = useCallback(async (enabled: boolean) => {\n const room: Room | null = roomRef.current;\n if (!room) return;\n await room.localParticipant.setMicrophoneEnabled(enabled);\n setIsMuted(!enabled);\n }, []);\n const mute = useCallback(() => setMicrophone(false), [setMicrophone]);\n const unmute = useCallback(() => setMicrophone(true), [setMicrophone]);\n\n const clearTranscript = useCallback(() => {\n committedSegmentIdsRef.current.clear();\n setTranscript([]);\n }, []);\n\n // Unmount teardown is deferred one tick so StrictMode's synchronous\n // unmount/remount of the same instance does not abort an in-flight\n // `createSession` (which would dispatch a second voice agent on remount).\n const unmountTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n if (unmountTimerRef.current !== null) {\n clearTimeout(unmountTimerRef.current);\n unmountTimerRef.current = null;\n }\n return () => {\n unmountTimerRef.current = setTimeout(() => {\n unmountTimerRef.current = null;\n void teardown();\n }, 0);\n };\n }, [teardown]);\n\n return useMemo<UseAthenaVoiceSessionReturn>(\n () => ({\n status,\n isConnecting: status === 'connecting',\n isConnected: status === 'connected' || status === 'reconnecting',\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n }),\n [\n status,\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n ],\n );\n};\n"],"names":["useParentBridge","useRef","useEffect","useCallback","useState","Track","Room","RoomEvent","useMemo"],"mappings":";;;;;AAmLA,MAAM,UAAU,CAAC,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAE1D,MAAM,YAA+B;AAAA,EACnC,OAAO;AAAA,EACP,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,OAAO;AACT;AAGA,MAAM,cAAc,MAAyB;AAE7C,MAAM,0BACJ;AASK,MAAM,2BAA2B,OAAO;AAAA,EAC7C;AAAA,EACA;AAAA,EACA,UAAU,CAAA;AAAA,EACV;AACF,MAO8C;AAC5C,QAAM,MAAc,GAAG,eAAe,QAAQ,QAAQ,EAAE,CAAC;AACzD,QAAM,WAAqB,MAAM,MAAM,KAAK;AAAA,IAC1C,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,KAAK;AAAA,IAAA;AAAA,IAEhC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B;AAAA,EAAA,CACD;AACD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,SAAiB,MAAM,SAAS,OAAO,MAAM,MAAM,EAAE;AAC3D,UAAM,IAAI;AAAA,MACR,yCAAyC,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,KAAK,EAAE;AAAA,IAAA;AAAA,EAE3F;AACA,SAAQ,MAAM,SAAS,KAAA;AACzB;AAEA,MAAM,YAAY,CAChB,aACA,SAEA,gBAAgB,UAChB,YAAY,aAAa,KAAK,iBAAiB,WAC3C,SACA;AAaC,MAAM,wBAAwB,CACnC,UAAwC,OACR;AAChC,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA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d,QAAI,gBAAgB,YAAY,MAAM;AACpC,mBAAa,gBAAgB,OAAO;AACpC,sBAAgB,UAAU;AAAA,IAC5B;AACA,WAAO,MAAM;AACX,sBAAgB,UAAU,WAAW,MAAM;AACzC,wBAAgB,UAAU;AAC1B,aAAK,SAAA;AAAA,MACP,GAAG,CAAC;AAAA,IACN;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAOM,MAAAA;AAAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA,cAAc,WAAW;AAAA,MACzB,aAAa,WAAW,eAAe,WAAW;AAAA,MAClD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;;;"}
@@ -1,14 +1,14 @@
1
1
  import { Room } from 'livekit-client';
2
2
  import { type ParentBridgeState } from '../runtime/auth';
3
3
  /**
4
- * LiveKit connection details for one Athena voice session. This is the shape
5
- * Orpheus returns from `POST /api/orpheus/create-session`; the hook only reads
6
- * these fields, so any server that proxies that call can hand it straight back.
4
+ * Realtime connection details for one Athena voice session. This is the shape
5
+ * the Athena voice session endpoint returns; the hook only reads these
6
+ * fields, so any server that proxies that call can hand it straight back.
7
7
  */
8
8
  export interface AthenaVoiceSessionCredentials {
9
- /** LiveKit signalling URL (`wss://…`). */
9
+ /** Realtime signalling URL (`wss://…`). */
10
10
  server_url: string;
11
- /** Short-lived LiveKit participant JWT scoped to `room_name`. */
11
+ /** Short-lived participant JWT scoped to `room_name`. */
12
12
  token: string;
13
13
  room_name?: string;
14
14
  /**
@@ -25,29 +25,28 @@ export interface AthenaVoiceTranscriptTurn {
25
25
  id: string;
26
26
  speaker: AthenaVoiceSpeaker;
27
27
  text: string;
28
- /** Segment start, in ms since the LiveKit room's epoch. */
28
+ /** Segment start, in ms since the room's epoch. */
29
29
  startTime: number;
30
30
  endTime: number;
31
31
  language: string;
32
32
  }
33
33
  /**
34
- * A voice tool the Orpheus worker can run for the agent. These are voice tool
34
+ * A voice tool the Athena voice agent can run. These are voice tool
35
35
  * names, not the chat `Toolkits` ids: `'web_search_browse_toolkit'` is not a
36
36
  * voice tool, `'web_search'` is. Only these names are accepted.
37
37
  *
38
- * The worker also has tools that call back into the client over LiveKit RPC
39
- * (`write_to_clipboard`, `replace_current_selection`, `open_in_olympus`,
40
- * `open_asset`, `get_screen_contents`). This hook registers no RPC handlers,
41
- * so they are not part of its contract.
38
+ * The agent also has tools that call back into the client over room RPC
39
+ * (clipboard, selection, screen contents, opening assets). This hook registers
40
+ * no RPC handlers, so they are not part of its contract.
42
41
  */
43
42
  export type AthenaVoiceToolId =
44
- /** Web search (Exa). */
43
+ /** Web search. */
45
44
  'web_search'
46
45
  /** Legacy alias of `web_search`; prefer `web_search`. */
47
46
  | 'search_web'
48
47
  /** Fetch and read one URL. */
49
48
  | 'browse'
50
- /** The workspace knowledge base (Ragie), where configured. */
49
+ /** The workspace knowledge base, where configured. */
51
50
  | 'search_knowledge_base'
52
51
  /** Same knowledge base, thorough long-running retrieval. */
53
52
  | 'search_knowledge_base_lr'
@@ -62,10 +61,10 @@ export type AthenaVoiceToolId =
62
61
  /** Current date and time, Eastern. */
63
62
  | 'get_current_time_est';
64
63
  /**
65
- * Orpheus agent configuration for a session the hook creates itself (see
66
- * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of
67
- * `POST /api/orpheus/create-session`; every field is optional and falls back
68
- * to the server default.
64
+ * Voice agent configuration for a session the hook creates itself (see
65
+ * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of the Athena
66
+ * voice session endpoint; every field is optional and falls back to the
67
+ * server default.
69
68
  */
70
69
  export interface AthenaVoiceSessionConfig {
71
70
  /** Persona / instructions for the voice agent. */
@@ -90,14 +89,14 @@ export interface AthenaVoiceSessionConfig {
90
89
  }
91
90
  export interface UseAthenaVoiceSessionOptions {
92
91
  /**
93
- * Creates the LiveKit session. Omit it when the app is served from a
94
- * Marathon computer-asset URL: the hook then calls
95
- * `POST {backendBaseUrl}/api/orpheus/create-session` itself with the
96
- * viewer's bearer token from `/_athena/auth`, so the session is created as
97
- * — and shows up in the sessions of — whoever is using the app.
92
+ * Creates the voice session. Omit it when the app is served from a
93
+ * Marathon computer-asset URL: the hook then calls the Athena voice session
94
+ * endpoint itself with the viewer's bearer token from `/_athena/auth`, so
95
+ * the session is created as — and shows up in the sessions of — whoever is
96
+ * using the app.
98
97
  *
99
98
  * Works for workspace members and external SSO viewers alike: the scoped
100
- * `athview_` viewer credential is authorized for the Orpheus route and
99
+ * `athview_` viewer credential is authorized for the voice session route and
101
100
  * `agents/general/invoke` the same way it is for `/api/v0/sessions`.
102
101
  *
103
102
  * Supply it when the app runs anywhere else (standalone, custom auth): it
@@ -154,12 +153,12 @@ export interface UseAthenaVoiceSessionReturn {
154
153
  clearTranscript: () => void;
155
154
  }
156
155
  /**
157
- * `POST /api/orpheus/create-session` as the current viewer. Exported so apps
158
- * with their own bridge state (or a server proxy holding a user bearer) can
159
- * reuse the exact request the hook makes.
156
+ * Creates an Athena voice session as the current viewer. Exported so apps with
157
+ * their own bridge state (or a server proxy holding a user bearer) can reuse
158
+ * the exact request the hook makes.
160
159
  */
161
160
  export declare const createAthenaVoiceSession: ({ backendBaseUrl, token, session, signal, }: {
162
- /** Bare Agora API base, e.g. `https://api.athenaintel.com`. */
161
+ /** Bare Athena API base, e.g. `https://api.athenaintel.com`. */
163
162
  backendBaseUrl: string;
164
163
  /** Bearer token for the user the session belongs to. */
165
164
  token: string;
@@ -167,12 +166,12 @@ export declare const createAthenaVoiceSession: ({ backendBaseUrl, token, session
167
166
  signal?: AbortSignal;
168
167
  }) => Promise<AthenaVoiceSessionCredentials>;
169
168
  /**
170
- * Runs one Athena voice session (Orpheus agent over LiveKit) from React.
169
+ * Runs one Athena voice session from React.
171
170
  *
172
- * Owns the whole browser-side lifecycle the Orpheus API leaves to the caller:
173
- * creating the session through the app's own server, joining the LiveKit room,
171
+ * Owns the whole browser-side lifecycle the voice API leaves to the caller:
172
+ * creating the session through the app's own server, joining the room,
174
173
  * publishing the microphone, playing the agent's audio, tracking who is
175
- * speaking, committing transcript turns from LiveKit transcription events, and
174
+ * speaking, committing transcript turns from room transcription events, and
176
175
  * tearing everything down on `stop()` or unmount. A second `start()` while a
177
176
  * session is live (or still connecting) is ignored, so React StrictMode's
178
177
  * double-invoked effects cannot dispatch two agents into one room.
@@ -31,7 +31,7 @@ const createAthenaVoiceSession = async ({
31
31
  if (!response.ok) {
32
32
  const detail = await response.text().catch(() => "");
33
33
  throw new Error(
34
- `Orpheus create-session failed (${response.status})${detail ? `: ${detail}` : ""}`
34
+ `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ""}`
35
35
  );
36
36
  }
37
37
  return await response.json();
@@ -1 +1 @@
1
- {"version":3,"file":"use-athena-voice-session.js","sources":["../../src/voice/use-athena-voice-session.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n Room,\n RoomEvent,\n Track,\n type Participant,\n type RemoteTrack,\n type TranscriptionSegment,\n} from 'livekit-client';\nimport { useParentBridge, type ParentBridgeState } from '../runtime/auth';\n\n/**\n * LiveKit connection details for one Athena voice session. This is the shape\n * Orpheus returns from `POST /api/orpheus/create-session`; the hook only reads\n * these fields, so any server that proxies that call can hand it straight back.\n */\nexport interface AthenaVoiceSessionCredentials {\n /** LiveKit signalling URL (`wss://…`). */\n server_url: string;\n /** Short-lived LiveKit participant JWT scoped to `room_name`. */\n token: string;\n room_name?: string;\n /**\n * Athena session asset the voice run is persisted into. Use it with\n * `GET /api/v0/sessions/{asset_id}/download` to retrieve the transcript\n * after the call.\n */\n asset_id?: string;\n}\n\nexport type AthenaVoiceSessionStatus =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'ended'\n | 'error';\n\nexport type AthenaVoiceSpeaker = 'user' | 'agent';\n\n/** One committed (final) transcription segment from either side of the call. */\nexport interface AthenaVoiceTranscriptTurn {\n id: string;\n speaker: AthenaVoiceSpeaker;\n text: string;\n /** Segment start, in ms since the LiveKit room's epoch. */\n startTime: number;\n endTime: number;\n language: string;\n}\n\n/**\n * A voice tool the Orpheus worker can run for the agent. These are voice tool\n * names, not the chat `Toolkits` ids: `'web_search_browse_toolkit'` is not a\n * voice tool, `'web_search'` is. Only these names are accepted.\n *\n * The worker also has tools that call back into the client over LiveKit RPC\n * (`write_to_clipboard`, `replace_current_selection`, `open_in_olympus`,\n * `open_asset`, `get_screen_contents`). This hook registers no RPC handlers,\n * so they are not part of its contract.\n */\nexport type AthenaVoiceToolId =\n /** Web search (Exa). */\n | 'web_search'\n /** Legacy alias of `web_search`; prefer `web_search`. */\n | 'search_web'\n /** Fetch and read one URL. */\n | 'browse'\n /** The workspace knowledge base (Ragie), where configured. */\n | 'search_knowledge_base'\n /** Same knowledge base, thorough long-running retrieval. */\n | 'search_knowledge_base_lr'\n /** Read Athena assets by id, as the viewer. */\n | 'read_full_asset'\n /** Search the viewer's Athena assets. */\n | 'search_assets'\n /** Hand a question to the general agent and speak its answer. */\n | 'ask_agent'\n /** Save a note for the user (a stub on the worker today). */\n | 'save_note'\n /** Current date and time, Eastern. */\n | 'get_current_time_est';\n\n/**\n * Orpheus agent configuration for a session the hook creates itself (see\n * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of\n * `POST /api/orpheus/create-session`; every field is optional and falls back\n * to the server default.\n */\nexport interface AthenaVoiceSessionConfig {\n /** Persona / instructions for the voice agent. */\n system_prompt?: string;\n /** Realtime provider, e.g. `'openai'` or `'google'`. */\n provider?: string;\n /** Provider model id, e.g. `'gpt-realtime-2'`. */\n model?: string;\n /** Provider voice id, e.g. `'marin'` (OpenAI) or `'Aoede'` (Google). */\n voice?: string;\n temperature?: number;\n /** BCP-47 language tag; default `'en'`. */\n language?: string;\n /**\n * Voice tools the agent may call. Omit it for the server's default set\n * (`web_search`, `search_knowledge_base`, `ask_agent`, …); pass `[]` for a\n * pure conversation with no tool calls.\n */\n enabled_tools?: AthenaVoiceToolId[];\n /** IANA timezone of the speaker, e.g. `'America/New_York'`. */\n timezone?: string;\n}\n\nexport interface UseAthenaVoiceSessionOptions {\n /**\n * Creates the LiveKit session. Omit it when the app is served from a\n * Marathon computer-asset URL: the hook then calls\n * `POST {backendBaseUrl}/api/orpheus/create-session` itself with the\n * viewer's bearer token from `/_athena/auth`, so the session is created as\n * — and shows up in the sessions of — whoever is using the app.\n *\n * Works for workspace members and external SSO viewers alike: the scoped\n * `athview_` viewer credential is authorized for the Orpheus route and\n * `agents/general/invoke` the same way it is for `/api/v0/sessions`.\n *\n * Supply it when the app runs anywhere else (standalone, custom auth): it\n * should run on the caller's own server so the Athena API key never reaches\n * the browser. The hook only reads the returned credentials.\n *\n * Decide once: switching between supplying and omitting it across renders\n * of the same component is not supported.\n */\n createSession?: (\n signal: AbortSignal,\n ) => Promise<AthenaVoiceSessionCredentials>;\n /**\n * Agent configuration for sessions the hook creates itself. Ignored when\n * `createSession` is supplied.\n */\n session?: AthenaVoiceSessionConfig;\n /** Called once per committed transcript turn, in arrival order. */\n onTranscript?: (turn: AthenaVoiceTranscriptTurn) => void;\n /** Called with interim (non-final) transcript text as it streams in. */\n onInterimTranscript?: (speaker: AthenaVoiceSpeaker, text: string) => void;\n onError?: (error: Error) => void;\n /**\n * Where to play the agent's audio. Defaults to a detached `<audio>` element\n * the hook creates and removes itself.\n */\n audioElement?: HTMLMediaElement | null;\n /** Enable the microphone as soon as the room connects. Default `true`. */\n autoEnableMicrophone?: boolean;\n /** @internal Overrides `new Room()`; used by tests. */\n createRoom?: () => Room;\n /** @internal Overrides `useParentBridge()`; used by tests. */\n useBridge?: () => ParentBridgeState;\n}\n\nexport interface UseAthenaVoiceSessionReturn {\n status: AthenaVoiceSessionStatus;\n /** True between `start()` resolving the session and the room connecting. */\n isConnecting: boolean;\n isConnected: boolean;\n /** Who is speaking right now, or `null` when the room is quiet. */\n activeSpeaker: AthenaVoiceSpeaker | null;\n isMuted: boolean;\n /** Committed transcript turns so far, in arrival order. */\n transcript: AthenaVoiceTranscriptTurn[];\n /** Athena session asset id, once the session has been created. */\n sessionId: string | null;\n roomName: string | null;\n error: Error | null;\n /** Creates a session and joins the room. No-op while a session is live. */\n start: () => Promise<void>;\n /** Leaves the room and stops local tracks. Safe to call at any time. */\n stop: () => Promise<void>;\n mute: () => Promise<void>;\n unmute: () => Promise<void>;\n /** Clears `transcript`; does not affect the live session. */\n clearTranscript: () => void;\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst NO_BRIDGE: ParentBridgeState = {\n token: null,\n statewireSyncUrl: null,\n backendBaseUrl: null,\n appUrl: null,\n hostAnswered: false,\n ready: true,\n};\n// Stands in for `useParentBridge` when the caller creates sessions itself, so\n// the hook never fetches `/_athena/auth` it would not use.\nconst useNoBridge = (): ParentBridgeState => NO_BRIDGE;\n\nconst NO_VIEWER_TOKEN_MESSAGE =\n 'useAthenaVoiceSession: no Athena viewer token. Either serve the app from ' +\n 'a Marathon computer-asset URL (which mints one via /_athena/auth) or pass ' +\n '`createSession` to create the session through your own server.';\n\n/**\n * `POST /api/orpheus/create-session` as the current viewer. Exported so apps\n * with their own bridge state (or a server proxy holding a user bearer) can\n * reuse the exact request the hook makes.\n */\nexport const createAthenaVoiceSession = async ({\n backendBaseUrl,\n token,\n session = {},\n signal,\n}: {\n /** Bare Agora API base, e.g. `https://api.athenaintel.com`. */\n backendBaseUrl: string;\n /** Bearer token for the user the session belongs to. */\n token: string;\n session?: AthenaVoiceSessionConfig;\n signal?: AbortSignal;\n}): Promise<AthenaVoiceSessionCredentials> => {\n const url: string = `${backendBaseUrl.replace(/\\/+$/, '')}/api/orpheus/create-session`;\n const response: Response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(session),\n signal,\n });\n if (!response.ok) {\n const detail: string = await response.text().catch(() => '');\n throw new Error(\n `Orpheus create-session failed (${response.status})${detail ? `: ${detail}` : ''}`,\n );\n }\n return (await response.json()) as AthenaVoiceSessionCredentials;\n};\n\nconst speakerOf = (\n participant: Participant | undefined,\n room: Room,\n): AthenaVoiceSpeaker =>\n participant !== undefined &&\n participant.identity === room.localParticipant.identity\n ? 'user'\n : 'agent';\n\n/**\n * Runs one Athena voice session (Orpheus agent over LiveKit) from React.\n *\n * Owns the whole browser-side lifecycle the Orpheus API leaves to the caller:\n * creating the session through the app's own server, joining the LiveKit room,\n * publishing the microphone, playing the agent's audio, tracking who is\n * speaking, committing transcript turns from LiveKit transcription events, and\n * tearing everything down on `stop()` or unmount. A second `start()` while a\n * session is live (or still connecting) is ignored, so React StrictMode's\n * double-invoked effects cannot dispatch two agents into one room.\n */\nexport const useAthenaVoiceSession = (\n options: UseAthenaVoiceSessionOptions = {},\n): UseAthenaVoiceSessionReturn => {\n const {\n createSession,\n session,\n onTranscript,\n onInterimTranscript,\n onError,\n audioElement,\n autoEnableMicrophone = true,\n createRoom,\n useBridge = createSession ? useNoBridge : useParentBridge,\n } = options;\n\n // Viewer identity minted by Marathon (`/_athena/auth`) or the Olympus iframe\n // bridge. Only consulted when the caller did not supply `createSession`.\n const bridge: ParentBridgeState = useBridge();\n const bridgeRef = useRef<ParentBridgeState>(bridge);\n bridgeRef.current = bridge;\n const bridgeReadyWaitersRef = useRef<Array<() => void>>([]);\n useEffect(() => {\n if (!bridge.ready) return;\n const waiters: Array<() => void> = bridgeReadyWaitersRef.current;\n bridgeReadyWaitersRef.current = [];\n for (const resolve of waiters) resolve();\n }, [bridge.ready]);\n\n const sessionRef = useRef<AthenaVoiceSessionConfig | undefined>(session);\n sessionRef.current = session;\n\n const createSessionAsViewer = useCallback(\n async (signal: AbortSignal): Promise<AthenaVoiceSessionCredentials> => {\n if (!bridgeRef.current.ready) {\n await new Promise<void>((resolve) => {\n bridgeReadyWaitersRef.current.push(resolve);\n signal.addEventListener('abort', () => resolve(), { once: true });\n });\n if (signal.aborted) throw new Error('aborted');\n }\n const { token, backendBaseUrl } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n return createAthenaVoiceSession({\n backendBaseUrl,\n token,\n session: sessionRef.current,\n signal,\n });\n },\n [],\n );\n\n const [status, setStatus] = useState<AthenaVoiceSessionStatus>('idle');\n const [activeSpeaker, setActiveSpeaker] = useState<AthenaVoiceSpeaker | null>(\n null,\n );\n const [isMuted, setIsMuted] = useState<boolean>(false);\n const [transcript, setTranscript] = useState<AthenaVoiceTranscriptTurn[]>([]);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [roomName, setRoomName] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Latest callbacks without re-subscribing room listeners on every render.\n const callbacksRef = useRef({\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n });\n callbacksRef.current = {\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n };\n\n const roomRef = useRef<Room | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const attachedElementsRef = useRef<HTMLMediaElement[]>([]);\n const ownedAudioRef = useRef<HTMLMediaElement | null>(null);\n const committedSegmentIdsRef = useRef<Set<string>>(new Set());\n // Guards `start()` against re-entry from the moment it is called, before any\n // state update lands — a StrictMode double effect fires both calls\n // synchronously in the same tick.\n const startingRef = useRef<boolean>(false);\n\n const fail = useCallback((cause: unknown) => {\n const err: Error = toError(cause);\n setError(err);\n setStatus('error');\n callbacksRef.current.onError?.(err);\n }, []);\n\n const detachAudio = useCallback(() => {\n for (const element of attachedElementsRef.current) {\n element.srcObject = null;\n if (element === ownedAudioRef.current) element.remove();\n }\n attachedElementsRef.current = [];\n ownedAudioRef.current = null;\n }, []);\n\n const teardown = useCallback(async () => {\n abortRef.current?.abort();\n abortRef.current = null;\n const room: Room | null = roomRef.current;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n if (room) {\n room.removeAllListeners();\n await room.disconnect(true);\n }\n }, [detachAudio]);\n\n const stop = useCallback(async () => {\n const hadRoom: boolean =\n roomRef.current !== null || abortRef.current !== null;\n await teardown();\n setActiveSpeaker(null);\n if (hadRoom) setStatus('ended');\n }, [teardown]);\n\n const attachTrack = useCallback(\n (track: RemoteTrack) => {\n if (track.kind !== Track.Kind.Audio) return;\n if (audioElement) {\n track.attach(audioElement);\n attachedElementsRef.current.push(audioElement);\n return;\n }\n const element: HTMLMediaElement = track.attach();\n element.setAttribute('data-athena-voice-audio', '');\n document.body.appendChild(element);\n ownedAudioRef.current = element;\n attachedElementsRef.current.push(element);\n },\n [audioElement],\n );\n\n const handleTranscription = useCallback(\n (\n segments: TranscriptionSegment[],\n participant: Participant | undefined,\n room: Room,\n ) => {\n const speaker: AthenaVoiceSpeaker = speakerOf(participant, room);\n const committed: AthenaVoiceTranscriptTurn[] = [];\n for (const segment of segments) {\n if (!segment.final) {\n callbacksRef.current.onInterimTranscript?.(speaker, segment.text);\n continue;\n }\n if (committedSegmentIdsRef.current.has(segment.id)) continue;\n committedSegmentIdsRef.current.add(segment.id);\n committed.push({\n id: segment.id,\n speaker,\n text: segment.text,\n startTime: segment.startTime,\n endTime: segment.endTime,\n language: segment.language,\n });\n }\n if (committed.length === 0) return;\n setTranscript((previous) => [...previous, ...committed]);\n for (const turn of committed) callbacksRef.current.onTranscript?.(turn);\n },\n [],\n );\n\n const start = useCallback(async () => {\n if (startingRef.current || roomRef.current) return;\n startingRef.current = true;\n setError(null);\n setSessionId(null);\n setRoomName(null);\n setStatus('connecting');\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n let credentials: AthenaVoiceSessionCredentials;\n try {\n credentials = await callbacksRef.current.createSession(controller.signal);\n } catch (cause) {\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n fail(cause);\n return;\n }\n if (controller.signal.aborted) return;\n\n setSessionId(credentials.asset_id ?? null);\n setRoomName(credentials.room_name ?? null);\n\n const room: Room = createRoom ? createRoom() : new Room();\n roomRef.current = room;\n\n room\n .on(RoomEvent.TrackSubscribed, attachTrack)\n .on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const first: Participant | undefined = speakers[0];\n setActiveSpeaker(first ? speakerOf(first, room) : null);\n })\n .on(RoomEvent.TranscriptionReceived, (segments, participant) =>\n handleTranscription(segments, participant, room),\n )\n .on(RoomEvent.Reconnecting, () => setStatus('reconnecting'))\n .on(RoomEvent.Reconnected, () => setStatus('connected'))\n .on(RoomEvent.Disconnected, () => {\n if (roomRef.current !== room) return;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n setActiveSpeaker(null);\n setStatus('ended');\n })\n .on(RoomEvent.MediaDevicesError, fail);\n\n try {\n await room.connect(credentials.server_url, credentials.token);\n if (controller.signal.aborted) return;\n if (autoEnableMicrophone) {\n await room.localParticipant.setMicrophoneEnabled(true);\n setIsMuted(false);\n } else {\n setIsMuted(true);\n }\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n setStatus('connected');\n } catch (cause) {\n if (controller.signal.aborted) return;\n await teardown();\n fail(cause);\n }\n }, [\n attachTrack,\n autoEnableMicrophone,\n createRoom,\n detachAudio,\n fail,\n handleTranscription,\n teardown,\n ]);\n\n const setMicrophone = useCallback(async (enabled: boolean) => {\n const room: Room | null = roomRef.current;\n if (!room) return;\n await room.localParticipant.setMicrophoneEnabled(enabled);\n setIsMuted(!enabled);\n }, []);\n const mute = useCallback(() => setMicrophone(false), [setMicrophone]);\n const unmute = useCallback(() => setMicrophone(true), [setMicrophone]);\n\n const clearTranscript = useCallback(() => {\n committedSegmentIdsRef.current.clear();\n setTranscript([]);\n }, []);\n\n // Unmount teardown is deferred one tick so StrictMode's synchronous\n // unmount/remount of the same instance does not abort an in-flight\n // `createSession` (which would dispatch a second Orpheus agent on remount).\n const unmountTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n if (unmountTimerRef.current !== null) {\n clearTimeout(unmountTimerRef.current);\n unmountTimerRef.current = null;\n }\n return () => {\n unmountTimerRef.current = setTimeout(() => {\n unmountTimerRef.current = null;\n void teardown();\n }, 0);\n };\n }, [teardown]);\n\n return useMemo<UseAthenaVoiceSessionReturn>(\n () => ({\n status,\n isConnecting: status === 'connecting',\n isConnected: status === 'connected' || status === 'reconnecting',\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n }),\n [\n status,\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n ],\n );\n};\n"],"names":[],"mappings":";;;AAoLA,MAAM,UAAU,CAAC,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAE1D,MAAM,YAA+B;AAAA,EACnC,OAAO;AAAA,EACP,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,OAAO;AACT;AAGA,MAAM,cAAc,MAAyB;AAE7C,MAAM,0BACJ;AASK,MAAM,2BAA2B,OAAO;AAAA,EAC7C;AAAA,EACA;AAAA,EACA,UAAU,CAAA;AAAA,EACV;AACF,MAO8C;AAC5C,QAAM,MAAc,GAAG,eAAe,QAAQ,QAAQ,EAAE,CAAC;AACzD,QAAM,WAAqB,MAAM,MAAM,KAAK;AAAA,IAC1C,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,KAAK;AAAA,IAAA;AAAA,IAEhC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B;AAAA,EAAA,CACD;AACD,MAAI,CAAC,SAAS,IA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L,QAAM,kBAAkB,OAA6C,IAAI;AACzE,YAAU,MAAM;AACd,QAAI,gBAAgB,YAAY,MAAM;AACpC,mBAAa,gBAAgB,OAAO;AACpC,sBAAgB,UAAU;AAAA,IAC5B;AACA,WAAO,MAAM;AACX,sBAAgB,UAAU,WAAW,MAAM;AACzC,wBAAgB,UAAU;AAC1B,aAAK,SAAA;AAAA,MACP,GAAG,CAAC;AAAA,IACN;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA,cAAc,WAAW;AAAA,MACzB,aAAa,WAAW,eAAe,WAAW;AAAA,MAClD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;"}
1
+ {"version":3,"file":"use-athena-voice-session.js","sources":["../../src/voice/use-athena-voice-session.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n Room,\n RoomEvent,\n Track,\n type Participant,\n type RemoteTrack,\n type TranscriptionSegment,\n} from 'livekit-client';\nimport { useParentBridge, type ParentBridgeState } from '../runtime/auth';\n\n/**\n * Realtime connection details for one Athena voice session. This is the shape\n * the Athena voice session endpoint returns; the hook only reads these\n * fields, so any server that proxies that call can hand it straight back.\n */\nexport interface AthenaVoiceSessionCredentials {\n /** Realtime signalling URL (`wss://…`). */\n server_url: string;\n /** Short-lived participant JWT scoped to `room_name`. */\n token: string;\n room_name?: string;\n /**\n * Athena session asset the voice run is persisted into. Use it with\n * `GET /api/v0/sessions/{asset_id}/download` to retrieve the transcript\n * after the call.\n */\n asset_id?: string;\n}\n\nexport type AthenaVoiceSessionStatus =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'ended'\n | 'error';\n\nexport type AthenaVoiceSpeaker = 'user' | 'agent';\n\n/** One committed (final) transcription segment from either side of the call. */\nexport interface AthenaVoiceTranscriptTurn {\n id: string;\n speaker: AthenaVoiceSpeaker;\n text: string;\n /** Segment start, in ms since the room's epoch. */\n startTime: number;\n endTime: number;\n language: string;\n}\n\n/**\n * A voice tool the Athena voice agent can run. These are voice tool\n * names, not the chat `Toolkits` ids: `'web_search_browse_toolkit'` is not a\n * voice tool, `'web_search'` is. Only these names are accepted.\n *\n * The agent also has tools that call back into the client over room RPC\n * (clipboard, selection, screen contents, opening assets). This hook registers\n * no RPC handlers, so they are not part of its contract.\n */\nexport type AthenaVoiceToolId =\n /** Web search. */\n | 'web_search'\n /** Legacy alias of `web_search`; prefer `web_search`. */\n | 'search_web'\n /** Fetch and read one URL. */\n | 'browse'\n /** The workspace knowledge base, where configured. */\n | 'search_knowledge_base'\n /** Same knowledge base, thorough long-running retrieval. */\n | 'search_knowledge_base_lr'\n /** Read Athena assets by id, as the viewer. */\n | 'read_full_asset'\n /** Search the viewer's Athena assets. */\n | 'search_assets'\n /** Hand a question to the general agent and speak its answer. */\n | 'ask_agent'\n /** Save a note for the user (a stub on the worker today). */\n | 'save_note'\n /** Current date and time, Eastern. */\n | 'get_current_time_est';\n\n/**\n * Voice agent configuration for a session the hook creates itself (see\n * `UseAthenaVoiceSessionOptions.session`). Mirrors the body of the Athena\n * voice session endpoint; every field is optional and falls back to the\n * server default.\n */\nexport interface AthenaVoiceSessionConfig {\n /** Persona / instructions for the voice agent. */\n system_prompt?: string;\n /** Realtime provider, e.g. `'openai'` or `'google'`. */\n provider?: string;\n /** Provider model id, e.g. `'gpt-realtime-2'`. */\n model?: string;\n /** Provider voice id, e.g. `'marin'` (OpenAI) or `'Aoede'` (Google). */\n voice?: string;\n temperature?: number;\n /** BCP-47 language tag; default `'en'`. */\n language?: string;\n /**\n * Voice tools the agent may call. Omit it for the server's default set\n * (`web_search`, `search_knowledge_base`, `ask_agent`, …); pass `[]` for a\n * pure conversation with no tool calls.\n */\n enabled_tools?: AthenaVoiceToolId[];\n /** IANA timezone of the speaker, e.g. `'America/New_York'`. */\n timezone?: string;\n}\n\nexport interface UseAthenaVoiceSessionOptions {\n /**\n * Creates the voice session. Omit it when the app is served from a\n * Marathon computer-asset URL: the hook then calls the Athena voice session\n * endpoint itself with the viewer's bearer token from `/_athena/auth`, so\n * the session is created as — and shows up in the sessions of — whoever is\n * using the app.\n *\n * Works for workspace members and external SSO viewers alike: the scoped\n * `athview_` viewer credential is authorized for the voice session route and\n * `agents/general/invoke` the same way it is for `/api/v0/sessions`.\n *\n * Supply it when the app runs anywhere else (standalone, custom auth): it\n * should run on the caller's own server so the Athena API key never reaches\n * the browser. The hook only reads the returned credentials.\n *\n * Decide once: switching between supplying and omitting it across renders\n * of the same component is not supported.\n */\n createSession?: (\n signal: AbortSignal,\n ) => Promise<AthenaVoiceSessionCredentials>;\n /**\n * Agent configuration for sessions the hook creates itself. Ignored when\n * `createSession` is supplied.\n */\n session?: AthenaVoiceSessionConfig;\n /** Called once per committed transcript turn, in arrival order. */\n onTranscript?: (turn: AthenaVoiceTranscriptTurn) => void;\n /** Called with interim (non-final) transcript text as it streams in. */\n onInterimTranscript?: (speaker: AthenaVoiceSpeaker, text: string) => void;\n onError?: (error: Error) => void;\n /**\n * Where to play the agent's audio. Defaults to a detached `<audio>` element\n * the hook creates and removes itself.\n */\n audioElement?: HTMLMediaElement | null;\n /** Enable the microphone as soon as the room connects. Default `true`. */\n autoEnableMicrophone?: boolean;\n /** @internal Overrides `new Room()`; used by tests. */\n createRoom?: () => Room;\n /** @internal Overrides `useParentBridge()`; used by tests. */\n useBridge?: () => ParentBridgeState;\n}\n\nexport interface UseAthenaVoiceSessionReturn {\n status: AthenaVoiceSessionStatus;\n /** True between `start()` resolving the session and the room connecting. */\n isConnecting: boolean;\n isConnected: boolean;\n /** Who is speaking right now, or `null` when the room is quiet. */\n activeSpeaker: AthenaVoiceSpeaker | null;\n isMuted: boolean;\n /** Committed transcript turns so far, in arrival order. */\n transcript: AthenaVoiceTranscriptTurn[];\n /** Athena session asset id, once the session has been created. */\n sessionId: string | null;\n roomName: string | null;\n error: Error | null;\n /** Creates a session and joins the room. No-op while a session is live. */\n start: () => Promise<void>;\n /** Leaves the room and stops local tracks. Safe to call at any time. */\n stop: () => Promise<void>;\n mute: () => Promise<void>;\n unmute: () => Promise<void>;\n /** Clears `transcript`; does not affect the live session. */\n clearTranscript: () => void;\n}\n\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\nconst NO_BRIDGE: ParentBridgeState = {\n token: null,\n statewireSyncUrl: null,\n backendBaseUrl: null,\n appUrl: null,\n hostAnswered: false,\n ready: true,\n};\n// Stands in for `useParentBridge` when the caller creates sessions itself, so\n// the hook never fetches `/_athena/auth` it would not use.\nconst useNoBridge = (): ParentBridgeState => NO_BRIDGE;\n\nconst NO_VIEWER_TOKEN_MESSAGE =\n 'useAthenaVoiceSession: no Athena viewer token. Either serve the app from ' +\n 'a Marathon computer-asset URL (which mints one via /_athena/auth) or pass ' +\n '`createSession` to create the session through your own server.';\n\n/**\n * Creates an Athena voice session as the current viewer. Exported so apps with\n * their own bridge state (or a server proxy holding a user bearer) can reuse\n * the exact request the hook makes.\n */\nexport const createAthenaVoiceSession = async ({\n backendBaseUrl,\n token,\n session = {},\n signal,\n}: {\n /** Bare Athena API base, e.g. `https://api.athenaintel.com`. */\n backendBaseUrl: string;\n /** Bearer token for the user the session belongs to. */\n token: string;\n session?: AthenaVoiceSessionConfig;\n signal?: AbortSignal;\n}): Promise<AthenaVoiceSessionCredentials> => {\n const url: string = `${backendBaseUrl.replace(/\\/+$/, '')}/api/orpheus/create-session`;\n const response: Response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(session),\n signal,\n });\n if (!response.ok) {\n const detail: string = await response.text().catch(() => '');\n throw new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n );\n }\n return (await response.json()) as AthenaVoiceSessionCredentials;\n};\n\nconst speakerOf = (\n participant: Participant | undefined,\n room: Room,\n): AthenaVoiceSpeaker =>\n participant !== undefined &&\n participant.identity === room.localParticipant.identity\n ? 'user'\n : 'agent';\n\n/**\n * Runs one Athena voice session from React.\n *\n * Owns the whole browser-side lifecycle the voice API leaves to the caller:\n * creating the session through the app's own server, joining the room,\n * publishing the microphone, playing the agent's audio, tracking who is\n * speaking, committing transcript turns from room transcription events, and\n * tearing everything down on `stop()` or unmount. A second `start()` while a\n * session is live (or still connecting) is ignored, so React StrictMode's\n * double-invoked effects cannot dispatch two agents into one room.\n */\nexport const useAthenaVoiceSession = (\n options: UseAthenaVoiceSessionOptions = {},\n): UseAthenaVoiceSessionReturn => {\n const {\n createSession,\n session,\n onTranscript,\n onInterimTranscript,\n onError,\n audioElement,\n autoEnableMicrophone = true,\n createRoom,\n useBridge = createSession ? useNoBridge : useParentBridge,\n } = options;\n\n // Viewer identity minted by Marathon (`/_athena/auth`) or the Athena app\n // iframe bridge. Only consulted when the caller did not supply `createSession`.\n const bridge: ParentBridgeState = useBridge();\n const bridgeRef = useRef<ParentBridgeState>(bridge);\n bridgeRef.current = bridge;\n const bridgeReadyWaitersRef = useRef<Array<() => void>>([]);\n useEffect(() => {\n if (!bridge.ready) return;\n const waiters: Array<() => void> = bridgeReadyWaitersRef.current;\n bridgeReadyWaitersRef.current = [];\n for (const resolve of waiters) resolve();\n }, [bridge.ready]);\n\n const sessionRef = useRef<AthenaVoiceSessionConfig | undefined>(session);\n sessionRef.current = session;\n\n const createSessionAsViewer = useCallback(\n async (signal: AbortSignal): Promise<AthenaVoiceSessionCredentials> => {\n if (!bridgeRef.current.ready) {\n await new Promise<void>((resolve) => {\n bridgeReadyWaitersRef.current.push(resolve);\n signal.addEventListener('abort', () => resolve(), { once: true });\n });\n if (signal.aborted) throw new Error('aborted');\n }\n const { token, backendBaseUrl } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n return createAthenaVoiceSession({\n backendBaseUrl,\n token,\n session: sessionRef.current,\n signal,\n });\n },\n [],\n );\n\n const [status, setStatus] = useState<AthenaVoiceSessionStatus>('idle');\n const [activeSpeaker, setActiveSpeaker] = useState<AthenaVoiceSpeaker | null>(\n null,\n );\n const [isMuted, setIsMuted] = useState<boolean>(false);\n const [transcript, setTranscript] = useState<AthenaVoiceTranscriptTurn[]>([]);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [roomName, setRoomName] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Latest callbacks without re-subscribing room listeners on every render.\n const callbacksRef = useRef({\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n });\n callbacksRef.current = {\n createSession: createSession ?? createSessionAsViewer,\n onTranscript,\n onInterimTranscript,\n onError,\n };\n\n const roomRef = useRef<Room | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n const attachedElementsRef = useRef<HTMLMediaElement[]>([]);\n const ownedAudioRef = useRef<HTMLMediaElement | null>(null);\n const committedSegmentIdsRef = useRef<Set<string>>(new Set());\n // Guards `start()` against re-entry from the moment it is called, before any\n // state update lands — a StrictMode double effect fires both calls\n // synchronously in the same tick.\n const startingRef = useRef<boolean>(false);\n\n const fail = useCallback((cause: unknown) => {\n const err: Error = toError(cause);\n setError(err);\n setStatus('error');\n callbacksRef.current.onError?.(err);\n }, []);\n\n const detachAudio = useCallback(() => {\n for (const element of attachedElementsRef.current) {\n element.srcObject = null;\n if (element === ownedAudioRef.current) element.remove();\n }\n attachedElementsRef.current = [];\n ownedAudioRef.current = null;\n }, []);\n\n const teardown = useCallback(async () => {\n abortRef.current?.abort();\n abortRef.current = null;\n const room: Room | null = roomRef.current;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n if (room) {\n room.removeAllListeners();\n await room.disconnect(true);\n }\n }, [detachAudio]);\n\n const stop = useCallback(async () => {\n const hadRoom: boolean =\n roomRef.current !== null || abortRef.current !== null;\n await teardown();\n setActiveSpeaker(null);\n if (hadRoom) setStatus('ended');\n }, [teardown]);\n\n const attachTrack = useCallback(\n (track: RemoteTrack) => {\n if (track.kind !== Track.Kind.Audio) return;\n if (audioElement) {\n track.attach(audioElement);\n attachedElementsRef.current.push(audioElement);\n return;\n }\n const element: HTMLMediaElement = track.attach();\n element.setAttribute('data-athena-voice-audio', '');\n document.body.appendChild(element);\n ownedAudioRef.current = element;\n attachedElementsRef.current.push(element);\n },\n [audioElement],\n );\n\n const handleTranscription = useCallback(\n (\n segments: TranscriptionSegment[],\n participant: Participant | undefined,\n room: Room,\n ) => {\n const speaker: AthenaVoiceSpeaker = speakerOf(participant, room);\n const committed: AthenaVoiceTranscriptTurn[] = [];\n for (const segment of segments) {\n if (!segment.final) {\n callbacksRef.current.onInterimTranscript?.(speaker, segment.text);\n continue;\n }\n if (committedSegmentIdsRef.current.has(segment.id)) continue;\n committedSegmentIdsRef.current.add(segment.id);\n committed.push({\n id: segment.id,\n speaker,\n text: segment.text,\n startTime: segment.startTime,\n endTime: segment.endTime,\n language: segment.language,\n });\n }\n if (committed.length === 0) return;\n setTranscript((previous) => [...previous, ...committed]);\n for (const turn of committed) callbacksRef.current.onTranscript?.(turn);\n },\n [],\n );\n\n const start = useCallback(async () => {\n if (startingRef.current || roomRef.current) return;\n startingRef.current = true;\n setError(null);\n setSessionId(null);\n setRoomName(null);\n setStatus('connecting');\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n let credentials: AthenaVoiceSessionCredentials;\n try {\n credentials = await callbacksRef.current.createSession(controller.signal);\n } catch (cause) {\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n fail(cause);\n return;\n }\n if (controller.signal.aborted) return;\n\n setSessionId(credentials.asset_id ?? null);\n setRoomName(credentials.room_name ?? null);\n\n const room: Room = createRoom ? createRoom() : new Room();\n roomRef.current = room;\n\n room\n .on(RoomEvent.TrackSubscribed, attachTrack)\n .on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const first: Participant | undefined = speakers[0];\n setActiveSpeaker(first ? speakerOf(first, room) : null);\n })\n .on(RoomEvent.TranscriptionReceived, (segments, participant) =>\n handleTranscription(segments, participant, room),\n )\n .on(RoomEvent.Reconnecting, () => setStatus('reconnecting'))\n .on(RoomEvent.Reconnected, () => setStatus('connected'))\n .on(RoomEvent.Disconnected, () => {\n if (roomRef.current !== room) return;\n roomRef.current = null;\n startingRef.current = false;\n detachAudio();\n setActiveSpeaker(null);\n setStatus('ended');\n })\n .on(RoomEvent.MediaDevicesError, fail);\n\n try {\n await room.connect(credentials.server_url, credentials.token);\n if (controller.signal.aborted) return;\n if (autoEnableMicrophone) {\n await room.localParticipant.setMicrophoneEnabled(true);\n setIsMuted(false);\n } else {\n setIsMuted(true);\n }\n if (controller.signal.aborted) return;\n abortRef.current = null;\n startingRef.current = false;\n setStatus('connected');\n } catch (cause) {\n if (controller.signal.aborted) return;\n await teardown();\n fail(cause);\n }\n }, [\n attachTrack,\n autoEnableMicrophone,\n createRoom,\n detachAudio,\n fail,\n handleTranscription,\n teardown,\n ]);\n\n const setMicrophone = useCallback(async (enabled: boolean) => {\n const room: Room | null = roomRef.current;\n if (!room) return;\n await room.localParticipant.setMicrophoneEnabled(enabled);\n setIsMuted(!enabled);\n }, []);\n const mute = useCallback(() => setMicrophone(false), [setMicrophone]);\n const unmute = useCallback(() => setMicrophone(true), [setMicrophone]);\n\n const clearTranscript = useCallback(() => {\n committedSegmentIdsRef.current.clear();\n setTranscript([]);\n }, []);\n\n // Unmount teardown is deferred one tick so StrictMode's synchronous\n // unmount/remount of the same instance does not abort an in-flight\n // `createSession` (which would dispatch a second voice agent on remount).\n const unmountTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n if (unmountTimerRef.current !== null) {\n clearTimeout(unmountTimerRef.current);\n unmountTimerRef.current = null;\n }\n return () => {\n unmountTimerRef.current = setTimeout(() => {\n unmountTimerRef.current = null;\n void teardown();\n }, 0);\n };\n }, [teardown]);\n\n return useMemo<UseAthenaVoiceSessionReturn>(\n () => ({\n status,\n isConnecting: status === 'connecting',\n isConnected: status === 'connected' || status === 'reconnecting',\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n }),\n [\n status,\n activeSpeaker,\n isMuted,\n transcript,\n sessionId,\n roomName,\n error,\n start,\n stop,\n mute,\n unmute,\n clearTranscript,\n ],\n );\n};\n"],"names":[],"mappings":";;;AAmLA,MAAM,UAAU,CAAC,UACf,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAE1D,MAAM,YAA+B;AAAA,EACnC,OAAO;AAAA,EACP,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,OAAO;AACT;AAGA,MAAM,cAAc,MAAyB;AAE7C,MAAM,0BACJ;AASK,MAAM,2BAA2B,OAAO;AAAA,EAC7C;AAAA,EACA;AAAA,EACA,UAAU,CAAA;AAAA,EACV;AACF,MAO8C;AAC5C,QAAM,MAAc,GAAG,eAAe,QAAQ,QAAQ,EAAE,CAAC;AACzD,QAAM,WAAqB,MAAM,MAAM,KAAK;AAAA,IAC1C,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,KAAK;AAAA,IAAA;AAAA,IAEhC,MAAM,KAAK,UAAU,OAAO;AAAA,IAC5B;AAAA,EAAA,CACD;AACD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,SAAiB,MAAM,SAAS,OAAO,MAAM,MAAM,EAAE;AAC3D,UAAM,IAAI;AAAA,MACR,yCAAyC,SAAS,MAAM,IAAI,SAAS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,UAAU;AAAA,IAC5B;AACA,WAAO,MAAM;AACX,sBAAgB,UAAU,WAAW,MAAM;AACzC,wBAAgB,UAAU;AAC1B,aAAK,SAAA;AAAA,MACP,GAAG,CAAC;AAAA,IACN;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA,cAAc,WAAW;AAAA,MACzB,aAAa,WAAW,eAAe,WAAW;AAAA,MAClD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@athenaintel/react",
3
- "version": "0.22.1",
3
+ "version": "0.22.3",
4
4
  "description": "Athena React SDK — Build AI-powered chat applications with the Athena platform",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",