@smooai/chat-widget 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-widget.global.js +472 -39
- package/dist/chat-widget.global.js.map +1 -1
- package/dist/index.d.ts +197 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +499 -40
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/config.ts +18 -1
- package/src/conversation.ts +23 -1
- package/src/element.ts +114 -1
- package/src/index.ts +19 -1
- package/src/styles.ts +41 -0
- package/src/voice-session.ts +420 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["ELEMENT_TAG"],"sources":["../src/markdown.ts","../src/config.ts","../src/fingerprint.ts","../src/persistence.ts","../src/conversation.ts","../src/logo.ts","../src/styles.ts","../src/element.ts","../src/loader-core.ts"],"sourcesContent":["/**\n * A tiny, safe-by-default Markdown → HTML renderer for the chat widget.\n *\n * ## Why a hand-rolled renderer (and not markdown-it / snarkdown)?\n *\n * The widget renders **untrusted** text in two places: the assistant's reply\n * (LLM output, which can echo attacker-supplied content) and citation snippets\n * (raw scraped page chunks). Today both are written via `textContent`, so\n * `**bold**`, numbered lists, and `[links](url)` show up literally. We want\n * them rendered — without re-opening the XSS hole that `textContent` was\n * guarding against.\n *\n * markdown-it with `html:false` is safe-by-default but ships ~30 kB min into\n * what is an embeddable **global** bundle, where every kilobyte is on the host\n * page's critical path. snarkdown is ~1 kB but emits raw HTML, so it would\n * require bolting on a separate sanitizer. Instead, this renderer is\n * **safe-by-construction**:\n *\n * 1. It is a *tokenizer*, not an HTML passthrough. It only ever emits a\n * fixed allowlist of tags (`p`, `br`, `strong`, `em`, `ul`/`ol`/`li`,\n * `code`/`pre`, `a`, `blockquote`). There is no code path that copies a\n * tag out of the input — a literal `<script>` in the input is treated as\n * plain text.\n * 2. **Every** text run is HTML-escaped via {@link escapeHtml} before it\n * reaches the output. Raw `<`, `>`, `&`, `\"`, `'` can never become markup.\n * 3. **Images are dropped entirely** — `` renders as its alt text,\n * no `<img>` is ever produced (a scraped tracking pixel must not load).\n * 4. **Links** are gated through {@link safeHttpUrl}: only absolute `http(s)`\n * URLs become anchors (with `target=\"_blank\"` + a hardened `rel`);\n * `javascript:`/`data:`/relative/etc. fall back to plain (escaped) text.\n * 5. **Headings** (`#`..`######`) are *downgraded* to bold lines — a full\n * `<h1>` is far too large inside a chat bubble or citation card.\n *\n * The output is a string of HTML that is only ever assigned to `innerHTML` of\n * an element the caller controls; because of (1)–(4) it can only contain the\n * allowlisted, attribute-sanitized tags.\n *\n * Supported subset (deliberately small):\n * - Paragraphs (blank-line separated) and hard/soft line breaks\n * - `**bold**` / `__bold__`, `*italic*` / `_italic_`\n * - `` `inline code` `` and fenced ``` ```code blocks``` ```\n * - `- ` / `* ` / `+ ` unordered lists, `1.` ordered lists\n * - `> ` blockquotes\n * - `[text](http(s)://url)` links (images dropped to alt text)\n * - `#`..`######` headings → bold line\n */\n\n/** Escape the five HTML-significant characters so a text run can never be markup. */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case '&':\n return '&';\n case '<':\n return '<';\n case '>':\n return '>';\n case '\"':\n return '"';\n default:\n return ''';\n }\n });\n}\n\n/**\n * Return `url` only if it is a valid absolute `http(s)` URL, else `null`.\n *\n * SECURITY: link targets here originate from untrusted content (LLM output /\n * scraped citation chunks). Allowing an arbitrary string as an `href` permits\n * `javascript:`/`data:`/`vbscript:` URLs that execute on click — a stored-XSS\n * vector. Only absolute http(s) links are rendered as anchors; anything else\n * falls back to plain text upstream.\n */\nexport function safeHttpUrl(url: string | undefined | null): string | null {\n if (!url) return null;\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\n// ───────────────────────────── Inline rendering ─────────────────────────────\n\n/**\n * Render the inline span grammar of a single line/segment to safe HTML.\n *\n * Order matters: code spans are extracted first (their contents are *not*\n * further parsed), then images are stripped to alt text, then links, then\n * emphasis. Every literal text run is escaped on the way out.\n */\nfunction renderInline(input: string): string {\n let out = '';\n let i = 0;\n const n = input.length;\n\n // Accumulate escaped literal text, flushing on each recognized token.\n let buf = '';\n const flush = () => {\n if (buf) {\n out += escapeHtml(buf);\n buf = '';\n }\n };\n\n while (i < n) {\n const ch = input[i]!;\n\n // Inline code: `...` — contents are literal (escaped), no nested parsing.\n if (ch === '`') {\n const end = input.indexOf('`', i + 1);\n if (end > i) {\n flush();\n out += `<code>${escapeHtml(input.slice(i + 1, end))}</code>`;\n i = end + 1;\n continue;\n }\n }\n\n // Image:  — DROPPED. Emit only the (escaped) alt text; never\n // produce an <img> (a scraped tracking pixel must not load).\n if (ch === '!' && input[i + 1] === '[') {\n const m = imageAt(input, i);\n if (m) {\n flush();\n out += renderInline(m.alt); // alt may itself contain emphasis\n i = m.end;\n continue;\n }\n }\n\n // Link: [text](href)\n if (ch === '[') {\n const m = linkAt(input, i);\n if (m) {\n flush();\n const safe = safeHttpUrl(m.href);\n const inner = renderInline(m.text);\n if (safe) {\n out += `<a href=\"${escapeHtml(safe)}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">${inner}</a>`;\n } else {\n // Unsafe scheme → render as plain (already-escaped) text, no anchor.\n out += inner;\n }\n i = m.end;\n continue;\n }\n }\n\n // Bold: **...** or __...__\n if ((ch === '*' && input[i + 1] === '*') || (ch === '_' && input[i + 1] === '_')) {\n const marker = ch + ch;\n const end = input.indexOf(marker, i + 2);\n if (end > i + 1) {\n flush();\n out += `<strong>${renderInline(input.slice(i + 2, end))}</strong>`;\n i = end + 2;\n continue;\n }\n }\n\n // Italic: *...* or _..._ (single marker, non-empty, not touching the other marker)\n if (ch === '*' || ch === '_') {\n const end = input.indexOf(ch, i + 1);\n if (end > i + 1 && input[i + 1] !== ch) {\n flush();\n out += `<em>${renderInline(input.slice(i + 1, end))}</em>`;\n i = end + 1;\n continue;\n }\n }\n\n buf += ch;\n i++;\n }\n\n flush();\n return out;\n}\n\n/** Parse a `[text](href)` link starting at `start` (`input[start] === '['`). */\nfunction linkAt(input: string, start: number): { text: string; href: string; end: number } | null {\n const close = matchBracket(input, start);\n if (close < 0 || input[close + 1] !== '(') return null;\n const paren = input.indexOf(')', close + 2);\n if (paren < 0) return null;\n const text = input.slice(start + 1, close);\n // href is the first whitespace-delimited token inside (...) — ignore any\n // markdown \"title\" portion; we never render titles.\n const href = input.slice(close + 2, paren).trim().split(/\\s+/)[0] ?? '';\n return { text, href, end: paren + 1 };\n}\n\n/** Parse a `` image starting at `start` (`input[start] === '!'`). */\nfunction imageAt(input: string, start: number): { alt: string; end: number } | null {\n const link = linkAt(input, start + 1);\n if (!link) return null;\n return { alt: link.text, end: link.end };\n}\n\n/** Find the matching `]` for a `[` at `open`, honoring one level of nesting. */\nfunction matchBracket(input: string, open: number): number {\n let depth = 0;\n for (let i = open; i < input.length; i++) {\n const c = input[i];\n if (c === '[') depth++;\n else if (c === ']') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\n// ───────────────────────────── Block rendering ──────────────────────────────\n\nconst UL_RE = /^\\s*[-*+]\\s+(.*)$/;\nconst OL_RE = /^\\s*\\d+[.)]\\s+(.*)$/;\nconst HEADING_RE = /^\\s{0,3}(#{1,6})\\s+(.*)$/;\nconst QUOTE_RE = /^\\s*>\\s?(.*)$/;\nconst FENCE_RE = /^\\s*(`{3,}|~{3,})\\s*(.*)$/;\n\n/**\n * Render a full Markdown string to safe HTML.\n *\n * @returns a string containing only the allowlisted tags described in the\n * module doc. Safe to assign to `innerHTML` of a caller-owned element.\n */\nexport function renderMarkdown(src: string): string {\n const lines = src.replace(/\\r\\n?/g, '\\n').split('\\n');\n const out: string[] = [];\n\n let i = 0;\n while (i < lines.length) {\n const line = lines[i]!;\n\n // Fenced code block: ```lang ... ```\n const fence = FENCE_RE.exec(line);\n if (fence) {\n const marker = fence[1]!;\n const body: string[] = [];\n i++;\n while (i < lines.length && !lines[i]!.trimStart().startsWith(marker)) {\n body.push(lines[i]!);\n i++;\n }\n if (i < lines.length) i++; // consume closing fence\n out.push(`<pre><code>${escapeHtml(body.join('\\n'))}</code></pre>`);\n continue;\n }\n\n // Blank line → paragraph boundary.\n if (line.trim() === '') {\n i++;\n continue;\n }\n\n // Heading → downgraded to a bold line (an <h1> is too big in a bubble).\n const heading = HEADING_RE.exec(line);\n if (heading) {\n out.push(`<p><strong>${renderInline(heading[2]!)}</strong></p>`);\n i++;\n continue;\n }\n\n // Unordered / ordered list — consume the contiguous run.\n if (UL_RE.test(line) || OL_RE.test(line)) {\n const ordered = OL_RE.test(line) && !UL_RE.test(line);\n const re = ordered ? OL_RE : UL_RE;\n const items: string[] = [];\n while (i < lines.length) {\n const m = re.exec(lines[i]!);\n if (!m) break;\n items.push(`<li>${renderInline(m[1]!)}</li>`);\n i++;\n }\n out.push(`<${ordered ? 'ol' : 'ul'}>${items.join('')}</${ordered ? 'ol' : 'ul'}>`);\n continue;\n }\n\n // Blockquote — consume the contiguous run.\n if (QUOTE_RE.test(line)) {\n const quoted: string[] = [];\n while (i < lines.length) {\n const m = QUOTE_RE.exec(lines[i]!);\n if (!m) break;\n quoted.push(m[1]!);\n i++;\n }\n out.push(`<blockquote>${renderInline(quoted.join('\\n')).replace(/\\n/g, '<br>')}</blockquote>`);\n continue;\n }\n\n // Paragraph — gather consecutive non-blank, non-block lines; soft breaks → <br>.\n const para: string[] = [];\n while (i < lines.length) {\n const l = lines[i]!;\n if (\n l.trim() === '' ||\n FENCE_RE.test(l) ||\n HEADING_RE.test(l) ||\n UL_RE.test(l) ||\n OL_RE.test(l) ||\n QUOTE_RE.test(l)\n ) {\n break;\n }\n para.push(l);\n i++;\n }\n out.push(`<p>${renderInline(para.join('\\n')).replace(/\\n/g, '<br>')}</p>`);\n }\n\n return out.join('');\n}\n\n// ───────────────────────── Citation-snippet cleanup ─────────────────────────\n\nconst SNIPPET_MAX = 260;\n\n/**\n * Clean a raw scraped citation snippet into a short, readable excerpt.\n *\n * Scraped chunks frequently begin with page boilerplate — a logo image wrapped\n * in a link, standalone nav, repeated whitespace — e.g.\n * `[](…) # Our Work We build…`. The source itself is already linked\n * from the citation card, so the snippet only needs to be a clean teaser.\n *\n * Steps:\n * 1. Strip a leading image / logo-link (`[](…)` or ``).\n * 2. Drop a leading standalone heading marker (`#`/`##`).\n * 3. Collapse all runs of whitespace to single spaces.\n * 4. Truncate to ~{@link SNIPPET_MAX} chars at a word boundary, adding `…`.\n *\n * The result is still rendered through {@link renderMarkdown} downstream, so any\n * remaining inline markup (bold/links) stays safe.\n */\nexport function cleanCitationSnippet(raw: string): string {\n let s = raw ?? '';\n\n // Repeatedly peel leading boilerplate tokens.\n let changed = true;\n while (changed) {\n changed = false;\n const before = s;\n // Leading linked image: [](href)\n s = s.replace(/^\\s*\\[!\\[[^\\]]*\\]\\([^)]*\\)\\]\\([^)]*\\)\\s*/, '');\n // Leading bare image: \n s = s.replace(/^\\s*!\\[[^\\]]*\\]\\([^)]*\\)\\s*/, '');\n // Leading heading marker(s): \"# \", \"## \" (keep the heading text)\n s = s.replace(/^\\s*#{1,6}\\s+/, '');\n if (s !== before) changed = true;\n }\n\n // Collapse whitespace.\n s = s.replace(/\\s+/g, ' ').trim();\n\n // Truncate at a word boundary.\n if (s.length > SNIPPET_MAX) {\n const cut = s.slice(0, SNIPPET_MAX);\n const lastSpace = cut.lastIndexOf(' ');\n s = (lastSpace > SNIPPET_MAX * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd() + '…';\n }\n\n return s;\n}\n","/**\n * Public configuration surface for the chat widget.\n *\n * A host page configures the widget either declaratively (HTML attributes on the\n * `<smooth-agent-chat>` element) or programmatically (passing this object to\n * {@link mountChatWidget} / `element.configure(...)`).\n */\nimport { safeHttpUrl } from './markdown.js';\n\nexport interface ChatWidgetTheme {\n /** Foreground text color for the widget chrome. */\n text?: string;\n /** Panel background color. */\n background?: string;\n /** Primary accent (launcher button, send button, outbound bubble). */\n primary?: string;\n /** Text color rendered on top of `primary`. */\n primaryText?: string;\n /** A secondary accent (used for subtle highlights). */\n secondary?: string;\n /** Inbound (assistant) chat bubble background. */\n assistantBubble?: string;\n /** Inbound (assistant) chat bubble text color. */\n assistantBubbleText?: string;\n /** Outbound (user) chat bubble background. Defaults to `primary`. */\n userBubble?: string;\n /** Outbound (user) chat bubble text color. Defaults to `primaryText`. */\n userBubbleText?: string;\n /** Border color for the panel and input. */\n border?: string;\n\n // ── Aliases for the dashboard's 10-color model (SmooAI agent widget config).\n // When provided, these take precedence over the canonical keys above, so a\n // config exported from the agent dashboard themes the widget directly.\n /** Alias for {@link assistantBubble}. */\n chatBubbleInbound?: string;\n /** Alias for {@link assistantBubbleText}. */\n chatBubbleInboundText?: string;\n /** Alias for {@link userBubble}. */\n chatBubbleOutbound?: string;\n /** Alias for {@link userBubbleText}. */\n chatBubbleOutboundText?: string;\n}\n\n/**\n * Layout mode for the widget.\n *\n * - `\"popover\"` (default) — the embeddable launcher bubble + floating panel.\n * - `\"fullpage\"` — no launcher; the chat fills its container/viewport with a\n * branded header, a scrollable message list, and an input bar. Ideal for a\n * dedicated support page (`/chat`, a docs site sidebar, an iframe, …).\n */\nexport type ChatWidgetMode = 'popover' | 'fullpage';\n\nexport interface ChatWidgetConfig {\n /**\n * smooth-operator WebSocket endpoint, e.g.\n * `ws://localhost:8787/ws` (local dev) or your deployed `wss://…/ws` URL.\n */\n endpoint: string;\n /**\n * Layout mode — `\"popover\"` (default, launcher + floating panel) or\n * `\"fullpage\"` (chat fills its container; no launcher). See {@link ChatWidgetMode}.\n */\n mode?: ChatWidgetMode;\n /** UUID of the agent to start a conversation session with. */\n agentId: string;\n /** Display name for the agent (header label). Defaults to \"Assistant\". */\n agentName?: string;\n /**\n * Brand logo shown in the full-page header avatar tile; falls back to the\n * Smooth icon. SECURITY: only absolute `http(s)` URLs are honored — any other\n * scheme (`javascript:`/`data:`/…) is ignored, so a hostile config can't\n * inject script.\n */\n logoUrl?: string;\n /** Optional display name for the user participant. */\n userName?: string;\n /** Optional email address for the user participant. */\n userEmail?: string;\n /** Optional phone number for the user participant (passed via session metadata). */\n userPhone?: string;\n /**\n * Optional pre-auth HMAC context. When the host page has a shared secret with\n * the agent, it can sign `{ userId, signature, timestamp }` so the chat-ws\n * wrapper's `/internal/*` identity routes (and the WS create path) verify the\n * caller without an OTP round-trip (ADR-046/ADR-048). Passed through verbatim.\n */\n authContext?: { userId: string; signature: string; timestamp: number };\n /** Placeholder text for the message input. */\n placeholder?: string;\n /** Greeting rendered when the conversation opens (before any messages). */\n greeting?: string;\n /** Message shown when the connection cannot be (re)established. */\n connectionErrorMessage?: string;\n /** Start the panel open instead of collapsed to the launcher. */\n startOpen?: boolean;\n /**\n * Hide the \"powered by smooth-operator\" branding in the header tag and the\n * composer footer. Defaults to `false` (branding shown). The `hide-branding`\n * HTML attribute maps to this.\n */\n hideBranding?: boolean;\n /**\n * Suggested starter prompts shown as clickable chips before the first message.\n * Clicking one sends it. Capped at 5 for layout.\n */\n examplePrompts?: string[];\n /**\n * Show mid-conversation suggested-reply chips (\"quick replies\") under the\n * latest assistant message when the agent returns follow-up suggestions.\n * Clicking one sends it. Defaults to `true` (shown unless explicitly `false`).\n */\n showSuggestedReplies?: boolean;\n /** Require the visitor's name before chatting. */\n requireName?: boolean;\n /** Require the visitor's email before chatting. */\n requireEmail?: boolean;\n /** Require the visitor's phone before chatting. */\n requirePhone?: boolean;\n /**\n * Show the phone field on the pre-chat form (optional unless {@link requirePhone}).\n * Defaults to `true` for this widget — phone rides the session metadata as\n * `userPhone` so the agent can follow up by SMS. Set `false` to hide it.\n */\n collectPhone?: boolean;\n /**\n * Show the email + SMS marketing-consent checkboxes on the pre-chat form.\n * Explicit opt-in, default UNCHECKED; a `consentAt` timestamp is stamped when\n * a box is ticked. Defaults to `true`. The consent record is threaded into the\n * session metadata (ADR-048).\n */\n collectConsent?: boolean;\n /**\n * Offer the cross-device \"Restore my chats\" affordance — an explicit link that\n * runs the identity-OTP → resolve → replay flow. Defaults to `true`.\n */\n allowChatRestore?: boolean;\n /**\n * Let visitors chat without providing any identity. When `true`, the\n * `require*` flags are ignored and the pre-chat form is skipped.\n */\n allowAnonymous?: boolean;\n /**\n * Show the agent's tool activity (grep / read_file / bash / knowledge_search…)\n * as inline chips interleaved with its prose, mirroring the smooth daemon SPA.\n *\n * Defaults to **`false`**: for a customer-facing support widget, surfacing raw\n * tool calls to an end-user is usually undesirable, so tool activity is hidden\n * and only the assistant's prose renders. Enable it for internal / power-user\n * surfaces where seeing what the agent did mid-turn is valuable.\n */\n showToolActivity?: boolean;\n /** Theme overrides. */\n theme?: ChatWidgetTheme;\n}\n\n/** The fully-resolved theme (canonical keys only — aliases are folded in). */\nexport type ResolvedTheme = Required<Omit<ChatWidgetTheme, 'chatBubbleInbound' | 'chatBubbleInboundText' | 'chatBubbleOutbound' | 'chatBubbleOutboundText'>>;\n\nexport type ResolvedConfig = Required<Omit<ChatWidgetConfig, 'theme' | 'userName' | 'userEmail' | 'userPhone' | 'authContext' | 'logoUrl'>> & {\n theme: ResolvedTheme;\n userName?: string;\n userEmail?: string;\n userPhone?: string;\n authContext?: { userId: string; signature: string; timestamp: number };\n /** Sanitized brand logo URL (`http(s)` only) or `undefined` — see {@link ChatWidgetConfig.logoUrl}. */\n logoUrl?: string;\n};\n\n/** Resolve a partial config against the built-in defaults. */\nexport function resolveConfig(config: ChatWidgetConfig): ResolvedConfig {\n const theme = config.theme ?? {};\n const primary = theme.primary ?? '#00a6a6';\n const primaryText = theme.primaryText ?? '#f8fafc';\n // Dashboard aliases win over canonical keys when present.\n const assistantBubble = theme.chatBubbleInbound ?? theme.assistantBubble ?? '#06134b';\n const assistantBubbleText = theme.chatBubbleInboundText ?? theme.assistantBubbleText ?? '#f8fafc';\n const userBubble = theme.chatBubbleOutbound ?? theme.userBubble ?? primary;\n const userBubbleText = theme.chatBubbleOutboundText ?? theme.userBubbleText ?? primaryText;\n return {\n endpoint: config.endpoint,\n mode: config.mode ?? 'popover',\n agentId: config.agentId,\n agentName: config.agentName ?? 'Assistant',\n // Only absolute http(s) URLs survive — anything else (javascript:/data:/\n // relative) is dropped so the header can never render a hostile logo src.\n logoUrl: safeHttpUrl(config.logoUrl) ?? undefined,\n userName: config.userName,\n userEmail: config.userEmail,\n userPhone: config.userPhone,\n authContext: config.authContext,\n placeholder: config.placeholder ?? 'Type a message…',\n greeting: config.greeting ?? 'Hi! How can I help you today?',\n connectionErrorMessage: config.connectionErrorMessage ?? \"We couldn't reach the chat. Please try again in a moment.\",\n startOpen: config.startOpen ?? false,\n hideBranding: config.hideBranding ?? false,\n examplePrompts: (config.examplePrompts ?? []).filter((p) => p.trim().length > 0).slice(0, 5),\n showSuggestedReplies: config.showSuggestedReplies ?? true,\n requireName: config.requireName ?? false,\n requireEmail: config.requireEmail ?? false,\n requirePhone: config.requirePhone ?? false,\n collectPhone: config.collectPhone ?? true,\n collectConsent: config.collectConsent ?? true,\n allowChatRestore: config.allowChatRestore ?? true,\n allowAnonymous: config.allowAnonymous ?? false,\n showToolActivity: config.showToolActivity ?? false,\n theme: {\n text: theme.text ?? '#f8fafc',\n background: theme.background ?? '#040d30',\n primary,\n primaryText,\n secondary: theme.secondary ?? '#ff6b6c',\n assistantBubble,\n assistantBubbleText,\n userBubble,\n userBubbleText,\n border: theme.border ?? 'rgba(255, 255, 255, 0.1)',\n },\n };\n}\n\n/**\n * Whether the pre-chat identity form should gate the conversation: at least one\n * field is required and anonymous chat is not allowed.\n */\nexport function needsUserInfo(resolved: ResolvedConfig): boolean {\n return !resolved.allowAnonymous && (resolved.requireName || resolved.requireEmail || resolved.requirePhone);\n}\n","/**\n * Browser fingerprint — a stable, privacy-light identifier used by the\n * smooth-operator server to correlate an anonymous visitor's sessions across\n * page loads (and, server-side, to match an anonymous fingerprint to a known\n * CRM contact). It rides every `create_conversation_session` as\n * `browserFingerprint` (see ADR-048).\n *\n * ## Why not ThumbmarkJS\n *\n * The ADR floats ThumbmarkJS as the reference implementation. For an *embed*\n * that is injected onto arbitrary host pages, ThumbmarkJS is too heavy: its\n * full build pulls in extensive device-detection tables and async\n * component collection, adding tens of kilobytes (and async surface) to a\n * bundle whose whole selling point is staying out of the host page's\n * LCP/TBT budget. The fingerprint here is a few hundred bytes.\n *\n * ## What this is (and the tradeoff)\n *\n * The correlation that actually matters — \"is this the same browser as last\n * time?\" — is carried by a **persisted random UUID** (the `browserFingerprint`\n * field in the persisted store). That UUID is generated once and reused for\n * the life of the localStorage entry, so same-browser resume is exact and\n * deterministic. The signal hash below is a best-effort entropy *supplement*\n * mixed into that UUID's derivation seed on first generation — it gives the\n * server-side resolver a soft signal for the (rare) cross-storage case where\n * the UUID was cleared but the device is unchanged. It is intentionally NOT a\n * high-entropy device fingerprint: no canvas/WebGL/audio probes, no font\n * enumeration, nothing that reads as invasive tracking. The tradeoff is weaker\n * cross-storage matching in exchange for a tiny, transparent, no-network,\n * XSS-safe implementation. The server's resolver (SMOODEV-2129d) is the source\n * of truth for any fuzzy matching; the client just supplies a stable token.\n */\n\n/** Collect a small set of stable, non-invasive browser signals. */\nfunction collectSignals(): string {\n const parts: string[] = [];\n try {\n const nav = typeof navigator !== 'undefined' ? navigator : undefined;\n if (nav) {\n parts.push(`ua:${nav.userAgent ?? ''}`);\n parts.push(`lang:${nav.language ?? ''}`);\n parts.push(`langs:${Array.isArray(nav.languages) ? nav.languages.join(',') : ''}`);\n // `platform` is deprecated but still widely present and stable.\n parts.push(`plat:${(nav as Navigator & { platform?: string }).platform ?? ''}`);\n parts.push(`hc:${(nav as Navigator & { hardwareConcurrency?: number }).hardwareConcurrency ?? ''}`);\n parts.push(`dm:${(nav as Navigator & { deviceMemory?: number }).deviceMemory ?? ''}`);\n }\n if (typeof screen !== 'undefined') {\n parts.push(`scr:${screen.width}x${screen.height}x${screen.colorDepth}`);\n }\n if (typeof Intl !== 'undefined') {\n try {\n parts.push(`tz:${Intl.DateTimeFormat().resolvedOptions().timeZone ?? ''}`);\n } catch {\n /* resolvedOptions can throw in locked-down environments */\n }\n }\n parts.push(`tzo:${new Date().getTimezoneOffset()}`);\n } catch {\n /* a hostile/locked-down navigator must never break widget boot */\n }\n return parts.join('|');\n}\n\n/**\n * A small, fast, non-cryptographic string hash (FNV-1a, 32-bit) rendered as\n * an unsigned hex string. Stable across runs for the same input. Not used for\n * any security decision — only to derive a deterministic seed from the signal\n * string above.\n */\nfunction fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n // 32-bit FNV prime multiply via shifts to stay in int range.\n h = Math.imul(h, 0x01000193);\n }\n // >>> 0 → unsigned; pad to 8 hex chars.\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Generate a UUID, preferring `crypto.randomUUID`, falling back to a v4-shaped string. */\nfunction generateUuid(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through to the manual generator */\n }\n // RFC 4122 v4 shape from Math.random — only reached when crypto.randomUUID\n // is unavailable (very old engines). Sufficient for a correlation token.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Compute a fresh fingerprint token: a stable random UUID, suffixed with the\n * FNV hash of the device signals so the server can recover a soft device\n * signal even if it only has the token. Called ONCE per browser (the result is\n * persisted and reused) — see {@link getOrCreateFingerprint}.\n */\nexport function computeFingerprint(): string {\n const signalHash = fnv1a(collectSignals());\n return `${generateUuid()}.${signalHash}`;\n}\n\n/**\n * Return the cached fingerprint if one was already computed for this browser,\n * otherwise compute + persist a new one via the provided accessors. The\n * persistence layer owns storage; this function owns the \"compute once\" policy.\n */\nexport function getOrCreateFingerprint(get: () => string | null, set: (fp: string) => void): string {\n const existing = get();\n if (existing) return existing;\n const fp = computeFingerprint();\n set(fp);\n return fp;\n}\n","/**\n * Persisted widget state — the identity / consent / session-pointer client layer\n * (ADR-048, SMOODEV-2129e).\n *\n * Built on Zustand's framework-agnostic `vanilla` store + the `persist`\n * middleware (the user explicitly chose Zustand; it's ~1KB and has no React\n * dependency, so it works inside the web component). The store is keyed per\n * agent — localStorage key `smoo-chat-widget:<agentId>` — so two agents embedded\n * on the same origin don't clobber each other.\n *\n * ## What persists (and, deliberately, what does NOT)\n *\n * Only a **pointer** to the conversation plus the visitor's identity + marketing\n * consent + verified email + browser fingerprint. The transcript is **never**\n * persisted: the smooth-operator server is the source of truth and the widget\n * re-hydrates history via `getMessages` on resume. This keeps localStorage small\n * and avoids stale/divergent transcripts.\n *\n * `version` drives `persist.migrate` so future shape changes can upgrade old\n * blobs in place instead of silently dropping them.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla';\nimport { persist, type PersistStorage } from 'zustand/middleware';\n\n/** Current persisted-shape version. Bump when the shape below changes incompatibly. */\nexport const PERSIST_VERSION = 1 as const;\n\n/** Marketing-consent record captured at the pre-chat form. */\nexport interface ConsentState {\n emailOptIn: boolean;\n smsOptIn: boolean;\n /** Where the consent was captured. The widget always stamps `chat-widget-prechat`. */\n consentSource?: string;\n /** ISO 8601 timestamp stamped when the visitor ticked a consent box. */\n consentAt?: string;\n}\n\n/** Visitor identity collected from config or the pre-chat form. */\nexport interface IdentityState {\n name?: string;\n email?: string;\n phone?: string;\n}\n\n/**\n * The exact persisted shape (ADR-048 §d). Only the pointer + identity + consent\n * persist — never the transcript.\n */\nexport interface PersistedWidgetState {\n version: typeof PERSIST_VERSION;\n /** Pointer to the active conversation session; cleared on ended/404. */\n sessionId: string | null;\n identity: IdentityState;\n consent: ConsentState;\n /**\n * Email proven via OTP for the CURRENT session. Session-scoped: cleared on\n * `clearSession()` so it can't leak across visitors on a shared browser, and\n * only threaded into session metadata when {@link verifiedEmailSessionId}\n * matches the live session (i.e. on resume of the verified session) — never\n * auto-stamped onto a brand-new session.\n */\n verifiedEmail: string | null;\n /** The sessionId the {@link verifiedEmail} was proven against (binds the proof to one session). */\n verifiedEmailSessionId: string | null;\n /** Stable per-browser correlation token (see fingerprint.ts). */\n browserFingerprint: string | null;\n}\n\n/** Store actions layered on top of the persisted state. */\nexport interface WidgetStoreActions {\n setSessionId: (sessionId: string | null) => void;\n /** Merge identity fields (undefined values don't clobber existing ones). */\n mergeIdentity: (identity: IdentityState) => void;\n /** Replace consent wholesale (the pre-chat form computes the full record). */\n setConsent: (consent: ConsentState) => void;\n /** Record an OTP-proven email bound to a specific session. */\n setVerifiedEmail: (email: string | null, sessionId?: string | null) => void;\n setBrowserFingerprint: (fp: string) => void;\n /**\n * Clear the session pointer (and the session-scoped `verifiedEmail` proof) but\n * KEEP identity / consent / fingerprint — used when a persisted session has\n * ended or 404s so the next turn starts a fresh session for a known visitor.\n * `verifiedEmail` is deliberately cleared here: it is a per-session OTP proof,\n * not a durable identity, so it must NOT survive onto a new session (which on a\n * shared browser could be a different visitor).\n */\n clearSession: () => void;\n}\n\nexport type WidgetStore = PersistedWidgetState & WidgetStoreActions;\n\nconst EMPTY_CONSENT: ConsentState = { emailOptIn: false, smsOptIn: false };\n\nfunction initialPersisted(): PersistedWidgetState {\n return {\n version: PERSIST_VERSION,\n sessionId: null,\n identity: {},\n consent: { ...EMPTY_CONSENT },\n verifiedEmail: null,\n verifiedEmailSessionId: null,\n browserFingerprint: null,\n };\n}\n\n/** localStorage key for an agent's persisted widget state. */\nexport function storageKey(agentId: string): string {\n return `smoo-chat-widget:${agentId}`;\n}\n\n/**\n * An explicit in-memory (Map-backed) `PersistStorage`. Used as the fallback when\n * real localStorage is unavailable.\n *\n * IMPORTANT: we must NOT return `undefined` from {@link safeStorage} in that case.\n * zustand v5's `persist` treats a missing `storage` option by falling back to its\n * OWN `createJSONStorage(() => localStorage)` — i.e. it re-engages the very\n * localStorage the guard was trying to avoid (throwing again in privacy mode).\n * Handing it this no-op storage keeps the store working purely in memory and\n * guarantees the fallback can't touch real localStorage.\n */\nfunction memoryStorage(): PersistStorage<PersistedWidgetState> {\n const mem = new Map<string, string>();\n return {\n getItem: (name) => {\n const raw = mem.get(name);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ReturnType<PersistStorage<PersistedWidgetState>['getItem']>;\n } catch {\n return null;\n }\n },\n setItem: (name, value) => {\n mem.set(name, JSON.stringify(value));\n },\n removeItem: (name) => {\n mem.delete(name);\n },\n };\n}\n\n/**\n * A `persist` storage adapter that tolerates the *absence* of localStorage\n * (SSR, privacy-mode throwing on access, sandboxed iframes). When storage is\n * unavailable the store still works in-memory; nothing is persisted, but the\n * widget never throws on boot.\n */\nfunction safeStorage(): PersistStorage<PersistedWidgetState> {\n let ls: Storage | null = null;\n try {\n ls = typeof localStorage !== 'undefined' ? localStorage : null;\n // Probe: some environments expose localStorage but throw on access.\n if (ls) {\n const probe = '__smoo_probe__';\n ls.setItem(probe, '1');\n ls.removeItem(probe);\n }\n } catch {\n ls = null;\n }\n // Fall back to an explicit in-memory store — NEVER `undefined` (see memoryStorage).\n if (!ls) return memoryStorage();\n const storage = ls;\n return {\n getItem: (name) => {\n try {\n const raw = storage.getItem(name);\n return raw ? (JSON.parse(raw) as ReturnType<PersistStorage<PersistedWidgetState>['getItem']>) : null;\n } catch {\n return null;\n }\n },\n setItem: (name, value) => {\n try {\n storage.setItem(name, JSON.stringify(value));\n } catch {\n /* quota / privacy-mode write failures are non-fatal */\n }\n },\n removeItem: (name) => {\n try {\n storage.removeItem(name);\n } catch {\n /* non-fatal */\n }\n },\n };\n}\n\n/**\n * Migrate a persisted blob from an older `version` to the current shape. Today\n * v1 is the only version, so this just backfills any missing fields onto an\n * unknown old blob; future versions add `case` branches here.\n */\nfunction migrate(persisted: unknown): PersistedWidgetState {\n const base = initialPersisted();\n if (!persisted || typeof persisted !== 'object') return base;\n const p = persisted as Partial<PersistedWidgetState>;\n return {\n version: PERSIST_VERSION,\n sessionId: typeof p.sessionId === 'string' ? p.sessionId : null,\n identity: {\n name: typeof p.identity?.name === 'string' ? p.identity.name : undefined,\n email: typeof p.identity?.email === 'string' ? p.identity.email : undefined,\n phone: typeof p.identity?.phone === 'string' ? p.identity.phone : undefined,\n },\n consent: {\n emailOptIn: p.consent?.emailOptIn === true,\n smsOptIn: p.consent?.smsOptIn === true,\n consentSource: typeof p.consent?.consentSource === 'string' ? p.consent.consentSource : undefined,\n consentAt: typeof p.consent?.consentAt === 'string' ? p.consent.consentAt : undefined,\n },\n verifiedEmail: typeof p.verifiedEmail === 'string' ? p.verifiedEmail : null,\n verifiedEmailSessionId: typeof p.verifiedEmailSessionId === 'string' ? p.verifiedEmailSessionId : null,\n browserFingerprint: typeof p.browserFingerprint === 'string' ? p.browserFingerprint : null,\n };\n}\n\n/**\n * Create the per-agent persisted Zustand store. The `partialize` step ensures\n * only the persisted shape (never any future transient action/UI state) is\n * written to localStorage.\n */\nexport function createWidgetStore(agentId: string): StoreApi<WidgetStore> {\n return createStore<WidgetStore>()(\n persist(\n (set) => ({\n ...initialPersisted(),\n setSessionId: (sessionId) => set({ sessionId }),\n mergeIdentity: (identity) =>\n set((state) => ({\n identity: {\n ...state.identity,\n ...(identity.name !== undefined ? { name: identity.name } : {}),\n ...(identity.email !== undefined ? { email: identity.email } : {}),\n ...(identity.phone !== undefined ? { phone: identity.phone } : {}),\n },\n })),\n setConsent: (consent) => set({ consent: { ...consent } }),\n setVerifiedEmail: (verifiedEmail, sessionId) =>\n set((state) => ({\n verifiedEmail,\n // Bind the proof to the session it was verified against. When the\n // caller omits sessionId, fall back to the live pointer so the\n // proof is never left unbound.\n verifiedEmailSessionId: verifiedEmail === null ? null : (sessionId ?? state.sessionId),\n })),\n setBrowserFingerprint: (browserFingerprint) => set({ browserFingerprint }),\n // Drop the pointer AND the session-scoped OTP proof; keep durable identity.\n clearSession: () => set({ sessionId: null, verifiedEmail: null, verifiedEmailSessionId: null }),\n }),\n {\n name: storageKey(agentId),\n version: PERSIST_VERSION,\n storage: safeStorage(),\n migrate,\n // Persist ONLY the data shape — never the action functions.\n partialize: (state): PersistedWidgetState => ({\n version: PERSIST_VERSION,\n sessionId: state.sessionId,\n identity: state.identity,\n consent: state.consent,\n verifiedEmail: state.verifiedEmail,\n verifiedEmailSessionId: state.verifiedEmailSessionId,\n browserFingerprint: state.browserFingerprint,\n }),\n },\n ),\n );\n}\n","/**\n * ConversationController — the bridge between the widget UI and the\n * `@smooai/smooth-operator` protocol client.\n *\n * This is the piece that was rewired: the original smooai widget spoke to\n * `@smooai/realtime`; here every protocol action goes through {@link SmoothAgentClient}.\n * The wire shapes are identical (the protocol was lifted from `@smooai/realtime`),\n * so the swap is purely at the client-library boundary.\n *\n * Flow:\n * 1. `connect()` → opens the WebSocket transport and `create_conversation_session`\n * (or RESUMES a persisted session via `get_session`/`get_messages`).\n * 2. `send(text)` → `send_message`, streaming `stream_token` deltas into the\n * in-progress assistant message, then the terminal\n * `eventual_response`.\n *\n * 0.7.0 (SMOODEV-2129e) adds the identity / persistence / consent client layer:\n * - `browserFingerprint` computed once + sent on every `create_conversation_session`.\n * - identity + marketing consent threaded into the session `metadata`.\n * - same-session RESUME on load (no engine change — `get_session` + `get_messages`).\n * - returning-visitor RESUME via `POST /internal/resume-by-fingerprint`, and\n * cross-device \"restore my chats\" via the `POST /internal/identity/{request-otp,\n * verify-otp,resolve}` routes on the chat-ws wrapper. The engine (smooth-operator\n * 1.8.0) owns the `/ws` dispatch and REJECTS unknown verbs, so these are HTTP\n * `fetch()` calls (origin-allowlisted + optional authContext, per ADR-046/048) —\n * NOT WS frames.\n *\n * The controller is UI-agnostic: it emits typed events and the view renders them.\n */\nimport { type Citation, ProtocolError, type ServerEvent, SmoothAgentClient } from '@smooai/smooth-operator';\nimport type { StoreApi } from 'zustand/vanilla';\nimport type { ChatWidgetConfig } from './config.js';\nimport { getOrCreateFingerprint } from './fingerprint.js';\nimport { type ConsentState, createWidgetStore, type WidgetStore } from './persistence.js';\n\n/**\n * Derive the HTTP base for the chat-ws wrapper's `/internal/*` REST routes from\n * the WS endpoint: `wss://ai.smoo.ai/ws` → `https://ai.smoo.ai`. The engine\n * (smooth-operator 1.8.0) owns the `/ws` dispatch and REJECTS unknown verbs, so\n * the cross-device identity flow + fingerprint resume are HTTP POST routes on the\n * wrapper (origin-allowlisted + authContext, per ADR-046/ADR-048) — NOT WS frames.\n */\nexport function httpBaseFromWsEndpoint(endpoint: string): string | null {\n try {\n const u = new URL(endpoint);\n u.protocol = u.protocol === 'ws:' ? 'http:' : u.protocol === 'wss:' ? 'https:' : u.protocol;\n // The REST routes live at the host root (`/internal/*`), not under `/ws`.\n return `${u.protocol}//${u.host}`;\n } catch {\n // FAIL LOUD on a non-absolute endpoint. A relative fallback (e.g.\n // `string.replace`) would yield a relative base, and `fetch(\\`${base}/internal/...\\`)`\n // would then POST identity/OTP data to the HOST page origin (e.g. smoo.ai)\n // instead of the operator host (ai.smoo.ai) — leaking it to the wrong origin.\n // Returning null forces the controller into an error state and refuses the\n // `/internal/*` calls rather than mis-targeting them.\n return null;\n }\n}\n\nexport type { Citation };\n\nexport type Role = 'user' | 'assistant';\n\n/**\n * One tool invocation within an assistant turn. Mirrors the smooth daemon SPA's\n * `ToolCall` (`crates/smooth-web/web/src/operator.ts`): opens `done: false` on the\n * tool call and resolves on the tool result.\n */\nexport interface ToolCall {\n /** Stable id for keyed rendering (assigned when the call opens). */\n id: string;\n name: string;\n /** Raw arguments, JSON-stringified. */\n args: string;\n /** Present once the tool resolves. */\n result?: string;\n isError?: boolean;\n done: boolean;\n}\n\n/**\n * One ordered segment of an assistant turn: a run of prose, or a tool call.\n * Preserves the interleave order the model produced (say a bit → call a tool →\n * say a bit → …) so the UI can render tool chips INLINE where the model called\n * them. Mirrors the daemon SPA's `MessageBlock`. Only populated when the widget\n * is configured with `showToolActivity: true`.\n */\nexport type MessageBlock = { kind: 'text'; text: string } | { kind: 'tool'; tool: ToolCall };\n\nexport interface ChatMessage {\n id: string;\n role: Role;\n /** Accumulated text (assistant messages grow as tokens stream in). */\n text: string;\n /** True while an assistant message is still streaming. */\n streaming: boolean;\n /**\n * Ordered text + tool segments, interleaved as the model produced them. Present\n * only on assistant messages when `showToolActivity` is enabled (absent\n * otherwise — the default popover renders `text` alone, byte-for-byte unchanged).\n */\n blocks?: MessageBlock[];\n /**\n * Sources that grounded an assistant answer, when the terminal\n * `eventual_response` carried any. Optional + back-compatible: absent when\n * the turn used no knowledge sources (or for user messages). Read\n * defensively off the terminal event — see {@link extractCitations}.\n */\n citations?: Citation[];\n /**\n * Suggested follow-up replies (\"quick replies\") the agent offered on the\n * terminal `eventual_response`. Set ONLY on the finalized assistant message —\n * never mid-stream. Read defensively (see {@link extractSuggestions}); capped\n * at 4 for layout. Absent when the turn offered none.\n */\n suggestions?: string[];\n}\n\nexport type ConnectionStatus = 'idle' | 'connecting' | 'ready' | 'error' | 'closed';\n\n/**\n * A mid-turn pause that needs the visitor to act before the agent can continue:\n *\n * - `otp` — the agent requested OTP verification before an authenticated action.\n * Resume with {@link ConversationController.verifyOtp}.\n * - `confirm` — the agent wants to run a state-mutating tool and needs approval.\n * Resume with {@link ConversationController.confirmTool}.\n * - `interaction` — the agent raised a Rich Interaction (structured card, e.g.\n * identity intake). Resume with {@link ConversationController.submitInteraction}\n * or {@link ConversationController.declineInteraction}.\n */\nexport type Interrupt =\n | {\n kind: 'otp';\n toolId?: string;\n actionDescription?: string;\n availableChannels: ('email' | 'sms')[];\n /** Set once the server confirms an OTP was dispatched. */\n sent?: { channel?: string; maskedDestination?: string };\n /** Set when a submitted code was rejected. */\n error?: string;\n attemptsRemaining?: number;\n }\n | { kind: 'confirm'; toolId?: string; actionDescription?: string }\n | {\n kind: 'interaction';\n /** Server-generated interaction instance id (echoed on submit). */\n interactionId: string;\n /** The Rich Interaction kind (e.g. `identity_intake`) — selects the card. */\n interactionKind: string;\n /** Kind-specific render spec (identity_intake: `{ fields: [...] }`). */\n spec: Record<string, unknown>;\n /** Why the agent raised it (card header copy). */\n reason?: string;\n /** Per-field server-side validation errors (from `interaction_invalid`). */\n errors?: { field: string; message: string }[];\n };\n\n/**\n * The Rich-Interaction render capabilities this widget declares at session\n * create (`supports`). Must stay aligned with the card registry in\n * `element.ts` (`INTERACTION_CARDS`) — registering a card IS declaring its\n * capability; a test asserts the two match.\n */\nexport const SUPPORTED_INTERACTION_CAPABILITIES: readonly string[] = ['identity_form'];\n\nexport interface UserInfo {\n name?: string;\n email?: string;\n phone?: string;\n /** Marketing-consent opt-ins captured at the pre-chat form (ADR-048). */\n consent?: { emailOptIn: boolean; smsOptIn: boolean };\n}\n\n/** One conversation surfaced by `resolve_identity` for the cross-device picker. */\nexport interface RestorableConversation {\n conversationId: string;\n sessionId: string;\n lastActivityAt?: string;\n preview?: string;\n}\n\n/**\n * State machine for the cross-device \"restore my chats\" flow. Driven by the three\n * HTTP POST routes on the chat-ws wrapper — `/internal/identity/request-otp` →\n * `/internal/identity/verify-otp` → `/internal/identity/resolve` (ADR-048 §c).\n * The view renders a panel off this.\n */\nexport type IdentityRestore =\n | { phase: 'idle' }\n /** UI-local: the email-entry step before any request is sent. */\n | { phase: 'awaiting_email'; error?: string }\n | { phase: 'requesting'; email: string; channel: 'email' | 'sms' }\n | { phase: 'awaiting_code'; email: string; channel: 'email' | 'sms'; maskedDestination?: string; error?: string; attemptsRemaining?: number }\n | { phase: 'verifying'; email: string; channel: 'email' | 'sms' }\n | { phase: 'resolving'; email: string }\n | { phase: 'resolved'; email: string; conversations: RestorableConversation[] }\n | { phase: 'error'; message: string };\n\nexport interface ConversationEvents {\n /** Fired whenever the message list changes (append, token delta, finalize). */\n onMessages: (messages: ChatMessage[]) => void;\n /** Fired on connection-status transitions. */\n onStatus: (status: ConnectionStatus, detail?: string) => void;\n /** Fired when a turn pauses for OTP / tool-confirmation, and `null` when it clears. */\n onInterrupt?: (interrupt: Interrupt | null) => void;\n /** Fired on cross-device identity-restore state transitions. */\n onIdentityRestore?: (state: IdentityRestore) => void;\n}\n\n/** Pull the final assistant text out of an `eventual_response` data payload. */\nfunction extractFinalText(response: unknown): string | null {\n if (!response || typeof response !== 'object') return null;\n const r = response as { responseParts?: unknown };\n if (Array.isArray(r.responseParts)) {\n return r.responseParts.filter((p): p is string => typeof p === 'string').join('\\n\\n');\n }\n return null;\n}\n\n/**\n * Pull the grounding {@link Citation}s out of a terminal `eventual_response`.\n *\n * The protocol client types these (`eventual_response.data.data.citations`),\n * but they're optional and back-compatible — absent when the turn used no\n * knowledge sources. We read them defensively (tolerating their total absence,\n * non-array shapes, and missing fields) so a server that doesn't emit them, or\n * an older client, can't break rendering. Each citation always carries\n * `id`/`title`/`snippet`/`score`; `url` is present only for web-sourced docs.\n */\nfunction extractCitations(inner: unknown): Citation[] {\n if (!inner || typeof inner !== 'object') return [];\n const raw = (inner as { citations?: unknown }).citations;\n if (!Array.isArray(raw)) return [];\n const out: Citation[] = [];\n for (const c of raw) {\n if (!c || typeof c !== 'object') continue;\n const obj = c as Record<string, unknown>;\n const id = typeof obj.id === 'string' ? obj.id : '';\n const title = typeof obj.title === 'string' ? obj.title : id || 'Source';\n const snippet = typeof obj.snippet === 'string' ? obj.snippet : '';\n const url = typeof obj.url === 'string' && obj.url ? obj.url : undefined;\n const score = typeof obj.score === 'number' ? obj.score : 0;\n out.push({ id, title, snippet, score, url });\n }\n return out;\n}\n\n/**\n * Pull the suggested follow-up replies out of a terminal `eventual_response`'s\n * `response` object (`response.suggestedNextActions`). Optional + back-compatible\n * like citations — read defensively (tolerating absence, non-array shapes, and\n * non-string / blank entries) and capped at 4 so a chatty agent can't overflow\n * the composer chip row.\n */\nfunction extractSuggestions(response: unknown): string[] {\n if (!response || typeof response !== 'object') return [];\n const raw = (response as { suggestedNextActions?: unknown }).suggestedNextActions;\n if (!Array.isArray(raw)) return [];\n return raw.filter((s): s is string => typeof s === 'string' && s.trim().length > 0).slice(0, 4);\n}\n\n/** A `get_conversation_messages` row, narrowed defensively off the wire. */\ninterface WireMessage {\n id?: string;\n direction?: 'inbound' | 'outbound';\n content?: { text?: string };\n createdAt?: string;\n}\n\n/** Convert a server message row into a finalized {@link ChatMessage}. */\nfunction wireMessageToChat(m: WireMessage, idx: number): ChatMessage | null {\n const text = typeof m.content?.text === 'string' ? m.content.text : '';\n if (!text) return null;\n const role: Role = m.direction === 'outbound' ? 'assistant' : 'user';\n return { id: typeof m.id === 'string' ? m.id : `hist-${idx}`, role, text, streaming: false };\n}\n\nlet toolSeq = 0;\nconst nextToolId = (): string => `tool-${++toolSeq}`;\n\n/** Grow the trailing text block, or open a new one if the last block was a tool. */\nfunction growTextBlock(blocks: MessageBlock[], text: string): void {\n if (!text) return;\n const last = blocks[blocks.length - 1];\n if (last && last.kind === 'text') last.text += text;\n else blocks.push({ kind: 'text', text });\n}\n\n/**\n * Fold a `stream_chunk` node-state into the ordered block list, returning `true`\n * when the chunk carried tool activity.\n *\n * Tool activity rides `state.rawResponse.toolCall` / `state.rawResponse.toolResult`\n * — **NOT** `state.toolResult`. Reading the wrong path leaves every chip stuck on\n * \"running…\" forever (the exact bug the daemon SPA hit and this mirror avoids).\n */\nfunction applyToolChunk(blocks: MessageBlock[], state: unknown): boolean {\n const raw = (state as { rawResponse?: unknown } | null | undefined)?.rawResponse;\n if (!raw || typeof raw !== 'object') return false;\n const call = (raw as { toolCall?: { name?: string; arguments?: unknown } }).toolCall;\n const res = (raw as { toolResult?: { name?: string; isError?: boolean; result?: unknown } }).toolResult;\n if (call) {\n const args = typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments ?? {});\n blocks.push({ kind: 'tool', tool: { id: nextToolId(), name: call.name ?? '', args, done: false } });\n return true;\n }\n if (res) {\n const result = typeof res.result === 'string' ? res.result : JSON.stringify(res.result ?? '');\n // Complete the most-recent still-open tool block matching this name.\n for (let i = blocks.length - 1; i >= 0; i--) {\n const b = blocks[i];\n if (b && b.kind === 'tool' && b.tool.name === (res.name ?? '') && !b.tool.done) {\n b.tool.done = true;\n b.tool.isError = !!res.isError;\n b.tool.result = result;\n break;\n }\n }\n return true;\n }\n return false;\n}\n\nexport class ConversationController {\n private readonly config: ChatWidgetConfig;\n private readonly events: ConversationEvents;\n private readonly store: StoreApi<WidgetStore>;\n private client: SmoothAgentClient | null = null;\n private sessionId: string | null = null;\n private readonly messages: ChatMessage[] = [];\n private status: ConnectionStatus = 'idle';\n private seq = 0;\n /** requestId of the in-flight turn — used to resume OTP / tool confirmations. */\n private activeRequestId: string | null = null;\n private interrupt: Interrupt | null = null;\n /** Values from the last interaction submit, merged into the persisted\n * identity (identity_intake only) once the server acks them. */\n private pendingInteractionValues: { kind: string; values: Record<string, unknown> } | null = null;\n private identityRestore: IdentityRestore = { phase: 'idle' };\n /**\n * True once the resume probe (persisted-pointer get_session OR the\n * `/internal/resume-by-fingerprint` POST) has run for this controller. Makes\n * `connect()` idempotent: re-entering after a transient `error` status (e.g. a\n * retried `send()`) creates a fresh session rather than re-running the resume\n * probe — which would fire another `resumeByFingerprint` POST and could adopt a\n * session we already decided not to resume.\n */\n private resumeAttempted = false;\n /**\n * HTTP base for the chat-ws wrapper's `/internal/*` REST routes. `null` when\n * the configured WS endpoint could not be parsed into an absolute origin — in\n * that case the `/internal/*` routes are refused (rather than mis-targeted at\n * the host page origin). See {@link httpBaseFromWsEndpoint}.\n */\n private readonly httpBase: string | null;\n\n constructor(config: ChatWidgetConfig, events: ConversationEvents, store?: StoreApi<WidgetStore>) {\n this.config = config;\n this.events = events;\n this.httpBase = httpBaseFromWsEndpoint(config.endpoint);\n if (this.httpBase === null) {\n // A non-absolute endpoint means the identity / resume `/internal/*` routes\n // have no safe target. Flag the controller in error so the UI surfaces it\n // and the routes refuse (see postInternal) rather than mis-targeting the\n // host page origin. Deferred to a microtask so listeners attached after\n // construction still observe the transition.\n queueMicrotask(() => this.setStatus('error', `Invalid chat endpoint: ${config.endpoint}`));\n }\n this.store = store ?? createWidgetStore(config.agentId);\n // Seed identity from config into the persisted store. `mergeIdentity` is\n // applied on EVERY construct, so a config-provided field always wins over\n // the persisted value (config is authoritative when present). Fields the\n // config does NOT provide keep their persisted value — those survive across\n // reloads; explicitly-configured ones are re-applied each load.\n const seed: { name?: string; email?: string; phone?: string } = {};\n if (config.userName) seed.name = config.userName;\n if (config.userEmail) seed.email = config.userEmail;\n if (config.userPhone) seed.phone = config.userPhone;\n if (Object.keys(seed).length > 0) this.store.getState().mergeIdentity(seed);\n }\n\n get connectionStatus(): ConnectionStatus {\n return this.status;\n }\n\n /** The persisted store, exposed so the view can read identity for the pre-chat gate. */\n getStore(): StoreApi<WidgetStore> {\n return this.store;\n }\n\n /** True when a persisted session pointer exists (drives the resume path). */\n hasPersistedSession(): boolean {\n return !!this.store.getState().sessionId;\n }\n\n /** True when persisted identity exists (lets the view skip the pre-chat form). */\n hasPersistedIdentity(): boolean {\n const id = this.store.getState().identity;\n return !!(id.name || id.email || id.phone);\n }\n\n /** Merge in visitor identity + consent (from the pre-chat form). Applied on next connect. */\n setUserInfo(info: UserInfo): void {\n const { name, email, phone, consent } = info;\n this.store.getState().mergeIdentity({ name, email, phone });\n if (consent) {\n const consentAt = consent.emailOptIn || consent.smsOptIn ? new Date().toISOString() : undefined;\n this.store.getState().setConsent({\n emailOptIn: consent.emailOptIn,\n smsOptIn: consent.smsOptIn,\n consentSource: 'chat-widget-prechat',\n consentAt,\n });\n }\n }\n\n private setInterrupt(interrupt: Interrupt | null): void {\n this.interrupt = interrupt;\n this.events.onInterrupt?.(interrupt);\n }\n\n private setIdentityRestore(state: IdentityRestore): void {\n this.identityRestore = state;\n this.events.onIdentityRestore?.(state);\n }\n\n get currentIdentityRestore(): IdentityRestore {\n return this.identityRestore;\n }\n\n /** Submit an OTP code to resume the paused turn. No-op if not awaiting OTP. */\n verifyOtp(code: string): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'otp') return;\n this.client.verifyOtp({ sessionId: this.sessionId, requestId: this.activeRequestId, code });\n }\n\n /** Approve or reject a pending tool write to resume the paused turn. */\n confirmTool(approved: boolean): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'confirm') return;\n this.client.confirmToolAction({ sessionId: this.sessionId, requestId: this.activeRequestId, approved });\n this.setInterrupt(null);\n }\n\n /**\n * Submit a Rich Interaction card to resume the parked turn. The server\n * routes to the kind's validator: invalid values come back as an\n * `interaction_invalid` event (the card re-renders with per-field errors —\n * the turn stays parked); a valid submit is acked and the turn resumes.\n * No-op if not awaiting an interaction.\n */\n submitInteraction(values: Record<string, unknown>): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'interaction') return;\n // Stash the values so the ack (immediate_response) can merge accepted\n // identity values into the persisted store.\n this.pendingInteractionValues = { kind: this.interrupt.interactionKind, values };\n this.client.submitInteraction({\n sessionId: this.sessionId,\n requestId: this.activeRequestId,\n interactionId: this.interrupt.interactionId,\n kind: this.interrupt.interactionKind,\n values,\n });\n }\n\n /** Decline the pending Rich Interaction; the agent continues without it. */\n declineInteraction(): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'interaction') return;\n this.client.submitInteraction({\n sessionId: this.sessionId,\n requestId: this.activeRequestId,\n interactionId: this.interrupt.interactionId,\n kind: this.interrupt.interactionKind,\n declined: true,\n });\n this.pendingInteractionValues = null;\n this.setInterrupt(null);\n }\n\n private nextId(prefix: string): string {\n this.seq += 1;\n return `${prefix}-${this.seq}-${Date.now().toString(36)}`;\n }\n\n private setStatus(status: ConnectionStatus, detail?: string): void {\n this.status = status;\n this.events.onStatus(status, detail);\n }\n\n private emitMessages(): void {\n // Hand out a shallow copy so the view can't mutate internal state.\n this.events.onMessages(this.messages.map((m) => ({ ...m })));\n }\n\n /** Compute (once) + return the persisted browser fingerprint. */\n private fingerprint(): string {\n const state = this.store.getState();\n return getOrCreateFingerprint(\n () => state.browserFingerprint,\n (fp) => this.store.getState().setBrowserFingerprint(fp),\n );\n }\n\n /**\n * Build the `metadata` payload threaded into `create_conversation_session`:\n * phone (no first-class engine field) and consent.\n *\n * NOTE: `verifiedEmail` is deliberately NOT stamped here. It is a per-session\n * OTP proof bound to the session it was verified against\n * (`verifiedEmailSessionId`), and the server only treats an actual OTP `verify`\n * as proof — metadata `verifiedEmail` is just a hint. Auto-stamping it onto\n * every brand-new `create_conversation_session` would mislabel a fresh\n * visitor's session with a prior (possibly different) visitor's email on a\n * shared browser. The verified email is only used when RESUMING the exact\n * session it was proven for — see {@link verifiedEmailForSession}.\n */\n private sessionMetadata(): Record<string, unknown> | undefined {\n const state = this.store.getState();\n const meta: Record<string, unknown> = {};\n if (state.identity.phone) meta.userPhone = state.identity.phone;\n const consent = state.consent;\n if (consent.emailOptIn || consent.smsOptIn || consent.consentAt) {\n const c: ConsentState = {\n emailOptIn: consent.emailOptIn,\n smsOptIn: consent.smsOptIn,\n consentSource: consent.consentSource ?? 'chat-widget-prechat',\n };\n if (consent.consentAt) c.consentAt = consent.consentAt;\n meta.consent = c;\n }\n return Object.keys(meta).length > 0 ? meta : undefined;\n }\n\n /**\n * The verified-email hint, but ONLY when the OTP proof is bound to the session\n * being resumed (`verifiedEmailSessionId === sessionId`). Returns null\n * otherwise so a stale/cross-visitor proof is never threaded onto a session it\n * wasn't proven for.\n */\n private verifiedEmailForSession(sessionId: string): string | null {\n const state = this.store.getState();\n if (state.verifiedEmail && state.verifiedEmailSessionId === sessionId) {\n return state.verifiedEmail;\n }\n return null;\n }\n\n /** Lazily open the WS client (default transport). Idempotent within a connect. */\n private async ensureClient(): Promise<void> {\n if (this.client) return;\n this.client = new SmoothAgentClient({ url: this.config.endpoint });\n await this.client.connect();\n }\n\n /**\n * Open the connection and either RESUME or create a session.\n *\n * 1. Persisted pointer (ADR-048 §b): `get_session` → if not `ended`, reuse +\n * hydrate from `get_messages` (newest-first, reversed). On ended/404 clear\n * ONLY the pointer (identity/consent survive).\n * 2. No persisted pointer: POST `/internal/resume-by-fingerprint` FIRST; if\n * `resumable`, adopt the returned session (the wrapper has primed the\n * operator registry), reuse the sessionId, and hydrate via get_session/\n * get_messages — rather than relying on createConversationSession to resume.\n * 3. Otherwise create a fresh session.\n */\n async connect(): Promise<void> {\n if (this.status === 'connecting' || this.status === 'ready') return;\n this.setStatus('connecting');\n try {\n await this.ensureClient();\n // The resume probe (persisted-pointer get_session OR the fingerprint\n // resume POST) runs AT MOST ONCE per controller lifecycle. Re-entering\n // connect() after a transient error (e.g. a retried send()) must not\n // re-run the probe — that would re-fire resumeByFingerprint and could\n // adopt a session we already chose not to resume. After the first\n // attempt, fall straight through to creating a fresh session.\n if (!this.resumeAttempted) {\n this.resumeAttempted = true;\n const persistedSessionId = this.store.getState().sessionId;\n if (persistedSessionId) {\n const resumed = await this.tryResume(persistedSessionId);\n if (resumed) {\n this.setStatus('ready');\n return;\n }\n // Resume failed (ended/404/gone) — clear the pointer, keep identity.\n this.store.getState().clearSession();\n } else {\n // Returning anonymous visitor with no stored pointer: ask the\n // wrapper to resolve a recent session for this fingerprint.\n const fpSessionId = await this.resumeByFingerprint();\n if (fpSessionId) {\n const resumed = await this.tryResume(fpSessionId);\n if (resumed) {\n this.store.getState().setSessionId(fpSessionId);\n this.setStatus('ready');\n return;\n }\n }\n }\n }\n await this.createSession();\n this.setStatus('ready');\n } catch (err) {\n this.setStatus('error', err instanceof Error ? err.message : String(err));\n throw err;\n }\n }\n\n // ─────────────────────── chat-ws `/internal/*` HTTP ─────────────────────────\n\n /**\n * Build the auth fields every `/internal/*` route shares: `agentId` (required\n * for the agent-policy lookup), `agentName` (used as the OTP email sender), and\n * the optional pre-auth `authContext` the host page may have configured. The\n * `Origin` header is sent automatically by the browser and checked server-side.\n */\n private authBody(): Record<string, unknown> {\n const body: Record<string, unknown> = { agentId: this.config.agentId };\n if (this.config.agentName) body.agentName = this.config.agentName;\n if (this.config.authContext) body.authContext = this.config.authContext;\n return body;\n }\n\n /** POST JSON to a `/internal/*` route; returns the parsed body (or throws). */\n private async postInternal(path: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (this.httpBase === null) {\n // No absolute origin could be derived from the WS endpoint — refuse the\n // call loudly rather than POST identity data to a relative (host-page) URL.\n throw new Error(`Cannot reach ${path}: the chat endpoint is not an absolute URL.`);\n }\n const res = await fetch(`${this.httpBase}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n // Auth is the `Origin` allowlist + the `authContext` body field — NOT\n // cookies. `credentials: 'include'` would force the server to reply with\n // `Access-Control-Allow-Credentials: true` AND a reflected origin (a\n // wildcard `*` is illegal with credentials), so a plain origin-allowlisted\n // CORS config would fail the preflight and break EVERY `/internal/*` call.\n // Omit credentials so the cross-origin POST works against an allowlist\n // that doesn't (and shouldn't need to) opt into credentialed CORS.\n credentials: 'omit',\n body: JSON.stringify({ ...this.authBody(), ...payload }),\n });\n let json: Record<string, unknown> = {};\n try {\n json = (await res.json()) as Record<string, unknown>;\n } catch {\n json = {};\n }\n if (!res.ok) {\n const err = json.error as { code?: string; message?: string } | undefined;\n throw new Error(err?.message ?? `${path} failed (${res.status})`);\n }\n return json;\n }\n\n /**\n * POST `/internal/resume-by-fingerprint`. Returns the resumable sessionId when\n * the wrapper found (and primed) a recent session for this fingerprint, else\n * null. Network/route failures are swallowed → null (fall through to create).\n */\n private async resumeByFingerprint(): Promise<string | null> {\n try {\n const json = await this.postInternal('/internal/resume-by-fingerprint', { browserFingerprint: this.fingerprint() });\n if (json.resumable === true && typeof json.sessionId === 'string') {\n return json.sessionId;\n }\n } catch {\n // Resume is best-effort; any failure just means a fresh session.\n }\n return null;\n }\n\n /** `create_conversation_session` with fingerprint + identity + consent metadata. */\n private async createSession(): Promise<void> {\n if (!this.client) throw new Error('Conversation is not connected');\n const state = this.store.getState();\n const metadata = this.sessionMetadata();\n const session = await this.client.createConversationSession({\n agentId: this.config.agentId,\n userName: state.identity.name,\n userEmail: state.identity.email,\n browserFingerprint: this.fingerprint(),\n // Declare the Rich-Interaction cards this widget can render (derived\n // from the card registry), so the server emits `interaction_required`\n // for those kinds instead of the conversational fallback.\n supports: [...SUPPORTED_INTERACTION_CAPABILITIES],\n ...(metadata ? { metadata } : {}),\n });\n this.sessionId = session.sessionId;\n this.store.getState().setSessionId(session.sessionId);\n }\n\n /**\n * Attempt to resume `sessionId`: returns true and hydrates the transcript when\n * the session is live, false when it has ended / can't be fetched.\n */\n private async tryResume(sessionId: string): Promise<boolean> {\n if (!this.client) return false;\n let snap: { status?: 'active' | 'idle' | 'ended' };\n try {\n snap = await this.client.getSession({ sessionId });\n } catch {\n return false; // 404 / SESSION_NOT_FOUND / network — start fresh.\n }\n if (snap.status === 'ended') return false;\n\n this.sessionId = sessionId;\n await this.hydrateHistory(sessionId);\n return true;\n }\n\n /** Page recent history (newest-first), reverse to chronological, and render. */\n private async hydrateHistory(sessionId: string): Promise<void> {\n if (!this.client) return;\n try {\n const page = await this.client.getMessages({ sessionId, limit: 50 });\n const rows = Array.isArray(page.messages) ? page.messages : [];\n // The server returns newest-first; reverse to chronological for the UI.\n const chronological = [...rows].reverse();\n const hydrated: ChatMessage[] = [];\n chronological.forEach((m, i) => {\n const chat = wireMessageToChat(m as WireMessage, i);\n if (chat) hydrated.push(chat);\n });\n this.messages.length = 0;\n this.messages.push(...hydrated);\n this.emitMessages();\n } catch {\n // History fetch is best-effort: a resumable session with no fetchable\n // history just shows an empty transcript rather than failing the resume.\n }\n }\n\n /**\n * Submit a user message. Appends the user bubble immediately, then streams the\n * assistant reply token-by-token, finalizing on `eventual_response`.\n */\n async send(text: string): Promise<void> {\n const trimmed = text.trim();\n if (!trimmed) return;\n if (!this.client || !this.sessionId || this.status !== 'ready') {\n await this.connect();\n }\n if (!this.client || !this.sessionId) {\n throw new Error('Conversation is not connected');\n }\n\n // 1. User bubble.\n this.messages.push({ id: this.nextId('u'), role: 'user', text: trimmed, streaming: false });\n\n // 2. Placeholder assistant bubble we grow as tokens arrive.\n const showTools = this.config.showToolActivity === true;\n const assistant: ChatMessage = { id: this.nextId('a'), role: 'assistant', text: '', streaming: true, blocks: showTools ? [] : undefined };\n this.messages.push(assistant);\n this.emitMessages();\n\n try {\n const turn = this.client.sendMessage({ sessionId: this.sessionId, message: trimmed, stream: true });\n this.activeRequestId = turn.requestId;\n\n for await (const event of turn) {\n if (event.type === 'stream_token') {\n const token = event.token ?? event.data?.token ?? '';\n if (token) {\n assistant.text += token;\n // Grow the trailing text block so prose interleaves with any\n // tool chips in the order the model produced them.\n if (showTools && assistant.blocks) growTextBlock(assistant.blocks, token);\n this.emitMessages();\n }\n } else if (showTools && event.type === 'stream_chunk') {\n // Tool activity (gated). Read state.rawResponse.toolCall/.toolResult.\n if (assistant.blocks && applyToolChunk(assistant.blocks, event.data?.state)) {\n this.emitMessages();\n }\n } else {\n // OTP / tool-confirmation pauses surface here; the loop keeps\n // iterating once the visitor resumes via verifyOtp/confirmTool.\n this.handleTurnEvent(event);\n }\n }\n\n const final = await turn;\n const inner = final.data?.data;\n const finalText = extractFinalText(inner?.response);\n if (finalText && finalText.length > assistant.text.length) {\n assistant.text = finalText;\n }\n if (!assistant.text) {\n assistant.text = '(no response)';\n }\n // Attach grounding sources from the terminal event, when present.\n const citations = extractCitations(inner);\n if (citations.length > 0) {\n assistant.citations = citations;\n }\n // Suggested follow-up replies from the terminal event, when present.\n const suggestions = extractSuggestions(inner?.response);\n if (suggestions.length > 0) {\n assistant.suggestions = suggestions;\n }\n // Only keep blocks for turns that actually invoked a tool — a prose-only\n // turn drops back to the normal markdown text path (with the final text).\n if (assistant.blocks && !assistant.blocks.some((b) => b.kind === 'tool')) {\n assistant.blocks = undefined;\n }\n assistant.streaming = false;\n this.emitMessages();\n } catch (err) {\n assistant.streaming = false;\n const message =\n err instanceof ProtocolError\n ? `Error: ${err.message}`\n : (this.config.connectionErrorMessage ?? \"We couldn't reach the chat.\");\n assistant.text = assistant.text ? `${assistant.text}\\n\\n${message}` : message;\n this.emitMessages();\n this.setStatus('error', err instanceof Error ? err.message : String(err));\n } finally {\n this.activeRequestId = null;\n this.setInterrupt(null);\n }\n }\n\n /** Map a non-token turn event (OTP / tool-confirmation lifecycle) to interrupt state. */\n private handleTurnEvent(event: ServerEvent): void {\n const inner = ((event as { data?: { data?: Record<string, unknown> } }).data?.data ?? {}) as Record<string, unknown>;\n const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined);\n const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);\n switch (event.type) {\n case 'otp_verification_required': {\n const channels: ('email' | 'sms')[] = Array.isArray(inner.availableChannels)\n ? inner.availableChannels.filter((c): c is 'email' | 'sms' => c === 'email' || c === 'sms')\n : ['email'];\n this.setInterrupt({\n kind: 'otp',\n toolId: str(inner.toolId),\n actionDescription: str(inner.actionDescription),\n availableChannels: channels.length > 0 ? channels : ['email'],\n });\n break;\n }\n case 'otp_sent':\n if (this.interrupt?.kind === 'otp') {\n this.setInterrupt({ ...this.interrupt, sent: { channel: str(inner.channel), maskedDestination: str(inner.maskedDestination) }, error: undefined });\n }\n break;\n case 'otp_verified':\n if (this.interrupt?.kind === 'otp') this.setInterrupt(null);\n break;\n case 'otp_invalid':\n if (this.interrupt?.kind === 'otp') {\n this.setInterrupt({ ...this.interrupt, error: str(inner.message) ?? 'That code was incorrect.', attemptsRemaining: num(inner.attemptsRemaining) });\n }\n break;\n case 'write_confirmation_required':\n this.setInterrupt({ kind: 'confirm', toolId: str(inner.toolId), actionDescription: str(inner.actionDescription) });\n break;\n case 'interaction_required': {\n const interactionId = str(inner.interactionId);\n const kind = str(inner.kind);\n const spec = inner.spec && typeof inner.spec === 'object' ? (inner.spec as Record<string, unknown>) : {};\n if (!interactionId || !kind) break; // not renderable — ignore\n this.pendingInteractionValues = null;\n this.setInterrupt({\n kind: 'interaction',\n interactionId,\n interactionKind: kind,\n spec,\n reason: str(inner.reason),\n });\n break;\n }\n case 'interaction_invalid':\n if (this.interrupt?.kind === 'interaction' && this.interrupt.interactionId === str(inner.interactionId)) {\n const errors: { field: string; message: string }[] = [];\n if (Array.isArray(inner.errors)) {\n for (const e of inner.errors) {\n if (!e || typeof e !== 'object') continue;\n const o = e as Record<string, unknown>;\n const field = str(o.field);\n if (field) errors.push({ field, message: str(o.message) ?? 'Invalid value' });\n }\n }\n this.pendingInteractionValues = null;\n this.setInterrupt({ ...this.interrupt, errors });\n }\n break;\n case 'immediate_response':\n // Mid-turn immediate_response while an interaction card is showing\n // is the submit/decline ack: the park resolved — clear the card\n // and, for accepted identity values, persist them.\n if (this.interrupt?.kind === 'interaction') {\n const pending = this.pendingInteractionValues;\n if (pending && pending.kind === 'identity_intake') {\n const v = pending.values as { name?: string; email?: string; phone?: string };\n this.store.getState().mergeIdentity({ name: v.name, email: v.email, phone: v.phone });\n }\n this.pendingInteractionValues = null;\n this.setInterrupt(null);\n }\n break;\n default:\n break;\n }\n }\n\n // ─────────────────── Cross-device \"restore my chats\" (§c) ───────────────────\n //\n // Three HTTP POST routes on the chat-ws wrapper (the engine `/ws` dispatch\n // rejects unknown verbs): request-otp → verify-otp → resolve. ALL THREE are\n // session-scoped — they require a live `sessionId` (a uuid). request-otp\n // establishes the session itself (idempotent connect) before sending, so the\n // whole flow shares one session and verify-otp can't hit \"No active session\"\n // even if the email was submitted before the initial connect() resolved.\n\n /**\n * Begin the cross-device restore: POST `/internal/identity/request-otp` for\n * `email` over `channel`. The view collects the email via an explicit affordance.\n */\n async requestIdentityOtp(email: string, channel: 'email' | 'sms' = 'email'): Promise<void> {\n const trimmed = email.trim();\n if (!trimmed) return;\n this.setIdentityRestore({ phase: 'requesting', email: trimmed, channel });\n // request-otp must be SESSION-CONSISTENT with verify-otp (which hard-requires\n // a sessionId). If the restore affordance fired request-otp before connect()\n // resolved, there'd be no sessionId here and verify-otp would later error\n // \"No active session.\" Establish a session first (idempotent connect), then\n // require it — so the whole request → verify flow shares one live session.\n if (!this.sessionId) {\n try {\n await this.connect();\n } catch {\n /* fall through: handled by the sessionId check below */\n }\n }\n if (!this.sessionId) {\n this.setIdentityRestore({ phase: 'error', message: 'No active session to verify against.' });\n return;\n }\n try {\n const json = await this.postInternal('/internal/identity/request-otp', {\n sessionId: this.sessionId,\n email: trimmed,\n channel,\n });\n const masked = typeof json.maskedDestination === 'string' ? json.maskedDestination : undefined;\n this.setIdentityRestore({ phase: 'awaiting_code', email: trimmed, channel, maskedDestination: masked });\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Could not send a verification code.' });\n }\n }\n\n /** Submit the code: POST `/internal/identity/verify-otp`, then resolve on success. */\n async verifyIdentityOtp(code: string): Promise<void> {\n const state = this.identityRestore;\n const trimmed = code.trim();\n if (!trimmed || state.phase !== 'awaiting_code') return;\n const { email, channel } = state;\n if (!this.sessionId) {\n this.setIdentityRestore({ phase: 'error', message: 'No active session to verify against.' });\n return;\n }\n this.setIdentityRestore({ phase: 'verifying', email, channel });\n try {\n const json = await this.postInternal('/internal/identity/verify-otp', { sessionId: this.sessionId, email, code: trimmed });\n if (json.event === 'otp_verified') {\n // Bind the OTP proof to the session it was verified against, so it\n // can't leak onto a different visitor's session on a shared browser.\n this.store.getState().setVerifiedEmail(email, this.sessionId);\n await this.resolveIdentity(email);\n } else if (json.event === 'otp_invalid') {\n const remaining = typeof json.attemptsRemaining === 'number' ? json.attemptsRemaining : undefined;\n this.setIdentityRestore({ phase: 'awaiting_code', email, channel, error: 'That code was incorrect.', attemptsRemaining: remaining });\n } else {\n this.setIdentityRestore({ phase: 'error', message: 'Verification failed.' });\n }\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Verification failed.' });\n }\n }\n\n /** Resolve the verified identity → restorable conversations via POST `/internal/identity/resolve`. */\n private async resolveIdentity(email: string): Promise<void> {\n if (!this.sessionId) return;\n this.setIdentityRestore({ phase: 'resolving', email });\n try {\n const json = await this.postInternal('/internal/identity/resolve', { sessionId: this.sessionId, email });\n if (json.resolved !== true) {\n this.setIdentityRestore({ phase: 'resolved', email, conversations: [] });\n return;\n }\n const raw = json.conversations;\n const conversations: RestorableConversation[] = Array.isArray(raw)\n ? raw\n .map((c): RestorableConversation | null => {\n if (!c || typeof c !== 'object') return null;\n const o = c as Record<string, unknown>;\n const conversationId = typeof o.conversationId === 'string' ? o.conversationId : '';\n const sessionId = typeof o.sessionId === 'string' ? o.sessionId : '';\n if (!sessionId) return null;\n return {\n conversationId,\n sessionId,\n lastActivityAt: typeof o.lastActivityAt === 'string' ? o.lastActivityAt : undefined,\n preview: typeof o.preview === 'string' ? o.preview : undefined,\n };\n })\n .filter((c): c is RestorableConversation => c !== null)\n : [];\n this.setIdentityRestore({ phase: 'resolved', email, conversations });\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Could not load your chats.' });\n }\n }\n\n /**\n * Replay a chosen restorable conversation: point the live session at its\n * sessionId, hydrate its transcript (get_session + get_messages), and persist\n * the new pointer so the next `sendMessage` continues it.\n */\n async restoreConversation(sessionId: string): Promise<void> {\n if (!this.client) await this.ensureClient();\n // Capture the OTP proof bound to the CURRENT live session BEFORE tryResume\n // repoints this.sessionId to the restored one. The visitor proved ownership\n // of this email in this very flow, so the proof legitimately follows the\n // conversation they chose to restore.\n const proven = this.sessionId ? this.verifiedEmailForSession(this.sessionId) : null;\n const resumed = await this.tryResume(sessionId);\n if (resumed) {\n this.store.getState().setSessionId(sessionId);\n // Rebind the proof to the restored session (keeps verifiedEmail\n // session-scoped, just now to the session it's actually used on). Only a\n // proof from the just-verified session follows — never an unrelated stale one.\n if (proven) this.store.getState().setVerifiedEmail(proven, sessionId);\n this.setIdentityRestore({ phase: 'idle' });\n this.setStatus('ready');\n } else {\n this.setIdentityRestore({ phase: 'error', message: 'That conversation is no longer available.' });\n }\n }\n\n /** Dismiss the cross-device restore panel. */\n cancelIdentityRestore(): void {\n this.setIdentityRestore({ phase: 'idle' });\n }\n\n /** Tear down the underlying client. */\n disconnect(): void {\n this.client?.disconnect('widget closed');\n this.client = null;\n this.sessionId = null;\n this.activeRequestId = null;\n // A full teardown ends the controller lifecycle: a subsequent connect() is a\n // genuine re-open and may resume again, so re-arm the resume probe.\n this.resumeAttempted = false;\n this.setInterrupt(null);\n this.setStatus('closed');\n }\n}\n","/**\n * The Smooth logo + icon, inlined as SVG strings so the full-page header can\n * render them without a separate network fetch (the IIFE bundle is\n * self-contained).\n *\n * GENERATED from `assets/smooth-logo.svg` / `assets/smooth-icon.svg` — do not\n * edit by hand. Regenerate with:\n * node -e 'const fs=require(\"fs\");process.stdout.write(JSON.stringify(fs.readFileSync(\"assets/smooth-icon.svg\",\"utf8\")))'\n */\n/* eslint-disable */\nexport const SMOOTH_LOGO_SVG = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<svg id=\\\"Layer_1\\\" data-name=\\\"Layer 1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" viewBox=\\\"0 0 550 135\\\">\\n <defs>\\n <style>\\n .cls-1 {\\n fill: url(#linear-gradient-3);\\n }\\n\\n .cls-2 {\\n fill: url(#linear-gradient-2);\\n }\\n\\n .cls-3 {\\n fill: url(#linear-gradient);\\n fill-rule: evenodd;\\n }\\n </style>\\n <linearGradient id=\\\"linear-gradient\\\" x1=\\\"115.59\\\" y1=\\\"112.81\\\" x2=\\\"25.08\\\" y2=\\\"22.3\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".3\\\" stop-color=\\\"#f49f0a\\\"/>\\n <stop offset=\\\".79\\\" stop-color=\\\"#fb7a4d\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#ff6b6c\\\"/>\\n </linearGradient>\\n <linearGradient id=\\\"linear-gradient-2\\\" x1=\\\"360.91\\\" y1=\\\"152.01\\\" x2=\\\"202.32\\\" y2=\\\"-6.59\\\" xlink:href=\\\"#linear-gradient\\\"/>\\n <linearGradient id=\\\"linear-gradient-3\\\" x1=\\\"443.91\\\" y1=\\\"30.15\\\" x2=\\\"531.36\\\" y2=\\\"117.59\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".43\\\" stop-color=\\\"#00a6a6\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#1238dd\\\"/>\\n </linearGradient>\\n </defs>\\n <path class=\\\"cls-3\\\" d=\\\"M48.28,14.96c-12.39,5.21-22.54,14.64-28.65,26.61-6.12,11.97-7.8,25.72-4.77,38.81,3.04,13.09,10.6,24.69,21.36,32.75,10.76,8.06,24.02,12.05,37.44,11.28,13.42-.77,26.13-6.26,35.9-15.5,9.76-9.24,15.95-21.63,17.46-34.99,1.51-13.36-1.74-26.82-9.19-38.01-1.07-1.61-.64-3.78.97-4.85,1.61-1.07,3.78-.64,4.85.97,8.36,12.56,12.02,27.68,10.32,42.67-1.7,15-8.64,28.91-19.61,39.28-10.96,10.37-25.24,16.54-40.31,17.4-15.07.87-29.96-3.62-42.04-12.66-12.08-9.05-20.58-22.07-23.99-36.77-3.41-14.7-1.51-30.14,5.35-43.58,6.87-13.44,18.26-24.02,32.17-29.87,13.91-5.85,29.44-6.6,43.85-2.11,1.85.57,2.88,2.54,2.3,4.38-.57,1.85-2.54,2.88-4.38,2.3-12.83-4-26.67-3.33-39.06,1.88ZM111.39,19.75c0,2.07-1.68,3.75-3.75,3.75s-3.75-1.68-3.75-3.75,1.68-3.75,3.75-3.75,3.75,1.68,3.75,3.75ZM64.64,59.93c0,1.91,2.39,2.56,7.69,3.88,3.89.97,6.6,2.18,8.15,3.63,1.53,1.45,2.29,3.53,2.29,6.25,0,3.57-1.03,6.26-3.11,8.08-2.07,1.82-5.09,2.73-9.09,2.73h-9.6c-1.97,0-3.57-1.6-3.59-3.57-.01-1.99,1.6-3.61,3.59-3.61h9.41c3.15-.12,4.79-.95,4.91-2.47,0-1.3-1.03-2.21-3.07-2.73-6.91-1.72-11.11-3.44-12.6-5.15-1.48-1.71-2.23-3.77-2.23-6.19,0-6.59,3.2-9.85,9.59-9.8h10.77c1.99,0,3.6,1.61,3.6,3.59s-1.61,3.59-3.6,3.59h-9.69c-1.83,0-3.43.06-3.43,1.77Z\\\"/>\\n <path class=\\\"cls-2\\\" d=\\\"M205.52,48.44h-8.86c-.44-3.75-2.23-6.65-5.38-8.72-3.16-2.07-7.03-3.1-11.6-3.1h0c-3.35,0-6.27.54-8.78,1.62-2.49,1.09-4.44,2.59-5.84,4.48-1.39,1.89-2.08,4.05-2.08,6.46h0c0,2.01.49,3.75,1.46,5.2.97,1.44,2.22,2.63,3.74,3.58,1.53.95,3.13,1.72,4.8,2.32,1.68.6,3.22,1.09,4.62,1.46h0l7.68,2.06c1.97.52,4.17,1.23,6.6,2.14,2.43.92,4.75,2.16,6.98,3.72,2.23,1.56,4.07,3.56,5.52,6,1.45,2.44,2.18,5.43,2.18,8.98h0c0,4.08-1.07,7.77-3.2,11.08-2.12,3.29-5.22,5.91-9.3,7.86-4.08,1.95-9.02,2.92-14.82,2.92h0c-5.43,0-10.11-.87-14.06-2.62-3.95-1.75-7.05-4.19-9.3-7.32-2.25-3.12-3.53-6.75-3.84-10.88h9.46c.25,2.85,1.22,5.21,2.9,7.06,1.69,1.87,3.83,3.25,6.42,4.14,2.6.89,5.41,1.34,8.42,1.34h0c3.49,0,6.63-.57,9.4-1.72,2.79-1.13,4.99-2.73,6.62-4.8,1.63-2.05,2.44-4.46,2.44-7.22h0c0-2.51-.7-4.55-2.1-6.12-1.41-1.57-3.26-2.85-5.54-3.84-2.29-.99-4.77-1.85-7.44-2.58h0l-9.3-2.66c-5.91-1.71-10.59-4.13-14.04-7.28-3.44-3.16-5.16-7.29-5.16-12.38h0c0-4.23,1.15-7.93,3.46-11.1,2.29-3.16,5.39-5.62,9.3-7.38,3.91-1.76,8.27-2.64,13.08-2.64h0c4.88,0,9.21.87,13,2.6,3.8,1.73,6.81,4.11,9.04,7.12,2.23,3,3.4,6.41,3.52,10.22h0ZM229.16,105.18h-8.72v-56.74h8.42v8.86h.74c1.19-3.03,3.1-5.38,5.74-7.06,2.63-1.69,5.79-2.54,9.48-2.54h0c3.75,0,6.87.85,9.36,2.54,2.51,1.68,4.46,4.03,5.86,7.06h.58c1.45-2.92,3.63-5.25,6.54-7,2.91-1.73,6.39-2.6,10.46-2.6h0c5.07,0,9.21,1.58,12.44,4.74,3.23,3.17,4.84,8.09,4.84,14.76h0v37.98h-8.72v-37.98c0-4.19-1.14-7.18-3.42-8.98-2.29-1.79-4.99-2.68-8.1-2.68h0c-3.99,0-7.07,1.2-9.26,3.6-2.2,2.4-3.3,5.43-3.3,9.1h0v36.94h-8.86v-38.86c0-3.23-1.05-5.83-3.14-7.82-2.09-1.97-4.79-2.96-8.08-2.96h0c-2.27,0-4.38.6-6.34,1.8-1.96,1.21-3.53,2.88-4.72,5-1.2,2.13-1.8,4.59-1.8,7.38h0v35.46ZM333.9,106.36h0c-5.12,0-9.61-1.22-13.46-3.66-3.85-2.44-6.86-5.85-9.02-10.24-2.15-4.37-3.22-9.49-3.22-15.36h0c0-5.91,1.07-11.07,3.22-15.48,2.16-4.4,5.17-7.82,9.02-10.26,3.85-2.44,8.34-3.66,13.46-3.66h0c5.12,0,9.61,1.22,13.46,3.66,3.85,2.44,6.86,5.86,9.02,10.26,2.15,4.41,3.22,9.57,3.22,15.48h0c0,5.87-1.07,10.99-3.22,15.36-2.16,4.39-5.17,7.8-9.02,10.24-3.85,2.44-8.34,3.66-13.46,3.66ZM333.9,98.52h0c3.89,0,7.09-.99,9.6-2.98,2.52-2,4.38-4.63,5.58-7.88,1.21-3.25,1.82-6.77,1.82-10.56h0c0-3.79-.61-7.32-1.82-10.6-1.2-3.27-3.06-5.91-5.58-7.94-2.51-2.01-5.71-3.02-9.6-3.02h0c-3.89,0-7.09,1.01-9.6,3.02-2.51,2.03-4.37,4.67-5.58,7.94-1.2,3.28-1.8,6.81-1.8,10.6h0c0,3.79.6,7.31,1.8,10.56,1.21,3.25,3.07,5.88,5.58,7.88,2.51,1.99,5.71,2.98,9.6,2.98ZM395.94,106.36h0c-5.12,0-9.61-1.22-13.46-3.66-3.85-2.44-6.85-5.85-9-10.24-2.16-4.37-3.24-9.49-3.24-15.36h0c0-5.91,1.08-11.07,3.24-15.48,2.15-4.4,5.15-7.82,9-10.26,3.85-2.44,8.34-3.66,13.46-3.66h0c5.12,0,9.61,1.22,13.46,3.66,3.85,2.44,6.86,5.86,9.02,10.26,2.16,4.41,3.24,9.57,3.24,15.48h0c0,5.87-1.08,10.99-3.24,15.36-2.16,4.39-5.17,7.8-9.02,10.24-3.85,2.44-8.34,3.66-13.46,3.66ZM395.94,98.52h0c3.89,0,7.09-.99,9.6-2.98,2.52-2,4.38-4.63,5.58-7.88,1.21-3.25,1.82-6.77,1.82-10.56h0c0-3.79-.61-7.32-1.82-10.6-1.2-3.27-3.06-5.91-5.58-7.94-2.51-2.01-5.71-3.02-9.6-3.02h0c-3.88,0-7.08,1.01-9.6,3.02-2.51,2.03-4.37,4.67-5.58,7.94-1.2,3.28-1.8,6.81-1.8,10.6h0c0,3.79.6,7.31,1.8,10.56,1.21,3.25,3.07,5.88,5.58,7.88,2.52,1.99,5.72,2.98,9.6,2.98Z\\\"/>\\n <path class=\\\"cls-1\\\" d=\\\"M467.88,48.02v13.28h-35.79v-13.28h35.79ZM439.68,34.38h17.89v53.42c0,1.5.36,2.62,1.08,3.36.72.74,1.88,1.1,3.49,1.1.62,0,1.48-.07,2.59-.21,1.11-.14,1.91-.27,2.38-.41l2.31,13.02c-2.02.58-3.97.97-5.84,1.18-1.88.21-3.66.31-5.33.31-6.08,0-10.7-1.43-13.84-4.28-3.15-2.85-4.72-7.01-4.72-12.48v-55.01ZM506.59,72.63v32.71h-17.89V28.95h17.53v33.53h-1.13c1.4-4.55,3.6-8.21,6.59-11,2.99-2.79,7.01-4.18,12.07-4.18,4,0,7.48.89,10.46,2.67,2.97,1.78,5.28,4.29,6.92,7.54,1.64,3.25,2.46,7.02,2.46,11.33v36.5h-17.89v-33.02c0-3.21-.82-5.73-2.46-7.56-1.64-1.83-3.93-2.74-6.87-2.74-1.92,0-3.62.42-5.1,1.26-1.49.84-2.64,2.04-3.46,3.61-.82,1.57-1.23,3.49-1.23,5.74Z\\\"/>\\n</svg>\";\n\n/** The square Smooth icon (the stylized `th` glyph) — used as the default full-page header avatar. */\nexport const SMOOTH_ICON_SVG = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<svg id=\\\"Layer_1\\\" data-name=\\\"Layer 1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" viewBox=\\\"0 0 150 150\\\">\\n <defs>\\n <style>\\n .cls-1 {\\n fill: url(#linear-gradient);\\n }\\n </style>\\n <linearGradient id=\\\"linear-gradient\\\" x1=\\\"31.06\\\" y1=\\\"37.6\\\" x2=\\\"118.5\\\" y2=\\\"125.04\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".43\\\" stop-color=\\\"#00a6a6\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#1238dd\\\"/>\\n </linearGradient>\\n </defs>\\n <path class=\\\"cls-1\\\" d=\\\"M55.03,55.47v13.28H19.24v-13.28h35.79ZM26.83,41.83h17.89v53.42c0,1.5.36,2.62,1.08,3.36.72.74,1.88,1.1,3.49,1.1.62,0,1.48-.07,2.59-.21,1.11-.14,1.91-.27,2.38-.41l2.31,13.02c-2.02.58-3.97.97-5.84,1.18-1.88.21-3.66.31-5.33.31-6.08,0-10.7-1.43-13.84-4.28-3.15-2.85-4.72-7.01-4.72-12.48v-55.01ZM93.74,80.08v32.71h-17.89V36.39h17.53v33.53h-1.13c1.4-4.55,3.6-8.21,6.59-11,2.99-2.79,7.01-4.18,12.07-4.18,4,0,7.48.89,10.46,2.67,2.97,1.78,5.28,4.29,6.92,7.54,1.64,3.25,2.46,7.02,2.46,11.33v36.5h-17.89v-33.02c0-3.21-.82-5.73-2.46-7.56-1.64-1.83-3.93-2.74-6.87-2.74-1.92,0-3.62.42-5.1,1.26-1.49.84-2.64,2.04-3.46,3.61-.82,1.57-1.23,3.49-1.23,5.74Z\\\"/>\\n</svg>\";\n","import type { ChatWidgetMode, ResolvedTheme } from './config.js';\n\n/**\n * Render the widget's scoped stylesheet — the \"Aurora Glass\" design system.\n *\n * Every brand value is injected as a CSS custom property on `:host` so a host\n * page can override colors per-instance and the rules below stay static. Two\n * extra tokens are *derived in CSS* from the brand vars so they adapt to any\n * theme (light or dark) without the caller supplying them:\n *\n * --sac-primary-2 a darker shade of `primary`, used as the second stop of the\n * launcher / send / user-bubble gradients (depth without a\n * second brand input).\n * --sac-surface-2 a faint wash derived from `text`, used for inset chrome\n * (composer field, close button, source cards). On a dark\n * panel it reads as a light overlay; on a light panel, dark.\n *\n * Deliberately framework-light: no Tailwind, no runtime CSS-in-JS — just a string\n * the web component drops into its shadow root. Modern color features\n * (`color-mix`) are used intentionally; the widget targets evergreen browsers.\n *\n * `mode` switches host positioning + panel sizing between the floating popover\n * (default) and the full-page layout (fills its container/viewport).\n */\nexport function buildStyles(theme: ResolvedTheme, mode: ChatWidgetMode = 'popover'): string {\n return `\n:host {\n --sac-text: ${theme.text};\n --sac-bg: ${theme.background};\n --sac-primary: ${theme.primary};\n --sac-primary-text: ${theme.primaryText};\n --sac-secondary: ${theme.secondary};\n --sac-assistant-bubble: ${theme.assistantBubble};\n --sac-assistant-bubble-text: ${theme.assistantBubbleText};\n --sac-user-bubble: ${theme.userBubble};\n --sac-user-bubble-text: ${theme.userBubbleText};\n --sac-border: ${theme.border};\n\n /* Derived tokens — adapt to any brand color without a second input. */\n --sac-primary-2: color-mix(in srgb, var(--sac-primary) 78%, #000 22%);\n --sac-surface-2: color-mix(in srgb, var(--sac-text) 5%, transparent);\n --sac-radius: 22px;\n --sac-ease: cubic-bezier(.16, 1, .3, 1);\n\n ${\n mode === 'fullpage'\n ? `/* Full-page: fill the host's box (sized by its container, else the viewport). */\n display: flex;\n flex-direction: column;\n position: relative;\n width: 100%;\n height: 100%;`\n : `/* Popover: float in the bottom-right corner. */\n position: fixed;\n bottom: 24px;\n right: 24px;\n z-index: 2147483000;`\n }\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n}\n${\n mode === 'fullpage'\n ? `\n/* Viewport fallback — the element sets this attribute only when the host's\n container gives it no resolved height (e.g. mounted straight into an\n auto-height <body>). A sized container always wins, so an embed inside a\n fixed-height box never overflows it (composer stays visible). */\n:host([data-viewport-fallback]) { min-height: 100dvh; }\n/* The render wrapper passes the host's box down to the panel via flex. */\n.wrap {\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n`\n : ''\n}\n* { box-sizing: border-box; }\n\n/* ───────────────────────────── Launcher ───────────────────────────── */\n.launcher {\n position: relative;\n width: 62px;\n height: 62px;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n padding: 0;\n background: radial-gradient(120% 120% at 30% 20%,\n color-mix(in srgb, var(--sac-primary) 78%, #fff 22%) 0%,\n var(--sac-primary) 42%,\n var(--sac-primary-2) 130%);\n color: var(--sac-primary-text);\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow:\n 0 1px 0 rgba(255, 255, 255, .25) inset,\n 0 10px 24px -6px color-mix(in srgb, var(--sac-primary) 55%, transparent),\n 0 18px 50px -12px rgba(0, 0, 0, .6);\n transition: transform .45s var(--sac-ease), box-shadow .45s var(--sac-ease), opacity .3s ease;\n isolation: isolate;\n}\n/* Breathing presence ring. */\n.launcher::before {\n content: '';\n position: absolute;\n inset: -6px;\n border-radius: 50%;\n z-index: -1;\n background: radial-gradient(closest-side, color-mix(in srgb, var(--sac-primary) 45%, transparent), transparent 75%);\n animation: sac-breathe 3.4s ease-in-out infinite;\n}\n@keyframes sac-breathe { 0%, 100% { transform: scale(1); opacity: .55 } 50% { transform: scale(1.28); opacity: 0 } }\n.launcher:hover {\n transform: translateY(-3px) scale(1.06);\n box-shadow:\n 0 1px 0 rgba(255, 255, 255, .3) inset,\n 0 16px 30px -6px color-mix(in srgb, var(--sac-primary) 60%, transparent),\n 0 26px 60px -14px rgba(0, 0, 0, .7);\n}\n.launcher:active { transform: translateY(-1px) scale(.98); }\n.launcher .ico { width: 27px; height: 27px; display: block; transition: transform .4s var(--sac-ease); }\n.launcher:hover .ico { transform: rotate(-6deg) scale(1.04); }\n.launcher.hidden { opacity: 0; transform: scale(.4) translateY(10px); pointer-events: none; }\n\n/* ─────────────────────────────── Panel ────────────────────────────── */\n.panel {\n width: 390px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 56px);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n border-radius: var(--sac-radius);\n background: linear-gradient(180deg, color-mix(in srgb, var(--sac-bg) 92%, #fff 8%) 0%, var(--sac-bg) 22%);\n color: var(--sac-text);\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n box-shadow:\n 0 0 0 1px rgba(255, 255, 255, .03) inset,\n 0 40px 80px -24px rgba(0, 0, 0, .65),\n 0 16px 40px -20px rgba(0, 0, 0, .5);\n transform-origin: bottom right;\n animation: sac-panel-in .5s var(--sac-ease) both;\n position: relative;\n}\n@keyframes sac-panel-in { from { opacity: 0; transform: translateY(16px) scale(.92) } to { opacity: 1; transform: none } }\n.panel.hidden { display: none; }\n/* Ambient brand glow bleeding from the top of the panel. */\n.panel::before {\n content: '';\n position: absolute;\n left: 0; right: 0; top: 0;\n height: 140px;\n pointer-events: none;\n background: radial-gradient(120% 100% at 50% 0%, color-mix(in srgb, var(--sac-primary) 22%, transparent), transparent 70%);\n}\n/* Full-page: the panel becomes the whole surface — it follows the host's box\n (via the .wrap flex chain), never a hardcoded viewport unit. */\n.panel.fullpage {\n width: 100%;\n flex: 1;\n height: auto;\n min-height: 0;\n max-width: none;\n max-height: none;\n border: none;\n border-radius: 0;\n box-shadow: none;\n animation: none;\n}\n\n/* ─────────────────────────────── Header ───────────────────────────── */\n.header {\n position: relative;\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px 16px 14px;\n}\n.avatar {\n width: 40px;\n height: 40px;\n border-radius: 13px;\n flex: none;\n background: linear-gradient(140deg, var(--sac-primary), var(--sac-primary-2));\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--sac-primary-text);\n box-shadow:\n 0 6px 16px -6px color-mix(in srgb, var(--sac-primary) 60%, transparent),\n 0 1px 0 rgba(255, 255, 255, .25) inset;\n}\n.avatar svg { width: 22px; height: 22px; }\n.avatar .logo-wrap { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; }\n.avatar .logo { height: 22px; width: auto; display: block; }\n.avatar .logo-img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; display: block; border-radius: 9px; }\n.meta { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; }\n.title { font-weight: 650; font-size: 15.5px; letter-spacing: -.01em; line-height: 1.1; }\n.status {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 12px;\n color: color-mix(in srgb, var(--sac-text) 62%, transparent);\n}\n.dot {\n width: 7px; height: 7px;\n border-radius: 50%;\n flex: none;\n background: #34d399;\n color: #34d399;\n box-shadow: 0 0 0 0 rgba(52, 211, 153, .6);\n animation: sac-pulse 2.4s ease-out infinite;\n}\n.dot.connecting { background: #fbbf24; color: #fbbf24; animation: sac-pulse 1.1s ease-out infinite; }\n.dot.error { background: #f87171; color: #f87171; animation: none; }\n.dot.off { background: #94a3b8; color: #94a3b8; animation: none; }\n@keyframes sac-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 55%, transparent) }\n 70% { box-shadow: 0 0 0 6px transparent }\n 100% { box-shadow: 0 0 0 0 transparent }\n}\n.close {\n margin-left: auto;\n width: 32px; height: 32px;\n border-radius: 10px;\n border: none;\n cursor: pointer;\n background: var(--sac-surface-2);\n color: inherit;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s ease, transform .2s ease;\n}\n.close:hover { background: color-mix(in srgb, var(--sac-text) 12%, transparent); transform: translateY(1px); }\n.close svg { width: 16px; height: 16px; opacity: .8; }\n.powered { margin-left: auto; font-size: 10.5px; letter-spacing: .02em; opacity: .6; color: inherit; text-decoration: none; }\n.powered:hover { opacity: .85; text-decoration: underline; }\n.header-sep { height: 1px; margin: 0 16px; background: linear-gradient(90deg, transparent, var(--sac-border), transparent); }\n\n/* Full-page header: taller, logo-led, no close. */\n.panel.fullpage .header { padding: 18px 22px; }\n.panel.fullpage .avatar { width: 44px; height: 44px; }\n.panel.fullpage .avatar .logo { height: 26px; }\n.panel.fullpage .avatar svg { width: 28px; height: 28px; }\n\n/* ────────────────────────────── Messages ──────────────────────────── */\n.messages {\n flex: 1;\n overflow-y: auto;\n padding: 18px 16px 8px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n scroll-behavior: smooth;\n}\n.messages::-webkit-scrollbar { width: 8px; }\n.messages::-webkit-scrollbar-thumb {\n background: color-mix(in srgb, var(--sac-text) 14%, transparent);\n border-radius: 99px;\n border: 2px solid transparent;\n background-clip: padding-box;\n}\n.messages::-webkit-scrollbar-thumb:hover {\n background: color-mix(in srgb, var(--sac-text) 24%, transparent);\n background-clip: padding-box;\n}\n\n.row {\n display: flex;\n gap: 9px;\n max-width: 88%;\n animation: sac-msg-in .42s var(--sac-ease) both;\n}\n@keyframes sac-msg-in { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }\n.row.user { align-self: flex-end; flex-direction: row-reverse; }\n.row.assistant { align-self: flex-start; }\n.mini {\n width: 26px; height: 26px;\n border-radius: 9px;\n flex: none;\n align-self: flex-end;\n background: linear-gradient(140deg, var(--sac-primary), var(--sac-primary-2));\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--sac-primary-text);\n}\n.mini svg { width: 15px; height: 15px; }\n\n.bubble {\n padding: 11px 14px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n white-space: pre-wrap;\n word-break: break-word;\n position: relative;\n}\n.bubble.assistant {\n background: linear-gradient(180deg, color-mix(in srgb, var(--sac-assistant-bubble) 86%, #fff 5%), var(--sac-assistant-bubble));\n color: var(--sac-assistant-bubble-text);\n border: 1px solid color-mix(in srgb, var(--sac-text) 8%, transparent);\n border-bottom-left-radius: 5px;\n box-shadow: 0 2px 8px -4px rgba(0, 0, 0, .4);\n}\n.bubble.user {\n background: linear-gradient(165deg,\n color-mix(in srgb, var(--sac-user-bubble) 88%, #fff 12%),\n var(--sac-user-bubble) 60%,\n color-mix(in srgb, var(--sac-user-bubble) 80%, var(--sac-primary-2) 20%));\n color: var(--sac-user-bubble-text);\n border-bottom-right-radius: 5px;\n box-shadow: 0 6px 16px -8px color-mix(in srgb, var(--sac-primary) 50%, transparent);\n}\n.bubble.greeting {\n background: transparent;\n border: 1px dashed color-mix(in srgb, var(--sac-text) 14%, transparent);\n color: color-mix(in srgb, var(--sac-text) 80%, transparent);\n box-shadow: none;\n}\n\n/* Typing indicator (assistant bubble with no text yet). */\n.bubble.typing { display: flex; gap: 4px; padding: 14px 15px; }\n.bubble.typing i {\n width: 7px; height: 7px;\n border-radius: 50%;\n background: color-mix(in srgb, var(--sac-assistant-bubble-text) 55%, transparent);\n animation: sac-typing 1.3s ease-in-out infinite;\n}\n.bubble.typing i:nth-child(2) { animation-delay: .18s; }\n.bubble.typing i:nth-child(3) { animation-delay: .36s; }\n@keyframes sac-typing { 0%, 60%, 100% { transform: translateY(0); opacity: .4 } 30% { transform: translateY(-5px); opacity: 1 } }\n\n.cursor::after {\n content: '';\n display: inline-block;\n width: 2px; height: 1.05em;\n margin-left: 2px;\n vertical-align: -2px;\n border-radius: 2px;\n background: currentColor;\n animation: sac-blink 1s steps(2, start) infinite;\n}\n@keyframes sac-blink { to { opacity: 0 } }\n\n/* Interleaved tool-activity strip (gated by showToolActivity): prose bubbles\n and inline tool chips stacked in the order the model produced them. */\n.blocks { display: flex; flex-direction: column; align-items: flex-start; gap: 7px; }\n.blocks .bubble { align-self: flex-start; }\n.toolchip {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n max-width: 100%;\n padding: 5px 10px;\n border-radius: 99px;\n font-size: 12px;\n line-height: 1.3;\n color: color-mix(in srgb, var(--sac-text) 78%, transparent);\n background: color-mix(in srgb, var(--sac-text) 6%, transparent);\n border: 1px solid color-mix(in srgb, var(--sac-text) 12%, transparent);\n animation: sac-msg-in .3s var(--sac-ease) both;\n}\n.toolchip .ti { display: inline-flex; flex: none; opacity: .8; }\n.toolchip .ti svg { width: 13px; height: 13px; }\n.toolchip .tn { font-weight: 600; letter-spacing: .01em; }\n.toolchip .ts { opacity: .7; }\n.toolchip .ta {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11px;\n opacity: .6;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n min-width: 0;\n}\n.toolchip.running { border-color: color-mix(in srgb, var(--sac-primary) 45%, transparent); }\n.toolchip.running .ts { color: var(--sac-primary); opacity: 1; animation: sac-typing 1.3s ease-in-out infinite; }\n.toolchip.done .ts::before { content: '✓ '; }\n.toolchip.error {\n color: var(--sac-secondary);\n border-color: color-mix(in srgb, var(--sac-secondary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-secondary) 10%, transparent);\n}\n.toolchip.error .ts::before { content: '! '; }\n\n/* ─────────────── Rendered markdown (assistant bubbles / snippets) ─────────── */\n/* The renderer (markdown.ts) emits a small allowlisted set of tags; these rules\n keep them legible inside the tight Aurora-Glass bubble + citation card. */\n/* Block-level markdown drives its own spacing/wrapping, so opt out of the\n bubble's pre-wrap (which would otherwise add stray blank lines). */\n.bubble.md { white-space: normal; }\n.md > :first-child { margin-top: 0; }\n.md > :last-child { margin-bottom: 0; }\n.md p { margin: 0 0 8px; }\n.md ul, .md ol { margin: 6px 0 8px; padding-left: 20px; }\n.md li { margin: 2px 0; }\n.md li::marker { color: color-mix(in srgb, var(--sac-primary) 75%, transparent); }\n.md a {\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n text-decoration: underline;\n text-underline-offset: 2px;\n word-break: break-word;\n}\n.md a:hover { text-decoration: none; }\n.md strong { font-weight: 700; }\n.md em { font-style: italic; }\n.md code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: .9em;\n padding: 1px 5px;\n border-radius: 5px;\n background: color-mix(in srgb, var(--sac-text) 10%, transparent);\n}\n.md pre {\n margin: 6px 0 8px;\n padding: 9px 11px;\n border-radius: 9px;\n overflow-x: auto;\n background: color-mix(in srgb, var(--sac-text) 9%, transparent);\n border: 1px solid color-mix(in srgb, var(--sac-text) 8%, transparent);\n}\n.md pre code { padding: 0; background: none; font-size: 12px; line-height: 1.45; }\n.md blockquote {\n margin: 6px 0;\n padding: 2px 0 2px 11px;\n border-left: 2px solid color-mix(in srgb, var(--sac-primary) 55%, transparent);\n color: color-mix(in srgb, var(--sac-text) 78%, transparent);\n}\n\n/* Full-page: center the conversation in a readable column. */\n.panel.fullpage .messages { padding: 26px 20px; }\n.panel.fullpage .row { max-width: 760px; width: 100%; margin-left: auto; margin-right: auto; }\n.panel.fullpage .row.user { max-width: 80%; margin-right: 0; }\n\n/* ───────────────── Sources (grounding citations) ──────────────────── */\n.sources {\n align-self: flex-start;\n max-width: 88%;\n margin: -4px 0 0 35px;\n}\n.panel.fullpage .sources { max-width: 760px; width: 100%; margin-left: auto; margin-right: auto; }\n.sources summary {\n cursor: pointer;\n list-style: none;\n display: inline-flex;\n align-items: center;\n gap: 7px;\n font-size: 12px;\n font-weight: 600;\n color: color-mix(in srgb, var(--sac-text) 70%, transparent);\n padding: 5px 0;\n user-select: none;\n}\n.sources summary::-webkit-details-marker { display: none; }\n.sources .chev { transition: transform .2s var(--sac-ease); flex: none; }\n.sources details[open] .chev { transform: rotate(90deg); }\n.sources .count {\n background: color-mix(in srgb, var(--sac-primary) 18%, transparent);\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n font-size: 10.5px;\n font-weight: 700;\n padding: 1px 7px;\n border-radius: 99px;\n}\n.sources ol { list-style: none; margin: 6px 0 2px; padding: 0; display: flex; flex-direction: column; gap: 7px; }\n.sources li {\n background: var(--sac-surface-2);\n border: 1px solid color-mix(in srgb, var(--sac-border) 70%, transparent);\n border-left: 2px solid var(--sac-primary);\n border-radius: 9px;\n padding: 8px 10px;\n}\n.sources .src-title {\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n font-weight: 600;\n font-size: 12.5px;\n text-decoration: none;\n word-break: break-word;\n}\n.sources a.src-title:hover { text-decoration: underline; }\n.sources span.src-title { color: var(--sac-text); opacity: .95; }\n.sources .src-snippet {\n display: block;\n margin-top: 3px;\n font-size: 11.5px;\n line-height: 1.45;\n color: color-mix(in srgb, var(--sac-text) 55%, transparent);\n white-space: normal;\n}\n\n/* ────────────────────────────── Composer ──────────────────────────── */\n.composer-wrap { padding: 12px 14px calc(12px + env(safe-area-inset-bottom)); }\n.composer {\n display: flex;\n align-items: flex-end;\n gap: 8px;\n padding: 7px 7px 7px 14px;\n border-radius: 18px;\n background: var(--sac-surface-2);\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n transition: border-color .25s ease, box-shadow .25s ease, background .25s ease;\n}\n.composer:focus-within {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n.composer textarea {\n flex: 1;\n resize: none;\n border: none;\n background: transparent;\n color: var(--sac-text);\n font-family: inherit;\n font-size: 14px;\n line-height: 1.45;\n max-height: 120px;\n padding: 6px 0;\n outline: none;\n}\n.composer textarea::placeholder { color: color-mix(in srgb, var(--sac-text) 42%, transparent); }\n.send {\n width: 38px; height: 38px;\n flex: none;\n border: none;\n border-radius: 13px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n box-shadow:\n 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent),\n 0 1px 0 rgba(255, 255, 255, .25) inset;\n transition: transform .2s var(--sac-ease), box-shadow .2s var(--sac-ease), opacity .2s ease;\n}\n.send svg { width: 18px; height: 18px; }\n.send:hover { transform: translateY(-1px) scale(1.05); }\n.send:active { transform: scale(.94); }\n.send:disabled { opacity: .4; cursor: default; transform: none; box-shadow: none; }\n.footer {\n text-align: center;\n margin-top: 9px;\n font-size: 10.5px;\n letter-spacing: .04em;\n color: color-mix(in srgb, var(--sac-text) 38%, transparent);\n}\n.footer b { font-weight: 600; color: color-mix(in srgb, var(--sac-text) 55%, transparent); }\n.footer a { color: inherit; text-decoration: none; }\n.footer a:hover { text-decoration: underline; }\n\n/* ─────────────────── Pre-chat identity form ───────────────────────── */\n.prechat { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 18px; padding: 22px 20px; }\n.pc-head { text-align: center; }\n.pc-title { font-size: 17px; font-weight: 650; letter-spacing: -.01em; }\n.pc-sub { margin-top: 4px; font-size: 13px; color: color-mix(in srgb, var(--sac-text) 60%, transparent); }\n.pc-form { display: flex; flex-direction: column; gap: 12px; }\n.pc-field { display: flex; flex-direction: column; gap: 5px; }\n.pc-field span { font-size: 12px; font-weight: 600; color: color-mix(in srgb, var(--sac-text) 70%, transparent); }\n.pc-field input {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 12px;\n padding: 11px 13px;\n font-family: inherit;\n font-size: 14px;\n outline: none;\n transition: border-color .2s ease, box-shadow .2s ease;\n}\n.pc-field input::placeholder { color: color-mix(in srgb, var(--sac-text) 42%, transparent); }\n.pc-field input:focus {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n/* Inline phone validity — subtle, themed. Empty stays neutral (optional field). */\n.pc-field.valid input {\n border-color: color-mix(in srgb, var(--sac-primary) 55%, #2faa6a 45%);\n}\n.pc-field.invalid input {\n border-color: color-mix(in srgb, #e2566b 62%, var(--sac-border) 38%);\n}\n.pc-field.invalid input:focus {\n box-shadow: 0 0 0 4px color-mix(in srgb, #e2566b 16%, transparent);\n}\n.pc-field .pc-hint {\n min-height: 13px;\n margin-top: 1px;\n font-size: 11.5px;\n font-weight: 500;\n line-height: 1.2;\n color: color-mix(in srgb, #e2566b 78%, var(--sac-text) 22%);\n}\n.pc-submit {\n margin-top: 4px;\n border: none;\n border-radius: 13px;\n padding: 12px;\n cursor: pointer;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n font-weight: 650;\n font-size: 14px;\n box-shadow: 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent), 0 1px 0 rgba(255, 255, 255, .25) inset;\n transition: transform .2s var(--sac-ease);\n}\n.pc-submit:hover { transform: translateY(-1px); }\n.pc-submit:active { transform: scale(.98); }\n.pc-consents { display: flex; flex-direction: column; gap: 9px; margin-top: 2px; }\n.pc-consent { display: flex; align-items: flex-start; gap: 9px; cursor: pointer; }\n.pc-consent input {\n margin-top: 2px;\n width: 16px;\n height: 16px;\n flex: 0 0 auto;\n accent-color: var(--sac-primary);\n cursor: pointer;\n}\n.pc-consent span { font-size: 12px; line-height: 1.4; color: color-mix(in srgb, var(--sac-text) 72%, transparent); }\n\n/* ─────────────────── Starter-prompt chips ─────────────────────────── */\n.prompts { display: flex; flex-wrap: wrap; gap: 8px; margin: 2px 0 2px 35px; }\n.panel.fullpage .prompts { margin-left: auto; margin-right: auto; max-width: 760px; width: 100%; }\n.chip {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 999px;\n padding: 8px 13px;\n font-family: inherit;\n font-size: 12.5px;\n cursor: pointer;\n text-align: left;\n transition: border-color .2s ease, background .2s ease, transform .2s ease;\n}\n.chip:hover {\n border-color: color-mix(in srgb, var(--sac-primary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-primary) 10%, var(--sac-surface-2));\n transform: translateY(-1px);\n}\n\n/* ───────────── Mid-conversation suggested-reply chips ─────────────── */\n.reply-suggestions { padding: 0 14px 4px; }\n.reply-suggestions:empty { display: none; }\n\n/* ─────────────── OTP / tool-confirmation interrupt ────────────────── */\n.interrupt { padding: 0 14px; }\n.int-card {\n border: 1px solid color-mix(in srgb, var(--sac-primary) 35%, var(--sac-border));\n background: color-mix(in srgb, var(--sac-primary) 8%, var(--sac-surface-2));\n border-radius: 14px;\n padding: 12px 13px;\n animation: sac-msg-in .3s var(--sac-ease) both;\n}\n.int-head { display: flex; align-items: center; gap: 8px; }\n.int-ico { display: flex; color: var(--sac-primary); }\n.int-ico svg { width: 17px; height: 17px; }\n.int-title { font-size: 13.5px; font-weight: 650; }\n.int-desc { margin-top: 5px; font-size: 12.5px; line-height: 1.45; color: color-mix(in srgb, var(--sac-text) 80%, transparent); }\n.int-sent { margin-top: 6px; font-size: 11.5px; color: color-mix(in srgb, var(--sac-text) 60%, transparent); }\n.int-row { display: flex; gap: 8px; margin-top: 10px; }\n.int-input {\n flex: 1;\n min-width: 0;\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-bg);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 11px;\n font-family: inherit;\n font-size: 14px;\n letter-spacing: .14em;\n outline: none;\n transition: border-color .2s ease, box-shadow .2s ease;\n}\n.int-input:focus {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n.int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 14px;\n font-family: inherit;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: transform .2s var(--sac-ease), background .2s ease, border-color .2s ease;\n}\n.int-btn:hover { transform: translateY(-1px); }\n.int-btn.primary {\n border: none;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n box-shadow: 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent);\n}\n.int-row .int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn { flex: 1; }\n.int-row .int-input + .int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn { flex: 0 0 auto; }\n.int-error { margin-top: 8px; font-size: 12px; color: #f87171; }\n.int-card { position: relative; }\n.int-close {\n position: absolute;\n top: 8px;\n right: 9px;\n border: none;\n background: transparent;\n color: color-mix(in srgb, var(--sac-text) 55%, transparent);\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n padding: 2px 4px;\n border-radius: 6px;\n transition: color .2s ease, background .2s ease;\n}\n.int-close:hover { color: var(--sac-text); background: color-mix(in srgb, var(--sac-text) 8%, transparent); }\n\n/* ─────────────── Cross-device \"Restore my chats\" ──────────────────── */\n.restore-link {\n border: none;\n background: none;\n padding: 0;\n font: inherit;\n font-size: 10.5px;\n letter-spacing: .04em;\n color: color-mix(in srgb, var(--sac-primary) 80%, var(--sac-text));\n cursor: pointer;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n.restore-link:hover { color: var(--sac-primary); }\n.restore-list { display: flex; flex-direction: column; gap: 7px; margin-top: 9px; }\n.restore-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n text-align: left;\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-bg);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 11px;\n font-family: inherit;\n font-size: 12.5px;\n cursor: pointer;\n transition: border-color .2s ease, background .2s ease, transform .2s ease;\n}\n.restore-item:hover {\n border-color: color-mix(in srgb, var(--sac-primary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-primary) 8%, var(--sac-bg));\n transform: translateY(-1px);\n}\n.restore-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.restore-when { flex: 0 0 auto; font-size: 11px; color: color-mix(in srgb, var(--sac-text) 55%, transparent); }\n\n.hidden { display: none !important; }\n\n@media (prefers-reduced-motion: reduce) {\n .launcher::before, .dot, .bubble.typing i { animation: none !important; }\n .panel, .row, .launcher, .send, .close { animation: none !important; transition: none !important; }\n}\n`;\n}\n","/**\n * `<smooth-agent-chat>` — a framework-light embeddable chat web component.\n *\n * A clean, dependency-light web component that preserves a familiar embedding\n * model — a launcher + popover panel, declarative HTML attributes, and a\n * programmatic API — while talking to the `@smooai/smooth-operator` protocol\n * client. The visual layer is the \"Aurora Glass\" design system (see\n * {@link buildStyles}): a spring launcher with a live presence pulse, a\n * glass-depth panel, a gradient brand avatar + status dot, an animated typing\n * indicator, message rise-in, refined source cards, and an icon composer. Every\n * color is driven by `--sac-*` custom properties so a host's brand flows through.\n *\n * Embedding model:\n * <smooth-agent-chat endpoint=\"ws://localhost:8787/ws\" agent-id=\"…\"></smooth-agent-chat>\n * or programmatically via {@link mountChatWidget}.\n */\nimport { AsYouType, isValidPhoneNumber, parsePhoneNumber } from 'libphonenumber-js/min';\nimport type { ChatWidgetConfig, ChatWidgetMode, ChatWidgetTheme } from './config.js';\nimport { needsUserInfo, resolveConfig } from './config.js';\nimport {\n type ChatMessage,\n type Citation,\n type ConnectionStatus,\n ConversationController,\n type IdentityRestore,\n type Interrupt,\n SUPPORTED_INTERACTION_CAPABILITIES,\n type ToolCall,\n} from './conversation.js';\nimport { SMOOTH_ICON_SVG } from './logo.js';\nimport { cleanCitationSnippet, escapeHtml, renderMarkdown, safeHttpUrl } from './markdown.js';\nimport { buildStyles } from './styles.js';\n\nexport const ELEMENT_TAG = 'smooth-agent-chat';\n\n/**\n * Default region for phone parsing/formatting on the pre-chat form. The widget\n * is US-first; the backend does the authoritative E.164 normalization (SMOODEV-2153),\n * so this only governs the as-you-type display + the inline validity hint and the\n * best-effort E.164 we send when the number already parses as valid.\n */\nconst PHONE_DEFAULT_REGION = 'US' as const;\n\n/**\n * Best-effort E.164 for an as-typed phone number. Returns the canonical\n * `+1…` form when the value parses to a valid number in {@link PHONE_DEFAULT_REGION},\n * otherwise `null` (caller falls back to sending the raw value — the backend\n * re-parses and normalizes/nulls authoritatively).\n */\nfunction phoneToE164(value: string): string | null {\n const v = value.trim();\n if (!v) return null;\n try {\n if (!isValidPhoneNumber(v, PHONE_DEFAULT_REGION)) return null;\n return parsePhoneNumber(v, PHONE_DEFAULT_REGION).number;\n } catch {\n return null;\n }\n}\n\n/** Public smooth-operator repo — the \"powered by\" header tag + footer link here. */\nconst SMOOTH_OPERATOR_URL = 'https://github.com/SmooAI/smooth-operator';\n\nconst OBSERVED = ['endpoint', 'agent-id', 'agent-name', 'logo-url', 'placeholder', 'greeting', 'start-open', 'mode', 'hide-branding', 'show-tool-activity'] as const;\n\n/**\n * Inline SVG icons (static, trusted strings — never interpolated with user data).\n * Kept here so the IIFE bundle is self-contained: no icon-font or network fetch.\n */\nconst ICON = {\n /** Launcher — a speech bubble carrying a spark (chat + AI). */\n spark: `<svg class=\"ico\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 3.5c-4.7 0-8.5 3.2-8.5 7.2 0 2.2 1.2 4.2 3 5.5v3.3l3.2-1.7c.7.1 1.5.2 2.3.2 4.7 0 8.5-3.2 8.5-7.3S16.7 3.5 12 3.5Z\" fill=\"currentColor\" opacity=\".22\"/><path d=\"M13.4 7.2 9 12.6h2.6l-1 4.2 4.4-5.4h-2.6l1-4.2Z\" fill=\"currentColor\"/></svg>`,\n /** Small assistant avatar used beside each assistant message. */\n bot: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"4.5\" y=\"7.5\" width=\"15\" height=\"11\" rx=\"3.5\" stroke=\"currentColor\" stroke-width=\"1.6\"/><path d=\"M12 4.5v3M8.5 12.2h.01M15.5 12.2h.01\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\"/><path d=\"M9.5 15.4c.7.6 1.5.9 2.5.9s1.8-.3 2.5-.9\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg>`,\n /** Close (collapse panel) — a downward chevron. */\n close: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"m7 10 5 5 5-5\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Send — an upward arrow. */\n send: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 19V6M12 6l-5.5 5.5M12 6l5.5 5.5\" stroke=\"currentColor\" stroke-width=\"1.9\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Sources disclosure caret. */\n chev: `<svg width=\"11\" height=\"11\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"m9 6 6 6-6 6\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** OTP interrupt — a padlock. */\n lock: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"5\" y=\"10.5\" width=\"14\" height=\"9.5\" rx=\"2.2\" stroke=\"currentColor\" stroke-width=\"1.7\"/><path d=\"M8 10.5V8a4 4 0 0 1 8 0v2.5\" stroke=\"currentColor\" stroke-width=\"1.7\"/></svg>`,\n /** Identity-intake interrupt — a person. */\n user: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"12\" cy=\"8.2\" r=\"3.4\" stroke=\"currentColor\" stroke-width=\"1.7\"/><path d=\"M5.5 19.5c.8-3.1 3.4-4.8 6.5-4.8s5.7 1.7 6.5 4.8\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\"/></svg>`,\n /** Tool-confirmation interrupt — a shield. */\n shield: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 3 5 6v5c0 4.4 3 7.2 7 8.5 4-1.3 7-4.1 7-8.5V6l-7-3Z\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linejoin=\"round\"/><path d=\"m9 11.5 2 2 4-4\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Tool-activity chip — a wrench. */\n tool: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M14.7 6.3a3.5 3.5 0 0 0-4.6 4.3l-5 5a1.6 1.6 0 0 0 2.3 2.3l5-5a3.5 3.5 0 0 0 4.3-4.6l-2 2-1.7-.3-.3-1.7 2-2Z\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/></svg>`,\n} as const;\n\n/**\n * The Rich Interactions **card registry**: interaction kind → overlay card.\n * `interaction_required { kind }` looks its card up here; registering a card IS\n * declaring the widget's render capability for that kind (see\n * `SUPPORTED_INTERACTION_CAPABILITIES` in conversation.ts — a test keeps the\n * two aligned). Adding a kind = one card builder + one entry.\n *\n * The existing OTP and tool-approval overlays are prior instances of this same\n * shape and should retrofit onto this registry later (their wire events predate\n * the pattern).\n */\nexport interface InteractionCardContext {\n /** Submit kind-shaped values (resumes the parked turn; server validates). */\n submit: (values: Record<string, unknown>) => void;\n /** Decline the interaction (the agent continues without it). */\n decline: () => void;\n /** Persisted visitor identity, for pre-filling known fields. */\n prefill: { name?: string; email?: string; phone?: string };\n /** Wire live phone formatting + validity hint onto a form's phone input. */\n wirePhoneField: (form: HTMLFormElement) => void;\n}\n\nexport interface InteractionCard {\n /** The render capability this card provides (goes into `supports`). */\n capability: string;\n /** Card header title. */\n title: string;\n /** Static, trusted header icon SVG. */\n icon: string;\n /** Build the card body for an `interaction` interrupt. */\n build: (it: Extract<Interrupt, { kind: 'interaction' }>, ctx: InteractionCardContext) => HTMLElement;\n}\n\n/**\n * The identity_intake card: the fields the agent requested (pre-chat form field\n * pattern — same classes, same phone formatting), per-field server errors, a\n * submit and a decline affordance. Server-supplied text (reason, labels, error\n * messages) is set via `textContent` — never innerHTML.\n */\nfunction buildIdentityIntakeCard(it: Extract<Interrupt, { kind: 'interaction' }>, ctx: InteractionCardContext): HTMLElement {\n const form = document.createElement('form');\n form.className = 'int-form';\n form.noValidate = true;\n\n if (it.reason) {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = it.reason;\n form.appendChild(desc);\n }\n\n const DEFAULTS: Record<string, { label: string; type: string; autocomplete: string }> = {\n name: { label: 'Name', type: 'text', autocomplete: 'name' },\n email: { label: 'Email', type: 'email', autocomplete: 'email' },\n phone: { label: 'Phone', type: 'tel', autocomplete: 'tel' },\n };\n\n // Parse the kind's spec defensively: `{ fields: [{ key, required, label? }] }`.\n const rawFields = Array.isArray(it.spec.fields) ? it.spec.fields : [];\n const fields: { key: 'name' | 'email' | 'phone'; required: boolean; label?: string }[] = [];\n for (const f of rawFields) {\n if (!f || typeof f !== 'object') continue;\n const o = f as Record<string, unknown>;\n const key = typeof o.key === 'string' ? o.key : '';\n if (key !== 'name' && key !== 'email' && key !== 'phone') continue;\n fields.push({ key, required: o.required === true, label: typeof o.label === 'string' ? o.label : undefined });\n }\n if (fields.length === 0) fields.push({ key: 'email', required: true });\n\n for (const f of fields) {\n const d = DEFAULTS[f.key]!;\n const label = document.createElement('label');\n label.className = 'pc-field';\n const caption = document.createElement('span');\n caption.textContent = f.label ?? d.label;\n const input = document.createElement('input');\n input.name = f.key;\n input.type = d.type;\n input.setAttribute('autocomplete', d.autocomplete);\n input.required = f.required;\n const prefill = ctx.prefill[f.key];\n if (prefill) input.value = prefill;\n label.append(caption, input);\n if (f.key === 'phone') {\n const hint = document.createElement('span');\n hint.className = 'pc-hint';\n hint.setAttribute('aria-live', 'polite');\n label.appendChild(hint);\n }\n // Per-field server-side validation error (interaction_invalid).\n const serverError = it.errors?.find((e) => e.field === f.key);\n if (serverError) {\n label.classList.add('invalid');\n const err = document.createElement('span');\n err.className = 'int-error';\n err.textContent = serverError.message;\n label.appendChild(err);\n }\n form.appendChild(label);\n }\n\n const row = document.createElement('div');\n row.className = 'int-row';\n const decline = document.createElement('button');\n decline.className = 'int-btn';\n decline.type = 'button';\n decline.textContent = 'No thanks';\n decline.addEventListener('click', () => ctx.decline());\n const share = document.createElement('button');\n share.className = 'int-btn primary';\n share.type = 'submit';\n share.textContent = 'Share details';\n row.append(decline, share);\n form.appendChild(row);\n\n form.addEventListener('submit', (ev) => {\n ev.preventDefault();\n if (!form.reportValidity()) return;\n const data = new FormData(form);\n const val = (k: string) => ((data.get(k) as string | null)?.trim() || undefined);\n\n // Phone: mirror the pre-chat rules — block a required-but-invalid number,\n // prefer canonical E.164 when it parses (the server re-validates anyway).\n const rawPhone = val('phone');\n const phoneInput = form.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (rawPhone && phoneInput && !isValidPhoneNumber(rawPhone, PHONE_DEFAULT_REGION)) {\n const field = phoneInput.closest('.pc-field');\n field?.classList.add('invalid');\n const hint = field?.querySelector('.pc-hint');\n if (hint) hint.textContent = 'Enter a valid phone number';\n if (phoneInput.hasAttribute('required')) {\n phoneInput.focus();\n return;\n }\n }\n const phone = rawPhone ? (phoneToE164(rawPhone) ?? rawPhone) : undefined;\n ctx.submit({ name: val('name'), email: val('email'), phone });\n });\n // Same live phone formatting + validity hint as the pre-chat form.\n ctx.wirePhoneField(form);\n queueMicrotask(() => (form.querySelector('input') as HTMLInputElement | null)?.focus());\n return form;\n}\n\n/** Kind → card. See the registry doc above. */\nexport const INTERACTION_CARDS: Record<string, InteractionCard> = {\n identity_intake: {\n capability: 'identity_form',\n title: 'Share your details',\n icon: ICON.user,\n build: buildIdentityIntakeCard,\n },\n};\n\n// `safeHttpUrl` / `escapeHtml` live in `./markdown.js` (the markdown renderer\n// needs them too); re-exported here for back-compat with existing importers.\nexport { escapeHtml, safeHttpUrl } from './markdown.js';\n\nexport class SmoothAgentChatElement extends HTMLElement {\n static get observedAttributes(): readonly string[] {\n return OBSERVED;\n }\n\n private readonly root: ShadowRoot;\n private controller: ConversationController | null = null;\n private overrides: Partial<ChatWidgetConfig> = {};\n private open = false;\n private messages: ChatMessage[] = [];\n private status: ConnectionStatus = 'idle';\n private mounted = false;\n /** True once the visitor has cleared the pre-chat identity gate (or it's not needed). */\n private userInfoSatisfied = false;\n /** True after the visitor has sent their first message (hides starter chips). */\n private hasSent = false;\n /** Starter prompts shown as chips in the empty state. */\n private examplePrompts: string[] = [];\n /** Whether mid-conversation suggested-reply chips are shown (config). */\n private showSuggestedReplies = true;\n /** Resolved greeting text, cached so async (rAF) renders can reuse it. */\n private greeting = '';\n /** Current mid-turn interrupt (OTP / tool-confirmation), or null. */\n private interrupt: Interrupt | null = null;\n private interruptEl: HTMLElement | null = null;\n /** Cross-device \"restore my chats\" flow state (ADR-048 §c). */\n private identityRestore: IdentityRestore = { phase: 'idle' };\n /** Whether the cross-device restore affordance is offered (config). */\n private allowChatRestore = true;\n /** True while the pre-chat identity gate is showing (blocks premature connect). */\n private gating = false;\n\n // Cached DOM refs (populated in render()).\n private panelEl: HTMLElement | null = null;\n private launcherEl: HTMLElement | null = null;\n private messagesEl: HTMLElement | null = null;\n private statusEl: HTMLElement | null = null;\n private dotEl: HTMLElement | null = null;\n private inputEl: HTMLTextAreaElement | null = null;\n private sendBtn: HTMLButtonElement | null = null;\n private suggestionsEl: HTMLElement | null = null;\n\n // ── Smooth streaming reveal ──\n // Tokens arrive in variable-size bursts at uneven rates, so revealing text in\n // lockstep with arrival looks jerky. Instead we buffer the full target text\n // and reveal it via a requestAnimationFrame \"typewriter\" at an adaptive rate\n // (chars/frame scales with the pending backlog so it never falls behind the\n // network). State below tracks the single in-flight streaming bubble.\n /** The live streaming assistant bubble whose textContent the rAF loop drives. */\n private streamBubbleEl: HTMLElement | null = null;\n /** Message id the reveal is bound to (guards against stale frames after rebuilds). */\n private streamMsgId: string | null = null;\n /** Full buffered target text for the streaming message (grows as tokens arrive). */\n private streamTarget = '';\n /** How many chars of {@link streamTarget} are currently shown. */\n private displayedLength = 0;\n private rafId = 0;\n /** Block structure signature of the last-rendered streaming message (tool chips\n * only — text growth doesn't change it), so a chip add/resolve forces a rebuild\n * while plain trailing-text growth stays on the fast reveal path. */\n private prevBlockSig = '';\n\n constructor() {\n super();\n this.root = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback(): void {\n this.mounted = true;\n this.render();\n }\n\n disconnectedCallback(): void {\n this.mounted = false;\n this.resetReveal();\n this.controller?.disconnect();\n this.controller = null;\n }\n\n attributeChangedCallback(): void {\n if (this.mounted) this.render();\n }\n\n /**\n * Programmatically merge config overrides (endpoint, agentId, theme, …). Values\n * set here take precedence over HTML attributes. Re-renders the widget.\n */\n configure(config: Partial<ChatWidgetConfig>): void {\n this.overrides = { ...this.overrides, ...config };\n if (config.theme) {\n this.overrides.theme = { ...(this.overrides.theme ?? {}), ...config.theme };\n }\n if (this.mounted) this.render();\n }\n\n /** Open the chat panel. */\n openChat(): void {\n this.open = true;\n this.syncOpenState();\n // Don't connect while the pre-chat identity gate is unsatisfied — connecting\n // here would create a session BEFORE the visitor submits their name/email/\n // consent, sending an empty identity. The form's submit handler connects.\n if (!this.gating) void this.controller?.connect().catch(() => {});\n }\n\n /** Collapse the chat panel back to the launcher. */\n closeChat(): void {\n this.open = false;\n this.syncOpenState();\n }\n\n // ─────────────────────────── Config resolution ─────────────────────────────\n\n private readConfig(): ChatWidgetConfig | null {\n const endpoint = this.overrides.endpoint ?? this.getAttribute('endpoint') ?? '';\n const agentId = this.overrides.agentId ?? this.getAttribute('agent-id') ?? '';\n if (!endpoint || !agentId) return null;\n\n const theme: ChatWidgetTheme | undefined = this.overrides.theme;\n const modeAttr = this.getAttribute('mode');\n const mode: ChatWidgetMode = this.overrides.mode ?? (modeAttr === 'fullpage' ? 'fullpage' : modeAttr === 'popover' ? 'popover' : undefined) ?? 'popover';\n return {\n endpoint,\n mode,\n agentId,\n agentName: this.overrides.agentName ?? this.getAttribute('agent-name') ?? undefined,\n logoUrl: this.overrides.logoUrl ?? this.getAttribute('logo-url') ?? undefined,\n userName: this.overrides.userName,\n userEmail: this.overrides.userEmail,\n userPhone: this.overrides.userPhone,\n authContext: this.overrides.authContext,\n placeholder: this.overrides.placeholder ?? this.getAttribute('placeholder') ?? undefined,\n greeting: this.overrides.greeting ?? this.getAttribute('greeting') ?? undefined,\n connectionErrorMessage: this.overrides.connectionErrorMessage,\n startOpen: this.overrides.startOpen ?? this.hasAttribute('start-open'),\n hideBranding: this.overrides.hideBranding ?? this.hasAttribute('hide-branding'),\n examplePrompts: this.overrides.examplePrompts,\n showSuggestedReplies: this.overrides.showSuggestedReplies,\n requireName: this.overrides.requireName,\n requireEmail: this.overrides.requireEmail,\n requirePhone: this.overrides.requirePhone,\n collectPhone: this.overrides.collectPhone,\n collectConsent: this.overrides.collectConsent,\n allowChatRestore: this.overrides.allowChatRestore,\n allowAnonymous: this.overrides.allowAnonymous,\n showToolActivity: this.overrides.showToolActivity ?? this.hasAttribute('show-tool-activity'),\n theme,\n };\n }\n\n // ───────────────────────────────── Render ──────────────────────────────────\n\n private render(): void {\n const config = this.readConfig();\n if (!config) {\n this.root.innerHTML = '';\n return;\n }\n const resolved = resolveConfig(config);\n\n this.allowChatRestore = resolved.allowChatRestore;\n\n // (Re)create the controller only when there isn't one yet. Attribute churn\n // (e.g. theme tweaks) re-renders the view without dropping the session.\n if (!this.controller) {\n this.controller = new ConversationController(config, {\n onMessages: (messages) => {\n this.handleMessages(messages, resolved.greeting);\n },\n onStatus: (status) => {\n this.status = status;\n this.renderStatus();\n this.renderComposerState();\n },\n onInterrupt: (interrupt) => {\n this.interrupt = interrupt;\n this.renderInterrupt();\n // Suggestion chips are hidden while an interrupt overlay is up.\n this.renderSuggestions();\n },\n onIdentityRestore: (state) => {\n this.identityRestore = state;\n this.renderInterrupt();\n // The restore overlay reuses the interrupt slot — hide chips too.\n this.renderSuggestions();\n },\n });\n if (resolved.startOpen) this.open = true;\n // Returning visitor: a persisted session or identity lets us skip the\n // pre-chat gate and resume straight into the conversation (ADR-048 §b).\n if (this.controller.hasPersistedSession() || this.controller.hasPersistedIdentity()) {\n this.userInfoSatisfied = true;\n }\n }\n\n const fullpage = resolved.mode === 'fullpage';\n // Full-page mode is always \"open\" — it fills its container and has no\n // launcher to toggle.\n if (fullpage) this.open = true;\n\n const style = document.createElement('style');\n style.textContent = buildStyles(resolved.theme, resolved.mode);\n\n // Header: in full-page mode lead with the brand logo in the avatar tile\n // and a subtle \"powered by\" tag; in popover mode show a brand-colored\n // monogram avatar + a compact close (collapse) button. The logo defaults\n // to the square Smooth icon, but a host page can override it with\n // `logoUrl` (already sanitized to http(s)-only by resolveConfig; escaped\n // here so it can't break out of the src attribute).\n const monogram = escapeHtml((resolved.agentName.trim().charAt(0) || 'A').toUpperCase());\n const headerLogo = resolved.logoUrl\n ? `<img src=\"${escapeHtml(resolved.logoUrl)}\" alt=\"\" class=\"logo-img\" />`\n : SMOOTH_ICON_SVG;\n const header = fullpage\n ? `<div class=\"header\">\n <div class=\"avatar\"><span class=\"logo-wrap\">${headerLogo}</span></div>\n <div class=\"meta\">\n <span class=\"title\">${escapeHtml(resolved.agentName)}</span>\n <span class=\"status\"><span class=\"dot off\"></span><span class=\"status-text\"></span></span>\n </div>\n ${\n resolved.hideBranding\n ? ''\n : `<a class=\"powered\" href=\"${SMOOTH_OPERATOR_URL}\" target=\"_blank\" rel=\"noopener noreferrer\">powered by smooth-operator</a>`\n }\n </div>`\n : `<div class=\"header\">\n <div class=\"avatar\">${monogram}</div>\n <div class=\"meta\">\n <span class=\"title\">${escapeHtml(resolved.agentName)}</span>\n <span class=\"status\"><span class=\"dot off\"></span><span class=\"status-text\"></span></span>\n </div>\n <button class=\"close\" aria-label=\"Close chat\">${ICON.close}</button>\n </div>`;\n\n // Remember starter prompts + greeting for the empty-state chips / async renders.\n this.examplePrompts = resolved.examplePrompts;\n this.showSuggestedReplies = resolved.showSuggestedReplies;\n this.greeting = resolved.greeting;\n\n // Gate the conversation behind a pre-chat identity form when required.\n const gating = needsUserInfo(resolved) && !this.userInfoSatisfied;\n this.gating = gating;\n // Phone is collected by default (optional unless requirePhone). Consent\n // checkboxes default to shown, explicit + unchecked (ADR-048 §a/§3).\n const showPhone = resolved.requirePhone || resolved.collectPhone;\n const field = (name: string, type: string, label: string, autocomplete: string, required: boolean, hint = false) =>\n `<label class=\"pc-field\"><span>${escapeHtml(label)}</span><input name=\"${name}\" type=\"${type}\" autocomplete=\"${autocomplete}\"${required ? ' required' : ''} />${\n hint ? '<span class=\"pc-hint\" aria-live=\"polite\"></span>' : ''\n }</label>`;\n const consentBox = (name: string, label: string) =>\n `<label class=\"pc-consent\"><input name=\"${name}\" type=\"checkbox\" /><span>${escapeHtml(label)}</span></label>`;\n const consentHtml = resolved.collectConsent\n ? `<div class=\"pc-consents\">\n ${consentBox('emailOptIn', 'Email me product news and offers.')}\n ${consentBox('smsOptIn', 'Text me updates by SMS. Message/data rates may apply.')}\n </div>`\n : '';\n const prechatHtml = `\n <div class=\"prechat\">\n <div class=\"pc-head\">\n <div class=\"pc-title\">Before we chat</div>\n <div class=\"pc-sub\">A couple details so ${escapeHtml(resolved.agentName)} can help.</div>\n </div>\n <form class=\"pc-form\" novalidate>\n ${resolved.requireName ? field('name', 'text', 'Name', 'name', true) : ''}\n ${resolved.requireEmail ? field('email', 'email', 'Email', 'email', true) : ''}\n ${showPhone ? field('phone', 'tel', 'Phone', 'tel', resolved.requirePhone, true) : ''}\n ${consentHtml}\n <button type=\"submit\" class=\"pc-submit\">Start chat</button>\n </form>\n </div>`;\n // Footer: optional \"powered by\" branding (hidden by hide-branding) and an\n // optional \"Restore my chats\" affordance. The \" · \" separator only appears\n // when both are present, and the footer is omitted entirely when neither is.\n const brandingHtml = resolved.hideBranding\n ? ''\n : `<a href=\"${SMOOTH_OPERATOR_URL}\" target=\"_blank\" rel=\"noopener noreferrer\">powered by <b>smooth‑operator</b></a>`;\n const restoreBtn = this.allowChatRestore ? `<button type=\"button\" class=\"restore-link\">Restore my chats</button>` : '';\n const footerInner = [brandingHtml, restoreBtn].filter(Boolean).join(' · ');\n const footerHtml = footerInner ? `<div class=\"footer\">${footerInner}</div>` : '';\n const chatHtml = `\n <div class=\"messages\"></div>\n <div class=\"reply-suggestions\"></div>\n <div class=\"interrupt hidden\"></div>\n <div class=\"composer-wrap\">\n <div class=\"composer\">\n <textarea rows=\"1\" placeholder=\"${escapeHtml(resolved.placeholder)}\"></textarea>\n <button class=\"send\" type=\"button\" aria-label=\"Send message\">${ICON.send}</button>\n </div>\n ${footerHtml}\n </div>`;\n\n const container = document.createElement('div');\n container.className = 'wrap';\n container.innerHTML = `\n ${fullpage ? '' : `<button class=\"launcher\" part=\"launcher\" aria-label=\"Open chat\">${ICON.spark}</button>`}\n <div class=\"panel${fullpage ? ' fullpage' : ' hidden'}\" part=\"panel\" role=\"${fullpage ? 'region' : 'dialog'}\" aria-label=\"${escapeHtml(resolved.agentName)} chat\">\n ${header}\n <div class=\"header-sep\"></div>\n ${gating ? prechatHtml : chatHtml}\n </div>\n `;\n\n // Tag the logo <svg> so styles can size it (the inlined SVG has its own id).\n const logoSvg = container.querySelector('.logo-wrap svg');\n if (logoSvg) logoSvg.setAttribute('class', 'logo');\n\n // A full DOM rebuild invalidates any cached streaming-bubble ref; cancel\n // the in-flight reveal loop so renderMessages can re-bind cleanly.\n this.resetReveal();\n this.root.replaceChildren(style, container);\n\n this.launcherEl = container.querySelector('.launcher');\n this.panelEl = container.querySelector('.panel');\n this.messagesEl = container.querySelector('.messages');\n this.statusEl = container.querySelector('.status-text');\n this.dotEl = container.querySelector('.dot');\n this.inputEl = container.querySelector('textarea');\n this.sendBtn = container.querySelector('.send');\n this.interruptEl = container.querySelector('.interrupt');\n this.suggestionsEl = container.querySelector('.reply-suggestions');\n\n this.launcherEl?.addEventListener('click', () => this.openChat());\n container.querySelector('.close')?.addEventListener('click', () => this.closeChat());\n this.sendBtn?.addEventListener('click', () => this.submit());\n this.inputEl?.addEventListener('input', () => this.autosize());\n this.inputEl?.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter' && !ev.shiftKey) {\n ev.preventDefault();\n this.submit();\n }\n });\n\n const pcForm = container.querySelector('.pc-form');\n pcForm?.addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.handlePrechatSubmit(pcForm as HTMLFormElement);\n });\n\n // Live phone formatting + validity hint (libphonenumber-js, US default).\n // The implicit <label>, type=\"tel\", and autocomplete=\"tel\" from field()\n // are preserved — autofill keeps working — and we also reformat on\n // `change` so a browser-autofilled value gets formatted/validated too.\n this.wirePhoneField(pcForm as HTMLFormElement | null);\n\n // Cross-device \"Restore my chats\": open the panel + start the email entry.\n // AWAIT connect() before showing the email step so a `sessionId` exists by\n // the time the visitor submits — otherwise request-otp could go out with no\n // session and verify-otp would then hard-error \"No active session.\" The\n // request-otp/verify-otp paths in the controller also require a session, so\n // gating here keeps the affordance race-free.\n container.querySelector('.restore-link')?.addEventListener('click', () => {\n void (async () => {\n this.identityRestore = { phase: 'awaiting_email' };\n this.renderInterrupt();\n // Establish a live session before the email entry can fire request-otp.\n await this.controller?.connect().catch(() => {});\n })();\n });\n\n // Full-page mode sizes to the host's box; fall back to the viewport only\n // when the container gives the host no height.\n if (fullpage) this.syncViewportFallback();\n\n // Full-page mode connects eagerly (there's no launcher click to trigger it) —\n // but only once any identity gate is cleared.\n if (fullpage && !gating) void this.controller?.connect().catch(() => {});\n\n this.syncOpenState();\n if (!gating) this.renderMessages();\n this.renderStatus();\n this.renderComposerState();\n this.renderInterrupt();\n }\n\n /**\n * Render (or clear) the mid-turn interrupt overlay above the composer:\n * an OTP code prompt or a tool-write confirmation. Server-supplied text is\n * set via `textContent` (never innerHTML); only static icons use innerHTML.\n */\n private renderInterrupt(): void {\n const el = this.interruptEl;\n if (!el) return;\n el.replaceChildren();\n const it = this.interrupt;\n if (!it) {\n // No mid-turn interrupt — but the cross-device restore flow may be\n // active, which reuses this same overlay slot.\n if (this.identityRestore.phase !== 'idle') {\n el.classList.remove('hidden');\n el.appendChild(this.buildRestoreCard());\n return;\n }\n el.classList.add('hidden');\n return;\n }\n el.classList.remove('hidden');\n\n const card = document.createElement('div');\n card.className = 'int-card';\n\n const head = document.createElement('div');\n head.className = 'int-head';\n const ico = document.createElement('span');\n ico.className = 'int-ico';\n const card_meta = it.kind === 'interaction' ? INTERACTION_CARDS[it.interactionKind] : undefined;\n if (it.kind === 'interaction' && !card_meta) {\n // A kind we have no card for (shouldn't happen — we only declare\n // capabilities for registered cards). Decline so the turn never hangs.\n this.controller?.declineInteraction();\n el.classList.add('hidden');\n return;\n }\n ico.innerHTML = it.kind === 'otp' ? ICON.lock : it.kind === 'interaction' ? (card_meta?.icon ?? ICON.user) : ICON.shield; // static, trusted\n const title = document.createElement('span');\n title.className = 'int-title';\n title.textContent = it.kind === 'otp' ? 'Verification required' : it.kind === 'interaction' ? (card_meta?.title ?? 'One more thing') : 'Confirm this action';\n head.append(ico, title);\n card.appendChild(head);\n\n if (it.kind !== 'interaction' && it.actionDescription) {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = it.actionDescription;\n card.appendChild(desc);\n }\n\n if (it.kind === 'interaction') {\n card.appendChild(\n card_meta!.build(it, {\n submit: (values) => this.controller?.submitInteraction(values),\n decline: () => this.controller?.declineInteraction(),\n prefill: this.controller?.getStore().getState().identity ?? {},\n wirePhoneField: (form) => this.wirePhoneField(form),\n }),\n );\n } else if (it.kind === 'otp') {\n if (it.sent?.maskedDestination) {\n const sent = document.createElement('div');\n sent.className = 'int-sent';\n sent.textContent = `Code sent to ${it.sent.maskedDestination}${it.sent.channel ? ` via ${it.sent.channel}` : ''}.`;\n card.appendChild(sent);\n }\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'text';\n input.inputMode = 'numeric';\n input.autocomplete = 'one-time-code';\n input.placeholder = 'Enter code';\n const submit = () => {\n const code = input.value.trim();\n if (code) this.controller?.verifyOtp(code);\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n submit();\n }\n });\n const verify = document.createElement('button');\n verify.className = 'int-btn primary';\n verify.type = 'button';\n verify.textContent = 'Verify';\n verify.addEventListener('click', submit);\n row.append(input, verify);\n card.appendChild(row);\n if (it.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = it.attemptsRemaining != null ? `${it.error} (${it.attemptsRemaining} left)` : it.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else {\n const row = document.createElement('div');\n row.className = 'int-row';\n const decline = document.createElement('button');\n decline.className = 'int-btn';\n decline.type = 'button';\n decline.textContent = 'Decline';\n decline.addEventListener('click', () => this.controller?.confirmTool(false));\n const approve = document.createElement('button');\n approve.className = 'int-btn primary';\n approve.type = 'button';\n approve.textContent = 'Approve';\n approve.addEventListener('click', () => this.controller?.confirmTool(true));\n row.append(decline, approve);\n card.appendChild(row);\n }\n\n el.appendChild(card);\n }\n\n /**\n * Build the cross-device \"Restore my chats\" card (ADR-048 §c). Reuses the\n * same overlay slot + visual language as the OTP interrupt. All server-supplied\n * strings (masked destination, conversation previews) are set via `textContent`\n * — never innerHTML — so they can't inject markup; only the static lock icon\n * uses innerHTML.\n */\n private buildRestoreCard(): HTMLElement {\n const state = this.identityRestore;\n const card = document.createElement('div');\n card.className = 'int-card';\n\n const head = document.createElement('div');\n head.className = 'int-head';\n const ico = document.createElement('span');\n ico.className = 'int-ico';\n ico.innerHTML = ICON.lock; // static, trusted\n const title = document.createElement('span');\n title.className = 'int-title';\n title.textContent = 'Restore your chats';\n head.append(ico, title);\n card.appendChild(head);\n\n const close = document.createElement('button');\n close.className = 'int-close';\n close.type = 'button';\n close.setAttribute('aria-label', 'Cancel');\n close.textContent = '×';\n close.addEventListener('click', () => {\n this.controller?.cancelIdentityRestore();\n this.identityRestore = { phase: 'idle' };\n this.renderInterrupt();\n });\n card.appendChild(close);\n\n if (state.phase === 'awaiting_email') {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = \"Enter your email and we'll send a code to find your previous chats.\";\n card.appendChild(desc);\n\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'email';\n input.autocomplete = 'email';\n input.placeholder = 'you@example.com';\n const go = () => {\n const email = input.value.trim();\n if (email) void this.controller?.requestIdentityOtp(email, 'email');\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n go();\n }\n });\n const send = document.createElement('button');\n send.className = 'int-btn primary';\n send.type = 'button';\n send.textContent = 'Send code';\n send.addEventListener('click', go);\n row.append(input, send);\n card.appendChild(row);\n if (state.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else if (state.phase === 'requesting' || state.phase === 'verifying' || state.phase === 'resolving') {\n const msg = document.createElement('div');\n msg.className = 'int-sent';\n msg.textContent = state.phase === 'requesting' ? 'Sending a code…' : state.phase === 'verifying' ? 'Verifying…' : 'Finding your chats…';\n card.appendChild(msg);\n } else if (state.phase === 'awaiting_code') {\n if (state.maskedDestination) {\n const sent = document.createElement('div');\n sent.className = 'int-sent';\n sent.textContent = `Code sent to ${state.maskedDestination}.`;\n card.appendChild(sent);\n }\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'text';\n input.inputMode = 'numeric';\n input.autocomplete = 'one-time-code';\n input.placeholder = 'Enter code';\n const submit = () => {\n const code = input.value.trim();\n if (code) void this.controller?.verifyIdentityOtp(code);\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n submit();\n }\n });\n const verify = document.createElement('button');\n verify.className = 'int-btn primary';\n verify.type = 'button';\n verify.textContent = 'Verify';\n verify.addEventListener('click', submit);\n row.append(input, verify);\n card.appendChild(row);\n if (state.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.attemptsRemaining != null ? `${state.error} (${state.attemptsRemaining} left)` : state.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else if (state.phase === 'resolved') {\n if (state.conversations.length === 0) {\n const none = document.createElement('div');\n none.className = 'int-desc';\n none.textContent = 'No previous chats found for that email.';\n card.appendChild(none);\n } else {\n const pick = document.createElement('div');\n pick.className = 'int-desc';\n pick.textContent = 'Pick a conversation to continue:';\n card.appendChild(pick);\n const list = document.createElement('div');\n list.className = 'restore-list';\n for (const conv of state.conversations) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'restore-item';\n const preview = document.createElement('span');\n preview.className = 'restore-preview';\n preview.textContent = conv.preview || 'Conversation';\n btn.appendChild(preview);\n if (conv.lastActivityAt) {\n const when = document.createElement('span');\n when.className = 'restore-when';\n when.textContent = this.formatWhen(conv.lastActivityAt);\n btn.appendChild(when);\n }\n btn.addEventListener('click', () => {\n void this.controller?.restoreConversation(conv.sessionId);\n });\n list.appendChild(btn);\n }\n card.appendChild(list);\n }\n } else if (state.phase === 'error') {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.message;\n card.appendChild(err);\n }\n\n return card;\n }\n\n /** Format an ISO timestamp as a short, locale-aware label (best-effort). */\n private formatWhen(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return '';\n try {\n return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n } catch {\n return '';\n }\n }\n\n /**\n * Wire as-you-type formatting + an inline validity hint onto the pre-chat\n * phone input (libphonenumber-js, US default region). Autofill is preserved:\n * the input keeps its `type=\"tel\"` + `autocomplete=\"tel\"` + implicit <label>,\n * and we also reformat on `change` so a browser-autofilled value gets\n * formatted/validated too.\n *\n * As-you-type caret note: `AsYouType` reformats the entire string, which\n * moves the caret to the end on a mid-string edit. To avoid fighting the\n * user, we only rewrite the value when the caret is at the end (the typical\n * append-a-digit case) and never on a deletion — so backspacing the\n * formatting characters works naturally.\n */\n private wirePhoneField(form: HTMLFormElement | null): void {\n const input = form?.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (!input) return;\n const hint = input.parentElement?.querySelector('.pc-hint') as HTMLElement | null;\n\n const updateHint = () => {\n const v = input.value.trim();\n const field = input.closest('.pc-field');\n if (!v) {\n // Empty is neutral — the field is optional unless requirePhone.\n field?.classList.remove('valid', 'invalid');\n if (hint) hint.textContent = '';\n return;\n }\n const ok = isValidPhoneNumber(v, PHONE_DEFAULT_REGION);\n field?.classList.toggle('valid', ok);\n field?.classList.toggle('invalid', !ok);\n if (hint) hint.textContent = ok ? '' : 'Enter a valid phone number';\n };\n\n const reformat = () => {\n const atEnd = input.selectionStart === input.value.length && input.selectionEnd === input.value.length;\n // Only reformat when appending at the end; never fight a mid-string\n // edit or a deletion (see the caret note above).\n if (atEnd) {\n const formatted = new AsYouType(PHONE_DEFAULT_REGION).input(input.value);\n // Avoid clobbering when the user is deleting: only grow/normalize,\n // not when the formatter would re-add a character they just removed.\n if (formatted.length >= input.value.length) {\n input.value = formatted;\n }\n }\n updateHint();\n };\n\n input.addEventListener('input', (ev) => {\n const ie = ev as InputEvent;\n // Don't reformat while deleting — let the user clear characters freely.\n if (typeof ie.inputType === 'string' && ie.inputType.startsWith('delete')) {\n updateHint();\n return;\n }\n reformat();\n });\n // Browser autofill / paste-then-blur lands here; format + validate it too.\n input.addEventListener('change', reformat);\n }\n\n /** Collect identity + consent from the pre-chat form, then drop into the chat view. */\n private handlePrechatSubmit(form: HTMLFormElement): void {\n if (!form.reportValidity()) return;\n const data = new FormData(form);\n const val = (k: string) => ((data.get(k) as string | null)?.trim() || undefined);\n const checked = (k: string) => data.get(k) === 'on';\n\n // Phone: when required, block on an invalid number and surface the hint.\n // When optional, allow submit — the backend normalizes/nulls authoritatively.\n const rawPhone = val('phone');\n const phoneInput = form.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (rawPhone && phoneInput && !isValidPhoneNumber(rawPhone, PHONE_DEFAULT_REGION)) {\n const required = phoneInput.hasAttribute('required');\n const field = phoneInput.closest('.pc-field');\n field?.classList.add('invalid');\n const hint = field?.querySelector('.pc-hint');\n if (hint) hint.textContent = 'Enter a valid phone number';\n if (required) {\n phoneInput.focus();\n return;\n }\n }\n // Prefer canonical E.164 when it parses; fall back to the raw value\n // otherwise (the backend re-parses + normalizes either way).\n const phone = rawPhone ? (phoneToE164(rawPhone) ?? rawPhone) : undefined;\n\n this.controller?.setUserInfo({\n name: val('name'),\n email: val('email'),\n phone,\n consent: { emailOptIn: checked('emailOptIn'), smsOptIn: checked('smsOptIn') },\n });\n this.userInfoSatisfied = true;\n this.render();\n void this.controller?.connect().catch(() => {});\n }\n\n /** Send a starter prompt (from a chip click). */\n private submitPrompt(text: string): void {\n if (!this.inputEl) return;\n this.inputEl.value = text;\n this.submit();\n }\n\n private syncOpenState(): void {\n // In full-page mode the panel always fills the host; nothing to toggle.\n if (this.panelEl?.classList.contains('fullpage')) {\n this.inputEl?.focus();\n return;\n }\n this.panelEl?.classList.toggle('hidden', !this.open);\n this.launcherEl?.classList.toggle('hidden', this.open);\n if (this.open) this.inputEl?.focus();\n }\n\n /** Grow the textarea with its content, up to the CSS max-height. */\n private autosize(): void {\n const ta = this.inputEl;\n if (!ta) return;\n ta.style.height = 'auto';\n ta.style.height = `${ta.scrollHeight}px`;\n }\n\n /**\n * Receive a new message snapshot from the controller and update the view.\n *\n * `onMessages` fires on *every* `stream_token` delta. Rebuilding the whole\n * list each frame is wasteful and fights the smooth reveal, so we take the\n * cheap path when the only change is the trailing streaming assistant message\n * growing: just bump the reveal *target* (the rAF loop drains it). Any\n * structural change (new message, finalize, citations) triggers a full\n * rebuild via {@link renderMessages}.\n */\n private handleMessages(messages: ChatMessage[], greeting: string): void {\n this.greeting = greeting;\n const prev = this.messages;\n const last = messages[messages.length - 1];\n const prevLast = prev[prev.length - 1];\n\n const structural =\n messages.length !== prev.length ||\n !last ||\n !prevLast ||\n last.id !== prevLast.id ||\n last.role !== prevLast.role ||\n // finalize transition (streaming → done) needs the markdown render + sources\n last.streaming !== prevLast.streaming ||\n // first token after the typing indicator needs the bubble swapped in\n (!!last.streaming && !prevLast.text && !!last.text) ||\n // a tool chip was added or resolved (text growth alone doesn't change this)\n this.blockSig(last) !== this.prevBlockSig;\n\n this.messages = messages;\n this.prevBlockSig = this.blockSig(last);\n\n if (!structural && last && last.streaming && this.tailKey(last) === this.streamMsgId) {\n // Fast path: the streaming (trailing) text just grew. Bump the reveal\n // target and let the rAF loop catch up — no DOM rebuild, no per-token\n // reflow. `tailText` is the live trailing text block for a tool turn, or\n // the whole message for a plain-prose turn.\n this.streamTarget = this.tailText(last);\n this.ensureRevealLoop();\n return;\n }\n\n this.renderMessages();\n }\n\n /** True when an assistant message's turn invoked at least one tool. */\n private hasToolBlocks(m?: ChatMessage): boolean {\n return !!m?.blocks?.some((b) => b.kind === 'tool');\n }\n\n /** Signature that changes only when a tool chip is added or resolved (text growth is 'x'). */\n private blockSig(m?: ChatMessage): string {\n if (!m?.blocks) return '';\n return m.blocks.map((b) => (b.kind === 'tool' ? `t:${b.tool.id}:${b.tool.done ? 1 : 0}` : 'x')).join('|');\n }\n\n /** The live (last) text block for a tool turn, else the whole message text. */\n private tailText(m: ChatMessage): string {\n if (this.hasToolBlocks(m) && m.blocks) {\n const last = m.blocks[m.blocks.length - 1];\n return last?.kind === 'text' ? last.text : '';\n }\n return m.text;\n }\n\n /** Reveal-binding key — composite for a tool-turn tail (so a new trailing block rebinds), else msg id. */\n private tailKey(m: ChatMessage): string {\n if (this.hasToolBlocks(m) && m.blocks) return `${m.id}#${m.blocks.length - 1}`;\n return m.id;\n }\n\n private renderMessages(): void {\n if (!this.messagesEl) return;\n this.resetReveal();\n this.messagesEl.replaceChildren();\n\n const greeting = this.greeting;\n if (this.messages.length === 0 && greeting) {\n this.messagesEl.appendChild(this.buildRow('assistant', this.greetingBubble(greeting)));\n }\n\n // Starter-prompt chips: shown until the visitor sends their first message.\n if (!this.hasSent && this.messages.length === 0 && this.examplePrompts.length > 0) {\n const chips = document.createElement('div');\n chips.className = 'prompts';\n for (const prompt of this.examplePrompts) {\n const chip = document.createElement('button');\n chip.type = 'button';\n chip.className = 'chip';\n chip.textContent = prompt;\n chip.addEventListener('click', () => this.submitPrompt(prompt));\n chips.appendChild(chip);\n }\n this.messagesEl.appendChild(chips);\n }\n\n for (const msg of this.messages) {\n // Tool-activity turns (gated by `showToolActivity`) render as an ordered\n // strip of prose bubbles + inline tool chips instead of one bubble.\n if (msg.role === 'assistant' && this.hasToolBlocks(msg)) {\n this.messagesEl.appendChild(this.buildRow('assistant', this.renderAssistantBlocks(msg)));\n if (!msg.streaming && msg.citations && msg.citations.length > 0) {\n this.messagesEl.appendChild(this.renderSources(msg.citations));\n }\n continue;\n }\n\n const bubble = document.createElement('div');\n bubble.className = `bubble ${msg.role}`;\n if (msg.role === 'assistant' && msg.streaming && !msg.text) {\n // No text yet → animated typing indicator.\n bubble.classList.add('typing');\n bubble.append(this.typingDot(), this.typingDot(), this.typingDot());\n } else if (msg.streaming) {\n // Mid-stream: partial/unclosed markdown renders ugly (half-open\n // `**`, dangling `[`), so keep plain text + the blinking cursor.\n // The text is revealed gradually by the rAF typewriter; seed the\n // bubble with whatever is already displayed and bind the reveal.\n bubble.classList.add('cursor');\n this.bindReveal(msg, bubble);\n } else if (msg.role === 'assistant') {\n // Final assistant turn → render the sanitized markdown subset.\n // `renderMarkdown` escapes all text, drops images, gates links to\n // http(s), and only emits an allowlisted set of tags, so this\n // `innerHTML` cannot inject markup (see markdown.ts).\n bubble.classList.add('md');\n bubble.innerHTML = renderMarkdown(msg.text);\n } else {\n // User bubbles stay plain text.\n bubble.textContent = msg.text;\n }\n this.messagesEl.appendChild(this.buildRow(msg.role, bubble));\n\n // Render a \"Sources (N)\" section under any assistant message whose\n // terminal eventual_response carried citations.\n if (msg.role === 'assistant' && !msg.streaming && msg.citations && msg.citations.length > 0) {\n this.messagesEl.appendChild(this.renderSources(msg.citations));\n }\n }\n this.scrollToBottom(true);\n this.renderSuggestions();\n }\n\n /**\n * Render (or clear) the mid-conversation suggested-reply chips under the\n * composer. Shown ONLY when: the feature is enabled, no interrupt / restore\n * overlay is active (those reuse the slot above the composer), and the LATEST\n * message is a finalized assistant turn that carried suggestions. A new turn\n * (agent or the visitor typing) appends messages, so the latest is no longer\n * that assistant message and the chips clear on the next render. Chips reuse\n * the empty-state `.prompts`/`.chip` styling and send via the same path.\n */\n private renderSuggestions(): void {\n const el = this.suggestionsEl;\n if (!el) return;\n el.replaceChildren();\n if (!this.showSuggestedReplies) return;\n // Hidden while an OTP / tool-confirmation / restore overlay is active.\n if (this.interrupt || this.identityRestore.phase !== 'idle') return;\n const last = this.messages[this.messages.length - 1];\n if (!last || last.role !== 'assistant' || last.streaming || !last.suggestions || last.suggestions.length === 0) return;\n\n const chips = document.createElement('div');\n chips.className = 'prompts';\n for (const suggestion of last.suggestions) {\n const chip = document.createElement('button');\n chip.type = 'button';\n chip.className = 'chip';\n chip.textContent = suggestion;\n chip.addEventListener('click', () => this.submitPrompt(suggestion));\n chips.appendChild(chip);\n }\n el.appendChild(chips);\n }\n\n // ─────────────────────── Smooth streaming reveal ───────────────────────────\n\n /** True when the host/user prefers reduced motion (snap, no typewriter). */\n private prefersReducedMotion(): boolean {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n }\n\n /**\n * Bind the rAF typewriter to a freshly built streaming bubble. Preserves the\n * already-revealed prefix across rebuilds (so a structural rebuild mid-stream\n * doesn't restart the reveal from zero), then resumes the loop.\n */\n private bindReveal(msg: ChatMessage, bubble: HTMLElement): void {\n // `tailKey`/`tailText` collapse to the message id + full text for a plain\n // prose turn, and to the live trailing text block for a tool turn — so both\n // the single streaming bubble and a tool turn's trailing prose share this path.\n const key = this.tailKey(msg);\n const target = this.tailText(msg);\n const carryOver = key === this.streamMsgId ? Math.min(this.displayedLength, target.length) : 0;\n this.streamBubbleEl = bubble;\n this.streamMsgId = key;\n this.streamTarget = target;\n this.displayedLength = carryOver;\n\n if (this.prefersReducedMotion()) {\n // No animation: show everything immediately.\n this.displayedLength = target.length;\n bubble.textContent = target;\n return;\n }\n bubble.textContent = target.slice(0, this.displayedLength);\n this.ensureRevealLoop();\n }\n\n /**\n * Render a tool-activity assistant turn as an ordered strip: prose bubbles and\n * inline tool chips in the order the model produced them (mirrors the daemon\n * SPA's `blocks`). The live trailing text block (while streaming) binds to the\n * rAF reveal; earlier/finalized text blocks render as sanitized markdown.\n */\n private renderAssistantBlocks(msg: ChatMessage): HTMLElement {\n const wrap = document.createElement('div');\n wrap.className = 'blocks';\n const blocks = msg.blocks ?? [];\n const lastIdx = blocks.length - 1;\n blocks.forEach((block, i) => {\n if (block.kind === 'tool') {\n wrap.appendChild(this.buildToolChip(block.tool));\n return;\n }\n const bubble = document.createElement('div');\n bubble.className = 'bubble assistant';\n if (msg.streaming && i === lastIdx) {\n // Live trailing prose → plain text + cursor, driven by the reveal loop.\n bubble.classList.add('cursor');\n this.bindReveal(msg, bubble);\n } else {\n // Settled prose → sanitized markdown (same allowlisted renderer as bubbles).\n bubble.classList.add('md');\n bubble.innerHTML = renderMarkdown(block.text);\n }\n wrap.appendChild(bubble);\n });\n return wrap;\n }\n\n /**\n * A single tool-activity chip: icon + tool name + status (running… / done / error),\n * with a truncated args preview. Tool name/args are set via `textContent` so a\n * tool payload can never inject markup.\n */\n private buildToolChip(tool: ToolCall): HTMLElement {\n const chip = document.createElement('div');\n chip.className = `toolchip ${tool.done ? (tool.isError ? 'error' : 'done') : 'running'}`;\n chip.setAttribute('part', 'tool-chip');\n\n const icon = document.createElement('span');\n icon.className = 'ti';\n icon.innerHTML = ICON.tool; // static, trusted\n const name = document.createElement('span');\n name.className = 'tn';\n name.textContent = tool.name || 'tool';\n const status = document.createElement('span');\n status.className = 'ts';\n status.textContent = tool.done ? (tool.isError ? 'error' : 'done') : 'running…';\n chip.append(icon, name, status);\n\n if (tool.args && tool.args !== '{}' && tool.args !== '\"\"') {\n const args = document.createElement('span');\n args.className = 'ta';\n args.textContent = tool.args.length > 80 ? `${tool.args.slice(0, 80)}…` : tool.args;\n chip.appendChild(args);\n }\n return chip;\n }\n\n /** Start the rAF loop if it isn't already running. */\n private ensureRevealLoop(): void {\n if (this.prefersReducedMotion() || typeof requestAnimationFrame !== 'function') {\n // No animation (reduced-motion or no rAF): snap to the full buffer.\n this.snapReveal();\n return;\n }\n if (this.rafId) return; // already running\n this.rafId = requestAnimationFrame(() => this.tickReveal());\n }\n\n /**\n * One animation frame of the reveal. Advances `displayedLength` toward the\n * buffered target at an ADAPTIVE rate — the deeper the backlog, the more\n * chars per frame — so the reveal stays smooth yet never falls behind the\n * network. Updates ONLY the bound bubble's textContent (no list rebuild).\n */\n private tickReveal(): void {\n this.rafId = 0;\n const bubble = this.streamBubbleEl;\n if (!bubble) return;\n\n const target = this.streamTarget;\n const remaining = target.length - this.displayedLength;\n\n if (remaining <= 0) {\n // Caught up to everything buffered so far → idle. A later token bump\n // (handleMessages → ensureRevealLoop) restarts the loop; the finalize\n // structural rebuild snaps to the full markdown render.\n return;\n }\n\n // Adaptive speed: ~1/8 of the backlog per frame (≈ catch up over a few\n // frames), clamped to a readable floor so short bursts still animate and\n // an aggressive ceiling so a deep buffer drains fast. At ~60fps this\n // comfortably outruns the wire — the reveal is steady, never bursty.\n const step = Math.max(2, Math.min(remaining, Math.ceil(remaining / 8)));\n this.displayedLength = Math.min(target.length, this.displayedLength + step);\n bubble.textContent = target.slice(0, this.displayedLength);\n this.scrollToBottom(false);\n\n this.rafId = requestAnimationFrame(() => this.tickReveal());\n }\n\n /** Snap the bound bubble to the full buffered text immediately (reduced-motion / no-rAF). */\n private snapReveal(): void {\n if (this.streamBubbleEl) {\n this.displayedLength = this.streamTarget.length;\n this.streamBubbleEl.textContent = this.streamTarget;\n }\n }\n\n /**\n * Full-page sizing probe: decide whether the host's container gives it a\n * real box. With the `.wrap` flex chain hidden, `height: 100%` of a SIZED\n * container still resolves (clientHeight > 0), while an auto-height parent\n * (e.g. mounted straight into `<body>`) collapses to ~0. Only the latter\n * gets `data-viewport-fallback`, whose CSS applies `min-height: 100dvh` —\n * so an embed inside a fixed-height box never overflows it (the composer\n * stays visible), and a bare full-page route still fills the viewport.\n */\n private syncViewportFallback(): void {\n const wrap = this.shadowRoot?.querySelector<HTMLElement>('.wrap');\n if (!wrap) return;\n const prev = wrap.style.display;\n wrap.style.display = 'none';\n const heightless = this.clientHeight < 8;\n wrap.style.display = prev;\n this.toggleAttribute('data-viewport-fallback', heightless);\n }\n\n /** Cancel any in-flight reveal loop and clear its state (called on full rebuild). */\n private resetReveal(): void {\n if (this.rafId && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.rafId);\n this.rafId = 0;\n this.streamBubbleEl = null;\n // streamMsgId/displayedLength are intentionally kept so bindReveal can\n // carry the revealed prefix across a structural rebuild of the same msg;\n // they're reset when a different message binds.\n }\n\n /**\n * Auto-scroll the message list to the bottom — but don't fight a visitor who\n * has scrolled up to read history. When `force` (a structural rebuild) we\n * always pin to bottom; during the streaming reveal we only follow if the\n * viewport is already near the bottom.\n */\n private scrollToBottom(force: boolean): void {\n const el = this.messagesEl;\n if (!el) return;\n if (force) {\n el.scrollTop = el.scrollHeight;\n return;\n }\n const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;\n if (nearBottom) el.scrollTop = el.scrollHeight;\n }\n\n /** Wrap a bubble in a `.row`, prefixing assistant rows with a mini avatar. */\n private buildRow(role: 'user' | 'assistant', bubble: HTMLElement): HTMLElement {\n const row = document.createElement('div');\n row.className = `row ${role}`;\n if (role === 'assistant') {\n const mini = document.createElement('div');\n mini.className = 'mini';\n mini.innerHTML = ICON.bot; // static, trusted\n row.appendChild(mini);\n }\n row.appendChild(bubble);\n return row;\n }\n\n private greetingBubble(greeting: string): HTMLElement {\n const b = document.createElement('div');\n b.className = 'bubble assistant greeting';\n b.textContent = greeting;\n return b;\n }\n\n private typingDot(): HTMLElement {\n return document.createElement('i');\n }\n\n /**\n * Build the collapsible \"Sources (N)\" block for an assistant message's\n * citations. Title/snippet are set via `textContent` (never innerHTML) so\n * citation text can't inject markup; only the static chevron + numeric count\n * use innerHTML.\n */\n private renderSources(citations: Citation[]): HTMLElement {\n const wrap = document.createElement('div');\n wrap.className = 'sources';\n wrap.setAttribute('part', 'sources');\n\n const details = document.createElement('details');\n details.open = true;\n\n const summary = document.createElement('summary');\n const chev = document.createElement('span');\n chev.className = 'chev';\n chev.innerHTML = ICON.chev; // static, trusted\n const label = document.createElement('span');\n label.textContent = 'Sources';\n const count = document.createElement('span');\n count.className = 'count';\n count.textContent = String(citations.length);\n summary.append(chev, label, count);\n details.appendChild(summary);\n\n const list = document.createElement('ol');\n for (const c of citations) {\n const li = document.createElement('li');\n\n let titleEl: HTMLElement;\n // SECURITY: only absolute http(s) URLs may become a link href. A\n // citation URL comes from indexed content (web/GitHub connectors), so\n // an attacker-influenceable doc could carry `javascript:`/`data:`/\n // `vbscript:` — assigning those to `a.href` is a one-click XSS. Anything\n // that isn't a valid absolute http(s) URL renders as plain text.\n const safeUrl = safeHttpUrl(c.url);\n if (safeUrl) {\n const a = document.createElement('a');\n a.className = 'src-title';\n a.href = safeUrl;\n a.target = '_blank';\n a.rel = 'noopener noreferrer nofollow';\n titleEl = a;\n } else {\n titleEl = document.createElement('span');\n titleEl.className = 'src-title';\n }\n titleEl.textContent = c.title || c.id || 'Source';\n li.appendChild(titleEl);\n\n if (c.snippet) {\n // The snippet is the raw scraped chunk — often led by page\n // boilerplate (logo link, nav, whitespace). Trim it to a clean\n // excerpt, then render the sanitized markdown subset. Both steps\n // escape text + drop images/unsafe links (see markdown.ts), so\n // this `innerHTML` is safe.\n const cleaned = cleanCitationSnippet(c.snippet);\n if (cleaned) {\n const snip = document.createElement('span');\n snip.className = 'src-snippet md';\n snip.innerHTML = renderMarkdown(cleaned);\n li.appendChild(snip);\n }\n }\n list.appendChild(li);\n }\n details.appendChild(list);\n wrap.appendChild(details);\n return wrap;\n }\n\n private renderStatus(): void {\n const label: Record<ConnectionStatus, string> = {\n idle: '',\n connecting: 'Connecting…',\n ready: 'Online',\n error: 'Connection issue',\n closed: 'Disconnected',\n };\n if (this.statusEl) this.statusEl.textContent = label[this.status];\n if (this.dotEl) {\n // ready → green (no modifier); connecting → amber; error → red; else grey.\n const mod = this.status === 'ready' ? '' : this.status === 'connecting' ? ' connecting' : this.status === 'error' ? ' error' : ' off';\n this.dotEl.className = `dot${mod}`;\n }\n }\n\n private renderComposerState(): void {\n const busy = this.status === 'connecting';\n if (this.sendBtn) this.sendBtn.disabled = busy;\n if (this.inputEl) this.inputEl.disabled = busy;\n }\n\n private submit(): void {\n if (!this.inputEl || !this.controller) return;\n const text = this.inputEl.value;\n if (!text.trim()) return;\n this.inputEl.value = '';\n this.hasSent = true;\n this.autosize();\n void this.controller.send(text);\n }\n}\n\n/** Register the custom element once. Safe to call multiple times. */\nexport function defineChatWidget(): void {\n if (typeof customElements !== 'undefined' && !customElements.get(ELEMENT_TAG)) {\n customElements.define(ELEMENT_TAG, SmoothAgentChatElement);\n }\n}\n\n/**\n * Programmatically create, configure, and append a widget to the page.\n * Returns the element so the host can drive `openChat()` / `closeChat()`.\n */\nexport function mountChatWidget(config: ChatWidgetConfig, target: HTMLElement = document.body): SmoothAgentChatElement {\n defineChatWidget();\n const el = document.createElement(ELEMENT_TAG) as SmoothAgentChatElement;\n el.configure(config);\n target.appendChild(el);\n return el;\n}\n\n/**\n * Ergonomic helper for the full-page layout: mounts a `<smooth-agent-chat>` in\n * `mode: \"fullpage\"` (no launcher — the chat fills its container/viewport with a\n * Smooth-branded header, a scrollable message list, and an input bar) and\n * returns the element.\n *\n * `target` defaults to `document.body`; pass a sized container to embed the\n * full-page chat inside a layout region (e.g. a `/chat` route shell or an\n * iframe). The `mode` is forced to `\"fullpage\"` regardless of the passed config.\n *\n * ```ts\n * mountFullPageChat({ endpoint: 'wss://…/ws', agentId: '…', agentName: 'Support' });\n * ```\n */\nexport function mountFullPageChat(config: Omit<ChatWidgetConfig, 'mode'>, target: HTMLElement = document.body): SmoothAgentChatElement {\n return mountChatWidget({ ...config, mode: 'fullpage' }, target);\n}\n","/**\n * Tiny, dependency-free deferred loader for `@smooai/chat-widget`.\n *\n * The recommended embed: a host includes this *small* script eagerly, and it\n * defers injecting the real (heavier) `chat-widget.global.js` module until the\n * page is past its critical render — so the widget never competes with the host\n * page's LCP/TBT. It triggers the real load on the **first** of:\n *\n * - `window` `load` → `requestIdleCallback` (idle time), or\n * - user intent (`pointerdown` / `keydown` / `scroll`), or\n * - an 8s fallback.\n *\n * After the module loads (which registers `<smooth-agent-chat>` and exposes\n * `window.SmoothAgentChat`), it mounts the widget with the host's config.\n *\n * Deliberately imports nothing from the widget itself — this file must stay a\n * few hundred bytes so including it eagerly is free.\n *\n * ## Config\n * Set a global before/with the loader (any `ChatWidgetConfig`, plus an optional\n * `src` pointing at the module bundle):\n *\n * ```html\n * <script>window.SmoothAgentChatConfig = { endpoint: 'wss://…/ws', agentId: '…' };</script>\n * <script src=\"https://cdn/…/chat-widget-loader.global.js\" async></script>\n * ```\n *\n * Or, for the simplest installs, `data-*` attributes on the loader's own tag\n * (`data-endpoint`, `data-agent-id`, `data-primary`, `data-mode`, `data-src`).\n * If no config is found, the module is still loaded (registering the element) so\n * a `<smooth-agent-chat …>` placed directly in markup upgrades itself.\n */\n\n/** Must match `ELEMENT_TAG` in `element.ts`; inlined to avoid importing it. */\nconst ELEMENT_TAG = 'smooth-agent-chat';\n/** Default module filename, resolved as a sibling of the loader script. */\nconst DEFAULT_MODULE = 'chat-widget.global.js';\n\ntype MountFn = (config: Record<string, unknown>, target?: HTMLElement) => unknown;\n\ninterface LoaderWindow extends Window {\n SmoothAgentChat?: { mount: MountFn };\n SmoothAgentChatConfig?: Record<string, unknown> & { src?: string };\n}\n\n/**\n * Resolve the module URL: explicit `src` (config or `data-src`) wins, else a\n * sibling of the loader script, else the bare default filename.\n */\nfunction resolveModuleSrc(win: LoaderWindow, script: HTMLScriptElement | null): string {\n const fromConfig = win.SmoothAgentChatConfig?.src;\n if (fromConfig) return fromConfig;\n const fromAttr = script?.getAttribute('data-src');\n if (fromAttr) return fromAttr;\n const selfSrc = script?.src;\n if (selfSrc) return selfSrc.replace(/[^/]*$/, DEFAULT_MODULE);\n return DEFAULT_MODULE;\n}\n\n/**\n * The widget mount config: the `SmoothAgentChatConfig` global (minus the\n * loader-only `src`), or `data-*` attributes. `undefined` ⇒ no programmatic\n * mount (a markup element will upgrade itself once the module registers it).\n */\nfunction resolveMountConfig(win: LoaderWindow, script: HTMLScriptElement | null): Record<string, unknown> | undefined {\n if (win.SmoothAgentChatConfig) {\n const { src: _src, ...config } = win.SmoothAgentChatConfig;\n // Only `src` (no real fields) ⇒ no programmatic mount; a markup element\n // upgrades itself once the module registers it.\n return Object.keys(config).length > 0 ? config : undefined;\n }\n if (!script) return undefined;\n const endpoint = script.getAttribute('data-endpoint');\n const agentId = script.getAttribute('data-agent-id');\n if (!endpoint && !agentId) return undefined;\n const config: Record<string, unknown> = {};\n if (endpoint) config.endpoint = endpoint;\n if (agentId) config.agentId = agentId;\n const primary = script.getAttribute('data-primary');\n if (primary) config.theme = { primary };\n const mode = script.getAttribute('data-mode');\n if (mode) config.mode = mode;\n return config;\n}\n\n/**\n * Install the deferred loader. Idempotent per call; the IIFE entry\n * (`loader.ts`) invokes it once on script execution.\n */\nexport function initChatWidgetLoader(): void {\n const win = window as LoaderWindow;\n const script = (document.currentScript as HTMLScriptElement | null) ?? null;\n const moduleSrc = resolveModuleSrc(win, script);\n\n let loaded = false;\n let idleId: number | undefined;\n let fallbackId: number | undefined;\n\n function mountWhenReady(): void {\n const config = resolveMountConfig(win, script);\n if (!config) return; // markup element upgrades itself; nothing to mount\n const apply = () => {\n try {\n win.SmoothAgentChat?.mount(config);\n } catch (error) {\n console.error('[chat-widget loader] mount failed', error);\n }\n };\n if (win.SmoothAgentChat) {\n apply();\n } else if (window.customElements?.whenDefined) {\n window.customElements.whenDefined(ELEMENT_TAG).then(apply, apply);\n } else {\n apply();\n }\n }\n\n function teardown(): void {\n if (idleId !== undefined) {\n // The id is either an idle handle or (fallback path) a timeout id;\n // both cancels are no-ops on the wrong kind, so calling both is safe.\n window.cancelIdleCallback?.(idleId);\n window.clearTimeout(idleId);\n }\n if (fallbackId !== undefined) window.clearTimeout(fallbackId);\n window.removeEventListener('pointerdown', load);\n window.removeEventListener('keydown', load);\n window.removeEventListener('scroll', load);\n }\n\n function load(): void {\n if (loaded) return;\n loaded = true;\n teardown();\n const tag = document.createElement('script');\n tag.src = moduleSrc;\n tag.onload = mountWhenReady;\n tag.onerror = () => console.error('[chat-widget loader] failed to load', moduleSrc);\n document.head.appendChild(tag);\n }\n\n function schedule(): void {\n if (window.requestIdleCallback) {\n idleId = window.requestIdleCallback(() => load(), { timeout: 5000 });\n } else {\n idleId = window.setTimeout(load, 2500) as unknown as number;\n }\n fallbackId = window.setTimeout(load, 8000) as unknown as number;\n }\n\n // User intent loads immediately (they're about to want the widget).\n window.addEventListener('pointerdown', load, { once: true, passive: true });\n window.addEventListener('keydown', load, { once: true });\n window.addEventListener('scroll', load, { once: true, passive: true });\n\n if (document.readyState === 'complete') {\n schedule();\n } else {\n window.addEventListener('load', schedule, { once: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,WAAW,OAAuB;CAC9C,OAAO,MAAM,QAAQ,aAAa,MAAM;EACpC,QAAQ,GAAR;GACI,KAAK,KACD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T,MAAM,MAAM,SAAS,cAAc,QAAQ;EAC3C,IAAI,MAAM;EACV,IAAI,SAAS;EACb,IAAI,gBAAgB,QAAQ,MAAM,uCAAuC,SAAS;EAClF,SAAS,KAAK,YAAY,GAAG;CACjC;CAEA,SAAS,WAAiB;EACtB,IAAI,OAAO,qBACP,SAAS,OAAO,0BAA0B,KAAK,GAAG,EAAE,SAAS,IAAK,CAAC;OAEnE,SAAS,OAAO,WAAW,MAAM,IAAI;EAEzC,aAAa,OAAO,WAAW,MAAM,GAAI;CAC7C;CAGA,OAAO,iBAAiB,eAAe,MAAM;EAAE,MAAM;EAAM,SAAS;CAAK,CAAC;CAC1E,OAAO,iBAAiB,WAAW,MAAM,EAAE,MAAM,KAAK,CAAC;CACvD,OAAO,iBAAiB,UAAU,MAAM;EAAE,MAAM;EAAM,SAAS;CAAK,CAAC;CAErE,IAAI,SAAS,eAAe,YACxB,SAAS;MAET,OAAO,iBAAiB,QAAQ,UAAU,EAAE,MAAM,KAAK,CAAC;AAEhE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["ELEMENT_TAG"],"sources":["../src/markdown.ts","../src/voice-session.ts","../src/config.ts","../src/fingerprint.ts","../src/persistence.ts","../src/conversation.ts","../src/logo.ts","../src/styles.ts","../src/element.ts","../src/loader-core.ts"],"sourcesContent":["/**\n * A tiny, safe-by-default Markdown → HTML renderer for the chat widget.\n *\n * ## Why a hand-rolled renderer (and not markdown-it / snarkdown)?\n *\n * The widget renders **untrusted** text in two places: the assistant's reply\n * (LLM output, which can echo attacker-supplied content) and citation snippets\n * (raw scraped page chunks). Today both are written via `textContent`, so\n * `**bold**`, numbered lists, and `[links](url)` show up literally. We want\n * them rendered — without re-opening the XSS hole that `textContent` was\n * guarding against.\n *\n * markdown-it with `html:false` is safe-by-default but ships ~30 kB min into\n * what is an embeddable **global** bundle, where every kilobyte is on the host\n * page's critical path. snarkdown is ~1 kB but emits raw HTML, so it would\n * require bolting on a separate sanitizer. Instead, this renderer is\n * **safe-by-construction**:\n *\n * 1. It is a *tokenizer*, not an HTML passthrough. It only ever emits a\n * fixed allowlist of tags (`p`, `br`, `strong`, `em`, `ul`/`ol`/`li`,\n * `code`/`pre`, `a`, `blockquote`). There is no code path that copies a\n * tag out of the input — a literal `<script>` in the input is treated as\n * plain text.\n * 2. **Every** text run is HTML-escaped via {@link escapeHtml} before it\n * reaches the output. Raw `<`, `>`, `&`, `\"`, `'` can never become markup.\n * 3. **Images are dropped entirely** — `` renders as its alt text,\n * no `<img>` is ever produced (a scraped tracking pixel must not load).\n * 4. **Links** are gated through {@link safeHttpUrl}: only absolute `http(s)`\n * URLs become anchors (with `target=\"_blank\"` + a hardened `rel`);\n * `javascript:`/`data:`/relative/etc. fall back to plain (escaped) text.\n * 5. **Headings** (`#`..`######`) are *downgraded* to bold lines — a full\n * `<h1>` is far too large inside a chat bubble or citation card.\n *\n * The output is a string of HTML that is only ever assigned to `innerHTML` of\n * an element the caller controls; because of (1)–(4) it can only contain the\n * allowlisted, attribute-sanitized tags.\n *\n * Supported subset (deliberately small):\n * - Paragraphs (blank-line separated) and hard/soft line breaks\n * - `**bold**` / `__bold__`, `*italic*` / `_italic_`\n * - `` `inline code` `` and fenced ``` ```code blocks``` ```\n * - `- ` / `* ` / `+ ` unordered lists, `1.` ordered lists\n * - `> ` blockquotes\n * - `[text](http(s)://url)` links (images dropped to alt text)\n * - `#`..`######` headings → bold line\n */\n\n/** Escape the five HTML-significant characters so a text run can never be markup. */\nexport function escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case '&':\n return '&';\n case '<':\n return '<';\n case '>':\n return '>';\n case '\"':\n return '"';\n default:\n return ''';\n }\n });\n}\n\n/**\n * Return `url` only if it is a valid absolute `http(s)` URL, else `null`.\n *\n * SECURITY: link targets here originate from untrusted content (LLM output /\n * scraped citation chunks). Allowing an arbitrary string as an `href` permits\n * `javascript:`/`data:`/`vbscript:` URLs that execute on click — a stored-XSS\n * vector. Only absolute http(s) links are rendered as anchors; anything else\n * falls back to plain text upstream.\n */\nexport function safeHttpUrl(url: string | undefined | null): string | null {\n if (!url) return null;\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;\n } catch {\n return null;\n }\n}\n\n// ───────────────────────────── Inline rendering ─────────────────────────────\n\n/**\n * Render the inline span grammar of a single line/segment to safe HTML.\n *\n * Order matters: code spans are extracted first (their contents are *not*\n * further parsed), then images are stripped to alt text, then links, then\n * emphasis. Every literal text run is escaped on the way out.\n */\nfunction renderInline(input: string): string {\n let out = '';\n let i = 0;\n const n = input.length;\n\n // Accumulate escaped literal text, flushing on each recognized token.\n let buf = '';\n const flush = () => {\n if (buf) {\n out += escapeHtml(buf);\n buf = '';\n }\n };\n\n while (i < n) {\n const ch = input[i]!;\n\n // Inline code: `...` — contents are literal (escaped), no nested parsing.\n if (ch === '`') {\n const end = input.indexOf('`', i + 1);\n if (end > i) {\n flush();\n out += `<code>${escapeHtml(input.slice(i + 1, end))}</code>`;\n i = end + 1;\n continue;\n }\n }\n\n // Image:  — DROPPED. Emit only the (escaped) alt text; never\n // produce an <img> (a scraped tracking pixel must not load).\n if (ch === '!' && input[i + 1] === '[') {\n const m = imageAt(input, i);\n if (m) {\n flush();\n out += renderInline(m.alt); // alt may itself contain emphasis\n i = m.end;\n continue;\n }\n }\n\n // Link: [text](href)\n if (ch === '[') {\n const m = linkAt(input, i);\n if (m) {\n flush();\n const safe = safeHttpUrl(m.href);\n const inner = renderInline(m.text);\n if (safe) {\n out += `<a href=\"${escapeHtml(safe)}\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">${inner}</a>`;\n } else {\n // Unsafe scheme → render as plain (already-escaped) text, no anchor.\n out += inner;\n }\n i = m.end;\n continue;\n }\n }\n\n // Bold: **...** or __...__\n if ((ch === '*' && input[i + 1] === '*') || (ch === '_' && input[i + 1] === '_')) {\n const marker = ch + ch;\n const end = input.indexOf(marker, i + 2);\n if (end > i + 1) {\n flush();\n out += `<strong>${renderInline(input.slice(i + 2, end))}</strong>`;\n i = end + 2;\n continue;\n }\n }\n\n // Italic: *...* or _..._ (single marker, non-empty, not touching the other marker)\n if (ch === '*' || ch === '_') {\n const end = input.indexOf(ch, i + 1);\n if (end > i + 1 && input[i + 1] !== ch) {\n flush();\n out += `<em>${renderInline(input.slice(i + 1, end))}</em>`;\n i = end + 1;\n continue;\n }\n }\n\n buf += ch;\n i++;\n }\n\n flush();\n return out;\n}\n\n/** Parse a `[text](href)` link starting at `start` (`input[start] === '['`). */\nfunction linkAt(input: string, start: number): { text: string; href: string; end: number } | null {\n const close = matchBracket(input, start);\n if (close < 0 || input[close + 1] !== '(') return null;\n const paren = input.indexOf(')', close + 2);\n if (paren < 0) return null;\n const text = input.slice(start + 1, close);\n // href is the first whitespace-delimited token inside (...) — ignore any\n // markdown \"title\" portion; we never render titles.\n const href = input.slice(close + 2, paren).trim().split(/\\s+/)[0] ?? '';\n return { text, href, end: paren + 1 };\n}\n\n/** Parse a `` image starting at `start` (`input[start] === '!'`). */\nfunction imageAt(input: string, start: number): { alt: string; end: number } | null {\n const link = linkAt(input, start + 1);\n if (!link) return null;\n return { alt: link.text, end: link.end };\n}\n\n/** Find the matching `]` for a `[` at `open`, honoring one level of nesting. */\nfunction matchBracket(input: string, open: number): number {\n let depth = 0;\n for (let i = open; i < input.length; i++) {\n const c = input[i];\n if (c === '[') depth++;\n else if (c === ']') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return -1;\n}\n\n// ───────────────────────────── Block rendering ──────────────────────────────\n\nconst UL_RE = /^\\s*[-*+]\\s+(.*)$/;\nconst OL_RE = /^\\s*\\d+[.)]\\s+(.*)$/;\nconst HEADING_RE = /^\\s{0,3}(#{1,6})\\s+(.*)$/;\nconst QUOTE_RE = /^\\s*>\\s?(.*)$/;\nconst FENCE_RE = /^\\s*(`{3,}|~{3,})\\s*(.*)$/;\n\n/**\n * Render a full Markdown string to safe HTML.\n *\n * @returns a string containing only the allowlisted tags described in the\n * module doc. Safe to assign to `innerHTML` of a caller-owned element.\n */\nexport function renderMarkdown(src: string): string {\n const lines = src.replace(/\\r\\n?/g, '\\n').split('\\n');\n const out: string[] = [];\n\n let i = 0;\n while (i < lines.length) {\n const line = lines[i]!;\n\n // Fenced code block: ```lang ... ```\n const fence = FENCE_RE.exec(line);\n if (fence) {\n const marker = fence[1]!;\n const body: string[] = [];\n i++;\n while (i < lines.length && !lines[i]!.trimStart().startsWith(marker)) {\n body.push(lines[i]!);\n i++;\n }\n if (i < lines.length) i++; // consume closing fence\n out.push(`<pre><code>${escapeHtml(body.join('\\n'))}</code></pre>`);\n continue;\n }\n\n // Blank line → paragraph boundary.\n if (line.trim() === '') {\n i++;\n continue;\n }\n\n // Heading → downgraded to a bold line (an <h1> is too big in a bubble).\n const heading = HEADING_RE.exec(line);\n if (heading) {\n out.push(`<p><strong>${renderInline(heading[2]!)}</strong></p>`);\n i++;\n continue;\n }\n\n // Unordered / ordered list — consume the contiguous run.\n if (UL_RE.test(line) || OL_RE.test(line)) {\n const ordered = OL_RE.test(line) && !UL_RE.test(line);\n const re = ordered ? OL_RE : UL_RE;\n const items: string[] = [];\n while (i < lines.length) {\n const m = re.exec(lines[i]!);\n if (!m) break;\n items.push(`<li>${renderInline(m[1]!)}</li>`);\n i++;\n }\n out.push(`<${ordered ? 'ol' : 'ul'}>${items.join('')}</${ordered ? 'ol' : 'ul'}>`);\n continue;\n }\n\n // Blockquote — consume the contiguous run.\n if (QUOTE_RE.test(line)) {\n const quoted: string[] = [];\n while (i < lines.length) {\n const m = QUOTE_RE.exec(lines[i]!);\n if (!m) break;\n quoted.push(m[1]!);\n i++;\n }\n out.push(`<blockquote>${renderInline(quoted.join('\\n')).replace(/\\n/g, '<br>')}</blockquote>`);\n continue;\n }\n\n // Paragraph — gather consecutive non-blank, non-block lines; soft breaks → <br>.\n const para: string[] = [];\n while (i < lines.length) {\n const l = lines[i]!;\n if (\n l.trim() === '' ||\n FENCE_RE.test(l) ||\n HEADING_RE.test(l) ||\n UL_RE.test(l) ||\n OL_RE.test(l) ||\n QUOTE_RE.test(l)\n ) {\n break;\n }\n para.push(l);\n i++;\n }\n out.push(`<p>${renderInline(para.join('\\n')).replace(/\\n/g, '<br>')}</p>`);\n }\n\n return out.join('');\n}\n\n// ───────────────────────── Citation-snippet cleanup ─────────────────────────\n\nconst SNIPPET_MAX = 260;\n\n/**\n * Clean a raw scraped citation snippet into a short, readable excerpt.\n *\n * Scraped chunks frequently begin with page boilerplate — a logo image wrapped\n * in a link, standalone nav, repeated whitespace — e.g.\n * `[](…) # Our Work We build…`. The source itself is already linked\n * from the citation card, so the snippet only needs to be a clean teaser.\n *\n * Steps:\n * 1. Strip a leading image / logo-link (`[](…)` or ``).\n * 2. Drop a leading standalone heading marker (`#`/`##`).\n * 3. Collapse all runs of whitespace to single spaces.\n * 4. Truncate to ~{@link SNIPPET_MAX} chars at a word boundary, adding `…`.\n *\n * The result is still rendered through {@link renderMarkdown} downstream, so any\n * remaining inline markup (bold/links) stays safe.\n */\nexport function cleanCitationSnippet(raw: string): string {\n let s = raw ?? '';\n\n // Repeatedly peel leading boilerplate tokens.\n let changed = true;\n while (changed) {\n changed = false;\n const before = s;\n // Leading linked image: [](href)\n s = s.replace(/^\\s*\\[!\\[[^\\]]*\\]\\([^)]*\\)\\]\\([^)]*\\)\\s*/, '');\n // Leading bare image: \n s = s.replace(/^\\s*!\\[[^\\]]*\\]\\([^)]*\\)\\s*/, '');\n // Leading heading marker(s): \"# \", \"## \" (keep the heading text)\n s = s.replace(/^\\s*#{1,6}\\s+/, '');\n if (s !== before) changed = true;\n }\n\n // Collapse whitespace.\n s = s.replace(/\\s+/g, ' ').trim();\n\n // Truncate at a word boundary.\n if (s.length > SNIPPET_MAX) {\n const cut = s.slice(0, SNIPPET_MAX);\n const lastSpace = cut.lastIndexOf(' ');\n s = (lastSpace > SNIPPET_MAX * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd() + '…';\n }\n\n return s;\n}\n","/**\n * VoiceSession — framework-free browser voice for the chat widget.\n *\n * Speaks the FROZEN browser-voice WebSocket protocol (SMOODEV-2534 / ADR-084):\n *\n * client → server:\n * - first frame, JSON: `{\"type\":\"start\",\"agent_id\":\"…\",\"conversation_id\":\"…?\",\"token\":\"…?\"}`\n * (public-agent auth is the `Origin` header the browser sends automatically;\n * `token` only for authenticated contexts)\n * - binary frames: raw PCM linear16 mono @ 16 kHz mic chunks\n * - JSON `{\"type\":\"interrupt\"}` (user barged in), `{\"type\":\"stop\"}`\n * server → client:\n * - JSON `transcript_partial` / `transcript_final` / `reply_text` /\n * `speaking_started` / `speaking_done` / `handoff` / `error {code}`\n * - binary frames: PCM linear16 mono @ 16 kHz TTS audio chunks\n *\n * The class owns: the WS lifecycle, mic capture (getUserMedia → AudioWorklet or\n * ScriptProcessor fallback → downsample to 16 kHz mono Int16 → binary frames),\n * gapless playback of incoming PCM through a 16 kHz AudioContext, and barge-in\n * (RMS speech detection while the agent is speaking → `interrupt` + playback\n * flush). Browser audio + WebSocket are thin injectable seams so unit tests run\n * under jsdom/happy-dom with no real audio.\n */\n\nexport const DEFAULT_VOICE_URL = 'wss://twilio-voice.smoo.ai/browser-voice/ws';\n\n/** Target wire format: PCM linear16 mono @ 16 kHz. */\nexport const VOICE_SAMPLE_RATE = 16000;\n\n// ─────────────────────────── Pure DSP helpers ───────────────────────────────\n\n/**\n * Downsample Float32 mic samples at `inputRate` to 16 kHz mono Int16 (linear16).\n * Bucket-averaging decimation: each output sample averages its source bucket,\n * which is a cheap low-pass that's plenty for speech (and handles non-integer\n * ratios like 44.1k → 16k). Values are clamped to the Int16 range.\n */\nexport function downsampleTo16k(samples: Float32Array, inputRate: number): Int16Array {\n const ratio = inputRate / VOICE_SAMPLE_RATE;\n const outLen = ratio <= 1 ? samples.length : Math.floor(samples.length / ratio);\n const out = new Int16Array(outLen);\n for (let i = 0; i < outLen; i++) {\n let v: number;\n if (ratio <= 1) {\n v = samples[i]!;\n } else {\n const start = Math.floor(i * ratio);\n const end = Math.min(samples.length, Math.max(start + 1, Math.floor((i + 1) * ratio)));\n let sum = 0;\n for (let j = start; j < end; j++) sum += samples[j]!;\n v = sum / (end - start);\n }\n out[i] = Math.max(-32768, Math.min(32767, Math.round(v * 32767)));\n }\n return out;\n}\n\n/** Root-mean-square level of a Float32 frame (0..1) — the barge-in speech gate. */\nexport function rmsLevel(samples: Float32Array): number {\n if (samples.length === 0) return 0;\n let sum = 0;\n for (let i = 0; i < samples.length; i++) sum += samples[i]! * samples[i]!;\n return Math.sqrt(sum / samples.length);\n}\n\n// ──────────────────────────── Injectable seams ──────────────────────────────\n\n/** The subset of WebSocket the session needs (mockable in tests). */\nexport interface VoiceWebSocket {\n binaryType: string;\n readyState: number;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n addEventListener(type: 'open' | 'message' | 'close' | 'error', fn: (ev: never) => void): void;\n}\n\n/** Playback sink for incoming 16 kHz PCM chunks (mockable in tests). */\nexport interface VoicePlayer {\n /** Queue a linear16 chunk for gapless playback. */\n enqueue(chunk: ArrayBuffer): void;\n /** Stop everything queued/playing immediately (barge-in). */\n flush(): void;\n /** Flush + release the audio device. */\n close(): void;\n}\n\n/**\n * Start mic capture, invoking `onFrame(samples, sampleRate)` with raw Float32\n * frames until the returned stop function is called.\n */\nexport type StartCapture = (onFrame: (samples: Float32Array, sampleRate: number) => void) => Promise<() => void>;\n\nexport interface VoiceSessionSeams {\n createWebSocket?: (url: string) => VoiceWebSocket;\n startCapture?: StartCapture;\n createPlayer?: () => VoicePlayer;\n}\n\n// ─────────────────────── Default (real-browser) seams ───────────────────────\n\n/**\n * The minimal AudioContext surface {@link PcmPlayer} uses — injectable so the\n * scheduling/flush logic is unit-testable without real audio hardware.\n */\nexport interface PlayerAudioContext {\n readonly currentTime: number;\n readonly destination: unknown;\n createBuffer(channels: number, length: number, sampleRate: number): { getChannelData(channel: number): Float32Array };\n createBufferSource(): {\n buffer: unknown;\n connect(dest: unknown): void;\n start(when?: number): void;\n stop(): void;\n onended: (() => void) | null;\n };\n close?(): Promise<void>;\n}\n\n/**\n * Gapless PCM playback: each incoming linear16 chunk becomes an AudioBuffer\n * scheduled back-to-back (`nextTime`) so consecutive chunks butt together with\n * no gaps. `flush()` stops every scheduled source (barge-in / mic-button stop).\n */\nexport class PcmPlayer implements VoicePlayer {\n private nextTime = 0;\n private readonly live = new Set<ReturnType<PlayerAudioContext['createBufferSource']>>();\n\n constructor(private readonly ctx: PlayerAudioContext) {}\n\n enqueue(chunk: ArrayBuffer): void {\n const int16 = new Int16Array(chunk);\n if (int16.length === 0) return;\n const buf = this.ctx.createBuffer(1, int16.length, VOICE_SAMPLE_RATE);\n const ch = buf.getChannelData(0);\n for (let i = 0; i < int16.length; i++) ch[i] = int16[i]! / 32768;\n const src = this.ctx.createBufferSource();\n src.buffer = buf;\n src.connect(this.ctx.destination);\n const start = Math.max(this.ctx.currentTime, this.nextTime);\n src.start(start);\n this.nextTime = start + int16.length / VOICE_SAMPLE_RATE;\n this.live.add(src);\n src.onended = () => this.live.delete(src);\n }\n\n flush(): void {\n for (const src of this.live) {\n try {\n src.stop();\n } catch {\n /* already stopped */\n }\n }\n this.live.clear();\n this.nextTime = 0;\n }\n\n close(): void {\n this.flush();\n void this.ctx.close?.();\n }\n}\n\n/** AudioWorklet processor source — posts each 128-sample mic block to the main thread. */\nconst CAPTURE_WORKLET_SRC = `\nregisterProcessor('sac-mic-capture', class extends AudioWorkletProcessor {\n process(inputs) {\n const ch = inputs[0] && inputs[0][0];\n if (ch && ch.length > 0) {\n const copy = new Float32Array(ch);\n this.port.postMessage(copy.buffer, [copy.buffer]);\n }\n return true;\n }\n});\n`;\n\n/** Real mic capture: getUserMedia → AudioWorklet (or ScriptProcessor fallback). */\nconst defaultStartCapture: StartCapture = async (onFrame) => {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },\n });\n const Ctx = (globalThis as { AudioContext?: typeof AudioContext }).AudioContext;\n if (!Ctx) {\n stream.getTracks().forEach((t) => t.stop());\n throw new Error('AudioContext is not available');\n }\n const ctx = new Ctx();\n const sampleRate = ctx.sampleRate;\n const source = ctx.createMediaStreamSource(stream);\n let disconnectNode: () => void;\n if (ctx.audioWorklet && typeof AudioWorkletNode === 'function') {\n const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET_SRC], { type: 'text/javascript' }));\n try {\n await ctx.audioWorklet.addModule(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n const node = new AudioWorkletNode(ctx, 'sac-mic-capture');\n node.port.onmessage = (ev: MessageEvent<ArrayBuffer>) => onFrame(new Float32Array(ev.data), sampleRate);\n source.connect(node);\n disconnectNode = () => node.disconnect();\n } else {\n // ponytail: deprecated ScriptProcessor fallback for browsers without AudioWorklet\n const node = ctx.createScriptProcessor(4096, 1, 1);\n node.onaudioprocess = (ev) => onFrame(new Float32Array(ev.inputBuffer.getChannelData(0)), sampleRate);\n source.connect(node);\n node.connect(ctx.destination); // ScriptProcessor only fires while connected\n disconnectNode = () => node.disconnect();\n }\n return () => {\n disconnectNode();\n source.disconnect();\n stream.getTracks().forEach((t) => t.stop());\n void ctx.close();\n };\n};\n\nconst defaultCreatePlayer = (): VoicePlayer => {\n const Ctx = (globalThis as { AudioContext?: new (opts?: { sampleRate?: number }) => AudioContext }).AudioContext;\n if (!Ctx) throw new Error('AudioContext is not available');\n return new PcmPlayer(new Ctx({ sampleRate: VOICE_SAMPLE_RATE }) as unknown as PlayerAudioContext);\n};\n\n// ────────────────────────────── VoiceSession ────────────────────────────────\n\nexport interface VoiceSessionOptions {\n /** Full browser-voice WS endpoint (default {@link DEFAULT_VOICE_URL}). */\n url?: string;\n /** UUID of the agent to talk to. */\n agentId: string;\n /** Existing conversation id so voice resumes the same thread. */\n conversationId?: string;\n /** Optional JWT for authenticated contexts (public agents auth by Origin). */\n token?: string;\n /**\n * RMS level (0..1) above which a mic frame counts as speech for barge-in\n * while the agent is speaking. Default 0.02 — comfortably above room noise\n * post-AGC, well below speech.\n */\n bargeInThreshold?: number;\n /** Injectable browser seams (tests). */\n seams?: VoiceSessionSeams;\n}\n\nexport interface VoiceSessionEvents {\n onTranscriptPartial?: (text: string) => void;\n onTranscriptFinal?: (text: string) => void;\n onReplyText?: (text: string) => void;\n /** Agent TTS started/stopped playing. */\n onSpeaking?: (speaking: boolean) => void;\n onError?: (code: string) => void;\n /** The session is over (stop, server close, handoff, or error). Fires once. */\n onEnded?: () => void;\n}\n\nexport type VoiceSessionState = 'idle' | 'connecting' | 'active' | 'ended';\n\nexport class VoiceSession {\n private readonly opts: VoiceSessionOptions;\n private readonly events: VoiceSessionEvents;\n private ws: VoiceWebSocket | null = null;\n private player: VoicePlayer | null = null;\n private stopCapture: (() => void) | null = null;\n private speaking = false;\n private ended = false;\n state: VoiceSessionState = 'idle';\n\n constructor(opts: VoiceSessionOptions, events: VoiceSessionEvents = {}) {\n this.opts = opts;\n this.events = events;\n }\n\n /** Open the WS, send the start frame, and begin streaming mic audio. */\n async start(): Promise<void> {\n if (this.state !== 'idle') return;\n this.state = 'connecting';\n const url = this.opts.url ?? DEFAULT_VOICE_URL;\n const createWs = this.opts.seams?.createWebSocket ?? ((u: string) => new WebSocket(u) as unknown as VoiceWebSocket);\n const startCapture = this.opts.seams?.startCapture ?? defaultStartCapture;\n const createPlayer = this.opts.seams?.createPlayer ?? defaultCreatePlayer;\n\n // Mic permission FIRST — if the visitor denies it, no socket ever opens.\n this.stopCapture = await startCapture((samples, rate) => this.handleMicFrame(samples, rate));\n try {\n this.player = createPlayer();\n const ws = createWs(url);\n ws.binaryType = 'arraybuffer';\n this.ws = ws;\n ws.addEventListener('open', () => {\n const start: Record<string, unknown> = { type: 'start', agent_id: this.opts.agentId };\n if (this.opts.conversationId) start.conversation_id = this.opts.conversationId;\n if (this.opts.token) start.token = this.opts.token;\n ws.send(JSON.stringify(start));\n this.state = 'active';\n });\n ws.addEventListener('message', (ev: MessageEvent) => this.handleServerFrame(ev.data as string | ArrayBuffer));\n ws.addEventListener('close', () => this.teardown());\n ws.addEventListener('error', () => {\n this.events.onError?.('connection_error');\n this.teardown();\n });\n } catch (err) {\n this.teardown();\n throw err;\n }\n }\n\n /** One raw mic frame: barge-in check, then downsample → binary frame. */\n private handleMicFrame(samples: Float32Array, sampleRate: number): void {\n const ws = this.ws;\n if (!ws || ws.readyState !== 1 /* OPEN */ || this.state !== 'active') return;\n // Barge-in: the visitor speaking over the agent's TTS interrupts it.\n if (this.speaking && rmsLevel(samples) > (this.opts.bargeInThreshold ?? 0.02)) {\n this.interrupt();\n }\n const pcm = downsampleTo16k(samples, sampleRate);\n ws.send(pcm.buffer as ArrayBuffer);\n }\n\n /** Route a server frame: binary = TTS audio, string = JSON control event. */\n private handleServerFrame(data: string | ArrayBuffer): void {\n if (typeof data !== 'string') {\n this.player?.enqueue(data);\n return;\n }\n let msg: { type?: string; text?: string; code?: string };\n try {\n msg = JSON.parse(data) as typeof msg;\n } catch {\n return; // not ours — ignore\n }\n switch (msg.type) {\n case 'transcript_partial':\n this.events.onTranscriptPartial?.(msg.text ?? '');\n break;\n case 'transcript_final':\n this.events.onTranscriptFinal?.(msg.text ?? '');\n break;\n case 'reply_text':\n this.events.onReplyText?.(msg.text ?? '');\n break;\n case 'speaking_started':\n this.setSpeaking(true);\n break;\n case 'speaking_done':\n this.setSpeaking(false);\n break;\n case 'handoff':\n // The agent handed the caller off — voice is over; back to text.\n this.stop();\n break;\n case 'error':\n this.events.onError?.(msg.code ?? 'unknown');\n this.stop();\n break;\n default:\n break;\n }\n }\n\n private setSpeaking(speaking: boolean): void {\n if (this.speaking === speaking) return;\n this.speaking = speaking;\n this.events.onSpeaking?.(speaking);\n }\n\n /** True while agent TTS is playing (between speaking_started/done). */\n get isSpeaking(): boolean {\n return this.speaking;\n }\n\n /**\n * Barge in: tell the server the user interrupted and flush queued TTS so the\n * agent goes silent immediately. Called automatically on mic speech during\n * playback; the widget also calls it when the visitor hits the mic button\n * mid-playback.\n */\n interrupt(): void {\n if (this.ws && this.ws.readyState === 1) {\n this.ws.send(JSON.stringify({ type: 'interrupt' }));\n }\n this.player?.flush();\n this.setSpeaking(false);\n }\n\n /** Graceful end: send `stop`, then tear everything down. */\n stop(): void {\n if (this.ws && this.ws.readyState === 1) {\n try {\n this.ws.send(JSON.stringify({ type: 'stop' }));\n } catch {\n /* socket already going down */\n }\n }\n this.teardown();\n }\n\n /** Idempotent teardown: capture, playback, socket, `ended` event. */\n private teardown(): void {\n if (this.ended) return;\n this.ended = true;\n this.state = 'ended';\n this.stopCapture?.();\n this.stopCapture = null;\n this.player?.close();\n this.player = null;\n const ws = this.ws;\n this.ws = null;\n if (ws && ws.readyState <= 1) {\n try {\n ws.close(1000, 'voice ended');\n } catch {\n /* already closed */\n }\n }\n this.setSpeaking(false);\n this.events.onEnded?.();\n }\n}\n","/**\n * Public configuration surface for the chat widget.\n *\n * A host page configures the widget either declaratively (HTML attributes on the\n * `<smooth-agent-chat>` element) or programmatically (passing this object to\n * {@link mountChatWidget} / `element.configure(...)`).\n */\nimport { safeHttpUrl } from './markdown.js';\nimport { DEFAULT_VOICE_URL } from './voice-session.js';\n\n/**\n * Browser voice input/output (SMOODEV-2534). OFF by default — when disabled the\n * widget renders zero voice UI. When enabled, a mic toggle appears in the\n * composer and speech flows over the browser-voice WebSocket.\n */\nexport interface ChatWidgetVoiceConfig {\n /** Turn the voice feature on. Default `false`. */\n enabled?: boolean;\n /** Browser-voice WS endpoint. Defaults to the hosted SmooAI voice service. */\n url?: string;\n}\n\nexport interface ChatWidgetTheme {\n /** Foreground text color for the widget chrome. */\n text?: string;\n /** Panel background color. */\n background?: string;\n /** Primary accent (launcher button, send button, outbound bubble). */\n primary?: string;\n /** Text color rendered on top of `primary`. */\n primaryText?: string;\n /** A secondary accent (used for subtle highlights). */\n secondary?: string;\n /** Inbound (assistant) chat bubble background. */\n assistantBubble?: string;\n /** Inbound (assistant) chat bubble text color. */\n assistantBubbleText?: string;\n /** Outbound (user) chat bubble background. Defaults to `primary`. */\n userBubble?: string;\n /** Outbound (user) chat bubble text color. Defaults to `primaryText`. */\n userBubbleText?: string;\n /** Border color for the panel and input. */\n border?: string;\n\n // ── Aliases for the dashboard's 10-color model (SmooAI agent widget config).\n // When provided, these take precedence over the canonical keys above, so a\n // config exported from the agent dashboard themes the widget directly.\n /** Alias for {@link assistantBubble}. */\n chatBubbleInbound?: string;\n /** Alias for {@link assistantBubbleText}. */\n chatBubbleInboundText?: string;\n /** Alias for {@link userBubble}. */\n chatBubbleOutbound?: string;\n /** Alias for {@link userBubbleText}. */\n chatBubbleOutboundText?: string;\n}\n\n/**\n * Layout mode for the widget.\n *\n * - `\"popover\"` (default) — the embeddable launcher bubble + floating panel.\n * - `\"fullpage\"` — no launcher; the chat fills its container/viewport with a\n * branded header, a scrollable message list, and an input bar. Ideal for a\n * dedicated support page (`/chat`, a docs site sidebar, an iframe, …).\n */\nexport type ChatWidgetMode = 'popover' | 'fullpage';\n\nexport interface ChatWidgetConfig {\n /**\n * smooth-operator WebSocket endpoint, e.g.\n * `ws://localhost:8787/ws` (local dev) or your deployed `wss://…/ws` URL.\n */\n endpoint: string;\n /**\n * Layout mode — `\"popover\"` (default, launcher + floating panel) or\n * `\"fullpage\"` (chat fills its container; no launcher). See {@link ChatWidgetMode}.\n */\n mode?: ChatWidgetMode;\n /** UUID of the agent to start a conversation session with. */\n agentId: string;\n /** Display name for the agent (header label). Defaults to \"Assistant\". */\n agentName?: string;\n /**\n * Brand logo shown in the full-page header avatar tile; falls back to the\n * Smooth icon. SECURITY: only absolute `http(s)` URLs are honored — any other\n * scheme (`javascript:`/`data:`/…) is ignored, so a hostile config can't\n * inject script.\n */\n logoUrl?: string;\n /** Optional display name for the user participant. */\n userName?: string;\n /** Optional email address for the user participant. */\n userEmail?: string;\n /** Optional phone number for the user participant (passed via session metadata). */\n userPhone?: string;\n /**\n * Optional pre-auth HMAC context. When the host page has a shared secret with\n * the agent, it can sign `{ userId, signature, timestamp }` so the chat-ws\n * wrapper's `/internal/*` identity routes (and the WS create path) verify the\n * caller without an OTP round-trip (ADR-046/ADR-048). Passed through verbatim.\n */\n authContext?: { userId: string; signature: string; timestamp: number };\n /** Placeholder text for the message input. */\n placeholder?: string;\n /** Greeting rendered when the conversation opens (before any messages). */\n greeting?: string;\n /** Message shown when the connection cannot be (re)established. */\n connectionErrorMessage?: string;\n /** Start the panel open instead of collapsed to the launcher. */\n startOpen?: boolean;\n /**\n * Hide the \"powered by smooth-operator\" branding in the header tag and the\n * composer footer. Defaults to `false` (branding shown). The `hide-branding`\n * HTML attribute maps to this.\n */\n hideBranding?: boolean;\n /**\n * Suggested starter prompts shown as clickable chips before the first message.\n * Clicking one sends it. Capped at 5 for layout.\n */\n examplePrompts?: string[];\n /**\n * Show mid-conversation suggested-reply chips (\"quick replies\") under the\n * latest assistant message when the agent returns follow-up suggestions.\n * Clicking one sends it. Defaults to `true` (shown unless explicitly `false`).\n */\n showSuggestedReplies?: boolean;\n /** Require the visitor's name before chatting. */\n requireName?: boolean;\n /** Require the visitor's email before chatting. */\n requireEmail?: boolean;\n /** Require the visitor's phone before chatting. */\n requirePhone?: boolean;\n /**\n * Show the phone field on the pre-chat form (optional unless {@link requirePhone}).\n * Defaults to `true` for this widget — phone rides the session metadata as\n * `userPhone` so the agent can follow up by SMS. Set `false` to hide it.\n */\n collectPhone?: boolean;\n /**\n * Show the email + SMS marketing-consent checkboxes on the pre-chat form.\n * Explicit opt-in, default UNCHECKED; a `consentAt` timestamp is stamped when\n * a box is ticked. Defaults to `true`. The consent record is threaded into the\n * session metadata (ADR-048).\n */\n collectConsent?: boolean;\n /**\n * Offer the cross-device \"Restore my chats\" affordance — an explicit link that\n * runs the identity-OTP → resolve → replay flow. Defaults to `true`.\n */\n allowChatRestore?: boolean;\n /**\n * Let visitors chat without providing any identity. When `true`, the\n * `require*` flags are ignored and the pre-chat form is skipped.\n */\n allowAnonymous?: boolean;\n /**\n * Show the agent's tool activity (grep / read_file / bash / knowledge_search…)\n * as inline chips interleaved with its prose, mirroring the smooth daemon SPA.\n *\n * Defaults to **`false`**: for a customer-facing support widget, surfacing raw\n * tool calls to an end-user is usually undesirable, so tool activity is hidden\n * and only the assistant's prose renders. Enable it for internal / power-user\n * surfaces where seeing what the agent did mid-turn is valuable.\n */\n showToolActivity?: boolean;\n /** Browser voice input/output. OFF by default (zero UI when off). */\n voice?: ChatWidgetVoiceConfig;\n /** Theme overrides. */\n theme?: ChatWidgetTheme;\n}\n\n/** The fully-resolved theme (canonical keys only — aliases are folded in). */\nexport type ResolvedTheme = Required<Omit<ChatWidgetTheme, 'chatBubbleInbound' | 'chatBubbleInboundText' | 'chatBubbleOutbound' | 'chatBubbleOutboundText'>>;\n\nexport type ResolvedConfig = Required<Omit<ChatWidgetConfig, 'theme' | 'userName' | 'userEmail' | 'userPhone' | 'authContext' | 'logoUrl' | 'voice'>> & {\n theme: ResolvedTheme;\n voice: { enabled: boolean; url: string };\n userName?: string;\n userEmail?: string;\n userPhone?: string;\n authContext?: { userId: string; signature: string; timestamp: number };\n /** Sanitized brand logo URL (`http(s)` only) or `undefined` — see {@link ChatWidgetConfig.logoUrl}. */\n logoUrl?: string;\n};\n\n/** Resolve a partial config against the built-in defaults. */\nexport function resolveConfig(config: ChatWidgetConfig): ResolvedConfig {\n const theme = config.theme ?? {};\n const primary = theme.primary ?? '#00a6a6';\n const primaryText = theme.primaryText ?? '#f8fafc';\n // Dashboard aliases win over canonical keys when present.\n const assistantBubble = theme.chatBubbleInbound ?? theme.assistantBubble ?? '#06134b';\n const assistantBubbleText = theme.chatBubbleInboundText ?? theme.assistantBubbleText ?? '#f8fafc';\n const userBubble = theme.chatBubbleOutbound ?? theme.userBubble ?? primary;\n const userBubbleText = theme.chatBubbleOutboundText ?? theme.userBubbleText ?? primaryText;\n return {\n endpoint: config.endpoint,\n mode: config.mode ?? 'popover',\n agentId: config.agentId,\n agentName: config.agentName ?? 'Assistant',\n // Only absolute http(s) URLs survive — anything else (javascript:/data:/\n // relative) is dropped so the header can never render a hostile logo src.\n logoUrl: safeHttpUrl(config.logoUrl) ?? undefined,\n userName: config.userName,\n userEmail: config.userEmail,\n userPhone: config.userPhone,\n authContext: config.authContext,\n placeholder: config.placeholder ?? 'Type a message…',\n greeting: config.greeting ?? 'Hi! How can I help you today?',\n connectionErrorMessage: config.connectionErrorMessage ?? \"We couldn't reach the chat. Please try again in a moment.\",\n startOpen: config.startOpen ?? false,\n hideBranding: config.hideBranding ?? false,\n examplePrompts: (config.examplePrompts ?? []).filter((p) => p.trim().length > 0).slice(0, 5),\n showSuggestedReplies: config.showSuggestedReplies ?? true,\n requireName: config.requireName ?? false,\n requireEmail: config.requireEmail ?? false,\n requirePhone: config.requirePhone ?? false,\n collectPhone: config.collectPhone ?? true,\n collectConsent: config.collectConsent ?? true,\n allowChatRestore: config.allowChatRestore ?? true,\n allowAnonymous: config.allowAnonymous ?? false,\n showToolActivity: config.showToolActivity ?? false,\n voice: { enabled: config.voice?.enabled ?? false, url: config.voice?.url ?? DEFAULT_VOICE_URL },\n theme: {\n text: theme.text ?? '#f8fafc',\n background: theme.background ?? '#040d30',\n primary,\n primaryText,\n secondary: theme.secondary ?? '#ff6b6c',\n assistantBubble,\n assistantBubbleText,\n userBubble,\n userBubbleText,\n border: theme.border ?? 'rgba(255, 255, 255, 0.1)',\n },\n };\n}\n\n/**\n * Whether the pre-chat identity form should gate the conversation: at least one\n * field is required and anonymous chat is not allowed.\n */\nexport function needsUserInfo(resolved: ResolvedConfig): boolean {\n return !resolved.allowAnonymous && (resolved.requireName || resolved.requireEmail || resolved.requirePhone);\n}\n","/**\n * Browser fingerprint — a stable, privacy-light identifier used by the\n * smooth-operator server to correlate an anonymous visitor's sessions across\n * page loads (and, server-side, to match an anonymous fingerprint to a known\n * CRM contact). It rides every `create_conversation_session` as\n * `browserFingerprint` (see ADR-048).\n *\n * ## Why not ThumbmarkJS\n *\n * The ADR floats ThumbmarkJS as the reference implementation. For an *embed*\n * that is injected onto arbitrary host pages, ThumbmarkJS is too heavy: its\n * full build pulls in extensive device-detection tables and async\n * component collection, adding tens of kilobytes (and async surface) to a\n * bundle whose whole selling point is staying out of the host page's\n * LCP/TBT budget. The fingerprint here is a few hundred bytes.\n *\n * ## What this is (and the tradeoff)\n *\n * The correlation that actually matters — \"is this the same browser as last\n * time?\" — is carried by a **persisted random UUID** (the `browserFingerprint`\n * field in the persisted store). That UUID is generated once and reused for\n * the life of the localStorage entry, so same-browser resume is exact and\n * deterministic. The signal hash below is a best-effort entropy *supplement*\n * mixed into that UUID's derivation seed on first generation — it gives the\n * server-side resolver a soft signal for the (rare) cross-storage case where\n * the UUID was cleared but the device is unchanged. It is intentionally NOT a\n * high-entropy device fingerprint: no canvas/WebGL/audio probes, no font\n * enumeration, nothing that reads as invasive tracking. The tradeoff is weaker\n * cross-storage matching in exchange for a tiny, transparent, no-network,\n * XSS-safe implementation. The server's resolver (SMOODEV-2129d) is the source\n * of truth for any fuzzy matching; the client just supplies a stable token.\n */\n\n/** Collect a small set of stable, non-invasive browser signals. */\nfunction collectSignals(): string {\n const parts: string[] = [];\n try {\n const nav = typeof navigator !== 'undefined' ? navigator : undefined;\n if (nav) {\n parts.push(`ua:${nav.userAgent ?? ''}`);\n parts.push(`lang:${nav.language ?? ''}`);\n parts.push(`langs:${Array.isArray(nav.languages) ? nav.languages.join(',') : ''}`);\n // `platform` is deprecated but still widely present and stable.\n parts.push(`plat:${(nav as Navigator & { platform?: string }).platform ?? ''}`);\n parts.push(`hc:${(nav as Navigator & { hardwareConcurrency?: number }).hardwareConcurrency ?? ''}`);\n parts.push(`dm:${(nav as Navigator & { deviceMemory?: number }).deviceMemory ?? ''}`);\n }\n if (typeof screen !== 'undefined') {\n parts.push(`scr:${screen.width}x${screen.height}x${screen.colorDepth}`);\n }\n if (typeof Intl !== 'undefined') {\n try {\n parts.push(`tz:${Intl.DateTimeFormat().resolvedOptions().timeZone ?? ''}`);\n } catch {\n /* resolvedOptions can throw in locked-down environments */\n }\n }\n parts.push(`tzo:${new Date().getTimezoneOffset()}`);\n } catch {\n /* a hostile/locked-down navigator must never break widget boot */\n }\n return parts.join('|');\n}\n\n/**\n * A small, fast, non-cryptographic string hash (FNV-1a, 32-bit) rendered as\n * an unsigned hex string. Stable across runs for the same input. Not used for\n * any security decision — only to derive a deterministic seed from the signal\n * string above.\n */\nfunction fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n // 32-bit FNV prime multiply via shifts to stay in int range.\n h = Math.imul(h, 0x01000193);\n }\n // >>> 0 → unsigned; pad to 8 hex chars.\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Generate a UUID, preferring `crypto.randomUUID`, falling back to a v4-shaped string. */\nfunction generateUuid(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through to the manual generator */\n }\n // RFC 4122 v4 shape from Math.random — only reached when crypto.randomUUID\n // is unavailable (very old engines). Sufficient for a correlation token.\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Compute a fresh fingerprint token: a stable random UUID, suffixed with the\n * FNV hash of the device signals so the server can recover a soft device\n * signal even if it only has the token. Called ONCE per browser (the result is\n * persisted and reused) — see {@link getOrCreateFingerprint}.\n */\nexport function computeFingerprint(): string {\n const signalHash = fnv1a(collectSignals());\n return `${generateUuid()}.${signalHash}`;\n}\n\n/**\n * Return the cached fingerprint if one was already computed for this browser,\n * otherwise compute + persist a new one via the provided accessors. The\n * persistence layer owns storage; this function owns the \"compute once\" policy.\n */\nexport function getOrCreateFingerprint(get: () => string | null, set: (fp: string) => void): string {\n const existing = get();\n if (existing) return existing;\n const fp = computeFingerprint();\n set(fp);\n return fp;\n}\n","/**\n * Persisted widget state — the identity / consent / session-pointer client layer\n * (ADR-048, SMOODEV-2129e).\n *\n * Built on Zustand's framework-agnostic `vanilla` store + the `persist`\n * middleware (the user explicitly chose Zustand; it's ~1KB and has no React\n * dependency, so it works inside the web component). The store is keyed per\n * agent — localStorage key `smoo-chat-widget:<agentId>` — so two agents embedded\n * on the same origin don't clobber each other.\n *\n * ## What persists (and, deliberately, what does NOT)\n *\n * Only a **pointer** to the conversation plus the visitor's identity + marketing\n * consent + verified email + browser fingerprint. The transcript is **never**\n * persisted: the smooth-operator server is the source of truth and the widget\n * re-hydrates history via `getMessages` on resume. This keeps localStorage small\n * and avoids stale/divergent transcripts.\n *\n * `version` drives `persist.migrate` so future shape changes can upgrade old\n * blobs in place instead of silently dropping them.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla';\nimport { persist, type PersistStorage } from 'zustand/middleware';\n\n/** Current persisted-shape version. Bump when the shape below changes incompatibly. */\nexport const PERSIST_VERSION = 1 as const;\n\n/** Marketing-consent record captured at the pre-chat form. */\nexport interface ConsentState {\n emailOptIn: boolean;\n smsOptIn: boolean;\n /** Where the consent was captured. The widget always stamps `chat-widget-prechat`. */\n consentSource?: string;\n /** ISO 8601 timestamp stamped when the visitor ticked a consent box. */\n consentAt?: string;\n}\n\n/** Visitor identity collected from config or the pre-chat form. */\nexport interface IdentityState {\n name?: string;\n email?: string;\n phone?: string;\n}\n\n/**\n * The exact persisted shape (ADR-048 §d). Only the pointer + identity + consent\n * persist — never the transcript.\n */\nexport interface PersistedWidgetState {\n version: typeof PERSIST_VERSION;\n /** Pointer to the active conversation session; cleared on ended/404. */\n sessionId: string | null;\n identity: IdentityState;\n consent: ConsentState;\n /**\n * Email proven via OTP for the CURRENT session. Session-scoped: cleared on\n * `clearSession()` so it can't leak across visitors on a shared browser, and\n * only threaded into session metadata when {@link verifiedEmailSessionId}\n * matches the live session (i.e. on resume of the verified session) — never\n * auto-stamped onto a brand-new session.\n */\n verifiedEmail: string | null;\n /** The sessionId the {@link verifiedEmail} was proven against (binds the proof to one session). */\n verifiedEmailSessionId: string | null;\n /** Stable per-browser correlation token (see fingerprint.ts). */\n browserFingerprint: string | null;\n}\n\n/** Store actions layered on top of the persisted state. */\nexport interface WidgetStoreActions {\n setSessionId: (sessionId: string | null) => void;\n /** Merge identity fields (undefined values don't clobber existing ones). */\n mergeIdentity: (identity: IdentityState) => void;\n /** Replace consent wholesale (the pre-chat form computes the full record). */\n setConsent: (consent: ConsentState) => void;\n /** Record an OTP-proven email bound to a specific session. */\n setVerifiedEmail: (email: string | null, sessionId?: string | null) => void;\n setBrowserFingerprint: (fp: string) => void;\n /**\n * Clear the session pointer (and the session-scoped `verifiedEmail` proof) but\n * KEEP identity / consent / fingerprint — used when a persisted session has\n * ended or 404s so the next turn starts a fresh session for a known visitor.\n * `verifiedEmail` is deliberately cleared here: it is a per-session OTP proof,\n * not a durable identity, so it must NOT survive onto a new session (which on a\n * shared browser could be a different visitor).\n */\n clearSession: () => void;\n}\n\nexport type WidgetStore = PersistedWidgetState & WidgetStoreActions;\n\nconst EMPTY_CONSENT: ConsentState = { emailOptIn: false, smsOptIn: false };\n\nfunction initialPersisted(): PersistedWidgetState {\n return {\n version: PERSIST_VERSION,\n sessionId: null,\n identity: {},\n consent: { ...EMPTY_CONSENT },\n verifiedEmail: null,\n verifiedEmailSessionId: null,\n browserFingerprint: null,\n };\n}\n\n/** localStorage key for an agent's persisted widget state. */\nexport function storageKey(agentId: string): string {\n return `smoo-chat-widget:${agentId}`;\n}\n\n/**\n * An explicit in-memory (Map-backed) `PersistStorage`. Used as the fallback when\n * real localStorage is unavailable.\n *\n * IMPORTANT: we must NOT return `undefined` from {@link safeStorage} in that case.\n * zustand v5's `persist` treats a missing `storage` option by falling back to its\n * OWN `createJSONStorage(() => localStorage)` — i.e. it re-engages the very\n * localStorage the guard was trying to avoid (throwing again in privacy mode).\n * Handing it this no-op storage keeps the store working purely in memory and\n * guarantees the fallback can't touch real localStorage.\n */\nfunction memoryStorage(): PersistStorage<PersistedWidgetState> {\n const mem = new Map<string, string>();\n return {\n getItem: (name) => {\n const raw = mem.get(name);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ReturnType<PersistStorage<PersistedWidgetState>['getItem']>;\n } catch {\n return null;\n }\n },\n setItem: (name, value) => {\n mem.set(name, JSON.stringify(value));\n },\n removeItem: (name) => {\n mem.delete(name);\n },\n };\n}\n\n/**\n * A `persist` storage adapter that tolerates the *absence* of localStorage\n * (SSR, privacy-mode throwing on access, sandboxed iframes). When storage is\n * unavailable the store still works in-memory; nothing is persisted, but the\n * widget never throws on boot.\n */\nfunction safeStorage(): PersistStorage<PersistedWidgetState> {\n let ls: Storage | null = null;\n try {\n ls = typeof localStorage !== 'undefined' ? localStorage : null;\n // Probe: some environments expose localStorage but throw on access.\n if (ls) {\n const probe = '__smoo_probe__';\n ls.setItem(probe, '1');\n ls.removeItem(probe);\n }\n } catch {\n ls = null;\n }\n // Fall back to an explicit in-memory store — NEVER `undefined` (see memoryStorage).\n if (!ls) return memoryStorage();\n const storage = ls;\n return {\n getItem: (name) => {\n try {\n const raw = storage.getItem(name);\n return raw ? (JSON.parse(raw) as ReturnType<PersistStorage<PersistedWidgetState>['getItem']>) : null;\n } catch {\n return null;\n }\n },\n setItem: (name, value) => {\n try {\n storage.setItem(name, JSON.stringify(value));\n } catch {\n /* quota / privacy-mode write failures are non-fatal */\n }\n },\n removeItem: (name) => {\n try {\n storage.removeItem(name);\n } catch {\n /* non-fatal */\n }\n },\n };\n}\n\n/**\n * Migrate a persisted blob from an older `version` to the current shape. Today\n * v1 is the only version, so this just backfills any missing fields onto an\n * unknown old blob; future versions add `case` branches here.\n */\nfunction migrate(persisted: unknown): PersistedWidgetState {\n const base = initialPersisted();\n if (!persisted || typeof persisted !== 'object') return base;\n const p = persisted as Partial<PersistedWidgetState>;\n return {\n version: PERSIST_VERSION,\n sessionId: typeof p.sessionId === 'string' ? p.sessionId : null,\n identity: {\n name: typeof p.identity?.name === 'string' ? p.identity.name : undefined,\n email: typeof p.identity?.email === 'string' ? p.identity.email : undefined,\n phone: typeof p.identity?.phone === 'string' ? p.identity.phone : undefined,\n },\n consent: {\n emailOptIn: p.consent?.emailOptIn === true,\n smsOptIn: p.consent?.smsOptIn === true,\n consentSource: typeof p.consent?.consentSource === 'string' ? p.consent.consentSource : undefined,\n consentAt: typeof p.consent?.consentAt === 'string' ? p.consent.consentAt : undefined,\n },\n verifiedEmail: typeof p.verifiedEmail === 'string' ? p.verifiedEmail : null,\n verifiedEmailSessionId: typeof p.verifiedEmailSessionId === 'string' ? p.verifiedEmailSessionId : null,\n browserFingerprint: typeof p.browserFingerprint === 'string' ? p.browserFingerprint : null,\n };\n}\n\n/**\n * Create the per-agent persisted Zustand store. The `partialize` step ensures\n * only the persisted shape (never any future transient action/UI state) is\n * written to localStorage.\n */\nexport function createWidgetStore(agentId: string): StoreApi<WidgetStore> {\n return createStore<WidgetStore>()(\n persist(\n (set) => ({\n ...initialPersisted(),\n setSessionId: (sessionId) => set({ sessionId }),\n mergeIdentity: (identity) =>\n set((state) => ({\n identity: {\n ...state.identity,\n ...(identity.name !== undefined ? { name: identity.name } : {}),\n ...(identity.email !== undefined ? { email: identity.email } : {}),\n ...(identity.phone !== undefined ? { phone: identity.phone } : {}),\n },\n })),\n setConsent: (consent) => set({ consent: { ...consent } }),\n setVerifiedEmail: (verifiedEmail, sessionId) =>\n set((state) => ({\n verifiedEmail,\n // Bind the proof to the session it was verified against. When the\n // caller omits sessionId, fall back to the live pointer so the\n // proof is never left unbound.\n verifiedEmailSessionId: verifiedEmail === null ? null : (sessionId ?? state.sessionId),\n })),\n setBrowserFingerprint: (browserFingerprint) => set({ browserFingerprint }),\n // Drop the pointer AND the session-scoped OTP proof; keep durable identity.\n clearSession: () => set({ sessionId: null, verifiedEmail: null, verifiedEmailSessionId: null }),\n }),\n {\n name: storageKey(agentId),\n version: PERSIST_VERSION,\n storage: safeStorage(),\n migrate,\n // Persist ONLY the data shape — never the action functions.\n partialize: (state): PersistedWidgetState => ({\n version: PERSIST_VERSION,\n sessionId: state.sessionId,\n identity: state.identity,\n consent: state.consent,\n verifiedEmail: state.verifiedEmail,\n verifiedEmailSessionId: state.verifiedEmailSessionId,\n browserFingerprint: state.browserFingerprint,\n }),\n },\n ),\n );\n}\n","/**\n * ConversationController — the bridge between the widget UI and the\n * `@smooai/smooth-operator` protocol client.\n *\n * This is the piece that was rewired: the original smooai widget spoke to\n * `@smooai/realtime`; here every protocol action goes through {@link SmoothAgentClient}.\n * The wire shapes are identical (the protocol was lifted from `@smooai/realtime`),\n * so the swap is purely at the client-library boundary.\n *\n * Flow:\n * 1. `connect()` → opens the WebSocket transport and `create_conversation_session`\n * (or RESUMES a persisted session via `get_session`/`get_messages`).\n * 2. `send(text)` → `send_message`, streaming `stream_token` deltas into the\n * in-progress assistant message, then the terminal\n * `eventual_response`.\n *\n * 0.7.0 (SMOODEV-2129e) adds the identity / persistence / consent client layer:\n * - `browserFingerprint` computed once + sent on every `create_conversation_session`.\n * - identity + marketing consent threaded into the session `metadata`.\n * - same-session RESUME on load (no engine change — `get_session` + `get_messages`).\n * - returning-visitor RESUME via `POST /internal/resume-by-fingerprint`, and\n * cross-device \"restore my chats\" via the `POST /internal/identity/{request-otp,\n * verify-otp,resolve}` routes on the chat-ws wrapper. The engine (smooth-operator\n * 1.8.0) owns the `/ws` dispatch and REJECTS unknown verbs, so these are HTTP\n * `fetch()` calls (origin-allowlisted + optional authContext, per ADR-046/048) —\n * NOT WS frames.\n *\n * The controller is UI-agnostic: it emits typed events and the view renders them.\n */\nimport { type Citation, ProtocolError, type ServerEvent, SmoothAgentClient } from '@smooai/smooth-operator';\nimport type { StoreApi } from 'zustand/vanilla';\nimport type { ChatWidgetConfig } from './config.js';\nimport { getOrCreateFingerprint } from './fingerprint.js';\nimport { type ConsentState, createWidgetStore, type WidgetStore } from './persistence.js';\n\n/**\n * Derive the HTTP base for the chat-ws wrapper's `/internal/*` REST routes from\n * the WS endpoint: `wss://ai.smoo.ai/ws` → `https://ai.smoo.ai`. The engine\n * (smooth-operator 1.8.0) owns the `/ws` dispatch and REJECTS unknown verbs, so\n * the cross-device identity flow + fingerprint resume are HTTP POST routes on the\n * wrapper (origin-allowlisted + authContext, per ADR-046/ADR-048) — NOT WS frames.\n */\nexport function httpBaseFromWsEndpoint(endpoint: string): string | null {\n try {\n const u = new URL(endpoint);\n u.protocol = u.protocol === 'ws:' ? 'http:' : u.protocol === 'wss:' ? 'https:' : u.protocol;\n // The REST routes live at the host root (`/internal/*`), not under `/ws`.\n return `${u.protocol}//${u.host}`;\n } catch {\n // FAIL LOUD on a non-absolute endpoint. A relative fallback (e.g.\n // `string.replace`) would yield a relative base, and `fetch(\\`${base}/internal/...\\`)`\n // would then POST identity/OTP data to the HOST page origin (e.g. smoo.ai)\n // instead of the operator host (ai.smoo.ai) — leaking it to the wrong origin.\n // Returning null forces the controller into an error state and refuses the\n // `/internal/*` calls rather than mis-targeting them.\n return null;\n }\n}\n\nexport type { Citation };\n\nexport type Role = 'user' | 'assistant';\n\n/**\n * One tool invocation within an assistant turn. Mirrors the smooth daemon SPA's\n * `ToolCall` (`crates/smooth-web/web/src/operator.ts`): opens `done: false` on the\n * tool call and resolves on the tool result.\n */\nexport interface ToolCall {\n /** Stable id for keyed rendering (assigned when the call opens). */\n id: string;\n name: string;\n /** Raw arguments, JSON-stringified. */\n args: string;\n /** Present once the tool resolves. */\n result?: string;\n isError?: boolean;\n done: boolean;\n}\n\n/**\n * One ordered segment of an assistant turn: a run of prose, or a tool call.\n * Preserves the interleave order the model produced (say a bit → call a tool →\n * say a bit → …) so the UI can render tool chips INLINE where the model called\n * them. Mirrors the daemon SPA's `MessageBlock`. Only populated when the widget\n * is configured with `showToolActivity: true`.\n */\nexport type MessageBlock = { kind: 'text'; text: string } | { kind: 'tool'; tool: ToolCall };\n\nexport interface ChatMessage {\n id: string;\n role: Role;\n /** Accumulated text (assistant messages grow as tokens stream in). */\n text: string;\n /** True while an assistant message is still streaming. */\n streaming: boolean;\n /**\n * Ordered text + tool segments, interleaved as the model produced them. Present\n * only on assistant messages when `showToolActivity` is enabled (absent\n * otherwise — the default popover renders `text` alone, byte-for-byte unchanged).\n */\n blocks?: MessageBlock[];\n /**\n * Sources that grounded an assistant answer, when the terminal\n * `eventual_response` carried any. Optional + back-compatible: absent when\n * the turn used no knowledge sources (or for user messages). Read\n * defensively off the terminal event — see {@link extractCitations}.\n */\n citations?: Citation[];\n /**\n * Suggested follow-up replies (\"quick replies\") the agent offered on the\n * terminal `eventual_response`. Set ONLY on the finalized assistant message —\n * never mid-stream. Read defensively (see {@link extractSuggestions}); capped\n * at 4 for layout. Absent when the turn offered none.\n */\n suggestions?: string[];\n}\n\nexport type ConnectionStatus = 'idle' | 'connecting' | 'ready' | 'error' | 'closed';\n\n/**\n * A mid-turn pause that needs the visitor to act before the agent can continue:\n *\n * - `otp` — the agent requested OTP verification before an authenticated action.\n * Resume with {@link ConversationController.verifyOtp}.\n * - `confirm` — the agent wants to run a state-mutating tool and needs approval.\n * Resume with {@link ConversationController.confirmTool}.\n * - `interaction` — the agent raised a Rich Interaction (structured card, e.g.\n * identity intake). Resume with {@link ConversationController.submitInteraction}\n * or {@link ConversationController.declineInteraction}.\n */\nexport type Interrupt =\n | {\n kind: 'otp';\n toolId?: string;\n actionDescription?: string;\n availableChannels: ('email' | 'sms')[];\n /** Set once the server confirms an OTP was dispatched. */\n sent?: { channel?: string; maskedDestination?: string };\n /** Set when a submitted code was rejected. */\n error?: string;\n attemptsRemaining?: number;\n }\n | { kind: 'confirm'; toolId?: string; actionDescription?: string }\n | {\n kind: 'interaction';\n /** Server-generated interaction instance id (echoed on submit). */\n interactionId: string;\n /** The Rich Interaction kind (e.g. `identity_intake`) — selects the card. */\n interactionKind: string;\n /** Kind-specific render spec (identity_intake: `{ fields: [...] }`). */\n spec: Record<string, unknown>;\n /** Why the agent raised it (card header copy). */\n reason?: string;\n /** Per-field server-side validation errors (from `interaction_invalid`). */\n errors?: { field: string; message: string }[];\n };\n\n/**\n * The Rich-Interaction render capabilities this widget declares at session\n * create (`supports`). Must stay aligned with the card registry in\n * `element.ts` (`INTERACTION_CARDS`) — registering a card IS declaring its\n * capability; a test asserts the two match.\n */\nexport const SUPPORTED_INTERACTION_CAPABILITIES: readonly string[] = ['identity_form'];\n\nexport interface UserInfo {\n name?: string;\n email?: string;\n phone?: string;\n /** Marketing-consent opt-ins captured at the pre-chat form (ADR-048). */\n consent?: { emailOptIn: boolean; smsOptIn: boolean };\n}\n\n/** One conversation surfaced by `resolve_identity` for the cross-device picker. */\nexport interface RestorableConversation {\n conversationId: string;\n sessionId: string;\n lastActivityAt?: string;\n preview?: string;\n}\n\n/**\n * State machine for the cross-device \"restore my chats\" flow. Driven by the three\n * HTTP POST routes on the chat-ws wrapper — `/internal/identity/request-otp` →\n * `/internal/identity/verify-otp` → `/internal/identity/resolve` (ADR-048 §c).\n * The view renders a panel off this.\n */\nexport type IdentityRestore =\n | { phase: 'idle' }\n /** UI-local: the email-entry step before any request is sent. */\n | { phase: 'awaiting_email'; error?: string }\n | { phase: 'requesting'; email: string; channel: 'email' | 'sms' }\n | { phase: 'awaiting_code'; email: string; channel: 'email' | 'sms'; maskedDestination?: string; error?: string; attemptsRemaining?: number }\n | { phase: 'verifying'; email: string; channel: 'email' | 'sms' }\n | { phase: 'resolving'; email: string }\n | { phase: 'resolved'; email: string; conversations: RestorableConversation[] }\n | { phase: 'error'; message: string };\n\nexport interface ConversationEvents {\n /** Fired whenever the message list changes (append, token delta, finalize). */\n onMessages: (messages: ChatMessage[]) => void;\n /** Fired on connection-status transitions. */\n onStatus: (status: ConnectionStatus, detail?: string) => void;\n /** Fired when a turn pauses for OTP / tool-confirmation, and `null` when it clears. */\n onInterrupt?: (interrupt: Interrupt | null) => void;\n /** Fired on cross-device identity-restore state transitions. */\n onIdentityRestore?: (state: IdentityRestore) => void;\n}\n\n/** Pull the final assistant text out of an `eventual_response` data payload. */\nfunction extractFinalText(response: unknown): string | null {\n if (!response || typeof response !== 'object') return null;\n const r = response as { responseParts?: unknown };\n if (Array.isArray(r.responseParts)) {\n return r.responseParts.filter((p): p is string => typeof p === 'string').join('\\n\\n');\n }\n return null;\n}\n\n/**\n * Pull the grounding {@link Citation}s out of a terminal `eventual_response`.\n *\n * The protocol client types these (`eventual_response.data.data.citations`),\n * but they're optional and back-compatible — absent when the turn used no\n * knowledge sources. We read them defensively (tolerating their total absence,\n * non-array shapes, and missing fields) so a server that doesn't emit them, or\n * an older client, can't break rendering. Each citation always carries\n * `id`/`title`/`snippet`/`score`; `url` is present only for web-sourced docs.\n */\nfunction extractCitations(inner: unknown): Citation[] {\n if (!inner || typeof inner !== 'object') return [];\n const raw = (inner as { citations?: unknown }).citations;\n if (!Array.isArray(raw)) return [];\n const out: Citation[] = [];\n for (const c of raw) {\n if (!c || typeof c !== 'object') continue;\n const obj = c as Record<string, unknown>;\n const id = typeof obj.id === 'string' ? obj.id : '';\n const title = typeof obj.title === 'string' ? obj.title : id || 'Source';\n const snippet = typeof obj.snippet === 'string' ? obj.snippet : '';\n const url = typeof obj.url === 'string' && obj.url ? obj.url : undefined;\n const score = typeof obj.score === 'number' ? obj.score : 0;\n out.push({ id, title, snippet, score, url });\n }\n return out;\n}\n\n/**\n * Pull the suggested follow-up replies out of a terminal `eventual_response`'s\n * `response` object (`response.suggestedNextActions`). Optional + back-compatible\n * like citations — read defensively (tolerating absence, non-array shapes, and\n * non-string / blank entries) and capped at 4 so a chatty agent can't overflow\n * the composer chip row.\n */\nfunction extractSuggestions(response: unknown): string[] {\n if (!response || typeof response !== 'object') return [];\n const raw = (response as { suggestedNextActions?: unknown }).suggestedNextActions;\n if (!Array.isArray(raw)) return [];\n return raw.filter((s): s is string => typeof s === 'string' && s.trim().length > 0).slice(0, 4);\n}\n\n/** A `get_conversation_messages` row, narrowed defensively off the wire. */\ninterface WireMessage {\n id?: string;\n direction?: 'inbound' | 'outbound';\n content?: { text?: string };\n createdAt?: string;\n}\n\n/** Convert a server message row into a finalized {@link ChatMessage}. */\nfunction wireMessageToChat(m: WireMessage, idx: number): ChatMessage | null {\n const text = typeof m.content?.text === 'string' ? m.content.text : '';\n if (!text) return null;\n const role: Role = m.direction === 'outbound' ? 'assistant' : 'user';\n return { id: typeof m.id === 'string' ? m.id : `hist-${idx}`, role, text, streaming: false };\n}\n\nlet toolSeq = 0;\nconst nextToolId = (): string => `tool-${++toolSeq}`;\n\n/** Grow the trailing text block, or open a new one if the last block was a tool. */\nfunction growTextBlock(blocks: MessageBlock[], text: string): void {\n if (!text) return;\n const last = blocks[blocks.length - 1];\n if (last && last.kind === 'text') last.text += text;\n else blocks.push({ kind: 'text', text });\n}\n\n/**\n * Fold a `stream_chunk` node-state into the ordered block list, returning `true`\n * when the chunk carried tool activity.\n *\n * Tool activity rides `state.rawResponse.toolCall` / `state.rawResponse.toolResult`\n * — **NOT** `state.toolResult`. Reading the wrong path leaves every chip stuck on\n * \"running…\" forever (the exact bug the daemon SPA hit and this mirror avoids).\n */\nfunction applyToolChunk(blocks: MessageBlock[], state: unknown): boolean {\n const raw = (state as { rawResponse?: unknown } | null | undefined)?.rawResponse;\n if (!raw || typeof raw !== 'object') return false;\n const call = (raw as { toolCall?: { name?: string; arguments?: unknown } }).toolCall;\n const res = (raw as { toolResult?: { name?: string; isError?: boolean; result?: unknown } }).toolResult;\n if (call) {\n const args = typeof call.arguments === 'string' ? call.arguments : JSON.stringify(call.arguments ?? {});\n blocks.push({ kind: 'tool', tool: { id: nextToolId(), name: call.name ?? '', args, done: false } });\n return true;\n }\n if (res) {\n const result = typeof res.result === 'string' ? res.result : JSON.stringify(res.result ?? '');\n // Complete the most-recent still-open tool block matching this name.\n for (let i = blocks.length - 1; i >= 0; i--) {\n const b = blocks[i];\n if (b && b.kind === 'tool' && b.tool.name === (res.name ?? '') && !b.tool.done) {\n b.tool.done = true;\n b.tool.isError = !!res.isError;\n b.tool.result = result;\n break;\n }\n }\n return true;\n }\n return false;\n}\n\nexport class ConversationController {\n private readonly config: ChatWidgetConfig;\n private readonly events: ConversationEvents;\n private readonly store: StoreApi<WidgetStore>;\n private client: SmoothAgentClient | null = null;\n private sessionId: string | null = null;\n /** Conversation id of the live session (create or resume) — lets voice join the same thread. */\n private conversationId: string | null = null;\n private readonly messages: ChatMessage[] = [];\n private status: ConnectionStatus = 'idle';\n private seq = 0;\n /** requestId of the in-flight turn — used to resume OTP / tool confirmations. */\n private activeRequestId: string | null = null;\n private interrupt: Interrupt | null = null;\n /** Values from the last interaction submit, merged into the persisted\n * identity (identity_intake only) once the server acks them. */\n private pendingInteractionValues: { kind: string; values: Record<string, unknown> } | null = null;\n private identityRestore: IdentityRestore = { phase: 'idle' };\n /**\n * True once the resume probe (persisted-pointer get_session OR the\n * `/internal/resume-by-fingerprint` POST) has run for this controller. Makes\n * `connect()` idempotent: re-entering after a transient `error` status (e.g. a\n * retried `send()`) creates a fresh session rather than re-running the resume\n * probe — which would fire another `resumeByFingerprint` POST and could adopt a\n * session we already decided not to resume.\n */\n private resumeAttempted = false;\n /**\n * HTTP base for the chat-ws wrapper's `/internal/*` REST routes. `null` when\n * the configured WS endpoint could not be parsed into an absolute origin — in\n * that case the `/internal/*` routes are refused (rather than mis-targeted at\n * the host page origin). See {@link httpBaseFromWsEndpoint}.\n */\n private readonly httpBase: string | null;\n\n constructor(config: ChatWidgetConfig, events: ConversationEvents, store?: StoreApi<WidgetStore>) {\n this.config = config;\n this.events = events;\n this.httpBase = httpBaseFromWsEndpoint(config.endpoint);\n if (this.httpBase === null) {\n // A non-absolute endpoint means the identity / resume `/internal/*` routes\n // have no safe target. Flag the controller in error so the UI surfaces it\n // and the routes refuse (see postInternal) rather than mis-targeting the\n // host page origin. Deferred to a microtask so listeners attached after\n // construction still observe the transition.\n queueMicrotask(() => this.setStatus('error', `Invalid chat endpoint: ${config.endpoint}`));\n }\n this.store = store ?? createWidgetStore(config.agentId);\n // Seed identity from config into the persisted store. `mergeIdentity` is\n // applied on EVERY construct, so a config-provided field always wins over\n // the persisted value (config is authoritative when present). Fields the\n // config does NOT provide keep their persisted value — those survive across\n // reloads; explicitly-configured ones are re-applied each load.\n const seed: { name?: string; email?: string; phone?: string } = {};\n if (config.userName) seed.name = config.userName;\n if (config.userEmail) seed.email = config.userEmail;\n if (config.userPhone) seed.phone = config.userPhone;\n if (Object.keys(seed).length > 0) this.store.getState().mergeIdentity(seed);\n }\n\n get connectionStatus(): ConnectionStatus {\n return this.status;\n }\n\n /** Conversation id of the live session, or null before connect (voice passes this as `conversation_id`). */\n get currentConversationId(): string | null {\n return this.conversationId;\n }\n\n /**\n * Append an already-finalized message to the transcript and emit — the voice\n * path reuses this so `transcript_final` (user) and `reply_text` (assistant)\n * turns land in the same message list / render pipeline as typed chat.\n */\n appendLocalMessage(role: Role, text: string): void {\n const trimmed = text.trim();\n if (!trimmed) return;\n this.messages.push({ id: this.nextId(role === 'user' ? 'u' : 'a'), role, text: trimmed, streaming: false });\n this.emitMessages();\n }\n\n /** The persisted store, exposed so the view can read identity for the pre-chat gate. */\n getStore(): StoreApi<WidgetStore> {\n return this.store;\n }\n\n /** True when a persisted session pointer exists (drives the resume path). */\n hasPersistedSession(): boolean {\n return !!this.store.getState().sessionId;\n }\n\n /** True when persisted identity exists (lets the view skip the pre-chat form). */\n hasPersistedIdentity(): boolean {\n const id = this.store.getState().identity;\n return !!(id.name || id.email || id.phone);\n }\n\n /** Merge in visitor identity + consent (from the pre-chat form). Applied on next connect. */\n setUserInfo(info: UserInfo): void {\n const { name, email, phone, consent } = info;\n this.store.getState().mergeIdentity({ name, email, phone });\n if (consent) {\n const consentAt = consent.emailOptIn || consent.smsOptIn ? new Date().toISOString() : undefined;\n this.store.getState().setConsent({\n emailOptIn: consent.emailOptIn,\n smsOptIn: consent.smsOptIn,\n consentSource: 'chat-widget-prechat',\n consentAt,\n });\n }\n }\n\n private setInterrupt(interrupt: Interrupt | null): void {\n this.interrupt = interrupt;\n this.events.onInterrupt?.(interrupt);\n }\n\n private setIdentityRestore(state: IdentityRestore): void {\n this.identityRestore = state;\n this.events.onIdentityRestore?.(state);\n }\n\n get currentIdentityRestore(): IdentityRestore {\n return this.identityRestore;\n }\n\n /** Submit an OTP code to resume the paused turn. No-op if not awaiting OTP. */\n verifyOtp(code: string): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'otp') return;\n this.client.verifyOtp({ sessionId: this.sessionId, requestId: this.activeRequestId, code });\n }\n\n /** Approve or reject a pending tool write to resume the paused turn. */\n confirmTool(approved: boolean): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'confirm') return;\n this.client.confirmToolAction({ sessionId: this.sessionId, requestId: this.activeRequestId, approved });\n this.setInterrupt(null);\n }\n\n /**\n * Submit a Rich Interaction card to resume the parked turn. The server\n * routes to the kind's validator: invalid values come back as an\n * `interaction_invalid` event (the card re-renders with per-field errors —\n * the turn stays parked); a valid submit is acked and the turn resumes.\n * No-op if not awaiting an interaction.\n */\n submitInteraction(values: Record<string, unknown>): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'interaction') return;\n // Stash the values so the ack (immediate_response) can merge accepted\n // identity values into the persisted store.\n this.pendingInteractionValues = { kind: this.interrupt.interactionKind, values };\n this.client.submitInteraction({\n sessionId: this.sessionId,\n requestId: this.activeRequestId,\n interactionId: this.interrupt.interactionId,\n kind: this.interrupt.interactionKind,\n values,\n });\n }\n\n /** Decline the pending Rich Interaction; the agent continues without it. */\n declineInteraction(): void {\n if (!this.client || !this.sessionId || !this.activeRequestId || this.interrupt?.kind !== 'interaction') return;\n this.client.submitInteraction({\n sessionId: this.sessionId,\n requestId: this.activeRequestId,\n interactionId: this.interrupt.interactionId,\n kind: this.interrupt.interactionKind,\n declined: true,\n });\n this.pendingInteractionValues = null;\n this.setInterrupt(null);\n }\n\n private nextId(prefix: string): string {\n this.seq += 1;\n return `${prefix}-${this.seq}-${Date.now().toString(36)}`;\n }\n\n private setStatus(status: ConnectionStatus, detail?: string): void {\n this.status = status;\n this.events.onStatus(status, detail);\n }\n\n private emitMessages(): void {\n // Hand out a shallow copy so the view can't mutate internal state.\n this.events.onMessages(this.messages.map((m) => ({ ...m })));\n }\n\n /** Compute (once) + return the persisted browser fingerprint. */\n private fingerprint(): string {\n const state = this.store.getState();\n return getOrCreateFingerprint(\n () => state.browserFingerprint,\n (fp) => this.store.getState().setBrowserFingerprint(fp),\n );\n }\n\n /**\n * Build the `metadata` payload threaded into `create_conversation_session`:\n * phone (no first-class engine field) and consent.\n *\n * NOTE: `verifiedEmail` is deliberately NOT stamped here. It is a per-session\n * OTP proof bound to the session it was verified against\n * (`verifiedEmailSessionId`), and the server only treats an actual OTP `verify`\n * as proof — metadata `verifiedEmail` is just a hint. Auto-stamping it onto\n * every brand-new `create_conversation_session` would mislabel a fresh\n * visitor's session with a prior (possibly different) visitor's email on a\n * shared browser. The verified email is only used when RESUMING the exact\n * session it was proven for — see {@link verifiedEmailForSession}.\n */\n private sessionMetadata(): Record<string, unknown> | undefined {\n const state = this.store.getState();\n const meta: Record<string, unknown> = {};\n if (state.identity.phone) meta.userPhone = state.identity.phone;\n const consent = state.consent;\n if (consent.emailOptIn || consent.smsOptIn || consent.consentAt) {\n const c: ConsentState = {\n emailOptIn: consent.emailOptIn,\n smsOptIn: consent.smsOptIn,\n consentSource: consent.consentSource ?? 'chat-widget-prechat',\n };\n if (consent.consentAt) c.consentAt = consent.consentAt;\n meta.consent = c;\n }\n return Object.keys(meta).length > 0 ? meta : undefined;\n }\n\n /**\n * The verified-email hint, but ONLY when the OTP proof is bound to the session\n * being resumed (`verifiedEmailSessionId === sessionId`). Returns null\n * otherwise so a stale/cross-visitor proof is never threaded onto a session it\n * wasn't proven for.\n */\n private verifiedEmailForSession(sessionId: string): string | null {\n const state = this.store.getState();\n if (state.verifiedEmail && state.verifiedEmailSessionId === sessionId) {\n return state.verifiedEmail;\n }\n return null;\n }\n\n /** Lazily open the WS client (default transport). Idempotent within a connect. */\n private async ensureClient(): Promise<void> {\n if (this.client) return;\n this.client = new SmoothAgentClient({ url: this.config.endpoint });\n await this.client.connect();\n }\n\n /**\n * Open the connection and either RESUME or create a session.\n *\n * 1. Persisted pointer (ADR-048 §b): `get_session` → if not `ended`, reuse +\n * hydrate from `get_messages` (newest-first, reversed). On ended/404 clear\n * ONLY the pointer (identity/consent survive).\n * 2. No persisted pointer: POST `/internal/resume-by-fingerprint` FIRST; if\n * `resumable`, adopt the returned session (the wrapper has primed the\n * operator registry), reuse the sessionId, and hydrate via get_session/\n * get_messages — rather than relying on createConversationSession to resume.\n * 3. Otherwise create a fresh session.\n */\n async connect(): Promise<void> {\n if (this.status === 'connecting' || this.status === 'ready') return;\n this.setStatus('connecting');\n try {\n await this.ensureClient();\n // The resume probe (persisted-pointer get_session OR the fingerprint\n // resume POST) runs AT MOST ONCE per controller lifecycle. Re-entering\n // connect() after a transient error (e.g. a retried send()) must not\n // re-run the probe — that would re-fire resumeByFingerprint and could\n // adopt a session we already chose not to resume. After the first\n // attempt, fall straight through to creating a fresh session.\n if (!this.resumeAttempted) {\n this.resumeAttempted = true;\n const persistedSessionId = this.store.getState().sessionId;\n if (persistedSessionId) {\n const resumed = await this.tryResume(persistedSessionId);\n if (resumed) {\n this.setStatus('ready');\n return;\n }\n // Resume failed (ended/404/gone) — clear the pointer, keep identity.\n this.store.getState().clearSession();\n } else {\n // Returning anonymous visitor with no stored pointer: ask the\n // wrapper to resolve a recent session for this fingerprint.\n const fpSessionId = await this.resumeByFingerprint();\n if (fpSessionId) {\n const resumed = await this.tryResume(fpSessionId);\n if (resumed) {\n this.store.getState().setSessionId(fpSessionId);\n this.setStatus('ready');\n return;\n }\n }\n }\n }\n await this.createSession();\n this.setStatus('ready');\n } catch (err) {\n this.setStatus('error', err instanceof Error ? err.message : String(err));\n throw err;\n }\n }\n\n // ─────────────────────── chat-ws `/internal/*` HTTP ─────────────────────────\n\n /**\n * Build the auth fields every `/internal/*` route shares: `agentId` (required\n * for the agent-policy lookup), `agentName` (used as the OTP email sender), and\n * the optional pre-auth `authContext` the host page may have configured. The\n * `Origin` header is sent automatically by the browser and checked server-side.\n */\n private authBody(): Record<string, unknown> {\n const body: Record<string, unknown> = { agentId: this.config.agentId };\n if (this.config.agentName) body.agentName = this.config.agentName;\n if (this.config.authContext) body.authContext = this.config.authContext;\n return body;\n }\n\n /** POST JSON to a `/internal/*` route; returns the parsed body (or throws). */\n private async postInternal(path: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (this.httpBase === null) {\n // No absolute origin could be derived from the WS endpoint — refuse the\n // call loudly rather than POST identity data to a relative (host-page) URL.\n throw new Error(`Cannot reach ${path}: the chat endpoint is not an absolute URL.`);\n }\n const res = await fetch(`${this.httpBase}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n // Auth is the `Origin` allowlist + the `authContext` body field — NOT\n // cookies. `credentials: 'include'` would force the server to reply with\n // `Access-Control-Allow-Credentials: true` AND a reflected origin (a\n // wildcard `*` is illegal with credentials), so a plain origin-allowlisted\n // CORS config would fail the preflight and break EVERY `/internal/*` call.\n // Omit credentials so the cross-origin POST works against an allowlist\n // that doesn't (and shouldn't need to) opt into credentialed CORS.\n credentials: 'omit',\n body: JSON.stringify({ ...this.authBody(), ...payload }),\n });\n let json: Record<string, unknown> = {};\n try {\n json = (await res.json()) as Record<string, unknown>;\n } catch {\n json = {};\n }\n if (!res.ok) {\n const err = json.error as { code?: string; message?: string } | undefined;\n throw new Error(err?.message ?? `${path} failed (${res.status})`);\n }\n return json;\n }\n\n /**\n * POST `/internal/resume-by-fingerprint`. Returns the resumable sessionId when\n * the wrapper found (and primed) a recent session for this fingerprint, else\n * null. Network/route failures are swallowed → null (fall through to create).\n */\n private async resumeByFingerprint(): Promise<string | null> {\n try {\n const json = await this.postInternal('/internal/resume-by-fingerprint', { browserFingerprint: this.fingerprint() });\n if (json.resumable === true && typeof json.sessionId === 'string') {\n return json.sessionId;\n }\n } catch {\n // Resume is best-effort; any failure just means a fresh session.\n }\n return null;\n }\n\n /** `create_conversation_session` with fingerprint + identity + consent metadata. */\n private async createSession(): Promise<void> {\n if (!this.client) throw new Error('Conversation is not connected');\n const state = this.store.getState();\n const metadata = this.sessionMetadata();\n const session = await this.client.createConversationSession({\n agentId: this.config.agentId,\n userName: state.identity.name,\n userEmail: state.identity.email,\n browserFingerprint: this.fingerprint(),\n // Declare the Rich-Interaction cards this widget can render (derived\n // from the card registry), so the server emits `interaction_required`\n // for those kinds instead of the conversational fallback.\n supports: [...SUPPORTED_INTERACTION_CAPABILITIES],\n ...(metadata ? { metadata } : {}),\n });\n this.sessionId = session.sessionId;\n this.conversationId = session.conversationId ?? null;\n this.store.getState().setSessionId(session.sessionId);\n }\n\n /**\n * Attempt to resume `sessionId`: returns true and hydrates the transcript when\n * the session is live, false when it has ended / can't be fetched.\n */\n private async tryResume(sessionId: string): Promise<boolean> {\n if (!this.client) return false;\n let snap: { status?: 'active' | 'idle' | 'ended'; conversationId?: string };\n try {\n snap = await this.client.getSession({ sessionId });\n } catch {\n return false; // 404 / SESSION_NOT_FOUND / network — start fresh.\n }\n if (snap.status === 'ended') return false;\n\n this.sessionId = sessionId;\n this.conversationId = snap.conversationId ?? null;\n await this.hydrateHistory(sessionId);\n return true;\n }\n\n /** Page recent history (newest-first), reverse to chronological, and render. */\n private async hydrateHistory(sessionId: string): Promise<void> {\n if (!this.client) return;\n try {\n const page = await this.client.getMessages({ sessionId, limit: 50 });\n const rows = Array.isArray(page.messages) ? page.messages : [];\n // The server returns newest-first; reverse to chronological for the UI.\n const chronological = [...rows].reverse();\n const hydrated: ChatMessage[] = [];\n chronological.forEach((m, i) => {\n const chat = wireMessageToChat(m as WireMessage, i);\n if (chat) hydrated.push(chat);\n });\n this.messages.length = 0;\n this.messages.push(...hydrated);\n this.emitMessages();\n } catch {\n // History fetch is best-effort: a resumable session with no fetchable\n // history just shows an empty transcript rather than failing the resume.\n }\n }\n\n /**\n * Submit a user message. Appends the user bubble immediately, then streams the\n * assistant reply token-by-token, finalizing on `eventual_response`.\n */\n async send(text: string): Promise<void> {\n const trimmed = text.trim();\n if (!trimmed) return;\n if (!this.client || !this.sessionId || this.status !== 'ready') {\n await this.connect();\n }\n if (!this.client || !this.sessionId) {\n throw new Error('Conversation is not connected');\n }\n\n // 1. User bubble.\n this.messages.push({ id: this.nextId('u'), role: 'user', text: trimmed, streaming: false });\n\n // 2. Placeholder assistant bubble we grow as tokens arrive.\n const showTools = this.config.showToolActivity === true;\n const assistant: ChatMessage = { id: this.nextId('a'), role: 'assistant', text: '', streaming: true, blocks: showTools ? [] : undefined };\n this.messages.push(assistant);\n this.emitMessages();\n\n try {\n const turn = this.client.sendMessage({ sessionId: this.sessionId, message: trimmed, stream: true });\n this.activeRequestId = turn.requestId;\n\n for await (const event of turn) {\n if (event.type === 'stream_token') {\n const token = event.token ?? event.data?.token ?? '';\n if (token) {\n assistant.text += token;\n // Grow the trailing text block so prose interleaves with any\n // tool chips in the order the model produced them.\n if (showTools && assistant.blocks) growTextBlock(assistant.blocks, token);\n this.emitMessages();\n }\n } else if (showTools && event.type === 'stream_chunk') {\n // Tool activity (gated). Read state.rawResponse.toolCall/.toolResult.\n if (assistant.blocks && applyToolChunk(assistant.blocks, event.data?.state)) {\n this.emitMessages();\n }\n } else {\n // OTP / tool-confirmation pauses surface here; the loop keeps\n // iterating once the visitor resumes via verifyOtp/confirmTool.\n this.handleTurnEvent(event);\n }\n }\n\n const final = await turn;\n const inner = final.data?.data;\n const finalText = extractFinalText(inner?.response);\n if (finalText && finalText.length > assistant.text.length) {\n assistant.text = finalText;\n }\n if (!assistant.text) {\n assistant.text = '(no response)';\n }\n // Attach grounding sources from the terminal event, when present.\n const citations = extractCitations(inner);\n if (citations.length > 0) {\n assistant.citations = citations;\n }\n // Suggested follow-up replies from the terminal event, when present.\n const suggestions = extractSuggestions(inner?.response);\n if (suggestions.length > 0) {\n assistant.suggestions = suggestions;\n }\n // Only keep blocks for turns that actually invoked a tool — a prose-only\n // turn drops back to the normal markdown text path (with the final text).\n if (assistant.blocks && !assistant.blocks.some((b) => b.kind === 'tool')) {\n assistant.blocks = undefined;\n }\n assistant.streaming = false;\n this.emitMessages();\n } catch (err) {\n assistant.streaming = false;\n const message =\n err instanceof ProtocolError\n ? `Error: ${err.message}`\n : (this.config.connectionErrorMessage ?? \"We couldn't reach the chat.\");\n assistant.text = assistant.text ? `${assistant.text}\\n\\n${message}` : message;\n this.emitMessages();\n this.setStatus('error', err instanceof Error ? err.message : String(err));\n } finally {\n this.activeRequestId = null;\n this.setInterrupt(null);\n }\n }\n\n /** Map a non-token turn event (OTP / tool-confirmation lifecycle) to interrupt state. */\n private handleTurnEvent(event: ServerEvent): void {\n const inner = ((event as { data?: { data?: Record<string, unknown> } }).data?.data ?? {}) as Record<string, unknown>;\n const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined);\n const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);\n switch (event.type) {\n case 'otp_verification_required': {\n const channels: ('email' | 'sms')[] = Array.isArray(inner.availableChannels)\n ? inner.availableChannels.filter((c): c is 'email' | 'sms' => c === 'email' || c === 'sms')\n : ['email'];\n this.setInterrupt({\n kind: 'otp',\n toolId: str(inner.toolId),\n actionDescription: str(inner.actionDescription),\n availableChannels: channels.length > 0 ? channels : ['email'],\n });\n break;\n }\n case 'otp_sent':\n if (this.interrupt?.kind === 'otp') {\n this.setInterrupt({ ...this.interrupt, sent: { channel: str(inner.channel), maskedDestination: str(inner.maskedDestination) }, error: undefined });\n }\n break;\n case 'otp_verified':\n if (this.interrupt?.kind === 'otp') this.setInterrupt(null);\n break;\n case 'otp_invalid':\n if (this.interrupt?.kind === 'otp') {\n this.setInterrupt({ ...this.interrupt, error: str(inner.message) ?? 'That code was incorrect.', attemptsRemaining: num(inner.attemptsRemaining) });\n }\n break;\n case 'write_confirmation_required':\n this.setInterrupt({ kind: 'confirm', toolId: str(inner.toolId), actionDescription: str(inner.actionDescription) });\n break;\n case 'interaction_required': {\n const interactionId = str(inner.interactionId);\n const kind = str(inner.kind);\n const spec = inner.spec && typeof inner.spec === 'object' ? (inner.spec as Record<string, unknown>) : {};\n if (!interactionId || !kind) break; // not renderable — ignore\n this.pendingInteractionValues = null;\n this.setInterrupt({\n kind: 'interaction',\n interactionId,\n interactionKind: kind,\n spec,\n reason: str(inner.reason),\n });\n break;\n }\n case 'interaction_invalid':\n if (this.interrupt?.kind === 'interaction' && this.interrupt.interactionId === str(inner.interactionId)) {\n const errors: { field: string; message: string }[] = [];\n if (Array.isArray(inner.errors)) {\n for (const e of inner.errors) {\n if (!e || typeof e !== 'object') continue;\n const o = e as Record<string, unknown>;\n const field = str(o.field);\n if (field) errors.push({ field, message: str(o.message) ?? 'Invalid value' });\n }\n }\n this.pendingInteractionValues = null;\n this.setInterrupt({ ...this.interrupt, errors });\n }\n break;\n case 'immediate_response':\n // Mid-turn immediate_response while an interaction card is showing\n // is the submit/decline ack: the park resolved — clear the card\n // and, for accepted identity values, persist them.\n if (this.interrupt?.kind === 'interaction') {\n const pending = this.pendingInteractionValues;\n if (pending && pending.kind === 'identity_intake') {\n const v = pending.values as { name?: string; email?: string; phone?: string };\n this.store.getState().mergeIdentity({ name: v.name, email: v.email, phone: v.phone });\n }\n this.pendingInteractionValues = null;\n this.setInterrupt(null);\n }\n break;\n default:\n break;\n }\n }\n\n // ─────────────────── Cross-device \"restore my chats\" (§c) ───────────────────\n //\n // Three HTTP POST routes on the chat-ws wrapper (the engine `/ws` dispatch\n // rejects unknown verbs): request-otp → verify-otp → resolve. ALL THREE are\n // session-scoped — they require a live `sessionId` (a uuid). request-otp\n // establishes the session itself (idempotent connect) before sending, so the\n // whole flow shares one session and verify-otp can't hit \"No active session\"\n // even if the email was submitted before the initial connect() resolved.\n\n /**\n * Begin the cross-device restore: POST `/internal/identity/request-otp` for\n * `email` over `channel`. The view collects the email via an explicit affordance.\n */\n async requestIdentityOtp(email: string, channel: 'email' | 'sms' = 'email'): Promise<void> {\n const trimmed = email.trim();\n if (!trimmed) return;\n this.setIdentityRestore({ phase: 'requesting', email: trimmed, channel });\n // request-otp must be SESSION-CONSISTENT with verify-otp (which hard-requires\n // a sessionId). If the restore affordance fired request-otp before connect()\n // resolved, there'd be no sessionId here and verify-otp would later error\n // \"No active session.\" Establish a session first (idempotent connect), then\n // require it — so the whole request → verify flow shares one live session.\n if (!this.sessionId) {\n try {\n await this.connect();\n } catch {\n /* fall through: handled by the sessionId check below */\n }\n }\n if (!this.sessionId) {\n this.setIdentityRestore({ phase: 'error', message: 'No active session to verify against.' });\n return;\n }\n try {\n const json = await this.postInternal('/internal/identity/request-otp', {\n sessionId: this.sessionId,\n email: trimmed,\n channel,\n });\n const masked = typeof json.maskedDestination === 'string' ? json.maskedDestination : undefined;\n this.setIdentityRestore({ phase: 'awaiting_code', email: trimmed, channel, maskedDestination: masked });\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Could not send a verification code.' });\n }\n }\n\n /** Submit the code: POST `/internal/identity/verify-otp`, then resolve on success. */\n async verifyIdentityOtp(code: string): Promise<void> {\n const state = this.identityRestore;\n const trimmed = code.trim();\n if (!trimmed || state.phase !== 'awaiting_code') return;\n const { email, channel } = state;\n if (!this.sessionId) {\n this.setIdentityRestore({ phase: 'error', message: 'No active session to verify against.' });\n return;\n }\n this.setIdentityRestore({ phase: 'verifying', email, channel });\n try {\n const json = await this.postInternal('/internal/identity/verify-otp', { sessionId: this.sessionId, email, code: trimmed });\n if (json.event === 'otp_verified') {\n // Bind the OTP proof to the session it was verified against, so it\n // can't leak onto a different visitor's session on a shared browser.\n this.store.getState().setVerifiedEmail(email, this.sessionId);\n await this.resolveIdentity(email);\n } else if (json.event === 'otp_invalid') {\n const remaining = typeof json.attemptsRemaining === 'number' ? json.attemptsRemaining : undefined;\n this.setIdentityRestore({ phase: 'awaiting_code', email, channel, error: 'That code was incorrect.', attemptsRemaining: remaining });\n } else {\n this.setIdentityRestore({ phase: 'error', message: 'Verification failed.' });\n }\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Verification failed.' });\n }\n }\n\n /** Resolve the verified identity → restorable conversations via POST `/internal/identity/resolve`. */\n private async resolveIdentity(email: string): Promise<void> {\n if (!this.sessionId) return;\n this.setIdentityRestore({ phase: 'resolving', email });\n try {\n const json = await this.postInternal('/internal/identity/resolve', { sessionId: this.sessionId, email });\n if (json.resolved !== true) {\n this.setIdentityRestore({ phase: 'resolved', email, conversations: [] });\n return;\n }\n const raw = json.conversations;\n const conversations: RestorableConversation[] = Array.isArray(raw)\n ? raw\n .map((c): RestorableConversation | null => {\n if (!c || typeof c !== 'object') return null;\n const o = c as Record<string, unknown>;\n const conversationId = typeof o.conversationId === 'string' ? o.conversationId : '';\n const sessionId = typeof o.sessionId === 'string' ? o.sessionId : '';\n if (!sessionId) return null;\n return {\n conversationId,\n sessionId,\n lastActivityAt: typeof o.lastActivityAt === 'string' ? o.lastActivityAt : undefined,\n preview: typeof o.preview === 'string' ? o.preview : undefined,\n };\n })\n .filter((c): c is RestorableConversation => c !== null)\n : [];\n this.setIdentityRestore({ phase: 'resolved', email, conversations });\n } catch (err) {\n this.setIdentityRestore({ phase: 'error', message: err instanceof Error ? err.message : 'Could not load your chats.' });\n }\n }\n\n /**\n * Replay a chosen restorable conversation: point the live session at its\n * sessionId, hydrate its transcript (get_session + get_messages), and persist\n * the new pointer so the next `sendMessage` continues it.\n */\n async restoreConversation(sessionId: string): Promise<void> {\n if (!this.client) await this.ensureClient();\n // Capture the OTP proof bound to the CURRENT live session BEFORE tryResume\n // repoints this.sessionId to the restored one. The visitor proved ownership\n // of this email in this very flow, so the proof legitimately follows the\n // conversation they chose to restore.\n const proven = this.sessionId ? this.verifiedEmailForSession(this.sessionId) : null;\n const resumed = await this.tryResume(sessionId);\n if (resumed) {\n this.store.getState().setSessionId(sessionId);\n // Rebind the proof to the restored session (keeps verifiedEmail\n // session-scoped, just now to the session it's actually used on). Only a\n // proof from the just-verified session follows — never an unrelated stale one.\n if (proven) this.store.getState().setVerifiedEmail(proven, sessionId);\n this.setIdentityRestore({ phase: 'idle' });\n this.setStatus('ready');\n } else {\n this.setIdentityRestore({ phase: 'error', message: 'That conversation is no longer available.' });\n }\n }\n\n /** Dismiss the cross-device restore panel. */\n cancelIdentityRestore(): void {\n this.setIdentityRestore({ phase: 'idle' });\n }\n\n /** Tear down the underlying client. */\n disconnect(): void {\n this.client?.disconnect('widget closed');\n this.client = null;\n this.sessionId = null;\n this.conversationId = null;\n this.activeRequestId = null;\n // A full teardown ends the controller lifecycle: a subsequent connect() is a\n // genuine re-open and may resume again, so re-arm the resume probe.\n this.resumeAttempted = false;\n this.setInterrupt(null);\n this.setStatus('closed');\n }\n}\n","/**\n * The Smooth logo + icon, inlined as SVG strings so the full-page header can\n * render them without a separate network fetch (the IIFE bundle is\n * self-contained).\n *\n * GENERATED from `assets/smooth-logo.svg` / `assets/smooth-icon.svg` — do not\n * edit by hand. Regenerate with:\n * node -e 'const fs=require(\"fs\");process.stdout.write(JSON.stringify(fs.readFileSync(\"assets/smooth-icon.svg\",\"utf8\")))'\n */\n/* eslint-disable */\nexport const SMOOTH_LOGO_SVG = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<svg id=\\\"Layer_1\\\" data-name=\\\"Layer 1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" viewBox=\\\"0 0 550 135\\\">\\n <defs>\\n <style>\\n .cls-1 {\\n fill: url(#linear-gradient-3);\\n }\\n\\n .cls-2 {\\n fill: url(#linear-gradient-2);\\n }\\n\\n .cls-3 {\\n fill: url(#linear-gradient);\\n fill-rule: evenodd;\\n }\\n </style>\\n <linearGradient id=\\\"linear-gradient\\\" x1=\\\"115.59\\\" y1=\\\"112.81\\\" x2=\\\"25.08\\\" y2=\\\"22.3\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".3\\\" stop-color=\\\"#f49f0a\\\"/>\\n <stop offset=\\\".79\\\" stop-color=\\\"#fb7a4d\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#ff6b6c\\\"/>\\n </linearGradient>\\n <linearGradient id=\\\"linear-gradient-2\\\" x1=\\\"360.91\\\" y1=\\\"152.01\\\" x2=\\\"202.32\\\" y2=\\\"-6.59\\\" xlink:href=\\\"#linear-gradient\\\"/>\\n <linearGradient id=\\\"linear-gradient-3\\\" x1=\\\"443.91\\\" y1=\\\"30.15\\\" x2=\\\"531.36\\\" y2=\\\"117.59\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".43\\\" stop-color=\\\"#00a6a6\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#1238dd\\\"/>\\n </linearGradient>\\n </defs>\\n <path class=\\\"cls-3\\\" d=\\\"M48.28,14.96c-12.39,5.21-22.54,14.64-28.65,26.61-6.12,11.97-7.8,25.72-4.77,38.81,3.04,13.09,10.6,24.69,21.36,32.75,10.76,8.06,24.02,12.05,37.44,11.28,13.42-.77,26.13-6.26,35.9-15.5,9.76-9.24,15.95-21.63,17.46-34.99,1.51-13.36-1.74-26.82-9.19-38.01-1.07-1.61-.64-3.78.97-4.85,1.61-1.07,3.78-.64,4.85.97,8.36,12.56,12.02,27.68,10.32,42.67-1.7,15-8.64,28.91-19.61,39.28-10.96,10.37-25.24,16.54-40.31,17.4-15.07.87-29.96-3.62-42.04-12.66-12.08-9.05-20.58-22.07-23.99-36.77-3.41-14.7-1.51-30.14,5.35-43.58,6.87-13.44,18.26-24.02,32.17-29.87,13.91-5.85,29.44-6.6,43.85-2.11,1.85.57,2.88,2.54,2.3,4.38-.57,1.85-2.54,2.88-4.38,2.3-12.83-4-26.67-3.33-39.06,1.88ZM111.39,19.75c0,2.07-1.68,3.75-3.75,3.75s-3.75-1.68-3.75-3.75,1.68-3.75,3.75-3.75,3.75,1.68,3.75,3.75ZM64.64,59.93c0,1.91,2.39,2.56,7.69,3.88,3.89.97,6.6,2.18,8.15,3.63,1.53,1.45,2.29,3.53,2.29,6.25,0,3.57-1.03,6.26-3.11,8.08-2.07,1.82-5.09,2.73-9.09,2.73h-9.6c-1.97,0-3.57-1.6-3.59-3.57-.01-1.99,1.6-3.61,3.59-3.61h9.41c3.15-.12,4.79-.95,4.91-2.47,0-1.3-1.03-2.21-3.07-2.73-6.91-1.72-11.11-3.44-12.6-5.15-1.48-1.71-2.23-3.77-2.23-6.19,0-6.59,3.2-9.85,9.59-9.8h10.77c1.99,0,3.6,1.61,3.6,3.59s-1.61,3.59-3.6,3.59h-9.69c-1.83,0-3.43.06-3.43,1.77Z\\\"/>\\n <path class=\\\"cls-2\\\" d=\\\"M205.52,48.44h-8.86c-.44-3.75-2.23-6.65-5.38-8.72-3.16-2.07-7.03-3.1-11.6-3.1h0c-3.35,0-6.27.54-8.78,1.62-2.49,1.09-4.44,2.59-5.84,4.48-1.39,1.89-2.08,4.05-2.08,6.46h0c0,2.01.49,3.75,1.46,5.2.97,1.44,2.22,2.63,3.74,3.58,1.53.95,3.13,1.72,4.8,2.32,1.68.6,3.22,1.09,4.62,1.46h0l7.68,2.06c1.97.52,4.17,1.23,6.6,2.14,2.43.92,4.75,2.16,6.98,3.72,2.23,1.56,4.07,3.56,5.52,6,1.45,2.44,2.18,5.43,2.18,8.98h0c0,4.08-1.07,7.77-3.2,11.08-2.12,3.29-5.22,5.91-9.3,7.86-4.08,1.95-9.02,2.92-14.82,2.92h0c-5.43,0-10.11-.87-14.06-2.62-3.95-1.75-7.05-4.19-9.3-7.32-2.25-3.12-3.53-6.75-3.84-10.88h9.46c.25,2.85,1.22,5.21,2.9,7.06,1.69,1.87,3.83,3.25,6.42,4.14,2.6.89,5.41,1.34,8.42,1.34h0c3.49,0,6.63-.57,9.4-1.72,2.79-1.13,4.99-2.73,6.62-4.8,1.63-2.05,2.44-4.46,2.44-7.22h0c0-2.51-.7-4.55-2.1-6.12-1.41-1.57-3.26-2.85-5.54-3.84-2.29-.99-4.77-1.85-7.44-2.58h0l-9.3-2.66c-5.91-1.71-10.59-4.13-14.04-7.28-3.44-3.16-5.16-7.29-5.16-12.38h0c0-4.23,1.15-7.93,3.46-11.1,2.29-3.16,5.39-5.62,9.3-7.38,3.91-1.76,8.27-2.64,13.08-2.64h0c4.88,0,9.21.87,13,2.6,3.8,1.73,6.81,4.11,9.04,7.12,2.23,3,3.4,6.41,3.52,10.22h0ZM229.16,105.18h-8.72v-56.74h8.42v8.86h.74c1.19-3.03,3.1-5.38,5.74-7.06,2.63-1.69,5.79-2.54,9.48-2.54h0c3.75,0,6.87.85,9.36,2.54,2.51,1.68,4.46,4.03,5.86,7.06h.58c1.45-2.92,3.63-5.25,6.54-7,2.91-1.73,6.39-2.6,10.46-2.6h0c5.07,0,9.21,1.58,12.44,4.74,3.23,3.17,4.84,8.09,4.84,14.76h0v37.98h-8.72v-37.98c0-4.19-1.14-7.18-3.42-8.98-2.29-1.79-4.99-2.68-8.1-2.68h0c-3.99,0-7.07,1.2-9.26,3.6-2.2,2.4-3.3,5.43-3.3,9.1h0v36.94h-8.86v-38.86c0-3.23-1.05-5.83-3.14-7.82-2.09-1.97-4.79-2.96-8.08-2.96h0c-2.27,0-4.38.6-6.34,1.8-1.96,1.21-3.53,2.88-4.72,5-1.2,2.13-1.8,4.59-1.8,7.38h0v35.46ZM333.9,106.36h0c-5.12,0-9.61-1.22-13.46-3.66-3.85-2.44-6.86-5.85-9.02-10.24-2.15-4.37-3.22-9.49-3.22-15.36h0c0-5.91,1.07-11.07,3.22-15.48,2.16-4.4,5.17-7.82,9.02-10.26,3.85-2.44,8.34-3.66,13.46-3.66h0c5.12,0,9.61,1.22,13.46,3.66,3.85,2.44,6.86,5.86,9.02,10.26,2.15,4.41,3.22,9.57,3.22,15.48h0c0,5.87-1.07,10.99-3.22,15.36-2.16,4.39-5.17,7.8-9.02,10.24-3.85,2.44-8.34,3.66-13.46,3.66ZM333.9,98.52h0c3.89,0,7.09-.99,9.6-2.98,2.52-2,4.38-4.63,5.58-7.88,1.21-3.25,1.82-6.77,1.82-10.56h0c0-3.79-.61-7.32-1.82-10.6-1.2-3.27-3.06-5.91-5.58-7.94-2.51-2.01-5.71-3.02-9.6-3.02h0c-3.89,0-7.09,1.01-9.6,3.02-2.51,2.03-4.37,4.67-5.58,7.94-1.2,3.28-1.8,6.81-1.8,10.6h0c0,3.79.6,7.31,1.8,10.56,1.21,3.25,3.07,5.88,5.58,7.88,2.51,1.99,5.71,2.98,9.6,2.98ZM395.94,106.36h0c-5.12,0-9.61-1.22-13.46-3.66-3.85-2.44-6.85-5.85-9-10.24-2.16-4.37-3.24-9.49-3.24-15.36h0c0-5.91,1.08-11.07,3.24-15.48,2.15-4.4,5.15-7.82,9-10.26,3.85-2.44,8.34-3.66,13.46-3.66h0c5.12,0,9.61,1.22,13.46,3.66,3.85,2.44,6.86,5.86,9.02,10.26,2.16,4.41,3.24,9.57,3.24,15.48h0c0,5.87-1.08,10.99-3.24,15.36-2.16,4.39-5.17,7.8-9.02,10.24-3.85,2.44-8.34,3.66-13.46,3.66ZM395.94,98.52h0c3.89,0,7.09-.99,9.6-2.98,2.52-2,4.38-4.63,5.58-7.88,1.21-3.25,1.82-6.77,1.82-10.56h0c0-3.79-.61-7.32-1.82-10.6-1.2-3.27-3.06-5.91-5.58-7.94-2.51-2.01-5.71-3.02-9.6-3.02h0c-3.88,0-7.08,1.01-9.6,3.02-2.51,2.03-4.37,4.67-5.58,7.94-1.2,3.28-1.8,6.81-1.8,10.6h0c0,3.79.6,7.31,1.8,10.56,1.21,3.25,3.07,5.88,5.58,7.88,2.52,1.99,5.72,2.98,9.6,2.98Z\\\"/>\\n <path class=\\\"cls-1\\\" d=\\\"M467.88,48.02v13.28h-35.79v-13.28h35.79ZM439.68,34.38h17.89v53.42c0,1.5.36,2.62,1.08,3.36.72.74,1.88,1.1,3.49,1.1.62,0,1.48-.07,2.59-.21,1.11-.14,1.91-.27,2.38-.41l2.31,13.02c-2.02.58-3.97.97-5.84,1.18-1.88.21-3.66.31-5.33.31-6.08,0-10.7-1.43-13.84-4.28-3.15-2.85-4.72-7.01-4.72-12.48v-55.01ZM506.59,72.63v32.71h-17.89V28.95h17.53v33.53h-1.13c1.4-4.55,3.6-8.21,6.59-11,2.99-2.79,7.01-4.18,12.07-4.18,4,0,7.48.89,10.46,2.67,2.97,1.78,5.28,4.29,6.92,7.54,1.64,3.25,2.46,7.02,2.46,11.33v36.5h-17.89v-33.02c0-3.21-.82-5.73-2.46-7.56-1.64-1.83-3.93-2.74-6.87-2.74-1.92,0-3.62.42-5.1,1.26-1.49.84-2.64,2.04-3.46,3.61-.82,1.57-1.23,3.49-1.23,5.74Z\\\"/>\\n</svg>\";\n\n/** The square Smooth icon (the stylized `th` glyph) — used as the default full-page header avatar. */\nexport const SMOOTH_ICON_SVG = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<svg id=\\\"Layer_1\\\" data-name=\\\"Layer 1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\" viewBox=\\\"0 0 150 150\\\">\\n <defs>\\n <style>\\n .cls-1 {\\n fill: url(#linear-gradient);\\n }\\n </style>\\n <linearGradient id=\\\"linear-gradient\\\" x1=\\\"31.06\\\" y1=\\\"37.6\\\" x2=\\\"118.5\\\" y2=\\\"125.04\\\" gradientUnits=\\\"userSpaceOnUse\\\">\\n <stop offset=\\\".43\\\" stop-color=\\\"#00a6a6\\\"/>\\n <stop offset=\\\"1\\\" stop-color=\\\"#1238dd\\\"/>\\n </linearGradient>\\n </defs>\\n <path class=\\\"cls-1\\\" d=\\\"M55.03,55.47v13.28H19.24v-13.28h35.79ZM26.83,41.83h17.89v53.42c0,1.5.36,2.62,1.08,3.36.72.74,1.88,1.1,3.49,1.1.62,0,1.48-.07,2.59-.21,1.11-.14,1.91-.27,2.38-.41l2.31,13.02c-2.02.58-3.97.97-5.84,1.18-1.88.21-3.66.31-5.33.31-6.08,0-10.7-1.43-13.84-4.28-3.15-2.85-4.72-7.01-4.72-12.48v-55.01ZM93.74,80.08v32.71h-17.89V36.39h17.53v33.53h-1.13c1.4-4.55,3.6-8.21,6.59-11,2.99-2.79,7.01-4.18,12.07-4.18,4,0,7.48.89,10.46,2.67,2.97,1.78,5.28,4.29,6.92,7.54,1.64,3.25,2.46,7.02,2.46,11.33v36.5h-17.89v-33.02c0-3.21-.82-5.73-2.46-7.56-1.64-1.83-3.93-2.74-6.87-2.74-1.92,0-3.62.42-5.1,1.26-1.49.84-2.64,2.04-3.46,3.61-.82,1.57-1.23,3.49-1.23,5.74Z\\\"/>\\n</svg>\";\n","import type { ChatWidgetMode, ResolvedTheme } from './config.js';\n\n/**\n * Render the widget's scoped stylesheet — the \"Aurora Glass\" design system.\n *\n * Every brand value is injected as a CSS custom property on `:host` so a host\n * page can override colors per-instance and the rules below stay static. Two\n * extra tokens are *derived in CSS* from the brand vars so they adapt to any\n * theme (light or dark) without the caller supplying them:\n *\n * --sac-primary-2 a darker shade of `primary`, used as the second stop of the\n * launcher / send / user-bubble gradients (depth without a\n * second brand input).\n * --sac-surface-2 a faint wash derived from `text`, used for inset chrome\n * (composer field, close button, source cards). On a dark\n * panel it reads as a light overlay; on a light panel, dark.\n *\n * Deliberately framework-light: no Tailwind, no runtime CSS-in-JS — just a string\n * the web component drops into its shadow root. Modern color features\n * (`color-mix`) are used intentionally; the widget targets evergreen browsers.\n *\n * `mode` switches host positioning + panel sizing between the floating popover\n * (default) and the full-page layout (fills its container/viewport).\n */\nexport function buildStyles(theme: ResolvedTheme, mode: ChatWidgetMode = 'popover'): string {\n return `\n:host {\n --sac-text: ${theme.text};\n --sac-bg: ${theme.background};\n --sac-primary: ${theme.primary};\n --sac-primary-text: ${theme.primaryText};\n --sac-secondary: ${theme.secondary};\n --sac-assistant-bubble: ${theme.assistantBubble};\n --sac-assistant-bubble-text: ${theme.assistantBubbleText};\n --sac-user-bubble: ${theme.userBubble};\n --sac-user-bubble-text: ${theme.userBubbleText};\n --sac-border: ${theme.border};\n\n /* Derived tokens — adapt to any brand color without a second input. */\n --sac-primary-2: color-mix(in srgb, var(--sac-primary) 78%, #000 22%);\n --sac-surface-2: color-mix(in srgb, var(--sac-text) 5%, transparent);\n --sac-radius: 22px;\n --sac-ease: cubic-bezier(.16, 1, .3, 1);\n\n ${\n mode === 'fullpage'\n ? `/* Full-page: fill the host's box (sized by its container, else the viewport). */\n display: flex;\n flex-direction: column;\n position: relative;\n width: 100%;\n height: 100%;`\n : `/* Popover: float in the bottom-right corner. */\n position: fixed;\n bottom: 24px;\n right: 24px;\n z-index: 2147483000;`\n }\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n}\n${\n mode === 'fullpage'\n ? `\n/* Viewport fallback — the element sets this attribute only when the host's\n container gives it no resolved height (e.g. mounted straight into an\n auto-height <body>). A sized container always wins, so an embed inside a\n fixed-height box never overflows it (composer stays visible). */\n:host([data-viewport-fallback]) { min-height: 100dvh; }\n/* The render wrapper passes the host's box down to the panel via flex. */\n.wrap {\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n`\n : ''\n}\n* { box-sizing: border-box; }\n\n/* ───────────────────────────── Launcher ───────────────────────────── */\n.launcher {\n position: relative;\n width: 62px;\n height: 62px;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n padding: 0;\n background: radial-gradient(120% 120% at 30% 20%,\n color-mix(in srgb, var(--sac-primary) 78%, #fff 22%) 0%,\n var(--sac-primary) 42%,\n var(--sac-primary-2) 130%);\n color: var(--sac-primary-text);\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow:\n 0 1px 0 rgba(255, 255, 255, .25) inset,\n 0 10px 24px -6px color-mix(in srgb, var(--sac-primary) 55%, transparent),\n 0 18px 50px -12px rgba(0, 0, 0, .6);\n transition: transform .45s var(--sac-ease), box-shadow .45s var(--sac-ease), opacity .3s ease;\n isolation: isolate;\n}\n/* Breathing presence ring. */\n.launcher::before {\n content: '';\n position: absolute;\n inset: -6px;\n border-radius: 50%;\n z-index: -1;\n background: radial-gradient(closest-side, color-mix(in srgb, var(--sac-primary) 45%, transparent), transparent 75%);\n animation: sac-breathe 3.4s ease-in-out infinite;\n}\n@keyframes sac-breathe { 0%, 100% { transform: scale(1); opacity: .55 } 50% { transform: scale(1.28); opacity: 0 } }\n.launcher:hover {\n transform: translateY(-3px) scale(1.06);\n box-shadow:\n 0 1px 0 rgba(255, 255, 255, .3) inset,\n 0 16px 30px -6px color-mix(in srgb, var(--sac-primary) 60%, transparent),\n 0 26px 60px -14px rgba(0, 0, 0, .7);\n}\n.launcher:active { transform: translateY(-1px) scale(.98); }\n.launcher .ico { width: 27px; height: 27px; display: block; transition: transform .4s var(--sac-ease); }\n.launcher:hover .ico { transform: rotate(-6deg) scale(1.04); }\n.launcher.hidden { opacity: 0; transform: scale(.4) translateY(10px); pointer-events: none; }\n\n/* ─────────────────────────────── Panel ────────────────────────────── */\n.panel {\n width: 390px;\n max-width: calc(100vw - 40px);\n height: 600px;\n max-height: calc(100vh - 56px);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n border-radius: var(--sac-radius);\n background: linear-gradient(180deg, color-mix(in srgb, var(--sac-bg) 92%, #fff 8%) 0%, var(--sac-bg) 22%);\n color: var(--sac-text);\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n box-shadow:\n 0 0 0 1px rgba(255, 255, 255, .03) inset,\n 0 40px 80px -24px rgba(0, 0, 0, .65),\n 0 16px 40px -20px rgba(0, 0, 0, .5);\n transform-origin: bottom right;\n animation: sac-panel-in .5s var(--sac-ease) both;\n position: relative;\n}\n@keyframes sac-panel-in { from { opacity: 0; transform: translateY(16px) scale(.92) } to { opacity: 1; transform: none } }\n.panel.hidden { display: none; }\n/* Ambient brand glow bleeding from the top of the panel. */\n.panel::before {\n content: '';\n position: absolute;\n left: 0; right: 0; top: 0;\n height: 140px;\n pointer-events: none;\n background: radial-gradient(120% 100% at 50% 0%, color-mix(in srgb, var(--sac-primary) 22%, transparent), transparent 70%);\n}\n/* Full-page: the panel becomes the whole surface — it follows the host's box\n (via the .wrap flex chain), never a hardcoded viewport unit. */\n.panel.fullpage {\n width: 100%;\n flex: 1;\n height: auto;\n min-height: 0;\n max-width: none;\n max-height: none;\n border: none;\n border-radius: 0;\n box-shadow: none;\n animation: none;\n}\n\n/* ─────────────────────────────── Header ───────────────────────────── */\n.header {\n position: relative;\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px 16px 14px;\n}\n.avatar {\n width: 40px;\n height: 40px;\n border-radius: 13px;\n flex: none;\n background: linear-gradient(140deg, var(--sac-primary), var(--sac-primary-2));\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--sac-primary-text);\n box-shadow:\n 0 6px 16px -6px color-mix(in srgb, var(--sac-primary) 60%, transparent),\n 0 1px 0 rgba(255, 255, 255, .25) inset;\n}\n.avatar svg { width: 22px; height: 22px; }\n.avatar .logo-wrap { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; }\n.avatar .logo { height: 22px; width: auto; display: block; }\n.avatar .logo-img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; display: block; border-radius: 9px; }\n.meta { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; }\n.title { font-weight: 650; font-size: 15.5px; letter-spacing: -.01em; line-height: 1.1; }\n.status {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 12px;\n color: color-mix(in srgb, var(--sac-text) 62%, transparent);\n}\n.dot {\n width: 7px; height: 7px;\n border-radius: 50%;\n flex: none;\n background: #34d399;\n color: #34d399;\n box-shadow: 0 0 0 0 rgba(52, 211, 153, .6);\n animation: sac-pulse 2.4s ease-out infinite;\n}\n.dot.connecting { background: #fbbf24; color: #fbbf24; animation: sac-pulse 1.1s ease-out infinite; }\n.dot.error { background: #f87171; color: #f87171; animation: none; }\n.dot.off { background: #94a3b8; color: #94a3b8; animation: none; }\n@keyframes sac-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 55%, transparent) }\n 70% { box-shadow: 0 0 0 6px transparent }\n 100% { box-shadow: 0 0 0 0 transparent }\n}\n.close {\n margin-left: auto;\n width: 32px; height: 32px;\n border-radius: 10px;\n border: none;\n cursor: pointer;\n background: var(--sac-surface-2);\n color: inherit;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s ease, transform .2s ease;\n}\n.close:hover { background: color-mix(in srgb, var(--sac-text) 12%, transparent); transform: translateY(1px); }\n.close svg { width: 16px; height: 16px; opacity: .8; }\n.powered { margin-left: auto; font-size: 10.5px; letter-spacing: .02em; opacity: .6; color: inherit; text-decoration: none; }\n.powered:hover { opacity: .85; text-decoration: underline; }\n.header-sep { height: 1px; margin: 0 16px; background: linear-gradient(90deg, transparent, var(--sac-border), transparent); }\n\n/* Full-page header: taller, logo-led, no close. */\n.panel.fullpage .header { padding: 18px 22px; }\n.panel.fullpage .avatar { width: 44px; height: 44px; }\n.panel.fullpage .avatar .logo { height: 26px; }\n.panel.fullpage .avatar svg { width: 28px; height: 28px; }\n\n/* ────────────────────────────── Messages ──────────────────────────── */\n.messages {\n flex: 1;\n overflow-y: auto;\n padding: 18px 16px 8px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n scroll-behavior: smooth;\n}\n.messages::-webkit-scrollbar { width: 8px; }\n.messages::-webkit-scrollbar-thumb {\n background: color-mix(in srgb, var(--sac-text) 14%, transparent);\n border-radius: 99px;\n border: 2px solid transparent;\n background-clip: padding-box;\n}\n.messages::-webkit-scrollbar-thumb:hover {\n background: color-mix(in srgb, var(--sac-text) 24%, transparent);\n background-clip: padding-box;\n}\n\n.row {\n display: flex;\n gap: 9px;\n max-width: 88%;\n animation: sac-msg-in .42s var(--sac-ease) both;\n}\n@keyframes sac-msg-in { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: none } }\n.row.user { align-self: flex-end; flex-direction: row-reverse; }\n.row.assistant { align-self: flex-start; }\n.mini {\n width: 26px; height: 26px;\n border-radius: 9px;\n flex: none;\n align-self: flex-end;\n background: linear-gradient(140deg, var(--sac-primary), var(--sac-primary-2));\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--sac-primary-text);\n}\n.mini svg { width: 15px; height: 15px; }\n\n.bubble {\n padding: 11px 14px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n white-space: pre-wrap;\n word-break: break-word;\n position: relative;\n}\n.bubble.assistant {\n background: linear-gradient(180deg, color-mix(in srgb, var(--sac-assistant-bubble) 86%, #fff 5%), var(--sac-assistant-bubble));\n color: var(--sac-assistant-bubble-text);\n border: 1px solid color-mix(in srgb, var(--sac-text) 8%, transparent);\n border-bottom-left-radius: 5px;\n box-shadow: 0 2px 8px -4px rgba(0, 0, 0, .4);\n}\n.bubble.user {\n background: linear-gradient(165deg,\n color-mix(in srgb, var(--sac-user-bubble) 88%, #fff 12%),\n var(--sac-user-bubble) 60%,\n color-mix(in srgb, var(--sac-user-bubble) 80%, var(--sac-primary-2) 20%));\n color: var(--sac-user-bubble-text);\n border-bottom-right-radius: 5px;\n box-shadow: 0 6px 16px -8px color-mix(in srgb, var(--sac-primary) 50%, transparent);\n}\n.bubble.greeting {\n background: transparent;\n border: 1px dashed color-mix(in srgb, var(--sac-text) 14%, transparent);\n color: color-mix(in srgb, var(--sac-text) 80%, transparent);\n box-shadow: none;\n}\n\n/* Typing indicator (assistant bubble with no text yet). */\n.bubble.typing { display: flex; gap: 4px; padding: 14px 15px; }\n.bubble.typing i {\n width: 7px; height: 7px;\n border-radius: 50%;\n background: color-mix(in srgb, var(--sac-assistant-bubble-text) 55%, transparent);\n animation: sac-typing 1.3s ease-in-out infinite;\n}\n.bubble.typing i:nth-child(2) { animation-delay: .18s; }\n.bubble.typing i:nth-child(3) { animation-delay: .36s; }\n@keyframes sac-typing { 0%, 60%, 100% { transform: translateY(0); opacity: .4 } 30% { transform: translateY(-5px); opacity: 1 } }\n\n.cursor::after {\n content: '';\n display: inline-block;\n width: 2px; height: 1.05em;\n margin-left: 2px;\n vertical-align: -2px;\n border-radius: 2px;\n background: currentColor;\n animation: sac-blink 1s steps(2, start) infinite;\n}\n@keyframes sac-blink { to { opacity: 0 } }\n\n/* Interleaved tool-activity strip (gated by showToolActivity): prose bubbles\n and inline tool chips stacked in the order the model produced them. */\n.blocks { display: flex; flex-direction: column; align-items: flex-start; gap: 7px; }\n.blocks .bubble { align-self: flex-start; }\n.toolchip {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n max-width: 100%;\n padding: 5px 10px;\n border-radius: 99px;\n font-size: 12px;\n line-height: 1.3;\n color: color-mix(in srgb, var(--sac-text) 78%, transparent);\n background: color-mix(in srgb, var(--sac-text) 6%, transparent);\n border: 1px solid color-mix(in srgb, var(--sac-text) 12%, transparent);\n animation: sac-msg-in .3s var(--sac-ease) both;\n}\n.toolchip .ti { display: inline-flex; flex: none; opacity: .8; }\n.toolchip .ti svg { width: 13px; height: 13px; }\n.toolchip .tn { font-weight: 600; letter-spacing: .01em; }\n.toolchip .ts { opacity: .7; }\n.toolchip .ta {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11px;\n opacity: .6;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n min-width: 0;\n}\n.toolchip.running { border-color: color-mix(in srgb, var(--sac-primary) 45%, transparent); }\n.toolchip.running .ts { color: var(--sac-primary); opacity: 1; animation: sac-typing 1.3s ease-in-out infinite; }\n.toolchip.done .ts::before { content: '✓ '; }\n.toolchip.error {\n color: var(--sac-secondary);\n border-color: color-mix(in srgb, var(--sac-secondary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-secondary) 10%, transparent);\n}\n.toolchip.error .ts::before { content: '! '; }\n\n/* ─────────────── Rendered markdown (assistant bubbles / snippets) ─────────── */\n/* The renderer (markdown.ts) emits a small allowlisted set of tags; these rules\n keep them legible inside the tight Aurora-Glass bubble + citation card. */\n/* Block-level markdown drives its own spacing/wrapping, so opt out of the\n bubble's pre-wrap (which would otherwise add stray blank lines). */\n.bubble.md { white-space: normal; }\n.md > :first-child { margin-top: 0; }\n.md > :last-child { margin-bottom: 0; }\n.md p { margin: 0 0 8px; }\n.md ul, .md ol { margin: 6px 0 8px; padding-left: 20px; }\n.md li { margin: 2px 0; }\n.md li::marker { color: color-mix(in srgb, var(--sac-primary) 75%, transparent); }\n.md a {\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n text-decoration: underline;\n text-underline-offset: 2px;\n word-break: break-word;\n}\n.md a:hover { text-decoration: none; }\n.md strong { font-weight: 700; }\n.md em { font-style: italic; }\n.md code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: .9em;\n padding: 1px 5px;\n border-radius: 5px;\n background: color-mix(in srgb, var(--sac-text) 10%, transparent);\n}\n.md pre {\n margin: 6px 0 8px;\n padding: 9px 11px;\n border-radius: 9px;\n overflow-x: auto;\n background: color-mix(in srgb, var(--sac-text) 9%, transparent);\n border: 1px solid color-mix(in srgb, var(--sac-text) 8%, transparent);\n}\n.md pre code { padding: 0; background: none; font-size: 12px; line-height: 1.45; }\n.md blockquote {\n margin: 6px 0;\n padding: 2px 0 2px 11px;\n border-left: 2px solid color-mix(in srgb, var(--sac-primary) 55%, transparent);\n color: color-mix(in srgb, var(--sac-text) 78%, transparent);\n}\n\n/* Full-page: center the conversation in a readable column. */\n.panel.fullpage .messages { padding: 26px 20px; }\n.panel.fullpage .row { max-width: 760px; width: 100%; margin-left: auto; margin-right: auto; }\n.panel.fullpage .row.user { max-width: 80%; margin-right: 0; }\n\n/* ───────────────── Sources (grounding citations) ──────────────────── */\n.sources {\n align-self: flex-start;\n max-width: 88%;\n margin: -4px 0 0 35px;\n}\n.panel.fullpage .sources { max-width: 760px; width: 100%; margin-left: auto; margin-right: auto; }\n.sources summary {\n cursor: pointer;\n list-style: none;\n display: inline-flex;\n align-items: center;\n gap: 7px;\n font-size: 12px;\n font-weight: 600;\n color: color-mix(in srgb, var(--sac-text) 70%, transparent);\n padding: 5px 0;\n user-select: none;\n}\n.sources summary::-webkit-details-marker { display: none; }\n.sources .chev { transition: transform .2s var(--sac-ease); flex: none; }\n.sources details[open] .chev { transform: rotate(90deg); }\n.sources .count {\n background: color-mix(in srgb, var(--sac-primary) 18%, transparent);\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n font-size: 10.5px;\n font-weight: 700;\n padding: 1px 7px;\n border-radius: 99px;\n}\n.sources ol { list-style: none; margin: 6px 0 2px; padding: 0; display: flex; flex-direction: column; gap: 7px; }\n.sources li {\n background: var(--sac-surface-2);\n border: 1px solid color-mix(in srgb, var(--sac-border) 70%, transparent);\n border-left: 2px solid var(--sac-primary);\n border-radius: 9px;\n padding: 8px 10px;\n}\n.sources .src-title {\n color: color-mix(in srgb, var(--sac-primary) 92%, #fff);\n font-weight: 600;\n font-size: 12.5px;\n text-decoration: none;\n word-break: break-word;\n}\n.sources a.src-title:hover { text-decoration: underline; }\n.sources span.src-title { color: var(--sac-text); opacity: .95; }\n.sources .src-snippet {\n display: block;\n margin-top: 3px;\n font-size: 11.5px;\n line-height: 1.45;\n color: color-mix(in srgb, var(--sac-text) 55%, transparent);\n white-space: normal;\n}\n\n/* ────────────────────────────── Composer ──────────────────────────── */\n.composer-wrap { padding: 12px 14px calc(12px + env(safe-area-inset-bottom)); }\n.composer {\n display: flex;\n align-items: flex-end;\n gap: 8px;\n padding: 7px 7px 7px 14px;\n border-radius: 18px;\n background: var(--sac-surface-2);\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n transition: border-color .25s ease, box-shadow .25s ease, background .25s ease;\n}\n.composer:focus-within {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n.composer textarea {\n flex: 1;\n resize: none;\n border: none;\n background: transparent;\n color: var(--sac-text);\n font-family: inherit;\n font-size: 14px;\n line-height: 1.45;\n max-height: 120px;\n padding: 6px 0;\n outline: none;\n}\n.composer textarea::placeholder { color: color-mix(in srgb, var(--sac-text) 42%, transparent); }\n.send {\n width: 38px; height: 38px;\n flex: none;\n border: none;\n border-radius: 13px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n box-shadow:\n 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent),\n 0 1px 0 rgba(255, 255, 255, .25) inset;\n transition: transform .2s var(--sac-ease), box-shadow .2s var(--sac-ease), opacity .2s ease;\n}\n.send svg { width: 18px; height: 18px; }\n.send:hover { transform: translateY(-1px) scale(1.05); }\n.send:active { transform: scale(.94); }\n.send:disabled { opacity: .4; cursor: default; transform: none; box-shadow: none; }\n\n/* Voice mic toggle (SMOODEV-2534) — ghost twin of .send; lights up while live. */\n.mic {\n width: 38px; height: 38px;\n flex: none;\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n border-radius: 13px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n color: color-mix(in srgb, var(--sac-text) 65%, transparent);\n transition: transform .2s var(--sac-ease), color .2s ease, background .25s ease, box-shadow .25s ease;\n}\n.mic svg { width: 18px; height: 18px; }\n.mic:hover { color: var(--sac-text); transform: translateY(-1px) scale(1.05); }\n.mic:active { transform: scale(.94); }\n.mic.active {\n border-color: transparent;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n animation: sac-mic-pulse 1.6s ease-out infinite;\n}\n/* Listening → soft expanding ring off the button (mirrors the presence pulse). */\n@keyframes sac-mic-pulse {\n 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--sac-primary) 45%, transparent); }\n 70% { box-shadow: 0 0 0 9px color-mix(in srgb, var(--sac-primary) 0%, transparent); }\n 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--sac-primary) 0%, transparent); }\n}\n/* Agent TTS playing → faster secondary-accent shimmer so \"speaking\" reads distinctly. */\n.mic.active.speaking {\n animation: sac-mic-speaking 0.9s ease-in-out infinite;\n}\n@keyframes sac-mic-speaking {\n 0%, 100% { box-shadow: 0 0 0 2px color-mix(in srgb, var(--sac-secondary) 35%, transparent); }\n 50% { box-shadow: 0 0 0 6px color-mix(in srgb, var(--sac-secondary) 12%, transparent); }\n}\n@media (prefers-reduced-motion: reduce) {\n .mic.active, .mic.active.speaking { animation: none; box-shadow: 0 0 0 2px color-mix(in srgb, var(--sac-primary) 40%, transparent); }\n}\n.footer {\n text-align: center;\n margin-top: 9px;\n font-size: 10.5px;\n letter-spacing: .04em;\n color: color-mix(in srgb, var(--sac-text) 38%, transparent);\n}\n.footer b { font-weight: 600; color: color-mix(in srgb, var(--sac-text) 55%, transparent); }\n.footer a { color: inherit; text-decoration: none; }\n.footer a:hover { text-decoration: underline; }\n\n/* ─────────────────── Pre-chat identity form ───────────────────────── */\n.prechat { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 18px; padding: 22px 20px; }\n.pc-head { text-align: center; }\n.pc-title { font-size: 17px; font-weight: 650; letter-spacing: -.01em; }\n.pc-sub { margin-top: 4px; font-size: 13px; color: color-mix(in srgb, var(--sac-text) 60%, transparent); }\n.pc-form { display: flex; flex-direction: column; gap: 12px; }\n.pc-field { display: flex; flex-direction: column; gap: 5px; }\n.pc-field span { font-size: 12px; font-weight: 600; color: color-mix(in srgb, var(--sac-text) 70%, transparent); }\n.pc-field input {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 12px;\n padding: 11px 13px;\n font-family: inherit;\n font-size: 14px;\n outline: none;\n transition: border-color .2s ease, box-shadow .2s ease;\n}\n.pc-field input::placeholder { color: color-mix(in srgb, var(--sac-text) 42%, transparent); }\n.pc-field input:focus {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n/* Inline phone validity — subtle, themed. Empty stays neutral (optional field). */\n.pc-field.valid input {\n border-color: color-mix(in srgb, var(--sac-primary) 55%, #2faa6a 45%);\n}\n.pc-field.invalid input {\n border-color: color-mix(in srgb, #e2566b 62%, var(--sac-border) 38%);\n}\n.pc-field.invalid input:focus {\n box-shadow: 0 0 0 4px color-mix(in srgb, #e2566b 16%, transparent);\n}\n.pc-field .pc-hint {\n min-height: 13px;\n margin-top: 1px;\n font-size: 11.5px;\n font-weight: 500;\n line-height: 1.2;\n color: color-mix(in srgb, #e2566b 78%, var(--sac-text) 22%);\n}\n.pc-submit {\n margin-top: 4px;\n border: none;\n border-radius: 13px;\n padding: 12px;\n cursor: pointer;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n font-weight: 650;\n font-size: 14px;\n box-shadow: 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent), 0 1px 0 rgba(255, 255, 255, .25) inset;\n transition: transform .2s var(--sac-ease);\n}\n.pc-submit:hover { transform: translateY(-1px); }\n.pc-submit:active { transform: scale(.98); }\n.pc-consents { display: flex; flex-direction: column; gap: 9px; margin-top: 2px; }\n.pc-consent { display: flex; align-items: flex-start; gap: 9px; cursor: pointer; }\n.pc-consent input {\n margin-top: 2px;\n width: 16px;\n height: 16px;\n flex: 0 0 auto;\n accent-color: var(--sac-primary);\n cursor: pointer;\n}\n.pc-consent span { font-size: 12px; line-height: 1.4; color: color-mix(in srgb, var(--sac-text) 72%, transparent); }\n\n/* ─────────────────── Starter-prompt chips ─────────────────────────── */\n.prompts { display: flex; flex-wrap: wrap; gap: 8px; margin: 2px 0 2px 35px; }\n.panel.fullpage .prompts { margin-left: auto; margin-right: auto; max-width: 760px; width: 100%; }\n.chip {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 999px;\n padding: 8px 13px;\n font-family: inherit;\n font-size: 12.5px;\n cursor: pointer;\n text-align: left;\n transition: border-color .2s ease, background .2s ease, transform .2s ease;\n}\n.chip:hover {\n border-color: color-mix(in srgb, var(--sac-primary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-primary) 10%, var(--sac-surface-2));\n transform: translateY(-1px);\n}\n\n/* ───────────── Mid-conversation suggested-reply chips ─────────────── */\n.reply-suggestions { padding: 0 14px 4px; }\n.reply-suggestions:empty { display: none; }\n\n/* ─────────────── OTP / tool-confirmation interrupt ────────────────── */\n.interrupt { padding: 0 14px; }\n.int-card {\n border: 1px solid color-mix(in srgb, var(--sac-primary) 35%, var(--sac-border));\n background: color-mix(in srgb, var(--sac-primary) 8%, var(--sac-surface-2));\n border-radius: 14px;\n padding: 12px 13px;\n animation: sac-msg-in .3s var(--sac-ease) both;\n}\n.int-head { display: flex; align-items: center; gap: 8px; }\n.int-ico { display: flex; color: var(--sac-primary); }\n.int-ico svg { width: 17px; height: 17px; }\n.int-title { font-size: 13.5px; font-weight: 650; }\n.int-desc { margin-top: 5px; font-size: 12.5px; line-height: 1.45; color: color-mix(in srgb, var(--sac-text) 80%, transparent); }\n.int-sent { margin-top: 6px; font-size: 11.5px; color: color-mix(in srgb, var(--sac-text) 60%, transparent); }\n.int-row { display: flex; gap: 8px; margin-top: 10px; }\n.int-input {\n flex: 1;\n min-width: 0;\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-bg);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 11px;\n font-family: inherit;\n font-size: 14px;\n letter-spacing: .14em;\n outline: none;\n transition: border-color .2s ease, box-shadow .2s ease;\n}\n.int-input:focus {\n border-color: color-mix(in srgb, var(--sac-primary) 60%, transparent);\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--sac-primary) 14%, transparent);\n}\n.int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn {\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-surface-2);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 14px;\n font-family: inherit;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: transform .2s var(--sac-ease), background .2s ease, border-color .2s ease;\n}\n.int-btn:hover { transform: translateY(-1px); }\n.int-btn.primary {\n border: none;\n background: linear-gradient(150deg, var(--sac-primary), var(--sac-primary-2));\n color: var(--sac-primary-text);\n box-shadow: 0 6px 14px -6px color-mix(in srgb, var(--sac-primary) 65%, transparent);\n}\n.int-row .int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn { flex: 1; }\n.int-row .int-input + .int-form { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; }\n.int-form .pc-field input { width: 100%; box-sizing: border-box; }\n.int-form .int-error { margin-top: 2px; }\n.int-btn { flex: 0 0 auto; }\n.int-error { margin-top: 8px; font-size: 12px; color: #f87171; }\n.int-card { position: relative; }\n.int-close {\n position: absolute;\n top: 8px;\n right: 9px;\n border: none;\n background: transparent;\n color: color-mix(in srgb, var(--sac-text) 55%, transparent);\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n padding: 2px 4px;\n border-radius: 6px;\n transition: color .2s ease, background .2s ease;\n}\n.int-close:hover { color: var(--sac-text); background: color-mix(in srgb, var(--sac-text) 8%, transparent); }\n\n/* ─────────────── Cross-device \"Restore my chats\" ──────────────────── */\n.restore-link {\n border: none;\n background: none;\n padding: 0;\n font: inherit;\n font-size: 10.5px;\n letter-spacing: .04em;\n color: color-mix(in srgb, var(--sac-primary) 80%, var(--sac-text));\n cursor: pointer;\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n.restore-link:hover { color: var(--sac-primary); }\n.restore-list { display: flex; flex-direction: column; gap: 7px; margin-top: 9px; }\n.restore-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n text-align: left;\n border: 1px solid color-mix(in srgb, var(--sac-border) 80%, transparent);\n background: var(--sac-bg);\n color: var(--sac-text);\n border-radius: 10px;\n padding: 9px 11px;\n font-family: inherit;\n font-size: 12.5px;\n cursor: pointer;\n transition: border-color .2s ease, background .2s ease, transform .2s ease;\n}\n.restore-item:hover {\n border-color: color-mix(in srgb, var(--sac-primary) 50%, transparent);\n background: color-mix(in srgb, var(--sac-primary) 8%, var(--sac-bg));\n transform: translateY(-1px);\n}\n.restore-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.restore-when { flex: 0 0 auto; font-size: 11px; color: color-mix(in srgb, var(--sac-text) 55%, transparent); }\n\n.hidden { display: none !important; }\n\n@media (prefers-reduced-motion: reduce) {\n .launcher::before, .dot, .bubble.typing i { animation: none !important; }\n .panel, .row, .launcher, .send, .close { animation: none !important; transition: none !important; }\n}\n`;\n}\n","/**\n * `<smooth-agent-chat>` — a framework-light embeddable chat web component.\n *\n * A clean, dependency-light web component that preserves a familiar embedding\n * model — a launcher + popover panel, declarative HTML attributes, and a\n * programmatic API — while talking to the `@smooai/smooth-operator` protocol\n * client. The visual layer is the \"Aurora Glass\" design system (see\n * {@link buildStyles}): a spring launcher with a live presence pulse, a\n * glass-depth panel, a gradient brand avatar + status dot, an animated typing\n * indicator, message rise-in, refined source cards, and an icon composer. Every\n * color is driven by `--sac-*` custom properties so a host's brand flows through.\n *\n * Embedding model:\n * <smooth-agent-chat endpoint=\"ws://localhost:8787/ws\" agent-id=\"…\"></smooth-agent-chat>\n * or programmatically via {@link mountChatWidget}.\n */\nimport { AsYouType, isValidPhoneNumber, parsePhoneNumber } from 'libphonenumber-js/min';\nimport type { ChatWidgetConfig, ChatWidgetMode, ChatWidgetTheme } from './config.js';\nimport { needsUserInfo, resolveConfig } from './config.js';\nimport {\n type ChatMessage,\n type Citation,\n type ConnectionStatus,\n ConversationController,\n type IdentityRestore,\n type Interrupt,\n SUPPORTED_INTERACTION_CAPABILITIES,\n type ToolCall,\n} from './conversation.js';\nimport { SMOOTH_ICON_SVG } from './logo.js';\nimport { cleanCitationSnippet, escapeHtml, renderMarkdown, safeHttpUrl } from './markdown.js';\nimport { buildStyles } from './styles.js';\nimport { VoiceSession } from './voice-session.js';\n\nexport const ELEMENT_TAG = 'smooth-agent-chat';\n\n/**\n * Default region for phone parsing/formatting on the pre-chat form. The widget\n * is US-first; the backend does the authoritative E.164 normalization (SMOODEV-2153),\n * so this only governs the as-you-type display + the inline validity hint and the\n * best-effort E.164 we send when the number already parses as valid.\n */\nconst PHONE_DEFAULT_REGION = 'US' as const;\n\n/**\n * Best-effort E.164 for an as-typed phone number. Returns the canonical\n * `+1…` form when the value parses to a valid number in {@link PHONE_DEFAULT_REGION},\n * otherwise `null` (caller falls back to sending the raw value — the backend\n * re-parses and normalizes/nulls authoritatively).\n */\nfunction phoneToE164(value: string): string | null {\n const v = value.trim();\n if (!v) return null;\n try {\n if (!isValidPhoneNumber(v, PHONE_DEFAULT_REGION)) return null;\n return parsePhoneNumber(v, PHONE_DEFAULT_REGION).number;\n } catch {\n return null;\n }\n}\n\n/** Public smooth-operator repo — the \"powered by\" header tag + footer link here. */\nconst SMOOTH_OPERATOR_URL = 'https://github.com/SmooAI/smooth-operator';\n\nconst OBSERVED = ['endpoint', 'agent-id', 'agent-name', 'logo-url', 'placeholder', 'greeting', 'start-open', 'mode', 'hide-branding', 'show-tool-activity'] as const;\n\n/**\n * Inline SVG icons (static, trusted strings — never interpolated with user data).\n * Kept here so the IIFE bundle is self-contained: no icon-font or network fetch.\n */\nconst ICON = {\n /** Launcher — a speech bubble carrying a spark (chat + AI). */\n spark: `<svg class=\"ico\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 3.5c-4.7 0-8.5 3.2-8.5 7.2 0 2.2 1.2 4.2 3 5.5v3.3l3.2-1.7c.7.1 1.5.2 2.3.2 4.7 0 8.5-3.2 8.5-7.3S16.7 3.5 12 3.5Z\" fill=\"currentColor\" opacity=\".22\"/><path d=\"M13.4 7.2 9 12.6h2.6l-1 4.2 4.4-5.4h-2.6l1-4.2Z\" fill=\"currentColor\"/></svg>`,\n /** Small assistant avatar used beside each assistant message. */\n bot: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"4.5\" y=\"7.5\" width=\"15\" height=\"11\" rx=\"3.5\" stroke=\"currentColor\" stroke-width=\"1.6\"/><path d=\"M12 4.5v3M8.5 12.2h.01M15.5 12.2h.01\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\"/><path d=\"M9.5 15.4c.7.6 1.5.9 2.5.9s1.8-.3 2.5-.9\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\"/></svg>`,\n /** Close (collapse panel) — a downward chevron. */\n close: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"m7 10 5 5 5-5\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Send — an upward arrow. */\n send: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 19V6M12 6l-5.5 5.5M12 6l5.5 5.5\" stroke=\"currentColor\" stroke-width=\"1.9\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Sources disclosure caret. */\n chev: `<svg width=\"11\" height=\"11\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"m9 6 6 6-6 6\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** OTP interrupt — a padlock. */\n lock: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"5\" y=\"10.5\" width=\"14\" height=\"9.5\" rx=\"2.2\" stroke=\"currentColor\" stroke-width=\"1.7\"/><path d=\"M8 10.5V8a4 4 0 0 1 8 0v2.5\" stroke=\"currentColor\" stroke-width=\"1.7\"/></svg>`,\n /** Identity-intake interrupt — a person. */\n user: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"12\" cy=\"8.2\" r=\"3.4\" stroke=\"currentColor\" stroke-width=\"1.7\"/><path d=\"M5.5 19.5c.8-3.1 3.4-4.8 6.5-4.8s5.7 1.7 6.5 4.8\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\"/></svg>`,\n /** Tool-confirmation interrupt — a shield. */\n shield: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 3 5 6v5c0 4.4 3 7.2 7 8.5 4-1.3 7-4.1 7-8.5V6l-7-3Z\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linejoin=\"round\"/><path d=\"m9 11.5 2 2 4-4\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`,\n /** Tool-activity chip — a wrench. */\n tool: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M14.7 6.3a3.5 3.5 0 0 0-4.6 4.3l-5 5a1.6 1.6 0 0 0 2.3 2.3l5-5a3.5 3.5 0 0 0 4.3-4.6l-2 2-1.7-.3-.3-1.7 2-2Z\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/></svg>`,\n /** Voice toggle — a microphone. */\n mic: `<svg viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect x=\"9\" y=\"3.5\" width=\"6\" height=\"11\" rx=\"3\" stroke=\"currentColor\" stroke-width=\"1.7\"/><path d=\"M5.5 11.5a6.5 6.5 0 0 0 13 0M12 18v2.5M9 20.5h6\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\"/></svg>`,\n} as const;\n\n/**\n * The Rich Interactions **card registry**: interaction kind → overlay card.\n * `interaction_required { kind }` looks its card up here; registering a card IS\n * declaring the widget's render capability for that kind (see\n * `SUPPORTED_INTERACTION_CAPABILITIES` in conversation.ts — a test keeps the\n * two aligned). Adding a kind = one card builder + one entry.\n *\n * The existing OTP and tool-approval overlays are prior instances of this same\n * shape and should retrofit onto this registry later (their wire events predate\n * the pattern).\n */\nexport interface InteractionCardContext {\n /** Submit kind-shaped values (resumes the parked turn; server validates). */\n submit: (values: Record<string, unknown>) => void;\n /** Decline the interaction (the agent continues without it). */\n decline: () => void;\n /** Persisted visitor identity, for pre-filling known fields. */\n prefill: { name?: string; email?: string; phone?: string };\n /** Wire live phone formatting + validity hint onto a form's phone input. */\n wirePhoneField: (form: HTMLFormElement) => void;\n}\n\nexport interface InteractionCard {\n /** The render capability this card provides (goes into `supports`). */\n capability: string;\n /** Card header title. */\n title: string;\n /** Static, trusted header icon SVG. */\n icon: string;\n /** Build the card body for an `interaction` interrupt. */\n build: (it: Extract<Interrupt, { kind: 'interaction' }>, ctx: InteractionCardContext) => HTMLElement;\n}\n\n/**\n * The identity_intake card: the fields the agent requested (pre-chat form field\n * pattern — same classes, same phone formatting), per-field server errors, a\n * submit and a decline affordance. Server-supplied text (reason, labels, error\n * messages) is set via `textContent` — never innerHTML.\n */\nfunction buildIdentityIntakeCard(it: Extract<Interrupt, { kind: 'interaction' }>, ctx: InteractionCardContext): HTMLElement {\n const form = document.createElement('form');\n form.className = 'int-form';\n form.noValidate = true;\n\n if (it.reason) {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = it.reason;\n form.appendChild(desc);\n }\n\n const DEFAULTS: Record<string, { label: string; type: string; autocomplete: string }> = {\n name: { label: 'Name', type: 'text', autocomplete: 'name' },\n email: { label: 'Email', type: 'email', autocomplete: 'email' },\n phone: { label: 'Phone', type: 'tel', autocomplete: 'tel' },\n };\n\n // Parse the kind's spec defensively: `{ fields: [{ key, required, label? }] }`.\n const rawFields = Array.isArray(it.spec.fields) ? it.spec.fields : [];\n const fields: { key: 'name' | 'email' | 'phone'; required: boolean; label?: string }[] = [];\n for (const f of rawFields) {\n if (!f || typeof f !== 'object') continue;\n const o = f as Record<string, unknown>;\n const key = typeof o.key === 'string' ? o.key : '';\n if (key !== 'name' && key !== 'email' && key !== 'phone') continue;\n fields.push({ key, required: o.required === true, label: typeof o.label === 'string' ? o.label : undefined });\n }\n if (fields.length === 0) fields.push({ key: 'email', required: true });\n\n for (const f of fields) {\n const d = DEFAULTS[f.key]!;\n const label = document.createElement('label');\n label.className = 'pc-field';\n const caption = document.createElement('span');\n caption.textContent = f.label ?? d.label;\n const input = document.createElement('input');\n input.name = f.key;\n input.type = d.type;\n input.setAttribute('autocomplete', d.autocomplete);\n input.required = f.required;\n const prefill = ctx.prefill[f.key];\n if (prefill) input.value = prefill;\n label.append(caption, input);\n if (f.key === 'phone') {\n const hint = document.createElement('span');\n hint.className = 'pc-hint';\n hint.setAttribute('aria-live', 'polite');\n label.appendChild(hint);\n }\n // Per-field server-side validation error (interaction_invalid).\n const serverError = it.errors?.find((e) => e.field === f.key);\n if (serverError) {\n label.classList.add('invalid');\n const err = document.createElement('span');\n err.className = 'int-error';\n err.textContent = serverError.message;\n label.appendChild(err);\n }\n form.appendChild(label);\n }\n\n const row = document.createElement('div');\n row.className = 'int-row';\n const decline = document.createElement('button');\n decline.className = 'int-btn';\n decline.type = 'button';\n decline.textContent = 'No thanks';\n decline.addEventListener('click', () => ctx.decline());\n const share = document.createElement('button');\n share.className = 'int-btn primary';\n share.type = 'submit';\n share.textContent = 'Share details';\n row.append(decline, share);\n form.appendChild(row);\n\n form.addEventListener('submit', (ev) => {\n ev.preventDefault();\n if (!form.reportValidity()) return;\n const data = new FormData(form);\n const val = (k: string) => ((data.get(k) as string | null)?.trim() || undefined);\n\n // Phone: mirror the pre-chat rules — block a required-but-invalid number,\n // prefer canonical E.164 when it parses (the server re-validates anyway).\n const rawPhone = val('phone');\n const phoneInput = form.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (rawPhone && phoneInput && !isValidPhoneNumber(rawPhone, PHONE_DEFAULT_REGION)) {\n const field = phoneInput.closest('.pc-field');\n field?.classList.add('invalid');\n const hint = field?.querySelector('.pc-hint');\n if (hint) hint.textContent = 'Enter a valid phone number';\n if (phoneInput.hasAttribute('required')) {\n phoneInput.focus();\n return;\n }\n }\n const phone = rawPhone ? (phoneToE164(rawPhone) ?? rawPhone) : undefined;\n ctx.submit({ name: val('name'), email: val('email'), phone });\n });\n // Same live phone formatting + validity hint as the pre-chat form.\n ctx.wirePhoneField(form);\n queueMicrotask(() => (form.querySelector('input') as HTMLInputElement | null)?.focus());\n return form;\n}\n\n/** Kind → card. See the registry doc above. */\nexport const INTERACTION_CARDS: Record<string, InteractionCard> = {\n identity_intake: {\n capability: 'identity_form',\n title: 'Share your details',\n icon: ICON.user,\n build: buildIdentityIntakeCard,\n },\n};\n\n// `safeHttpUrl` / `escapeHtml` live in `./markdown.js` (the markdown renderer\n// needs them too); re-exported here for back-compat with existing importers.\nexport { escapeHtml, safeHttpUrl } from './markdown.js';\n\nexport class SmoothAgentChatElement extends HTMLElement {\n static get observedAttributes(): readonly string[] {\n return OBSERVED;\n }\n\n private readonly root: ShadowRoot;\n private controller: ConversationController | null = null;\n private overrides: Partial<ChatWidgetConfig> = {};\n private open = false;\n private messages: ChatMessage[] = [];\n private status: ConnectionStatus = 'idle';\n private mounted = false;\n /** True once the visitor has cleared the pre-chat identity gate (or it's not needed). */\n private userInfoSatisfied = false;\n /** True after the visitor has sent their first message (hides starter chips). */\n private hasSent = false;\n /** Starter prompts shown as chips in the empty state. */\n private examplePrompts: string[] = [];\n /** Whether mid-conversation suggested-reply chips are shown (config). */\n private showSuggestedReplies = true;\n /** Resolved greeting text, cached so async (rAF) renders can reuse it. */\n private greeting = '';\n /** Current mid-turn interrupt (OTP / tool-confirmation), or null. */\n private interrupt: Interrupt | null = null;\n private interruptEl: HTMLElement | null = null;\n /** Cross-device \"restore my chats\" flow state (ADR-048 §c). */\n private identityRestore: IdentityRestore = { phase: 'idle' };\n /** Whether the cross-device restore affordance is offered (config). */\n private allowChatRestore = true;\n /** True while the pre-chat identity gate is showing (blocks premature connect). */\n private gating = false;\n /** Voice config (SMOODEV-2534) — enabled=false renders zero voice UI. */\n private voiceCfg: { enabled: boolean; url: string } = { enabled: false, url: '' };\n /** Live voice session, or null when voice is off. */\n private voiceSession: VoiceSession | null = null;\n\n // Cached DOM refs (populated in render()).\n private panelEl: HTMLElement | null = null;\n private launcherEl: HTMLElement | null = null;\n private messagesEl: HTMLElement | null = null;\n private statusEl: HTMLElement | null = null;\n private dotEl: HTMLElement | null = null;\n private inputEl: HTMLTextAreaElement | null = null;\n private sendBtn: HTMLButtonElement | null = null;\n private micBtn: HTMLButtonElement | null = null;\n private suggestionsEl: HTMLElement | null = null;\n\n // ── Smooth streaming reveal ──\n // Tokens arrive in variable-size bursts at uneven rates, so revealing text in\n // lockstep with arrival looks jerky. Instead we buffer the full target text\n // and reveal it via a requestAnimationFrame \"typewriter\" at an adaptive rate\n // (chars/frame scales with the pending backlog so it never falls behind the\n // network). State below tracks the single in-flight streaming bubble.\n /** The live streaming assistant bubble whose textContent the rAF loop drives. */\n private streamBubbleEl: HTMLElement | null = null;\n /** Message id the reveal is bound to (guards against stale frames after rebuilds). */\n private streamMsgId: string | null = null;\n /** Full buffered target text for the streaming message (grows as tokens arrive). */\n private streamTarget = '';\n /** How many chars of {@link streamTarget} are currently shown. */\n private displayedLength = 0;\n private rafId = 0;\n /** Block structure signature of the last-rendered streaming message (tool chips\n * only — text growth doesn't change it), so a chip add/resolve forces a rebuild\n * while plain trailing-text growth stays on the fast reveal path. */\n private prevBlockSig = '';\n\n constructor() {\n super();\n this.root = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback(): void {\n this.mounted = true;\n this.render();\n }\n\n disconnectedCallback(): void {\n this.mounted = false;\n this.resetReveal();\n this.stopVoice();\n this.controller?.disconnect();\n this.controller = null;\n }\n\n attributeChangedCallback(): void {\n if (this.mounted) this.render();\n }\n\n /**\n * Programmatically merge config overrides (endpoint, agentId, theme, …). Values\n * set here take precedence over HTML attributes. Re-renders the widget.\n */\n configure(config: Partial<ChatWidgetConfig>): void {\n this.overrides = { ...this.overrides, ...config };\n if (config.theme) {\n this.overrides.theme = { ...(this.overrides.theme ?? {}), ...config.theme };\n }\n if (this.mounted) this.render();\n }\n\n /** Open the chat panel. */\n openChat(): void {\n this.open = true;\n this.syncOpenState();\n // Don't connect while the pre-chat identity gate is unsatisfied — connecting\n // here would create a session BEFORE the visitor submits their name/email/\n // consent, sending an empty identity. The form's submit handler connects.\n if (!this.gating) void this.controller?.connect().catch(() => {});\n }\n\n /** Collapse the chat panel back to the launcher. */\n closeChat(): void {\n this.open = false;\n this.syncOpenState();\n }\n\n // ─────────────────────────── Config resolution ─────────────────────────────\n\n private readConfig(): ChatWidgetConfig | null {\n const endpoint = this.overrides.endpoint ?? this.getAttribute('endpoint') ?? '';\n const agentId = this.overrides.agentId ?? this.getAttribute('agent-id') ?? '';\n if (!endpoint || !agentId) return null;\n\n const theme: ChatWidgetTheme | undefined = this.overrides.theme;\n const modeAttr = this.getAttribute('mode');\n const mode: ChatWidgetMode = this.overrides.mode ?? (modeAttr === 'fullpage' ? 'fullpage' : modeAttr === 'popover' ? 'popover' : undefined) ?? 'popover';\n return {\n endpoint,\n mode,\n agentId,\n agentName: this.overrides.agentName ?? this.getAttribute('agent-name') ?? undefined,\n logoUrl: this.overrides.logoUrl ?? this.getAttribute('logo-url') ?? undefined,\n userName: this.overrides.userName,\n userEmail: this.overrides.userEmail,\n userPhone: this.overrides.userPhone,\n authContext: this.overrides.authContext,\n placeholder: this.overrides.placeholder ?? this.getAttribute('placeholder') ?? undefined,\n greeting: this.overrides.greeting ?? this.getAttribute('greeting') ?? undefined,\n connectionErrorMessage: this.overrides.connectionErrorMessage,\n startOpen: this.overrides.startOpen ?? this.hasAttribute('start-open'),\n hideBranding: this.overrides.hideBranding ?? this.hasAttribute('hide-branding'),\n examplePrompts: this.overrides.examplePrompts,\n showSuggestedReplies: this.overrides.showSuggestedReplies,\n requireName: this.overrides.requireName,\n requireEmail: this.overrides.requireEmail,\n requirePhone: this.overrides.requirePhone,\n collectPhone: this.overrides.collectPhone,\n collectConsent: this.overrides.collectConsent,\n allowChatRestore: this.overrides.allowChatRestore,\n allowAnonymous: this.overrides.allowAnonymous,\n showToolActivity: this.overrides.showToolActivity ?? this.hasAttribute('show-tool-activity'),\n voice: this.overrides.voice,\n theme,\n };\n }\n\n // ───────────────────────────────── Render ──────────────────────────────────\n\n private render(): void {\n const config = this.readConfig();\n if (!config) {\n this.root.innerHTML = '';\n return;\n }\n const resolved = resolveConfig(config);\n\n this.allowChatRestore = resolved.allowChatRestore;\n\n // (Re)create the controller only when there isn't one yet. Attribute churn\n // (e.g. theme tweaks) re-renders the view without dropping the session.\n if (!this.controller) {\n this.controller = new ConversationController(config, {\n onMessages: (messages) => {\n this.handleMessages(messages, resolved.greeting);\n },\n onStatus: (status) => {\n this.status = status;\n this.renderStatus();\n this.renderComposerState();\n },\n onInterrupt: (interrupt) => {\n this.interrupt = interrupt;\n this.renderInterrupt();\n // Suggestion chips are hidden while an interrupt overlay is up.\n this.renderSuggestions();\n },\n onIdentityRestore: (state) => {\n this.identityRestore = state;\n this.renderInterrupt();\n // The restore overlay reuses the interrupt slot — hide chips too.\n this.renderSuggestions();\n },\n });\n if (resolved.startOpen) this.open = true;\n // Returning visitor: a persisted session or identity lets us skip the\n // pre-chat gate and resume straight into the conversation (ADR-048 §b).\n if (this.controller.hasPersistedSession() || this.controller.hasPersistedIdentity()) {\n this.userInfoSatisfied = true;\n }\n }\n\n const fullpage = resolved.mode === 'fullpage';\n // Full-page mode is always \"open\" — it fills its container and has no\n // launcher to toggle.\n if (fullpage) this.open = true;\n\n const style = document.createElement('style');\n style.textContent = buildStyles(resolved.theme, resolved.mode);\n\n // Header: in full-page mode lead with the brand logo in the avatar tile\n // and a subtle \"powered by\" tag; in popover mode show a brand-colored\n // monogram avatar + a compact close (collapse) button. The logo defaults\n // to the square Smooth icon, but a host page can override it with\n // `logoUrl` (already sanitized to http(s)-only by resolveConfig; escaped\n // here so it can't break out of the src attribute).\n const monogram = escapeHtml((resolved.agentName.trim().charAt(0) || 'A').toUpperCase());\n const headerLogo = resolved.logoUrl\n ? `<img src=\"${escapeHtml(resolved.logoUrl)}\" alt=\"\" class=\"logo-img\" />`\n : SMOOTH_ICON_SVG;\n const header = fullpage\n ? `<div class=\"header\">\n <div class=\"avatar\"><span class=\"logo-wrap\">${headerLogo}</span></div>\n <div class=\"meta\">\n <span class=\"title\">${escapeHtml(resolved.agentName)}</span>\n <span class=\"status\"><span class=\"dot off\"></span><span class=\"status-text\"></span></span>\n </div>\n ${\n resolved.hideBranding\n ? ''\n : `<a class=\"powered\" href=\"${SMOOTH_OPERATOR_URL}\" target=\"_blank\" rel=\"noopener noreferrer\">powered by smooth-operator</a>`\n }\n </div>`\n : `<div class=\"header\">\n <div class=\"avatar\">${monogram}</div>\n <div class=\"meta\">\n <span class=\"title\">${escapeHtml(resolved.agentName)}</span>\n <span class=\"status\"><span class=\"dot off\"></span><span class=\"status-text\"></span></span>\n </div>\n <button class=\"close\" aria-label=\"Close chat\">${ICON.close}</button>\n </div>`;\n\n // Remember starter prompts + greeting for the empty-state chips / async renders.\n this.examplePrompts = resolved.examplePrompts;\n this.showSuggestedReplies = resolved.showSuggestedReplies;\n this.greeting = resolved.greeting;\n\n // Gate the conversation behind a pre-chat identity form when required.\n const gating = needsUserInfo(resolved) && !this.userInfoSatisfied;\n this.gating = gating;\n // Phone is collected by default (optional unless requirePhone). Consent\n // checkboxes default to shown, explicit + unchecked (ADR-048 §a/§3).\n const showPhone = resolved.requirePhone || resolved.collectPhone;\n const field = (name: string, type: string, label: string, autocomplete: string, required: boolean, hint = false) =>\n `<label class=\"pc-field\"><span>${escapeHtml(label)}</span><input name=\"${name}\" type=\"${type}\" autocomplete=\"${autocomplete}\"${required ? ' required' : ''} />${\n hint ? '<span class=\"pc-hint\" aria-live=\"polite\"></span>' : ''\n }</label>`;\n const consentBox = (name: string, label: string) =>\n `<label class=\"pc-consent\"><input name=\"${name}\" type=\"checkbox\" /><span>${escapeHtml(label)}</span></label>`;\n const consentHtml = resolved.collectConsent\n ? `<div class=\"pc-consents\">\n ${consentBox('emailOptIn', 'Email me product news and offers.')}\n ${consentBox('smsOptIn', 'Text me updates by SMS. Message/data rates may apply.')}\n </div>`\n : '';\n const prechatHtml = `\n <div class=\"prechat\">\n <div class=\"pc-head\">\n <div class=\"pc-title\">Before we chat</div>\n <div class=\"pc-sub\">A couple details so ${escapeHtml(resolved.agentName)} can help.</div>\n </div>\n <form class=\"pc-form\" novalidate>\n ${resolved.requireName ? field('name', 'text', 'Name', 'name', true) : ''}\n ${resolved.requireEmail ? field('email', 'email', 'Email', 'email', true) : ''}\n ${showPhone ? field('phone', 'tel', 'Phone', 'tel', resolved.requirePhone, true) : ''}\n ${consentHtml}\n <button type=\"submit\" class=\"pc-submit\">Start chat</button>\n </form>\n </div>`;\n // Footer: optional \"powered by\" branding (hidden by hide-branding) and an\n // optional \"Restore my chats\" affordance. The \" · \" separator only appears\n // when both are present, and the footer is omitted entirely when neither is.\n const brandingHtml = resolved.hideBranding\n ? ''\n : `<a href=\"${SMOOTH_OPERATOR_URL}\" target=\"_blank\" rel=\"noopener noreferrer\">powered by <b>smooth‑operator</b></a>`;\n const restoreBtn = this.allowChatRestore ? `<button type=\"button\" class=\"restore-link\">Restore my chats</button>` : '';\n const footerInner = [brandingHtml, restoreBtn].filter(Boolean).join(' · ');\n const footerHtml = footerInner ? `<div class=\"footer\">${footerInner}</div>` : '';\n // Voice (SMOODEV-2534): mic toggle in the composer, only when enabled.\n this.voiceCfg = resolved.voice;\n const micHtml = resolved.voice.enabled\n ? `<button class=\"mic\" type=\"button\" aria-label=\"Start voice\" aria-pressed=\"false\" title=\"Talk to ${escapeHtml(resolved.agentName)}\">${ICON.mic}</button>`\n : '';\n const chatHtml = `\n <div class=\"messages\"></div>\n <div class=\"reply-suggestions\"></div>\n <div class=\"interrupt hidden\"></div>\n <div class=\"composer-wrap\">\n <div class=\"composer\">\n <textarea rows=\"1\" placeholder=\"${escapeHtml(resolved.placeholder)}\"></textarea>\n ${micHtml}\n <button class=\"send\" type=\"button\" aria-label=\"Send message\">${ICON.send}</button>\n </div>\n ${footerHtml}\n </div>`;\n\n const container = document.createElement('div');\n container.className = 'wrap';\n container.innerHTML = `\n ${fullpage ? '' : `<button class=\"launcher\" part=\"launcher\" aria-label=\"Open chat\">${ICON.spark}</button>`}\n <div class=\"panel${fullpage ? ' fullpage' : ' hidden'}\" part=\"panel\" role=\"${fullpage ? 'region' : 'dialog'}\" aria-label=\"${escapeHtml(resolved.agentName)} chat\">\n ${header}\n <div class=\"header-sep\"></div>\n ${gating ? prechatHtml : chatHtml}\n </div>\n `;\n\n // Tag the logo <svg> so styles can size it (the inlined SVG has its own id).\n const logoSvg = container.querySelector('.logo-wrap svg');\n if (logoSvg) logoSvg.setAttribute('class', 'logo');\n\n // A full DOM rebuild invalidates any cached streaming-bubble ref; cancel\n // the in-flight reveal loop so renderMessages can re-bind cleanly. A live\n // voice session is bound to the old composer's mic button — end it too.\n this.resetReveal();\n this.stopVoice();\n this.root.replaceChildren(style, container);\n\n this.launcherEl = container.querySelector('.launcher');\n this.panelEl = container.querySelector('.panel');\n this.messagesEl = container.querySelector('.messages');\n this.statusEl = container.querySelector('.status-text');\n this.dotEl = container.querySelector('.dot');\n this.inputEl = container.querySelector('textarea');\n this.sendBtn = container.querySelector('.send');\n this.micBtn = container.querySelector('.mic');\n this.interruptEl = container.querySelector('.interrupt');\n this.suggestionsEl = container.querySelector('.reply-suggestions');\n\n this.launcherEl?.addEventListener('click', () => this.openChat());\n container.querySelector('.close')?.addEventListener('click', () => this.closeChat());\n this.sendBtn?.addEventListener('click', () => this.submit());\n this.micBtn?.addEventListener('click', () => this.toggleVoice());\n this.inputEl?.addEventListener('input', () => this.autosize());\n this.inputEl?.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter' && !ev.shiftKey) {\n ev.preventDefault();\n this.submit();\n }\n });\n\n const pcForm = container.querySelector('.pc-form');\n pcForm?.addEventListener('submit', (ev) => {\n ev.preventDefault();\n this.handlePrechatSubmit(pcForm as HTMLFormElement);\n });\n\n // Live phone formatting + validity hint (libphonenumber-js, US default).\n // The implicit <label>, type=\"tel\", and autocomplete=\"tel\" from field()\n // are preserved — autofill keeps working — and we also reformat on\n // `change` so a browser-autofilled value gets formatted/validated too.\n this.wirePhoneField(pcForm as HTMLFormElement | null);\n\n // Cross-device \"Restore my chats\": open the panel + start the email entry.\n // AWAIT connect() before showing the email step so a `sessionId` exists by\n // the time the visitor submits — otherwise request-otp could go out with no\n // session and verify-otp would then hard-error \"No active session.\" The\n // request-otp/verify-otp paths in the controller also require a session, so\n // gating here keeps the affordance race-free.\n container.querySelector('.restore-link')?.addEventListener('click', () => {\n void (async () => {\n this.identityRestore = { phase: 'awaiting_email' };\n this.renderInterrupt();\n // Establish a live session before the email entry can fire request-otp.\n await this.controller?.connect().catch(() => {});\n })();\n });\n\n // Full-page mode sizes to the host's box; fall back to the viewport only\n // when the container gives the host no height.\n if (fullpage) this.syncViewportFallback();\n\n // Full-page mode connects eagerly (there's no launcher click to trigger it) —\n // but only once any identity gate is cleared.\n if (fullpage && !gating) void this.controller?.connect().catch(() => {});\n\n this.syncOpenState();\n if (!gating) this.renderMessages();\n this.renderStatus();\n this.renderComposerState();\n this.renderInterrupt();\n }\n\n /**\n * Render (or clear) the mid-turn interrupt overlay above the composer:\n * an OTP code prompt or a tool-write confirmation. Server-supplied text is\n * set via `textContent` (never innerHTML); only static icons use innerHTML.\n */\n private renderInterrupt(): void {\n const el = this.interruptEl;\n if (!el) return;\n el.replaceChildren();\n const it = this.interrupt;\n if (!it) {\n // No mid-turn interrupt — but the cross-device restore flow may be\n // active, which reuses this same overlay slot.\n if (this.identityRestore.phase !== 'idle') {\n el.classList.remove('hidden');\n el.appendChild(this.buildRestoreCard());\n return;\n }\n el.classList.add('hidden');\n return;\n }\n el.classList.remove('hidden');\n\n const card = document.createElement('div');\n card.className = 'int-card';\n\n const head = document.createElement('div');\n head.className = 'int-head';\n const ico = document.createElement('span');\n ico.className = 'int-ico';\n const card_meta = it.kind === 'interaction' ? INTERACTION_CARDS[it.interactionKind] : undefined;\n if (it.kind === 'interaction' && !card_meta) {\n // A kind we have no card for (shouldn't happen — we only declare\n // capabilities for registered cards). Decline so the turn never hangs.\n this.controller?.declineInteraction();\n el.classList.add('hidden');\n return;\n }\n ico.innerHTML = it.kind === 'otp' ? ICON.lock : it.kind === 'interaction' ? (card_meta?.icon ?? ICON.user) : ICON.shield; // static, trusted\n const title = document.createElement('span');\n title.className = 'int-title';\n title.textContent = it.kind === 'otp' ? 'Verification required' : it.kind === 'interaction' ? (card_meta?.title ?? 'One more thing') : 'Confirm this action';\n head.append(ico, title);\n card.appendChild(head);\n\n if (it.kind !== 'interaction' && it.actionDescription) {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = it.actionDescription;\n card.appendChild(desc);\n }\n\n if (it.kind === 'interaction') {\n card.appendChild(\n card_meta!.build(it, {\n submit: (values) => this.controller?.submitInteraction(values),\n decline: () => this.controller?.declineInteraction(),\n prefill: this.controller?.getStore().getState().identity ?? {},\n wirePhoneField: (form) => this.wirePhoneField(form),\n }),\n );\n } else if (it.kind === 'otp') {\n if (it.sent?.maskedDestination) {\n const sent = document.createElement('div');\n sent.className = 'int-sent';\n sent.textContent = `Code sent to ${it.sent.maskedDestination}${it.sent.channel ? ` via ${it.sent.channel}` : ''}.`;\n card.appendChild(sent);\n }\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'text';\n input.inputMode = 'numeric';\n input.autocomplete = 'one-time-code';\n input.placeholder = 'Enter code';\n const submit = () => {\n const code = input.value.trim();\n if (code) this.controller?.verifyOtp(code);\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n submit();\n }\n });\n const verify = document.createElement('button');\n verify.className = 'int-btn primary';\n verify.type = 'button';\n verify.textContent = 'Verify';\n verify.addEventListener('click', submit);\n row.append(input, verify);\n card.appendChild(row);\n if (it.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = it.attemptsRemaining != null ? `${it.error} (${it.attemptsRemaining} left)` : it.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else {\n const row = document.createElement('div');\n row.className = 'int-row';\n const decline = document.createElement('button');\n decline.className = 'int-btn';\n decline.type = 'button';\n decline.textContent = 'Decline';\n decline.addEventListener('click', () => this.controller?.confirmTool(false));\n const approve = document.createElement('button');\n approve.className = 'int-btn primary';\n approve.type = 'button';\n approve.textContent = 'Approve';\n approve.addEventListener('click', () => this.controller?.confirmTool(true));\n row.append(decline, approve);\n card.appendChild(row);\n }\n\n el.appendChild(card);\n }\n\n /**\n * Build the cross-device \"Restore my chats\" card (ADR-048 §c). Reuses the\n * same overlay slot + visual language as the OTP interrupt. All server-supplied\n * strings (masked destination, conversation previews) are set via `textContent`\n * — never innerHTML — so they can't inject markup; only the static lock icon\n * uses innerHTML.\n */\n private buildRestoreCard(): HTMLElement {\n const state = this.identityRestore;\n const card = document.createElement('div');\n card.className = 'int-card';\n\n const head = document.createElement('div');\n head.className = 'int-head';\n const ico = document.createElement('span');\n ico.className = 'int-ico';\n ico.innerHTML = ICON.lock; // static, trusted\n const title = document.createElement('span');\n title.className = 'int-title';\n title.textContent = 'Restore your chats';\n head.append(ico, title);\n card.appendChild(head);\n\n const close = document.createElement('button');\n close.className = 'int-close';\n close.type = 'button';\n close.setAttribute('aria-label', 'Cancel');\n close.textContent = '×';\n close.addEventListener('click', () => {\n this.controller?.cancelIdentityRestore();\n this.identityRestore = { phase: 'idle' };\n this.renderInterrupt();\n });\n card.appendChild(close);\n\n if (state.phase === 'awaiting_email') {\n const desc = document.createElement('div');\n desc.className = 'int-desc';\n desc.textContent = \"Enter your email and we'll send a code to find your previous chats.\";\n card.appendChild(desc);\n\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'email';\n input.autocomplete = 'email';\n input.placeholder = 'you@example.com';\n const go = () => {\n const email = input.value.trim();\n if (email) void this.controller?.requestIdentityOtp(email, 'email');\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n go();\n }\n });\n const send = document.createElement('button');\n send.className = 'int-btn primary';\n send.type = 'button';\n send.textContent = 'Send code';\n send.addEventListener('click', go);\n row.append(input, send);\n card.appendChild(row);\n if (state.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else if (state.phase === 'requesting' || state.phase === 'verifying' || state.phase === 'resolving') {\n const msg = document.createElement('div');\n msg.className = 'int-sent';\n msg.textContent = state.phase === 'requesting' ? 'Sending a code…' : state.phase === 'verifying' ? 'Verifying…' : 'Finding your chats…';\n card.appendChild(msg);\n } else if (state.phase === 'awaiting_code') {\n if (state.maskedDestination) {\n const sent = document.createElement('div');\n sent.className = 'int-sent';\n sent.textContent = `Code sent to ${state.maskedDestination}.`;\n card.appendChild(sent);\n }\n const row = document.createElement('div');\n row.className = 'int-row';\n const input = document.createElement('input');\n input.className = 'int-input';\n input.type = 'text';\n input.inputMode = 'numeric';\n input.autocomplete = 'one-time-code';\n input.placeholder = 'Enter code';\n const submit = () => {\n const code = input.value.trim();\n if (code) void this.controller?.verifyIdentityOtp(code);\n };\n input.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n submit();\n }\n });\n const verify = document.createElement('button');\n verify.className = 'int-btn primary';\n verify.type = 'button';\n verify.textContent = 'Verify';\n verify.addEventListener('click', submit);\n row.append(input, verify);\n card.appendChild(row);\n if (state.error) {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.attemptsRemaining != null ? `${state.error} (${state.attemptsRemaining} left)` : state.error;\n card.appendChild(err);\n }\n queueMicrotask(() => input.focus());\n } else if (state.phase === 'resolved') {\n if (state.conversations.length === 0) {\n const none = document.createElement('div');\n none.className = 'int-desc';\n none.textContent = 'No previous chats found for that email.';\n card.appendChild(none);\n } else {\n const pick = document.createElement('div');\n pick.className = 'int-desc';\n pick.textContent = 'Pick a conversation to continue:';\n card.appendChild(pick);\n const list = document.createElement('div');\n list.className = 'restore-list';\n for (const conv of state.conversations) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'restore-item';\n const preview = document.createElement('span');\n preview.className = 'restore-preview';\n preview.textContent = conv.preview || 'Conversation';\n btn.appendChild(preview);\n if (conv.lastActivityAt) {\n const when = document.createElement('span');\n when.className = 'restore-when';\n when.textContent = this.formatWhen(conv.lastActivityAt);\n btn.appendChild(when);\n }\n btn.addEventListener('click', () => {\n void this.controller?.restoreConversation(conv.sessionId);\n });\n list.appendChild(btn);\n }\n card.appendChild(list);\n }\n } else if (state.phase === 'error') {\n const err = document.createElement('div');\n err.className = 'int-error';\n err.textContent = state.message;\n card.appendChild(err);\n }\n\n return card;\n }\n\n /** Format an ISO timestamp as a short, locale-aware label (best-effort). */\n private formatWhen(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return '';\n try {\n return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n } catch {\n return '';\n }\n }\n\n /**\n * Wire as-you-type formatting + an inline validity hint onto the pre-chat\n * phone input (libphonenumber-js, US default region). Autofill is preserved:\n * the input keeps its `type=\"tel\"` + `autocomplete=\"tel\"` + implicit <label>,\n * and we also reformat on `change` so a browser-autofilled value gets\n * formatted/validated too.\n *\n * As-you-type caret note: `AsYouType` reformats the entire string, which\n * moves the caret to the end on a mid-string edit. To avoid fighting the\n * user, we only rewrite the value when the caret is at the end (the typical\n * append-a-digit case) and never on a deletion — so backspacing the\n * formatting characters works naturally.\n */\n private wirePhoneField(form: HTMLFormElement | null): void {\n const input = form?.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (!input) return;\n const hint = input.parentElement?.querySelector('.pc-hint') as HTMLElement | null;\n\n const updateHint = () => {\n const v = input.value.trim();\n const field = input.closest('.pc-field');\n if (!v) {\n // Empty is neutral — the field is optional unless requirePhone.\n field?.classList.remove('valid', 'invalid');\n if (hint) hint.textContent = '';\n return;\n }\n const ok = isValidPhoneNumber(v, PHONE_DEFAULT_REGION);\n field?.classList.toggle('valid', ok);\n field?.classList.toggle('invalid', !ok);\n if (hint) hint.textContent = ok ? '' : 'Enter a valid phone number';\n };\n\n const reformat = () => {\n const atEnd = input.selectionStart === input.value.length && input.selectionEnd === input.value.length;\n // Only reformat when appending at the end; never fight a mid-string\n // edit or a deletion (see the caret note above).\n if (atEnd) {\n const formatted = new AsYouType(PHONE_DEFAULT_REGION).input(input.value);\n // Avoid clobbering when the user is deleting: only grow/normalize,\n // not when the formatter would re-add a character they just removed.\n if (formatted.length >= input.value.length) {\n input.value = formatted;\n }\n }\n updateHint();\n };\n\n input.addEventListener('input', (ev) => {\n const ie = ev as InputEvent;\n // Don't reformat while deleting — let the user clear characters freely.\n if (typeof ie.inputType === 'string' && ie.inputType.startsWith('delete')) {\n updateHint();\n return;\n }\n reformat();\n });\n // Browser autofill / paste-then-blur lands here; format + validate it too.\n input.addEventListener('change', reformat);\n }\n\n /** Collect identity + consent from the pre-chat form, then drop into the chat view. */\n private handlePrechatSubmit(form: HTMLFormElement): void {\n if (!form.reportValidity()) return;\n const data = new FormData(form);\n const val = (k: string) => ((data.get(k) as string | null)?.trim() || undefined);\n const checked = (k: string) => data.get(k) === 'on';\n\n // Phone: when required, block on an invalid number and surface the hint.\n // When optional, allow submit — the backend normalizes/nulls authoritatively.\n const rawPhone = val('phone');\n const phoneInput = form.querySelector('input[name=\"phone\"]') as HTMLInputElement | null;\n if (rawPhone && phoneInput && !isValidPhoneNumber(rawPhone, PHONE_DEFAULT_REGION)) {\n const required = phoneInput.hasAttribute('required');\n const field = phoneInput.closest('.pc-field');\n field?.classList.add('invalid');\n const hint = field?.querySelector('.pc-hint');\n if (hint) hint.textContent = 'Enter a valid phone number';\n if (required) {\n phoneInput.focus();\n return;\n }\n }\n // Prefer canonical E.164 when it parses; fall back to the raw value\n // otherwise (the backend re-parses + normalizes either way).\n const phone = rawPhone ? (phoneToE164(rawPhone) ?? rawPhone) : undefined;\n\n this.controller?.setUserInfo({\n name: val('name'),\n email: val('email'),\n phone,\n consent: { emailOptIn: checked('emailOptIn'), smsOptIn: checked('smsOptIn') },\n });\n this.userInfoSatisfied = true;\n this.render();\n void this.controller?.connect().catch(() => {});\n }\n\n /** Send a starter prompt (from a chip click). */\n private submitPrompt(text: string): void {\n if (!this.inputEl) return;\n this.inputEl.value = text;\n this.submit();\n }\n\n private syncOpenState(): void {\n // In full-page mode the panel always fills the host; nothing to toggle.\n if (this.panelEl?.classList.contains('fullpage')) {\n this.inputEl?.focus();\n return;\n }\n this.panelEl?.classList.toggle('hidden', !this.open);\n this.launcherEl?.classList.toggle('hidden', this.open);\n if (this.open) this.inputEl?.focus();\n }\n\n /** Grow the textarea with its content, up to the CSS max-height. */\n private autosize(): void {\n const ta = this.inputEl;\n if (!ta) return;\n ta.style.height = 'auto';\n ta.style.height = `${ta.scrollHeight}px`;\n }\n\n /**\n * Receive a new message snapshot from the controller and update the view.\n *\n * `onMessages` fires on *every* `stream_token` delta. Rebuilding the whole\n * list each frame is wasteful and fights the smooth reveal, so we take the\n * cheap path when the only change is the trailing streaming assistant message\n * growing: just bump the reveal *target* (the rAF loop drains it). Any\n * structural change (new message, finalize, citations) triggers a full\n * rebuild via {@link renderMessages}.\n */\n private handleMessages(messages: ChatMessage[], greeting: string): void {\n this.greeting = greeting;\n const prev = this.messages;\n const last = messages[messages.length - 1];\n const prevLast = prev[prev.length - 1];\n\n const structural =\n messages.length !== prev.length ||\n !last ||\n !prevLast ||\n last.id !== prevLast.id ||\n last.role !== prevLast.role ||\n // finalize transition (streaming → done) needs the markdown render + sources\n last.streaming !== prevLast.streaming ||\n // first token after the typing indicator needs the bubble swapped in\n (!!last.streaming && !prevLast.text && !!last.text) ||\n // a tool chip was added or resolved (text growth alone doesn't change this)\n this.blockSig(last) !== this.prevBlockSig;\n\n this.messages = messages;\n this.prevBlockSig = this.blockSig(last);\n\n if (!structural && last && last.streaming && this.tailKey(last) === this.streamMsgId) {\n // Fast path: the streaming (trailing) text just grew. Bump the reveal\n // target and let the rAF loop catch up — no DOM rebuild, no per-token\n // reflow. `tailText` is the live trailing text block for a tool turn, or\n // the whole message for a plain-prose turn.\n this.streamTarget = this.tailText(last);\n this.ensureRevealLoop();\n return;\n }\n\n this.renderMessages();\n }\n\n /** True when an assistant message's turn invoked at least one tool. */\n private hasToolBlocks(m?: ChatMessage): boolean {\n return !!m?.blocks?.some((b) => b.kind === 'tool');\n }\n\n /** Signature that changes only when a tool chip is added or resolved (text growth is 'x'). */\n private blockSig(m?: ChatMessage): string {\n if (!m?.blocks) return '';\n return m.blocks.map((b) => (b.kind === 'tool' ? `t:${b.tool.id}:${b.tool.done ? 1 : 0}` : 'x')).join('|');\n }\n\n /** The live (last) text block for a tool turn, else the whole message text. */\n private tailText(m: ChatMessage): string {\n if (this.hasToolBlocks(m) && m.blocks) {\n const last = m.blocks[m.blocks.length - 1];\n return last?.kind === 'text' ? last.text : '';\n }\n return m.text;\n }\n\n /** Reveal-binding key — composite for a tool-turn tail (so a new trailing block rebinds), else msg id. */\n private tailKey(m: ChatMessage): string {\n if (this.hasToolBlocks(m) && m.blocks) return `${m.id}#${m.blocks.length - 1}`;\n return m.id;\n }\n\n private renderMessages(): void {\n if (!this.messagesEl) return;\n this.resetReveal();\n this.messagesEl.replaceChildren();\n\n const greeting = this.greeting;\n if (this.messages.length === 0 && greeting) {\n this.messagesEl.appendChild(this.buildRow('assistant', this.greetingBubble(greeting)));\n }\n\n // Starter-prompt chips: shown until the visitor sends their first message.\n if (!this.hasSent && this.messages.length === 0 && this.examplePrompts.length > 0) {\n const chips = document.createElement('div');\n chips.className = 'prompts';\n for (const prompt of this.examplePrompts) {\n const chip = document.createElement('button');\n chip.type = 'button';\n chip.className = 'chip';\n chip.textContent = prompt;\n chip.addEventListener('click', () => this.submitPrompt(prompt));\n chips.appendChild(chip);\n }\n this.messagesEl.appendChild(chips);\n }\n\n for (const msg of this.messages) {\n // Tool-activity turns (gated by `showToolActivity`) render as an ordered\n // strip of prose bubbles + inline tool chips instead of one bubble.\n if (msg.role === 'assistant' && this.hasToolBlocks(msg)) {\n this.messagesEl.appendChild(this.buildRow('assistant', this.renderAssistantBlocks(msg)));\n if (!msg.streaming && msg.citations && msg.citations.length > 0) {\n this.messagesEl.appendChild(this.renderSources(msg.citations));\n }\n continue;\n }\n\n const bubble = document.createElement('div');\n bubble.className = `bubble ${msg.role}`;\n if (msg.role === 'assistant' && msg.streaming && !msg.text) {\n // No text yet → animated typing indicator.\n bubble.classList.add('typing');\n bubble.append(this.typingDot(), this.typingDot(), this.typingDot());\n } else if (msg.streaming) {\n // Mid-stream: partial/unclosed markdown renders ugly (half-open\n // `**`, dangling `[`), so keep plain text + the blinking cursor.\n // The text is revealed gradually by the rAF typewriter; seed the\n // bubble with whatever is already displayed and bind the reveal.\n bubble.classList.add('cursor');\n this.bindReveal(msg, bubble);\n } else if (msg.role === 'assistant') {\n // Final assistant turn → render the sanitized markdown subset.\n // `renderMarkdown` escapes all text, drops images, gates links to\n // http(s), and only emits an allowlisted set of tags, so this\n // `innerHTML` cannot inject markup (see markdown.ts).\n bubble.classList.add('md');\n bubble.innerHTML = renderMarkdown(msg.text);\n } else {\n // User bubbles stay plain text.\n bubble.textContent = msg.text;\n }\n this.messagesEl.appendChild(this.buildRow(msg.role, bubble));\n\n // Render a \"Sources (N)\" section under any assistant message whose\n // terminal eventual_response carried citations.\n if (msg.role === 'assistant' && !msg.streaming && msg.citations && msg.citations.length > 0) {\n this.messagesEl.appendChild(this.renderSources(msg.citations));\n }\n }\n this.scrollToBottom(true);\n this.renderSuggestions();\n }\n\n /**\n * Render (or clear) the mid-conversation suggested-reply chips under the\n * composer. Shown ONLY when: the feature is enabled, no interrupt / restore\n * overlay is active (those reuse the slot above the composer), and the LATEST\n * message is a finalized assistant turn that carried suggestions. A new turn\n * (agent or the visitor typing) appends messages, so the latest is no longer\n * that assistant message and the chips clear on the next render. Chips reuse\n * the empty-state `.prompts`/`.chip` styling and send via the same path.\n */\n private renderSuggestions(): void {\n const el = this.suggestionsEl;\n if (!el) return;\n el.replaceChildren();\n if (!this.showSuggestedReplies) return;\n // Hidden while an OTP / tool-confirmation / restore overlay is active.\n if (this.interrupt || this.identityRestore.phase !== 'idle') return;\n const last = this.messages[this.messages.length - 1];\n if (!last || last.role !== 'assistant' || last.streaming || !last.suggestions || last.suggestions.length === 0) return;\n\n const chips = document.createElement('div');\n chips.className = 'prompts';\n for (const suggestion of last.suggestions) {\n const chip = document.createElement('button');\n chip.type = 'button';\n chip.className = 'chip';\n chip.textContent = suggestion;\n chip.addEventListener('click', () => this.submitPrompt(suggestion));\n chips.appendChild(chip);\n }\n el.appendChild(chips);\n }\n\n // ─────────────────────── Smooth streaming reveal ───────────────────────────\n\n /** True when the host/user prefers reduced motion (snap, no typewriter). */\n private prefersReducedMotion(): boolean {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n }\n\n /**\n * Bind the rAF typewriter to a freshly built streaming bubble. Preserves the\n * already-revealed prefix across rebuilds (so a structural rebuild mid-stream\n * doesn't restart the reveal from zero), then resumes the loop.\n */\n private bindReveal(msg: ChatMessage, bubble: HTMLElement): void {\n // `tailKey`/`tailText` collapse to the message id + full text for a plain\n // prose turn, and to the live trailing text block for a tool turn — so both\n // the single streaming bubble and a tool turn's trailing prose share this path.\n const key = this.tailKey(msg);\n const target = this.tailText(msg);\n const carryOver = key === this.streamMsgId ? Math.min(this.displayedLength, target.length) : 0;\n this.streamBubbleEl = bubble;\n this.streamMsgId = key;\n this.streamTarget = target;\n this.displayedLength = carryOver;\n\n if (this.prefersReducedMotion()) {\n // No animation: show everything immediately.\n this.displayedLength = target.length;\n bubble.textContent = target;\n return;\n }\n bubble.textContent = target.slice(0, this.displayedLength);\n this.ensureRevealLoop();\n }\n\n /**\n * Render a tool-activity assistant turn as an ordered strip: prose bubbles and\n * inline tool chips in the order the model produced them (mirrors the daemon\n * SPA's `blocks`). The live trailing text block (while streaming) binds to the\n * rAF reveal; earlier/finalized text blocks render as sanitized markdown.\n */\n private renderAssistantBlocks(msg: ChatMessage): HTMLElement {\n const wrap = document.createElement('div');\n wrap.className = 'blocks';\n const blocks = msg.blocks ?? [];\n const lastIdx = blocks.length - 1;\n blocks.forEach((block, i) => {\n if (block.kind === 'tool') {\n wrap.appendChild(this.buildToolChip(block.tool));\n return;\n }\n const bubble = document.createElement('div');\n bubble.className = 'bubble assistant';\n if (msg.streaming && i === lastIdx) {\n // Live trailing prose → plain text + cursor, driven by the reveal loop.\n bubble.classList.add('cursor');\n this.bindReveal(msg, bubble);\n } else {\n // Settled prose → sanitized markdown (same allowlisted renderer as bubbles).\n bubble.classList.add('md');\n bubble.innerHTML = renderMarkdown(block.text);\n }\n wrap.appendChild(bubble);\n });\n return wrap;\n }\n\n /**\n * A single tool-activity chip: icon + tool name + status (running… / done / error),\n * with a truncated args preview. Tool name/args are set via `textContent` so a\n * tool payload can never inject markup.\n */\n private buildToolChip(tool: ToolCall): HTMLElement {\n const chip = document.createElement('div');\n chip.className = `toolchip ${tool.done ? (tool.isError ? 'error' : 'done') : 'running'}`;\n chip.setAttribute('part', 'tool-chip');\n\n const icon = document.createElement('span');\n icon.className = 'ti';\n icon.innerHTML = ICON.tool; // static, trusted\n const name = document.createElement('span');\n name.className = 'tn';\n name.textContent = tool.name || 'tool';\n const status = document.createElement('span');\n status.className = 'ts';\n status.textContent = tool.done ? (tool.isError ? 'error' : 'done') : 'running…';\n chip.append(icon, name, status);\n\n if (tool.args && tool.args !== '{}' && tool.args !== '\"\"') {\n const args = document.createElement('span');\n args.className = 'ta';\n args.textContent = tool.args.length > 80 ? `${tool.args.slice(0, 80)}…` : tool.args;\n chip.appendChild(args);\n }\n return chip;\n }\n\n /** Start the rAF loop if it isn't already running. */\n private ensureRevealLoop(): void {\n if (this.prefersReducedMotion() || typeof requestAnimationFrame !== 'function') {\n // No animation (reduced-motion or no rAF): snap to the full buffer.\n this.snapReveal();\n return;\n }\n if (this.rafId) return; // already running\n this.rafId = requestAnimationFrame(() => this.tickReveal());\n }\n\n /**\n * One animation frame of the reveal. Advances `displayedLength` toward the\n * buffered target at an ADAPTIVE rate — the deeper the backlog, the more\n * chars per frame — so the reveal stays smooth yet never falls behind the\n * network. Updates ONLY the bound bubble's textContent (no list rebuild).\n */\n private tickReveal(): void {\n this.rafId = 0;\n const bubble = this.streamBubbleEl;\n if (!bubble) return;\n\n const target = this.streamTarget;\n const remaining = target.length - this.displayedLength;\n\n if (remaining <= 0) {\n // Caught up to everything buffered so far → idle. A later token bump\n // (handleMessages → ensureRevealLoop) restarts the loop; the finalize\n // structural rebuild snaps to the full markdown render.\n return;\n }\n\n // Adaptive speed: ~1/8 of the backlog per frame (≈ catch up over a few\n // frames), clamped to a readable floor so short bursts still animate and\n // an aggressive ceiling so a deep buffer drains fast. At ~60fps this\n // comfortably outruns the wire — the reveal is steady, never bursty.\n const step = Math.max(2, Math.min(remaining, Math.ceil(remaining / 8)));\n this.displayedLength = Math.min(target.length, this.displayedLength + step);\n bubble.textContent = target.slice(0, this.displayedLength);\n this.scrollToBottom(false);\n\n this.rafId = requestAnimationFrame(() => this.tickReveal());\n }\n\n /** Snap the bound bubble to the full buffered text immediately (reduced-motion / no-rAF). */\n private snapReveal(): void {\n if (this.streamBubbleEl) {\n this.displayedLength = this.streamTarget.length;\n this.streamBubbleEl.textContent = this.streamTarget;\n }\n }\n\n /**\n * Full-page sizing probe: decide whether the host's container gives it a\n * real box. With the `.wrap` flex chain hidden, `height: 100%` of a SIZED\n * container still resolves (clientHeight > 0), while an auto-height parent\n * (e.g. mounted straight into `<body>`) collapses to ~0. Only the latter\n * gets `data-viewport-fallback`, whose CSS applies `min-height: 100dvh` —\n * so an embed inside a fixed-height box never overflows it (the composer\n * stays visible), and a bare full-page route still fills the viewport.\n */\n private syncViewportFallback(): void {\n const wrap = this.shadowRoot?.querySelector<HTMLElement>('.wrap');\n if (!wrap) return;\n const prev = wrap.style.display;\n wrap.style.display = 'none';\n const heightless = this.clientHeight < 8;\n wrap.style.display = prev;\n this.toggleAttribute('data-viewport-fallback', heightless);\n }\n\n /** Cancel any in-flight reveal loop and clear its state (called on full rebuild). */\n private resetReveal(): void {\n if (this.rafId && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.rafId);\n this.rafId = 0;\n this.streamBubbleEl = null;\n // streamMsgId/displayedLength are intentionally kept so bindReveal can\n // carry the revealed prefix across a structural rebuild of the same msg;\n // they're reset when a different message binds.\n }\n\n /**\n * Auto-scroll the message list to the bottom — but don't fight a visitor who\n * has scrolled up to read history. When `force` (a structural rebuild) we\n * always pin to bottom; during the streaming reveal we only follow if the\n * viewport is already near the bottom.\n */\n private scrollToBottom(force: boolean): void {\n const el = this.messagesEl;\n if (!el) return;\n if (force) {\n el.scrollTop = el.scrollHeight;\n return;\n }\n const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;\n if (nearBottom) el.scrollTop = el.scrollHeight;\n }\n\n /** Wrap a bubble in a `.row`, prefixing assistant rows with a mini avatar. */\n private buildRow(role: 'user' | 'assistant', bubble: HTMLElement): HTMLElement {\n const row = document.createElement('div');\n row.className = `row ${role}`;\n if (role === 'assistant') {\n const mini = document.createElement('div');\n mini.className = 'mini';\n mini.innerHTML = ICON.bot; // static, trusted\n row.appendChild(mini);\n }\n row.appendChild(bubble);\n return row;\n }\n\n private greetingBubble(greeting: string): HTMLElement {\n const b = document.createElement('div');\n b.className = 'bubble assistant greeting';\n b.textContent = greeting;\n return b;\n }\n\n private typingDot(): HTMLElement {\n return document.createElement('i');\n }\n\n /**\n * Build the collapsible \"Sources (N)\" block for an assistant message's\n * citations. Title/snippet are set via `textContent` (never innerHTML) so\n * citation text can't inject markup; only the static chevron + numeric count\n * use innerHTML.\n */\n private renderSources(citations: Citation[]): HTMLElement {\n const wrap = document.createElement('div');\n wrap.className = 'sources';\n wrap.setAttribute('part', 'sources');\n\n const details = document.createElement('details');\n details.open = true;\n\n const summary = document.createElement('summary');\n const chev = document.createElement('span');\n chev.className = 'chev';\n chev.innerHTML = ICON.chev; // static, trusted\n const label = document.createElement('span');\n label.textContent = 'Sources';\n const count = document.createElement('span');\n count.className = 'count';\n count.textContent = String(citations.length);\n summary.append(chev, label, count);\n details.appendChild(summary);\n\n const list = document.createElement('ol');\n for (const c of citations) {\n const li = document.createElement('li');\n\n let titleEl: HTMLElement;\n // SECURITY: only absolute http(s) URLs may become a link href. A\n // citation URL comes from indexed content (web/GitHub connectors), so\n // an attacker-influenceable doc could carry `javascript:`/`data:`/\n // `vbscript:` — assigning those to `a.href` is a one-click XSS. Anything\n // that isn't a valid absolute http(s) URL renders as plain text.\n const safeUrl = safeHttpUrl(c.url);\n if (safeUrl) {\n const a = document.createElement('a');\n a.className = 'src-title';\n a.href = safeUrl;\n a.target = '_blank';\n a.rel = 'noopener noreferrer nofollow';\n titleEl = a;\n } else {\n titleEl = document.createElement('span');\n titleEl.className = 'src-title';\n }\n titleEl.textContent = c.title || c.id || 'Source';\n li.appendChild(titleEl);\n\n if (c.snippet) {\n // The snippet is the raw scraped chunk — often led by page\n // boilerplate (logo link, nav, whitespace). Trim it to a clean\n // excerpt, then render the sanitized markdown subset. Both steps\n // escape text + drop images/unsafe links (see markdown.ts), so\n // this `innerHTML` is safe.\n const cleaned = cleanCitationSnippet(c.snippet);\n if (cleaned) {\n const snip = document.createElement('span');\n snip.className = 'src-snippet md';\n snip.innerHTML = renderMarkdown(cleaned);\n li.appendChild(snip);\n }\n }\n list.appendChild(li);\n }\n details.appendChild(list);\n wrap.appendChild(details);\n return wrap;\n }\n\n private renderStatus(): void {\n const label: Record<ConnectionStatus, string> = {\n idle: '',\n connecting: 'Connecting…',\n ready: 'Online',\n error: 'Connection issue',\n closed: 'Disconnected',\n };\n if (this.statusEl) this.statusEl.textContent = label[this.status];\n if (this.dotEl) {\n // ready → green (no modifier); connecting → amber; error → red; else grey.\n const mod = this.status === 'ready' ? '' : this.status === 'connecting' ? ' connecting' : this.status === 'error' ? ' error' : ' off';\n this.dotEl.className = `dot${mod}`;\n }\n }\n\n private renderComposerState(): void {\n const busy = this.status === 'connecting';\n if (this.sendBtn) this.sendBtn.disabled = busy;\n if (this.inputEl) this.inputEl.disabled = busy;\n }\n\n // ───────────────────────── Voice (SMOODEV-2534) ─────────────────────────────\n\n /**\n * Mic button: start a voice session, or — when one is live — end it. Hitting\n * the button while the agent's TTS is playing barges in first (interrupt +\n * playback flush) so the audio dies instantly, then the session ends.\n */\n private toggleVoice(): void {\n if (this.voiceSession) {\n if (this.voiceSession.isSpeaking) this.voiceSession.interrupt();\n this.stopVoice();\n return;\n }\n void this.startVoice();\n }\n\n private async startVoice(): Promise<void> {\n if (!this.controller || this.voiceSession || !this.voiceCfg.enabled) return;\n const config = this.readConfig();\n if (!config) return;\n // Best-effort: join the text thread when one exists. If the text session\n // hasn't connected yet, voice starts a fresh thread (the frozen protocol\n // never returns the voice-created conversation id, so it can't be adopted\n // for later text turns — tracked as a follow-up on the server protocol).\n const conversationId = this.controller.currentConversationId ?? undefined;\n const controller = this.controller;\n const session = new VoiceSession(\n { url: this.voiceCfg.url, agentId: config.agentId, conversationId },\n {\n onTranscriptPartial: (text) => {\n // Live partial transcript in the input area while listening.\n if (this.inputEl) {\n this.inputEl.value = text;\n this.autosize();\n }\n },\n onTranscriptFinal: (text) => {\n if (this.inputEl) {\n this.inputEl.value = '';\n this.autosize();\n }\n // Finalized speech lands as a normal user message.\n controller.appendLocalMessage('user', text);\n },\n onReplyText: (text) => {\n // Agent replies render through the normal chat message path.\n controller.appendLocalMessage('assistant', text);\n },\n onSpeaking: (speaking) => {\n this.micBtn?.classList.toggle('speaking', speaking);\n },\n onError: () => this.stopVoice(),\n onEnded: () => {\n // Server-side end (handoff / close) — reset the UI. stopVoice()\n // is idempotent, so a local stop lands here harmlessly too.\n this.voiceSession = null;\n this.syncVoiceUi(false);\n },\n },\n );\n this.voiceSession = session;\n this.syncVoiceUi(true);\n try {\n await session.start();\n } catch {\n // Mic permission denied / audio unavailable — back to text.\n this.voiceSession = null;\n this.syncVoiceUi(false);\n }\n }\n\n /** End any live voice session and reset the composer UI. Idempotent. */\n private stopVoice(): void {\n const session = this.voiceSession;\n this.voiceSession = null;\n session?.stop();\n this.syncVoiceUi(false);\n }\n\n /** Toggle the mic button's listening state + clear the partial transcript. */\n private syncVoiceUi(active: boolean): void {\n this.micBtn?.classList.toggle('active', active);\n this.micBtn?.setAttribute('aria-pressed', String(active));\n this.micBtn?.setAttribute('aria-label', active ? 'Stop voice' : 'Start voice');\n if (!active) {\n this.micBtn?.classList.remove('speaking');\n if (this.inputEl && this.inputEl.value) {\n this.inputEl.value = '';\n this.autosize();\n }\n }\n }\n\n private submit(): void {\n if (!this.inputEl || !this.controller) return;\n const text = this.inputEl.value;\n if (!text.trim()) return;\n this.inputEl.value = '';\n this.hasSent = true;\n this.autosize();\n void this.controller.send(text);\n }\n}\n\n/** Register the custom element once. Safe to call multiple times. */\nexport function defineChatWidget(): void {\n if (typeof customElements !== 'undefined' && !customElements.get(ELEMENT_TAG)) {\n customElements.define(ELEMENT_TAG, SmoothAgentChatElement);\n }\n}\n\n/**\n * Programmatically create, configure, and append a widget to the page.\n * Returns the element so the host can drive `openChat()` / `closeChat()`.\n */\nexport function mountChatWidget(config: ChatWidgetConfig, target: HTMLElement = document.body): SmoothAgentChatElement {\n defineChatWidget();\n const el = document.createElement(ELEMENT_TAG) as SmoothAgentChatElement;\n el.configure(config);\n target.appendChild(el);\n return el;\n}\n\n/**\n * Ergonomic helper for the full-page layout: mounts a `<smooth-agent-chat>` in\n * `mode: \"fullpage\"` (no launcher — the chat fills its container/viewport with a\n * Smooth-branded header, a scrollable message list, and an input bar) and\n * returns the element.\n *\n * `target` defaults to `document.body`; pass a sized container to embed the\n * full-page chat inside a layout region (e.g. a `/chat` route shell or an\n * iframe). The `mode` is forced to `\"fullpage\"` regardless of the passed config.\n *\n * ```ts\n * mountFullPageChat({ endpoint: 'wss://…/ws', agentId: '…', agentName: 'Support' });\n * ```\n */\nexport function mountFullPageChat(config: Omit<ChatWidgetConfig, 'mode'>, target: HTMLElement = document.body): SmoothAgentChatElement {\n return mountChatWidget({ ...config, mode: 'fullpage' }, target);\n}\n","/**\n * Tiny, dependency-free deferred loader for `@smooai/chat-widget`.\n *\n * The recommended embed: a host includes this *small* script eagerly, and it\n * defers injecting the real (heavier) `chat-widget.global.js` module until the\n * page is past its critical render — so the widget never competes with the host\n * page's LCP/TBT. It triggers the real load on the **first** of:\n *\n * - `window` `load` → `requestIdleCallback` (idle time), or\n * - user intent (`pointerdown` / `keydown` / `scroll`), or\n * - an 8s fallback.\n *\n * After the module loads (which registers `<smooth-agent-chat>` and exposes\n * `window.SmoothAgentChat`), it mounts the widget with the host's config.\n *\n * Deliberately imports nothing from the widget itself — this file must stay a\n * few hundred bytes so including it eagerly is free.\n *\n * ## Config\n * Set a global before/with the loader (any `ChatWidgetConfig`, plus an optional\n * `src` pointing at the module bundle):\n *\n * ```html\n * <script>window.SmoothAgentChatConfig = { endpoint: 'wss://…/ws', agentId: '…' };</script>\n * <script src=\"https://cdn/…/chat-widget-loader.global.js\" async></script>\n * ```\n *\n * Or, for the simplest installs, `data-*` attributes on the loader's own tag\n * (`data-endpoint`, `data-agent-id`, `data-primary`, `data-mode`, `data-src`).\n * If no config is found, the module is still loaded (registering the element) so\n * a `<smooth-agent-chat …>` placed directly in markup upgrades itself.\n */\n\n/** Must match `ELEMENT_TAG` in `element.ts`; inlined to avoid importing it. */\nconst ELEMENT_TAG = 'smooth-agent-chat';\n/** Default module filename, resolved as a sibling of the loader script. */\nconst DEFAULT_MODULE = 'chat-widget.global.js';\n\ntype MountFn = (config: Record<string, unknown>, target?: HTMLElement) => unknown;\n\ninterface LoaderWindow extends Window {\n SmoothAgentChat?: { mount: MountFn };\n SmoothAgentChatConfig?: Record<string, unknown> & { src?: string };\n}\n\n/**\n * Resolve the module URL: explicit `src` (config or `data-src`) wins, else a\n * sibling of the loader script, else the bare default filename.\n */\nfunction resolveModuleSrc(win: LoaderWindow, script: HTMLScriptElement | null): string {\n const fromConfig = win.SmoothAgentChatConfig?.src;\n if (fromConfig) return fromConfig;\n const fromAttr = script?.getAttribute('data-src');\n if (fromAttr) return fromAttr;\n const selfSrc = script?.src;\n if (selfSrc) return selfSrc.replace(/[^/]*$/, DEFAULT_MODULE);\n return DEFAULT_MODULE;\n}\n\n/**\n * The widget mount config: the `SmoothAgentChatConfig` global (minus the\n * loader-only `src`), or `data-*` attributes. `undefined` ⇒ no programmatic\n * mount (a markup element will upgrade itself once the module registers it).\n */\nfunction resolveMountConfig(win: LoaderWindow, script: HTMLScriptElement | null): Record<string, unknown> | undefined {\n if (win.SmoothAgentChatConfig) {\n const { src: _src, ...config } = win.SmoothAgentChatConfig;\n // Only `src` (no real fields) ⇒ no programmatic mount; a markup element\n // upgrades itself once the module registers it.\n return Object.keys(config).length > 0 ? config : undefined;\n }\n if (!script) return undefined;\n const endpoint = script.getAttribute('data-endpoint');\n const agentId = script.getAttribute('data-agent-id');\n if (!endpoint && !agentId) return undefined;\n const config: Record<string, unknown> = {};\n if (endpoint) config.endpoint = endpoint;\n if (agentId) config.agentId = agentId;\n const primary = script.getAttribute('data-primary');\n if (primary) config.theme = { primary };\n const mode = script.getAttribute('data-mode');\n if (mode) config.mode = mode;\n return config;\n}\n\n/**\n * Install the deferred loader. Idempotent per call; the IIFE entry\n * (`loader.ts`) invokes it once on script execution.\n */\nexport function initChatWidgetLoader(): void {\n const win = window as LoaderWindow;\n const script = (document.currentScript as HTMLScriptElement | null) ?? null;\n const moduleSrc = resolveModuleSrc(win, script);\n\n let loaded = false;\n let idleId: number | undefined;\n let fallbackId: number | undefined;\n\n function mountWhenReady(): void {\n const config = resolveMountConfig(win, script);\n if (!config) return; // markup element upgrades itself; nothing to mount\n const apply = () => {\n try {\n win.SmoothAgentChat?.mount(config);\n } catch (error) {\n console.error('[chat-widget loader] mount failed', error);\n }\n };\n if (win.SmoothAgentChat) {\n apply();\n } else if (window.customElements?.whenDefined) {\n window.customElements.whenDefined(ELEMENT_TAG).then(apply, apply);\n } else {\n apply();\n }\n }\n\n function teardown(): void {\n if (idleId !== undefined) {\n // The id is either an idle handle or (fallback path) a timeout id;\n // both cancels are no-ops on the wrong kind, so calling both is safe.\n window.cancelIdleCallback?.(idleId);\n window.clearTimeout(idleId);\n }\n if (fallbackId !== undefined) window.clearTimeout(fallbackId);\n window.removeEventListener('pointerdown', load);\n window.removeEventListener('keydown', load);\n window.removeEventListener('scroll', load);\n }\n\n function load(): void {\n if (loaded) return;\n loaded = true;\n teardown();\n const tag = document.createElement('script');\n tag.src = moduleSrc;\n tag.onload = mountWhenReady;\n tag.onerror = () => console.error('[chat-widget loader] failed to load', moduleSrc);\n document.head.appendChild(tag);\n }\n\n function schedule(): void {\n if (window.requestIdleCallback) {\n idleId = window.requestIdleCallback(() => load(), { timeout: 5000 });\n } else {\n idleId = window.setTimeout(load, 2500) as unknown as number;\n }\n fallbackId = window.setTimeout(load, 8000) as unknown as number;\n }\n\n // User intent loads immediately (they're about to want the widget).\n window.addEventListener('pointerdown', load, { once: true, passive: true });\n window.addEventListener('keydown', load, { once: true });\n window.addEventListener('scroll', load, { once: true, passive: true });\n\n if (document.readyState === 'complete') {\n schedule();\n } else {\n window.addEventListener('load', schedule, { once: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,S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