@smooai/chat-widget 0.10.2 → 0.12.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/README.md +3 -0
- package/dist/chat-widget.global.js +326 -9
- package/dist/chat-widget.global.js.map +1 -1
- package/dist/index.d.ts +275 -223
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +307 -6
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/config.ts +7 -0
- package/src/conversation.ts +138 -2
- package/src/element.ts +222 -5
- package/src/styles.ts +15 -2
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 /** 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 /** 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 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 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\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 * 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\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 */\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\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/** 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\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 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 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 ...(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 assistant: ChatMessage = { id: this.nextId('a'), role: 'assistant', text: '', streaming: true };\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 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 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 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-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/* ─────────────── 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/* ─────────────── 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-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-btn { flex: 1; }\n.int-row .int-input + .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 { type ChatMessage, type Citation, type ConnectionStatus, ConversationController, type IdentityRestore, type Interrupt } 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'] 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 /** 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} as const;\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 /** 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\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\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 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 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 },\n onIdentityRestore: (state) => {\n this.identityRestore = state;\n this.renderInterrupt();\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.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=\"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\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 ico.innerHTML = it.kind === 'otp' ? ICON.lock : ICON.shield; // static, trusted\n const title = document.createElement('span');\n title.className = 'int-title';\n title.textContent = it.kind === 'otp' ? 'Verification required' : 'Confirm this action';\n head.append(ico, title);\n card.appendChild(head);\n\n if (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 === '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\n this.messages = messages;\n\n if (!structural && last && last.streaming && last.id === this.streamMsgId) {\n // Fast path: the streaming tail just grew. Bump the reveal target and\n // let the rAF loop catch up — no DOM rebuild, no per-token reflow.\n this.streamTarget = last.text;\n this.ensureRevealLoop();\n return;\n }\n\n this.renderMessages();\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 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 }\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 const carryOver = msg.id === this.streamMsgId ? Math.min(this.displayedLength, msg.text.length) : 0;\n this.streamBubbleEl = bubble;\n this.streamMsgId = msg.id;\n this.streamTarget = msg.text;\n this.displayedLength = carryOver;\n\n if (this.prefersReducedMotion()) {\n // No animation: show everything immediately.\n this.displayedLength = msg.text.length;\n bubble.textContent = msg.text;\n return;\n }\n bubble.textContent = msg.text.slice(0, this.displayedLength);\n this.ensureRevealLoop();\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,OAAO;GACX,KAAK,KACD,OAAO;GACX,KAAK,KACD,OAAO;GACX,KAAK,MACD,OAAO;GACX,SACI,OAAO;EACf;CACJ,CAAC;AACL;;;;;;;;;;AAWA,SAAgB,YAAY,KAA+C;CACvE,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACA,MAAM,SAAS,IAAI,IAAI,GAAG;EAC1B,OAAO,OAAO,aAAa,WAAW,OAAO,aAAa,WAAW,OAAO,OAAO;CACvF,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;;;;AAWA,SAAS,aAAa,OAAuB;CACzC,IAAI,MAAM;CACV,IAAI,IAAI;CACR,MAAM,IAAI,MAAM;CAGhB,IAAI,MAAM;CACV,MAAM,cAAc;EAChB,IAAI,KAAK;GACL,OAAO,WAAW,GAAG;GACrB,MAAM;EACV;CACJ;CAEA,OAAO,IAAI,GAAG;EACV,MAAM,KAAK,MAAM;EAGjB,IAAI,OAAO,KAAK;GACZ,MAAM,MAAM,MAAM,QAAQ,KAAK,IAAI,CAAC;GACpC,IAAI,MAAM,GAAG;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AS,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/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 /** 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 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\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 * 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\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 assistant: ChatMessage = { id: this.nextId('a'), role: 'assistant', text: '', streaming: true };\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 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 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-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/* ─────────────── 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 { type ChatMessage, type Citation, type ConnectionStatus, ConversationController, type IdentityRestore, type Interrupt, SUPPORTED_INTERACTION_CAPABILITIES } 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'] 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} 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\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 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\n this.messages = messages;\n\n if (!structural && last && last.streaming && last.id === this.streamMsgId) {\n // Fast path: the streaming tail just grew. Bump the reveal target and\n // let the rAF loop catch up — no DOM rebuild, no per-token reflow.\n this.streamTarget = last.text;\n this.ensureRevealLoop();\n return;\n }\n\n this.renderMessages();\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 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 const carryOver = msg.id === this.streamMsgId ? Math.min(this.displayedLength, msg.text.length) : 0;\n this.streamBubbleEl = bubble;\n this.streamMsgId = msg.id;\n this.streamTarget = msg.text;\n this.displayedLength = carryOver;\n\n if (this.prefersReducedMotion()) {\n // No animation: show everything immediately.\n this.displayedLength = msg.text.length;\n bubble.textContent = msg.text;\n return;\n }\n bubble.textContent = msg.text.slice(0, this.displayedLength);\n this.ensureRevealLoop();\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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