@athenaintel/react 0.26.3 → 0.26.6
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.
- package/README.md +22 -0
- package/dist/auth/AthenaAuthProvider.d.ts +1 -1
- package/dist/auth/AthenaSSOProvider.d.ts +1 -1
- package/dist/chat/AthenaChat.cjs +1 -1
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +1 -1
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireApprovalCard.cjs +68 -9
- package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
- package/dist/chat/StatewireApprovalCard.d.ts +0 -31
- package/dist/chat/StatewireApprovalCard.js +70 -11
- package/dist/chat/StatewireApprovalCard.js.map +1 -1
- package/dist/chat/StatewireQueuedMessages.cjs +44 -1
- package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
- package/dist/chat/StatewireQueuedMessages.js +45 -2
- package/dist/chat/StatewireQueuedMessages.js.map +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.d.ts +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.d.ts +2 -2
- package/dist/chat/super-grouping/ToolTimeline.d.ts +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +6 -1
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.d.ts +20 -0
- package/dist/chat/use-statewire-approval-request.js +6 -1
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/header/chat-header.cjs +4 -4
- package/dist/chat-ui/header/chat-header.cjs.map +1 -1
- package/dist/chat-ui/header/chat-header.d.ts +3 -3
- package/dist/chat-ui/header/chat-header.js +1 -1
- package/dist/chat-ui/header/chat-header.js.map +1 -1
- package/dist/chat-ui/header/conversation-history-panel.d.ts +1 -1
- package/dist/chat-ui/index.cjs +8 -7
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.d.ts +2 -1
- package/dist/chat-ui/index.js +2 -1
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/markdown-storage.cjs +2 -1
- package/dist/chat-ui/markdown-storage.cjs.map +1 -1
- package/dist/chat-ui/markdown-storage.d.ts +3 -0
- package/dist/chat-ui/markdown-storage.js +2 -1
- package/dist/chat-ui/markdown-storage.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +6 -0
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.d.ts +2 -0
- package/dist/chat-ui/mentions/mention-chip.js +6 -0
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-breadcrumbs.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-item.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-list.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-skeleton.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-summary.d.ts +1 -1
- package/dist/chat-ui/mentions/suggestions/shims.d.ts +1 -1
- package/dist/chat-ui/messages/message-components.cjs +13 -59
- package/dist/chat-ui/messages/message-components.cjs.map +1 -1
- package/dist/chat-ui/messages/message-components.d.ts +2 -14
- package/dist/chat-ui/messages/message-components.js +2 -47
- package/dist/chat-ui/messages/message-components.js.map +1 -1
- package/dist/chat-ui/messages/runtime-message.cjs +1 -1
- package/dist/chat-ui/messages/runtime-message.cjs.map +1 -1
- package/dist/chat-ui/messages/runtime-message.js +1 -1
- package/dist/chat-ui/messages/runtime-message.js.map +1 -1
- package/dist/chat-ui/messages/thread-chrome.cjs +59 -0
- package/dist/chat-ui/messages/thread-chrome.cjs.map +1 -0
- package/dist/chat-ui/messages/thread-chrome.d.ts +14 -0
- package/dist/chat-ui/messages/thread-chrome.js +59 -0
- package/dist/chat-ui/messages/thread-chrome.js.map +1 -0
- package/dist/chat-ui/messages/wake-marker.cjs +1 -1
- package/dist/chat-ui/messages/wake-marker.cjs.map +1 -1
- package/dist/chat-ui/messages/wake-marker.js +1 -1
- package/dist/chat-ui/messages/wake-marker.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-link.d.ts +2 -2
- package/dist/chat-ui/rich-text/chat-message-body.d.ts +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.d.ts +5 -5
- package/dist/chat-ui/rich-text/chat-text-schema.cjs +9 -1
- package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.d.ts +7 -0
- package/dist/chat-ui/rich-text/chat-text-schema.js +9 -1
- package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -1
- package/dist/chat-ui/thread/chat-composer-dock.d.ts +1 -1
- package/dist/chat-ui/thread/chat-thread-shell.cjs +4 -3
- package/dist/chat-ui/thread/chat-thread-shell.cjs.map +1 -1
- package/dist/chat-ui/thread/chat-thread-shell.d.ts +1 -1
- package/dist/chat-ui/thread/chat-thread-shell.js +2 -1
- package/dist/chat-ui/thread/chat-thread-shell.js.map +1 -1
- package/dist/composer/AttachmentContext.d.ts +1 -1
- package/dist/composer/QuoteContext.d.ts +1 -1
- package/dist/lib/posthog/before-send.cjs +12 -0
- package/dist/lib/posthog/before-send.cjs.map +1 -1
- package/dist/lib/posthog/before-send.js +12 -0
- package/dist/lib/posthog/before-send.js.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +2 -0
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +2 -0
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/packages/agent-runtime/src/messages.cjs +15 -1
- package/dist/packages/agent-runtime/src/messages.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/messages.js +15 -1
- package/dist/packages/agent-runtime/src/messages.js.map +1 -1
- package/dist/packages/agent-runtime/src/tool-metadata.cjs +15 -0
- package/dist/packages/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/tool-metadata.js +15 -0
- package/dist/packages/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/dist/packages/tiptap-markdown-table/src/markdown-table-serializer.cjs +114 -0
- package/dist/packages/tiptap-markdown-table/src/markdown-table-serializer.cjs.map +1 -0
- package/dist/packages/tiptap-markdown-table/src/markdown-table-serializer.js +114 -0
- package/dist/packages/tiptap-markdown-table/src/markdown-table-serializer.js.map +1 -0
- package/dist/provider/AthenaProvider.d.ts +1 -1
- package/dist/provider/PostHogProvider.d.ts +1 -1
- package/dist/threads/SessionList.d.ts +1 -1
- package/dist/threads/ThreadList.d.ts +1 -1
- package/dist/threads/statewire-thread-list.d.ts +1 -1
- package/dist/tools/primitives.d.ts +3 -3
- package/dist/tools/tool-fallback.d.ts +8 -8
- package/dist/ui/button.d.ts +1 -1
- package/dist/ui/collapsible.d.ts +3 -3
- package/dist/ui/popover.d.ts +3 -3
- package/dist/ui/tooltip.d.ts +4 -4
- package/dist/voice/use-athena-voice-session.cjs.map +1 -1
- package/dist/voice/use-athena-voice-session.d.ts +5 -0
- package/dist/voice/use-athena-voice-session.js.map +1 -1
- package/package.json +3 -2
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { getHTMLFromFragment } from "@tiptap/core";
|
|
2
|
+
import { Fragment } from "@tiptap/pm/model";
|
|
3
|
+
function escapeTableCellPipes(markdown) {
|
|
4
|
+
return markdown.replace(/\|/g, "\\|");
|
|
5
|
+
}
|
|
6
|
+
function markdownHtmlOption(editor) {
|
|
7
|
+
const storage = Reflect.get(editor.storage, "markdown");
|
|
8
|
+
const options = typeof storage === "object" && storage !== null ? Reflect.get(storage, "options") : void 0;
|
|
9
|
+
const html = typeof options === "object" && options !== null ? Reflect.get(options, "html") : void 0;
|
|
10
|
+
if (typeof html !== "boolean") {
|
|
11
|
+
throw new Error("tiptap-markdown is not registered on this editor");
|
|
12
|
+
}
|
|
13
|
+
return html;
|
|
14
|
+
}
|
|
15
|
+
function renderCellInline({
|
|
16
|
+
state,
|
|
17
|
+
cellContent
|
|
18
|
+
}) {
|
|
19
|
+
const { text, write } = state;
|
|
20
|
+
state.text = (content, escapeMarkdown) => {
|
|
21
|
+
const start = state.out.length;
|
|
22
|
+
text.call(state, content, escapeMarkdown);
|
|
23
|
+
state.out = state.out.slice(0, start) + escapeTableCellPipes(state.out.slice(start));
|
|
24
|
+
};
|
|
25
|
+
state.write = (content) => {
|
|
26
|
+
write.call(state, content === void 0 ? content : escapeTableCellPipes(content));
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
state.renderInline(cellContent);
|
|
30
|
+
} finally {
|
|
31
|
+
state.text = text;
|
|
32
|
+
state.write = write;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function hasSpan(cell) {
|
|
36
|
+
return cell.attrs.colspan > 1 || cell.attrs.rowspan > 1;
|
|
37
|
+
}
|
|
38
|
+
function isMarkdownSerializable(table) {
|
|
39
|
+
const [firstRow, ...bodyRows] = table.children;
|
|
40
|
+
const headerCells = (firstRow == null ? void 0 : firstRow.children) ?? [];
|
|
41
|
+
if (headerCells.some(
|
|
42
|
+
(cell) => cell.type.name !== "tableHeader" || hasSpan(cell) || cell.childCount > 1
|
|
43
|
+
)) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return !bodyRows.some(
|
|
47
|
+
(row) => row.children.some(
|
|
48
|
+
(cell) => cell.type.name === "tableHeader" || hasSpan(cell) || cell.childCount > 1
|
|
49
|
+
)
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
function formatHtmlBlock(html) {
|
|
53
|
+
const body = new window.DOMParser().parseFromString(`<body>${html}</body>`, "text/html").body;
|
|
54
|
+
const element = body.firstElementChild;
|
|
55
|
+
if (!element) return html;
|
|
56
|
+
element.innerHTML = element.innerHTML.trim() ? `
|
|
57
|
+
${element.innerHTML}
|
|
58
|
+
` : "\n";
|
|
59
|
+
return element.outerHTML;
|
|
60
|
+
}
|
|
61
|
+
function serializeTableAsHtml({
|
|
62
|
+
editor,
|
|
63
|
+
state,
|
|
64
|
+
node,
|
|
65
|
+
parent
|
|
66
|
+
}) {
|
|
67
|
+
if (markdownHtmlOption(editor)) {
|
|
68
|
+
const { schema } = node.type;
|
|
69
|
+
const html = getHTMLFromFragment(Fragment.from(node), schema);
|
|
70
|
+
const isTopLevel = parent instanceof Fragment || parent.type.name === schema.topNodeType.name;
|
|
71
|
+
state.write(isTopLevel ? formatHtmlBlock(html) : html);
|
|
72
|
+
} else {
|
|
73
|
+
console.warn(`Tiptap Markdown: "${node.type.name}" node is only available in html mode`);
|
|
74
|
+
state.write(`[${node.type.name}]`);
|
|
75
|
+
}
|
|
76
|
+
state.closeBlock(node);
|
|
77
|
+
}
|
|
78
|
+
function serializeMarkdownTable(state, node, parent) {
|
|
79
|
+
if (!isMarkdownSerializable(node)) {
|
|
80
|
+
serializeTableAsHtml({ editor: this.editor, state, node, parent });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
state.inTable = true;
|
|
84
|
+
node.forEach((row, _rowOffset, rowIndex) => {
|
|
85
|
+
state.write("| ");
|
|
86
|
+
row.forEach((cell, _cellOffset, cellIndex) => {
|
|
87
|
+
if (cellIndex) {
|
|
88
|
+
state.write(" | ");
|
|
89
|
+
}
|
|
90
|
+
const cellContent = cell.firstChild;
|
|
91
|
+
if (cellContent == null ? void 0 : cellContent.textContent.trim()) {
|
|
92
|
+
renderCellInline({ state, cellContent });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
state.write(" |");
|
|
96
|
+
state.ensureNewLine();
|
|
97
|
+
if (!rowIndex) {
|
|
98
|
+
const delimiterRow = Array.from({ length: row.childCount }, () => "---").join(" | ");
|
|
99
|
+
state.write(`| ${delimiterRow} |`);
|
|
100
|
+
state.ensureNewLine();
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
state.closeBlock(node);
|
|
104
|
+
state.inTable = false;
|
|
105
|
+
}
|
|
106
|
+
function markdownTableStorage() {
|
|
107
|
+
return { markdown: { serialize: serializeMarkdownTable } };
|
|
108
|
+
}
|
|
109
|
+
export {
|
|
110
|
+
escapeTableCellPipes,
|
|
111
|
+
markdownTableStorage,
|
|
112
|
+
serializeMarkdownTable
|
|
113
|
+
};
|
|
114
|
+
//# sourceMappingURL=markdown-table-serializer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown-table-serializer.js","sources":["../../../../../tiptap-markdown-table/src/markdown-table-serializer.ts"],"sourcesContent":["/**\n * The table writer every Tiptap editor that writes Markdown through\n * tiptap-markdown shares: Olympus's docs `TableNode` and Skill editor, and the\n * `@athenaintel/react` chat composer's `ChatTableExtension`. A table node takes\n * it through {@link markdownTableStorage}.\n */\nimport { type Editor, getHTMLFromFragment } from \"@tiptap/core\";\nimport { Fragment, type Node as ProseMirrorNode } from \"@tiptap/pm/model\";\n\n/**\n * A table cell's markdown with each `|` escaped, so none of them ends the cell.\n * GFM ends a cell at every unescaped pipe, inside a code span or a link target\n * too; markdown-it drops the backslash of each `\\|` as it splits the row, so the\n * cell (and any code span in it) reads back with its literal pipe. The AOP\n * converter's markdown read escapes cells the same way\n * (`agora/converter-olympus/src/utils/turndown-helpers.ts`).\n */\nexport function escapeTableCellPipes(markdown: string): string {\n return markdown.replace(/\\|/g, \"\\\\|\");\n}\n\n/**\n * What the table serializer uses of tiptap-markdown's serializer state:\n * prosemirror-markdown's `MarkdownSerializerState` plus tiptap-markdown's\n * `inTable` flag, which makes a hard break inside a cell write `<br>`.\n */\ninterface MarkdownTableSerializerState {\n out: string;\n inTable: boolean;\n write(content?: string): void;\n text(text: string, escapeMarkdown?: boolean): void;\n ensureNewLine(): void;\n closeBlock(node: ProseMirrorNode): void;\n renderInline(parent: ProseMirrorNode, fromBlockStart?: boolean): void;\n}\n\n/** The `this` tiptap-markdown binds a node's `serialize` to. */\ninterface MarkdownSpecContext {\n editor: Editor;\n}\n\n/**\n * tiptap-markdown's `html` option, from the storage it keeps in\n * `editor.storage.markdown`. Tiptap 3 types `editor.storage` as an interface\n * each extension augments, and tiptap-markdown's own typings declare only\n * `getMarkdown()`, so the option is read through a guard rather than by\n * augmenting `@tiptap/core` for every editor that imports this module. Throws\n * when tiptap-markdown is not registered on the editor.\n */\nfunction markdownHtmlOption(editor: Editor): boolean {\n const storage: unknown = Reflect.get(editor.storage, \"markdown\");\n const options: unknown =\n typeof storage === \"object\" && storage !== null ? Reflect.get(storage, \"options\") : undefined;\n const html: unknown =\n typeof options === \"object\" && options !== null ? Reflect.get(options, \"html\") : undefined;\n if (typeof html !== \"boolean\") {\n throw new Error(\"tiptap-markdown is not registered on this editor\");\n }\n return html;\n}\n\n/**\n * Renders a cell's inline content with every `|` it writes escaped. Everything\n * a cell's inline content writes goes through the state's `text` (text, code\n * spans, mark delimiters, link targets) or `write` (inline nodes such as\n * mentions, images and inline HTML), so both are wrapped for the cell and\n * restored after it. Escaping as the output is written, not afterwards, keeps\n * the output offsets tiptap-markdown records to move emphasis delimiters in\n * step with the output.\n */\nfunction renderCellInline({\n state,\n cellContent,\n}: {\n state: MarkdownTableSerializerState;\n cellContent: ProseMirrorNode;\n}): void {\n const { text, write } = state;\n state.text = (content, escapeMarkdown) => {\n const start = state.out.length;\n text.call(state, content, escapeMarkdown);\n state.out = state.out.slice(0, start) + escapeTableCellPipes(state.out.slice(start));\n };\n state.write = (content) => {\n write.call(state, content === undefined ? content : escapeTableCellPipes(content));\n };\n try {\n state.renderInline(cellContent);\n } finally {\n state.text = text;\n state.write = write;\n }\n}\n\nfunction hasSpan(cell: ProseMirrorNode): boolean {\n return cell.attrs.colspan > 1 || cell.attrs.rowspan > 1;\n}\n\n/**\n * A GFM pipe table holds one header row of single-paragraph header cells over\n * body rows of single-paragraph data cells, with no merged cells. Any other\n * table is written as HTML.\n */\nfunction isMarkdownSerializable(table: ProseMirrorNode): boolean {\n const [firstRow, ...bodyRows] = table.children;\n const headerCells = firstRow?.children ?? [];\n if (\n headerCells.some(\n (cell) => cell.type.name !== \"tableHeader\" || hasSpan(cell) || cell.childCount > 1,\n )\n ) {\n return false;\n }\n return !bodyRows.some((row) =>\n row.children.some(\n (cell) => cell.type.name === \"tableHeader\" || hasSpan(cell) || cell.childCount > 1,\n ),\n );\n}\n\n/** An HTML block as CommonMark reads one: the element's content on lines of its own. */\nfunction formatHtmlBlock(html: string): string {\n const body = new window.DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\").body;\n const element = body.firstElementChild;\n if (!element) return html;\n element.innerHTML = element.innerHTML.trim() ? `\\n${element.innerHTML}\\n` : \"\\n\";\n return element.outerHTML;\n}\n\nfunction serializeTableAsHtml({\n editor,\n state,\n node,\n parent,\n}: {\n editor: Editor;\n state: MarkdownTableSerializerState;\n node: ProseMirrorNode;\n parent: ProseMirrorNode | Fragment;\n}): void {\n if (markdownHtmlOption(editor)) {\n const { schema } = node.type;\n const html = getHTMLFromFragment(Fragment.from(node), schema);\n const isTopLevel = parent instanceof Fragment || parent.type.name === schema.topNodeType.name;\n state.write(isTopLevel ? formatHtmlBlock(html) : html);\n } else {\n console.warn(`Tiptap Markdown: \"${node.type.name}\" node is only available in html mode`);\n state.write(`[${node.type.name}]`);\n }\n state.closeBlock(node);\n}\n\n/**\n * tiptap-markdown 0.9.0's table serializer, except that a `|` inside a cell is\n * written as `\\|` (see {@link escapeTableCellPipes}). The library writes it\n * bare — it escapes only `<` / `>` in text, and prosemirror-markdown only\n * `` `*\\~[]_ `` — so a cell holding `a | b` or `` `x|y` `` read back as extra\n * columns and markdown-it dropped every cell past the header's width. A table\n * that is not a GFM pipe table is still written as HTML, and everything else is\n * written exactly as the library writes it.\n */\nexport function serializeMarkdownTable(\n this: MarkdownSpecContext,\n state: MarkdownTableSerializerState,\n node: ProseMirrorNode,\n parent: ProseMirrorNode | Fragment,\n): void {\n if (!isMarkdownSerializable(node)) {\n serializeTableAsHtml({ editor: this.editor, state, node, parent });\n return;\n }\n state.inTable = true;\n node.forEach((row, _rowOffset, rowIndex) => {\n state.write(\"| \");\n row.forEach((cell, _cellOffset, cellIndex) => {\n if (cellIndex) {\n state.write(\" | \");\n }\n const cellContent = cell.firstChild;\n if (cellContent?.textContent.trim()) {\n renderCellInline({ state, cellContent });\n }\n });\n state.write(\" |\");\n state.ensureNewLine();\n if (!rowIndex) {\n const delimiterRow = Array.from({ length: row.childCount }, () => \"---\").join(\" | \");\n state.write(`| ${delimiterRow} |`);\n state.ensureNewLine();\n }\n });\n state.closeBlock(node);\n state.inTable = false;\n}\n\n/**\n * The storage that makes tiptap-markdown serialize a table node with\n * {@link serializeMarkdownTable}: tiptap-markdown reads a node's markdown spec\n * from `storage.markdown`, over its own spec for the node's name.\n */\nexport function markdownTableStorage(): {\n markdown: { serialize: typeof serializeMarkdownTable };\n} {\n return { markdown: { serialize: serializeMarkdownTable } };\n}\n"],"names":[],"mappings":";;AAiBO,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,SAAS,QAAQ,OAAO,KAAK;AACtC;AA8BA,SAAS,mBAAmB,QAAyB;AACnD,QAAM,UAAmB,QAAQ,IAAI,OAAO,SAAS,UAAU;AAC/D,QAAM,UACJ,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,IAAI,SAAS,SAAS,IAAI;AACtF,QAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,IAAI,SAAS,MAAM,IAAI;AACnF,MAAI,OAAO,SAAS,WAAW;AAC7B,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,SAAO;AACT;AAWA,SAAS,iBAAiB;AAAA,EACxB;AAAA,EACA;AACF,GAGS;AACP,QAAM,EAAE,MAAM,MAAA,IAAU;AACxB,QAAM,OAAO,CAAC,SAAS,mBAAmB;AACxC,UAAM,QAAQ,MAAM,IA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|
* error handling, so integrations never fail silently. */
|
|
129
129
|
onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;
|
|
130
130
|
}
|
|
131
|
-
export declare function AthenaProvider({ children, config, apiKey, token: tokenProp, agent, channel, model, tools, frontendTools, disableAutoOpen, apiUrl, backendUrl, appUrl, environment, statewireSyncUrl, getToken, extraRunConfig, workbench, knowledgeBase, systemPrompt, appId, threadId: threadIdProp, enableThreadList, threadListIncludePullRequests, theme, linkClicks, citationLinks, posthog: posthogProp, debug, onDiagnostic, onError, }: AthenaProviderProps): import("react
|
|
131
|
+
export declare function AthenaProvider({ children, config, apiKey, token: tokenProp, agent, channel, model, tools, frontendTools, disableAutoOpen, apiUrl, backendUrl, appUrl, environment, statewireSyncUrl, getToken, extraRunConfig, workbench, knowledgeBase, systemPrompt, appId, threadId: threadIdProp, enableThreadList, threadListIncludePullRequests, theme, linkClicks, citationLinks, posthog: posthogProp, debug, onDiagnostic, onError, }: AthenaProviderProps): import("react").JSX.Element | null;
|
|
@@ -11,4 +11,4 @@ export declare function getPostHogInstance<TClient = unknown>(): TClient | null;
|
|
|
11
11
|
export declare function PostHogProvider({ children, config, }: {
|
|
12
12
|
children: ReactNode;
|
|
13
13
|
config?: PostHogConfig;
|
|
14
|
-
}): import("react
|
|
14
|
+
}): import("react").JSX.Element;
|
|
@@ -57,4 +57,4 @@ export declare const SessionListSkeleton: FC<{
|
|
|
57
57
|
* state appears only after a settled empty answer, and a background refresh
|
|
58
58
|
* never blanks the rows it already has.
|
|
59
59
|
*/
|
|
60
|
-
export declare function SessionList({ className, grouped, showSearch, showPinToggle, showRename, showArchive, prefetchOnHover, }: SessionListProps): import("react
|
|
60
|
+
export declare function SessionList({ className, grouped, showSearch, showPinToggle, showRename, showArchive, prefetchOnHover, }: SessionListProps): import("react").JSX.Element | null;
|
|
@@ -6,4 +6,4 @@ export interface ThreadListProps {
|
|
|
6
6
|
* `<AthenaProvider enableThreadList>` provides and renders nothing outside
|
|
7
7
|
* that mode — a standalone provider hosts exactly one thread.
|
|
8
8
|
*/
|
|
9
|
-
export declare function ThreadList({ className }: ThreadListProps): import("react
|
|
9
|
+
export declare function ThreadList({ className }: ThreadListProps): import("react").JSX.Element | null;
|
|
@@ -191,7 +191,7 @@ export declare function AthenaStatewireThreadListProvider({ backendUrl, syncUrl,
|
|
|
191
191
|
includePullRequests?: boolean;
|
|
192
192
|
snapshotCache?: DeepAgentThreadSnapshotCache;
|
|
193
193
|
children: ReactNode;
|
|
194
|
-
}): import("react
|
|
194
|
+
}): import("react").JSX.Element;
|
|
195
195
|
/** How long after a thread's first message the title poll starts (exported for tests). */
|
|
196
196
|
export declare const TITLE_POLL_DELAY_MS = 5000;
|
|
197
197
|
/**
|
|
@@ -32,7 +32,7 @@ export interface ToolCardProps {
|
|
|
32
32
|
* `ToolFallback` shell), so a dedicated UI and a generic fallback share one
|
|
33
33
|
* anatomy there; with no provider it is the boxed card below, unchanged.
|
|
34
34
|
*/
|
|
35
|
-
export declare function ToolCard(props: ToolCardProps): import("react
|
|
35
|
+
export declare function ToolCard(props: ToolCardProps): import("react").JSX.Element;
|
|
36
36
|
/** Copies `{ tool_name, arguments, result }` as JSON — the tool spec a support ticket needs. */
|
|
37
37
|
export declare function CopyToolSpecButton({ toolName, args, argsText, result, className, }: {
|
|
38
38
|
toolName: string;
|
|
@@ -40,9 +40,9 @@ export declare function CopyToolSpecButton({ toolName, args, argsText, result, c
|
|
|
40
40
|
argsText?: string;
|
|
41
41
|
result?: unknown;
|
|
42
42
|
className?: string;
|
|
43
|
-
}): import("react
|
|
43
|
+
}): import("react").JSX.Element;
|
|
44
44
|
export declare function ExpandableSection({ label, children, defaultOpen, }: {
|
|
45
45
|
label?: string;
|
|
46
46
|
children: ReactNode;
|
|
47
47
|
defaultOpen?: boolean;
|
|
48
|
-
}): import("react
|
|
48
|
+
}): import("react").JSX.Element;
|
|
@@ -62,7 +62,7 @@ export type ToolFallbackRootProps = Omit<React.ComponentProps<typeof Collapsible
|
|
|
62
62
|
defaultOpen?: boolean;
|
|
63
63
|
appearance?: ToolAppearance;
|
|
64
64
|
};
|
|
65
|
-
declare function ToolFallbackRoot({ className, open: controlledOpen, onOpenChange: controlledOnOpenChange, defaultOpen, appearance: appearanceProp, children, ...props }: ToolFallbackRootProps): import("react
|
|
65
|
+
declare function ToolFallbackRoot({ className, open: controlledOpen, onOpenChange: controlledOnOpenChange, defaultOpen, appearance: appearanceProp, children, ...props }: ToolFallbackRootProps): import("react").JSX.Element;
|
|
66
66
|
export interface ToolFallbackTriggerProps extends Omit<React.ComponentProps<typeof CollapsibleTrigger>, "children"> {
|
|
67
67
|
toolName: string;
|
|
68
68
|
argsText?: string;
|
|
@@ -80,18 +80,18 @@ export interface ToolFallbackTriggerProps extends Omit<React.ComponentProps<type
|
|
|
80
80
|
/** A short count or state chip after the target ("8 results"). */
|
|
81
81
|
badge?: string;
|
|
82
82
|
}
|
|
83
|
-
declare function ToolFallbackTrigger({ toolName, argsText, result, status, isError, classification: givenClassification, displayName, activeLabel, icon, appearance: appearanceProp, secondary: secondaryProp, badge, className, ...props }: ToolFallbackTriggerProps): import("react
|
|
83
|
+
declare function ToolFallbackTrigger({ toolName, argsText, result, status, isError, classification: givenClassification, displayName, activeLabel, icon, appearance: appearanceProp, secondary: secondaryProp, badge, className, ...props }: ToolFallbackTriggerProps): import("react").JSX.Element;
|
|
84
84
|
declare function ToolFallbackContent({ className, children, appearance: appearanceProp, ...props }: React.ComponentProps<typeof CollapsibleContent> & {
|
|
85
85
|
appearance?: ToolAppearance;
|
|
86
|
-
}): import("react
|
|
86
|
+
}): import("react").JSX.Element;
|
|
87
87
|
declare function ToolFallbackArgs({ argsText, hideInternalIdArgs, className, ...props }: React.ComponentProps<"div"> & {
|
|
88
88
|
argsText?: string;
|
|
89
89
|
hideInternalIdArgs?: boolean;
|
|
90
|
-
}): import("react
|
|
90
|
+
}): import("react").JSX.Element | null;
|
|
91
91
|
declare function ToolFallbackResult({ result, classification, className, ...props }: React.ComponentProps<"div"> & {
|
|
92
92
|
result?: unknown;
|
|
93
93
|
classification?: ToolResultClassification;
|
|
94
|
-
}): import("react
|
|
94
|
+
}): import("react").JSX.Element | null;
|
|
95
95
|
/**
|
|
96
96
|
* The failure a status-incomplete call carries, for the expanded body. The
|
|
97
97
|
* always-visible failure line is {@link ToolFallbackNotice}; this repeats the
|
|
@@ -99,7 +99,7 @@ declare function ToolFallbackResult({ result, classification, className, ...prop
|
|
|
99
99
|
*/
|
|
100
100
|
declare function ToolFallbackError({ status, className, ...props }: React.ComponentProps<"div"> & {
|
|
101
101
|
status?: ToolCallMessagePartStatus;
|
|
102
|
-
}): import("react
|
|
102
|
+
}): import("react").JSX.Element | null;
|
|
103
103
|
/**
|
|
104
104
|
* The always-visible line under the header for a failed or paused call — the
|
|
105
105
|
* failure's code and message, or the runtime's pause notice — so a reader
|
|
@@ -108,7 +108,7 @@ declare function ToolFallbackError({ status, className, ...props }: React.Compon
|
|
|
108
108
|
declare function ToolFallbackNotice({ classification, appearance: appearanceProp, className, ...props }: React.ComponentProps<"div"> & {
|
|
109
109
|
classification: ToolResultClassification;
|
|
110
110
|
appearance?: ToolAppearance;
|
|
111
|
-
}): import("react
|
|
111
|
+
}): import("react").JSX.Element | null;
|
|
112
112
|
/**
|
|
113
113
|
* Sets the tool-card anatomy for every tool call rendered below it — generic
|
|
114
114
|
* fallbacks, dedicated tool UIs built on `ToolCard`, nested PTC sub-calls.
|
|
@@ -118,7 +118,7 @@ declare function ToolFallbackNotice({ classification, appearance: appearanceProp
|
|
|
118
118
|
export declare function ToolFallbackAppearanceProvider({ appearance, children, }: {
|
|
119
119
|
appearance: ToolAppearance;
|
|
120
120
|
children?: ReactNode;
|
|
121
|
-
}): import("react
|
|
121
|
+
}): import("react").JSX.Element;
|
|
122
122
|
declare const ToolFallback: ToolCallMessagePartComponent & ((props: ToolFallbackProps) => ReactNode) & {
|
|
123
123
|
Root: typeof ToolFallbackRoot;
|
|
124
124
|
Trigger: typeof ToolFallbackTrigger;
|
package/dist/ui/button.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ declare const buttonVariants: (props?: ({
|
|
|
6
6
|
} & import("class-variance-authority/types").ClassProp) | undefined) => string;
|
|
7
7
|
declare function Button({ className, variant, size, asChild, ...props }: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & {
|
|
8
8
|
asChild?: boolean;
|
|
9
|
-
}):
|
|
9
|
+
}): React.JSX.Element;
|
|
10
10
|
export { Button, buttonVariants };
|
package/dist/ui/collapsible.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Collapsible as CollapsiblePrimitive } from "radix-ui";
|
|
2
|
-
declare function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>): import("react
|
|
3
|
-
declare function CollapsibleTrigger({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>): import("react
|
|
4
|
-
declare function CollapsibleContent({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>): import("react
|
|
2
|
+
declare function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>): import("react").JSX.Element;
|
|
3
|
+
declare function CollapsibleTrigger({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>): import("react").JSX.Element;
|
|
4
|
+
declare function CollapsibleContent({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>): import("react").JSX.Element;
|
|
5
5
|
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
|
package/dist/ui/popover.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
import { Popover as PopoverPrimitive } from "radix-ui";
|
|
3
|
-
declare function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>):
|
|
4
|
-
declare function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>):
|
|
5
|
-
declare function PopoverContent({ className, style, align, sideOffset, collisionPadding, ...props }: React.ComponentProps<typeof PopoverPrimitive.Content>):
|
|
3
|
+
declare function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>): React.JSX.Element;
|
|
4
|
+
declare function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>): React.JSX.Element;
|
|
5
|
+
declare function PopoverContent({ className, style, align, sideOffset, collisionPadding, ...props }: React.ComponentProps<typeof PopoverPrimitive.Content>): React.JSX.Element;
|
|
6
6
|
export { Popover, PopoverTrigger, PopoverContent };
|
package/dist/ui/tooltip.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
import { Tooltip as TooltipPrimitive } from "radix-ui";
|
|
3
|
-
declare function TooltipProvider({ delayDuration, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>):
|
|
4
|
-
declare function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>):
|
|
5
|
-
declare function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>):
|
|
6
|
-
declare function TooltipContent({ className, sideOffset, children, ...props }: React.ComponentProps<typeof TooltipPrimitive.Content>):
|
|
3
|
+
declare function TooltipProvider({ delayDuration, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>): React.JSX.Element;
|
|
4
|
+
declare function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>): React.JSX.Element;
|
|
5
|
+
declare function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>): React.JSX.Element;
|
|
6
|
+
declare function TooltipContent({ className, sideOffset, children, ...props }: React.ComponentProps<typeof TooltipPrimitive.Content>): React.JSX.Element;
|
|
7
7
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
|
@@ -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 { type ParentBridge, useParentBridge, type ParentBridgeState } from '../runtime/auth';\nimport { isCredentialRefusal } from '../runtime/credential-renewal';\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 & Partial<Pick<ParentBridge, 'renewToken'>>;\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 // `status` lets a caller tell a refused credential (401) from any other failure.\n throw Object.assign(\n new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n ),\n { status: response.status },\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 & Partial<Pick<ParentBridge, 'renewToken'>> = useBridge();\n const bridgeRef = useRef(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, renewToken } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n const create = (viewerToken: string) =>\n createAthenaVoiceSession({\n backendBaseUrl,\n token: viewerToken,\n session: sessionRef.current,\n signal,\n });\n try {\n return await create(token);\n } catch (error) {\n // The host refused the viewer token: renew it through the bridge (a\n // Marathon re-mint or the parent window's next token) and try once more.\n if (!isCredentialRefusal(error) || !renewToken) throw error;\n const renewed = await renewToken({ force: true });\n if (!renewed || renewed === token) throw error;\n return create(renewed);\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","error","isCredentialRefusal","useState","Track","Room","RoomEvent","useMemo"],"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,IAAI;AAChB,UAAM,SAAiB,MAAM,SAAS,OAAO,MAAM,MAAM,EAAE;AAE3D,UAAM,OAAO;AAAA,MACX,IAAI;AAAA,QACF,yCAAyC,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,KAAK,EAAE;AAAA,MAAA;AAAA,MAEzF,EAAE,QAAQ,SAAS,OAAA;AAAA,IAAO;AAAA,EAE9B;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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,uBA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AA,YAAY,MAAM,cAAc,IAAI,GAAG,CAAC,aAAa,CAAC;AAErE,QAAM,kBAAkBA,MAAAA,YAAY,MAAM;AACxC,2BAAuB,QAAQ,MAAA;AAC/B,kBAAc,CAAA,CAAE;AAAA,EAClB,GAAG,CAAA,CAAE;AAKL,QAAM,kBAAkBF,MAAAA,OAA6C,IAAI;AACzEC,QAAAA,UAAU,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,SAAOQ,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
|
+
{"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 { type ParentBridge, useParentBridge, type ParentBridgeState } from '../runtime/auth';\nimport { isCredentialRefusal } from '../runtime/credential-renewal';\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 * Start without the agent's opening greeting: it stays quiet (no audio, no\n * transcript turn) until a participant speaks. Default `false`.\n */\n silent_start?: boolean;\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 & Partial<Pick<ParentBridge, 'renewToken'>>;\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 // `status` lets a caller tell a refused credential (401) from any other failure.\n throw Object.assign(\n new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n ),\n { status: response.status },\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 & Partial<Pick<ParentBridge, 'renewToken'>> = useBridge();\n const bridgeRef = useRef(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, renewToken } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n const create = (viewerToken: string) =>\n createAthenaVoiceSession({\n backendBaseUrl,\n token: viewerToken,\n session: sessionRef.current,\n signal,\n });\n try {\n return await create(token);\n } catch (error) {\n // The host refused the viewer token: renew it through the bridge (a\n // Marathon re-mint or the parent window's next token) and try once more.\n if (!isCredentialRefusal(error) || !renewToken) throw error;\n const renewed = await renewToken({ force: true });\n if (!renewed || renewed === token) throw error;\n return create(renewed);\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","error","isCredentialRefusal","useState","Track","Room","RoomEvent","useMemo"],"mappings":";;;;;;AAyLA,MAAM,UAAU,CAAC,UACf,iBAAi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BAAc,CAAA,CAAE;AAAA,EAClB,GAAG,CAAA,CAAE;AAKL,QAAM,kBAAkBF,MAAAA,OAA6C,IAAI;AACzEC,QAAAA,UAAU,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,SAAOQ,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;;;"}
|
|
@@ -86,6 +86,11 @@ export interface AthenaVoiceSessionConfig {
|
|
|
86
86
|
enabled_tools?: AthenaVoiceToolId[];
|
|
87
87
|
/** IANA timezone of the speaker, e.g. `'America/New_York'`. */
|
|
88
88
|
timezone?: string;
|
|
89
|
+
/**
|
|
90
|
+
* Start without the agent's opening greeting: it stays quiet (no audio, no
|
|
91
|
+
* transcript turn) until a participant speaks. Default `false`.
|
|
92
|
+
*/
|
|
93
|
+
silent_start?: boolean;
|
|
89
94
|
}
|
|
90
95
|
export interface UseAthenaVoiceSessionOptions {
|
|
91
96
|
/**
|
|
@@ -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 { type ParentBridge, useParentBridge, type ParentBridgeState } from '../runtime/auth';\nimport { isCredentialRefusal } from '../runtime/credential-renewal';\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 & Partial<Pick<ParentBridge, 'renewToken'>>;\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 // `status` lets a caller tell a refused credential (401) from any other failure.\n throw Object.assign(\n new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n ),\n { status: response.status },\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 & Partial<Pick<ParentBridge, 'renewToken'>> = useBridge();\n const bridgeRef = useRef(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, renewToken } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n const create = (viewerToken: string) =>\n createAthenaVoiceSession({\n backendBaseUrl,\n token: viewerToken,\n session: sessionRef.current,\n signal,\n });\n try {\n return await create(token);\n } catch (error) {\n // The host refused the viewer token: renew it through the bridge (a\n // Marathon re-mint or the parent window's next token) and try once more.\n if (!isCredentialRefusal(error) || !renewToken) throw error;\n const renewed = await renewToken({ force: true });\n if (!renewed || renewed === token) throw error;\n return create(renewed);\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,\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gB,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 { type ParentBridge, useParentBridge, type ParentBridgeState } from '../runtime/auth';\nimport { isCredentialRefusal } from '../runtime/credential-renewal';\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 * Start without the agent's opening greeting: it stays quiet (no audio, no\n * transcript turn) until a participant speaks. Default `false`.\n */\n silent_start?: boolean;\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 & Partial<Pick<ParentBridge, 'renewToken'>>;\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 // `status` lets a caller tell a refused credential (401) from any other failure.\n throw Object.assign(\n new Error(\n `Athena voice session creation failed (${response.status})${detail ? `: ${detail}` : ''}`,\n ),\n { status: response.status },\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 & Partial<Pick<ParentBridge, 'renewToken'>> = useBridge();\n const bridgeRef = useRef(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, renewToken } = bridgeRef.current;\n if (!token || !backendBaseUrl) throw new Error(NO_VIEWER_TOKEN_MESSAGE);\n const create = (viewerToken: string) =>\n createAthenaVoiceSession({\n backendBaseUrl,\n token: viewerToken,\n session: sessionRef.current,\n signal,\n });\n try {\n return await create(token);\n } catch (error) {\n // The host refused the viewer token: renew it through the bridge (a\n // Marathon re-mint or the parent window's next token) and try once more.\n if (!isCredentialRefusal(error) || !renewToken) throw error;\n const renewed = await renewToken({ force: true });\n if (!renewed || renewed === token) throw error;\n return create(renewed);\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":["error"],"mappings":";;;;AAyLA,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,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