@smooai/chat-widget 0.5.2 → 0.7.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.
@@ -1 +1 @@
1
- {"version":3,"file":"chat-widget.global.js","names":[],"sources":["../src/config.ts","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/transport.js","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/types.js","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/client.js","../src/conversation.ts","../src/logo.ts","../src/styles.ts","../src/element.ts","../src/standalone.ts"],"sourcesContent":["/**\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 */\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 /** 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 /** 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 * 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 * 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'>> & {\n theme: ResolvedTheme;\n userName?: string;\n userEmail?: string;\n userPhone?: 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 userName: config.userName,\n userEmail: config.userEmail,\n userPhone: config.userPhone,\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 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 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 * Transport abstraction for the client.\n *\n * The client is deliberately decoupled from any concrete WebSocket implementation\n * so it can be unit-tested with a mock and run on Node, the browser, or a custom\n * socket. A transport is anything that can send a string frame and surface\n * incoming string frames + lifecycle events.\n */\nconst WS_CONNECTING = 0;\nconst WS_OPEN = 1;\nconst WS_CLOSING = 2;\n/** Default connect timeout (ms) for the WebSocket transport. */\nconst DEFAULT_CONNECT_TIMEOUT = 30_000;\n/**\n * Default transport backed by a `WebSocket`-like object. By default it uses the\n * global `WebSocket`; pass a `factory` to inject one (e.g. the `ws` package on\n * Node, or a mock in tests).\n */\nexport class WebSocketTransport {\n socket = null;\n url;\n factory;\n connectTimeout;\n messageHandlers = new Set();\n closeHandlers = new Set();\n errorHandlers = new Set();\n constructor(url, factory, connectTimeout = DEFAULT_CONNECT_TIMEOUT) {\n this.url = url;\n this.connectTimeout = connectTimeout;\n if (factory) {\n this.factory = factory;\n }\n else {\n const G = globalThis;\n if (!G.WebSocket) {\n throw new Error('No global WebSocket available; pass a WebSocketFactory to WebSocketTransport.');\n }\n const Ctor = G.WebSocket;\n this.factory = (u) => new Ctor(u);\n }\n }\n get state() {\n if (!this.socket)\n return 'closed';\n switch (this.socket.readyState) {\n case WS_CONNECTING:\n return 'connecting';\n case WS_OPEN:\n return 'open';\n case WS_CLOSING:\n return 'closing';\n default:\n return 'closed';\n }\n }\n connect() {\n if (this.socket && this.socket.readyState === WS_OPEN)\n return Promise.resolve();\n // A prior socket that never reached OPEN (failed/half-open dial, or a closed\n // socket from a previous attempt) would otherwise be orphaned: its listeners\n // stay registered and keep dispatching into the shared handler sets, so a late\n // message/close from the dead socket double-fires. Close it and detach it\n // before dialing a fresh one. (WebSocketLike has no removeEventListener, so we\n // also guard every handler below with an identity check on `this.socket`.)\n if (this.socket && this.socket.readyState !== WS_OPEN) {\n const stale = this.socket;\n this.socket = null;\n try {\n stale.close();\n }\n catch {\n // ignore — best-effort teardown of a half-open socket\n }\n }\n return new Promise((resolve, reject) => {\n const socket = this.factory(this.url);\n this.socket = socket;\n let settled = false;\n const timer = this.connectTimeout > 0\n ? setTimeout(() => {\n if (settled)\n return;\n settled = true;\n // Tear down the half-open socket so it can't leak / fire later.\n if (this.socket === socket)\n this.socket = null;\n try {\n socket.close();\n }\n catch {\n // ignore\n }\n reject(new Error(`WebSocket connect to ${this.url} timed out after ${this.connectTimeout}ms`));\n }, this.connectTimeout)\n : undefined;\n socket.addEventListener('open', () => {\n // Ignore events from a socket we've already replaced/abandoned.\n if (this.socket !== socket)\n return;\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n resolve();\n });\n socket.addEventListener('error', (ev) => {\n if (this.socket !== socket)\n return;\n for (const h of this.errorHandlers)\n h(ev);\n if (!settled && this.state !== 'open') {\n settled = true;\n if (timer)\n clearTimeout(timer);\n if (this.socket === socket)\n this.socket = null;\n // Release the failed socket so it can't linger / fire later.\n try {\n socket.close();\n }\n catch {\n // ignore\n }\n reject(ev instanceof Error ? ev : new Error('WebSocket connection error'));\n }\n });\n socket.addEventListener('close', (ev) => {\n if (this.socket !== socket)\n return;\n if (timer)\n clearTimeout(timer);\n for (const h of this.closeHandlers)\n h({ code: ev.code, reason: ev.reason });\n });\n socket.addEventListener('message', (ev) => {\n if (this.socket !== socket)\n return;\n const data = typeof ev.data === 'string' ? ev.data : String(ev.data);\n for (const h of this.messageHandlers)\n h(data);\n });\n });\n }\n send(data) {\n if (!this.socket || this.socket.readyState !== WS_OPEN) {\n throw new Error(`Cannot send: transport is \"${this.state}\"`);\n }\n this.socket.send(data);\n }\n close(code, reason) {\n this.socket?.close(code, reason);\n }\n onMessage(handler) {\n this.messageHandlers.add(handler);\n return () => this.messageHandlers.delete(handler);\n }\n onClose(handler) {\n this.closeHandlers.add(handler);\n return () => this.closeHandlers.delete(handler);\n }\n onError(handler) {\n this.errorHandlers.add(handler);\n return () => this.errorHandlers.delete(handler);\n }\n}\n//# sourceMappingURL=transport.js.map","export * from './generated/types.js';\n// ───────────────────────────── Discriminators ──────────────────────────────\n/** Every client→server `action` discriminator value. */\nexport const ACTION_TYPES = [\n 'create_conversation_session',\n 'send_message',\n 'get_session',\n 'get_conversation_messages',\n 'confirm_tool_action',\n 'verify_otp',\n 'ping',\n];\n/** Every server→client `type` discriminator value. */\nexport const EVENT_TYPES = [\n 'immediate_response',\n 'eventual_response',\n 'stream_chunk',\n 'stream_token',\n 'keepalive',\n 'write_confirmation_required',\n 'otp_verification_required',\n 'otp_sent',\n 'otp_verified',\n 'otp_invalid',\n 'error',\n 'pong',\n];\n// ───────────────────────────── Type guards ─────────────────────────────────\n/** True if `frame` is a server event of the given `type`, narrowing accordingly. */\nexport function isEvent(frame, type) {\n return isServerEvent(frame) && frame.type === type;\n}\n/** True if `frame` looks like any server event (has a known `type` discriminator). */\nexport function isServerEvent(frame) {\n return (typeof frame === 'object' &&\n frame !== null &&\n 'type' in frame &&\n typeof frame.type === 'string' &&\n EVENT_TYPES.includes(frame.type));\n}\n/** True if `frame` looks like any client action (has a known `action` discriminator). */\nexport function isClientAction(frame) {\n return (typeof frame === 'object' &&\n frame !== null &&\n 'action' in frame &&\n typeof frame.action === 'string' &&\n ACTION_TYPES.includes(frame.action));\n}\n//# sourceMappingURL=types.js.map","/**\n * SmoothAgentClient — a minimal, idiomatic, transport-agnostic client for the\n * smooth-operator WebSocket protocol.\n *\n * Design goals\n * ------------\n * - **Transport-agnostic.** The client never touches a real socket directly; it\n * talks to an injectable {@link Transport}. The default ({@link WebSocketTransport})\n * uses the global `WebSocket`, but tests inject a mock and Node can inject `ws`.\n * - **Request/response correlation by `requestId`.** Every action gets a generated\n * `requestId`; the client routes incoming events back to the originating call.\n * - **Streaming as an async iterator.** `sendMessage` returns a {@link MessageTurn}\n * that is both awaitable (resolves with the terminal `eventual_response`) and\n * async-iterable (yields each `stream_token` / `stream_chunk` / HITL event in\n * order). This models the `stream_token`/`stream_chunk` → `eventual_response`\n * flow without forcing a callback style on the caller.\n * - **No live server required.** Correctness is fully unit-testable with a mock\n * transport (see `test/client.test.ts`).\n */\nimport { WebSocketTransport, } from './transport.js';\nimport { isServerEvent } from './types.js';\n/** Events that terminate a streaming turn (success or error). */\nconst TURN_TERMINAL = new Set(['eventual_response', 'error']);\n/** A timeout that yields no terminal event. */\nclass RequestTimeoutError extends Error {\n constructor(requestId, ms) {\n super(`Request ${requestId} timed out after ${ms}ms`);\n this.name = 'RequestTimeoutError';\n }\n}\n/**\n * A streaming turn that received no terminal `eventual_response` / `error` within the\n * configured {@link SmoothAgentClientOptions.turnTimeout}. The turn rejects with this\n * and its async iteration throws it, so a stuck server can never hang the caller.\n */\nexport class TurnTimeoutError extends Error {\n requestId;\n constructor(requestId, ms) {\n super(`Turn ${requestId} timed out after ${ms}ms without a terminal response`);\n this.name = 'TurnTimeoutError';\n this.requestId = requestId;\n }\n}\n/** A protocol-level error event surfaced as a throwable. */\nexport class ProtocolError extends Error {\n code;\n requestId;\n constructor(code, message, requestId) {\n super(message);\n this.name = 'ProtocolError';\n this.code = code;\n this.requestId = requestId;\n }\n}\n/**\n * A streaming message turn. Await it for the terminal {@link EventualResponse},\n * or async-iterate it to receive every intermediate event in arrival order.\n *\n * ```ts\n * const turn = client.sendMessage({ sessionId, message: 'hi' });\n * for await (const ev of turn) {\n * if (ev.type === 'stream_token') process.stdout.write(ev.token ?? '');\n * }\n * const final = await turn; // EventualResponse\n * ```\n */\nexport class MessageTurn {\n /** The requestId this turn is correlated on. */\n requestId;\n queue = [];\n waiter = null;\n done = false;\n finalEvent = null;\n error = null;\n settled;\n settle;\n fail;\n onClose;\n timeoutTimer;\n constructor(requestId, onClose, turnTimeout = 0) {\n this.requestId = requestId;\n this.onClose = onClose;\n this.settled = new Promise((resolve, reject) => {\n this.settle = resolve;\n this.fail = reject;\n });\n // Avoid unhandled-rejection noise if the caller only iterates and never awaits.\n this.settled.catch(() => { });\n // Bound the turn: a server that accepts the message but never emits a terminal\n // event must not hang the caller forever.\n if (turnTimeout > 0) {\n this.timeoutTimer = setTimeout(() => {\n this.finish(null, new TurnTimeoutError(this.requestId, turnTimeout));\n }, turnTimeout);\n }\n }\n /** Feed an event into the turn (called by the client's dispatcher). */\n push(event) {\n if (this.done)\n return;\n if (event.type === 'error') {\n const code = event.data?.error?.code ?? 'INTERNAL_ERROR';\n const message = event.data?.error?.message ?? 'Unknown protocol error';\n this.deliver(event);\n this.finish(null, new ProtocolError(code, message, this.requestId));\n return;\n }\n this.deliver(event);\n if (event.type === 'eventual_response') {\n this.finish(event, null);\n }\n }\n /** Force-close the turn (e.g. on disconnect) with an error. */\n abort(err) {\n if (this.done)\n return;\n this.finish(null, err);\n }\n deliver(event) {\n if (this.waiter) {\n const w = this.waiter;\n this.waiter = null;\n w.resolve({ value: event, done: false });\n }\n else {\n this.queue.push(event);\n }\n }\n finish(final, err) {\n if (this.done)\n return;\n this.done = true;\n this.finalEvent = final;\n this.error = err;\n if (this.timeoutTimer) {\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n }\n this.onClose();\n if (err)\n this.fail(err);\n else if (final)\n this.settle(final);\n // Release any pending iterator waiter now that the stream has ended. On error\n // the parked next() must *reject* (mirroring the queued-error path in next())\n // so a pure `for await` consumer sees the terminal error thrown instead of a\n // silent, indistinguishable `{ done: true }`.\n if (this.waiter) {\n const w = this.waiter;\n this.waiter = null;\n if (err) {\n w.reject(err);\n }\n else {\n w.resolve({ value: undefined, done: true });\n }\n }\n }\n [Symbol.asyncIterator]() {\n return {\n next: () => {\n if (this.queue.length > 0) {\n return Promise.resolve({ value: this.queue.shift(), done: false });\n }\n if (this.done) {\n if (this.error)\n return Promise.reject(this.error);\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n this.waiter = { resolve, reject };\n });\n },\n };\n }\n // PromiseLike — `await turn` resolves with the EventualResponse.\n then(onfulfilled, onrejected) {\n return this.settled.then(onfulfilled, onrejected);\n }\n}\nexport class SmoothAgentClient {\n transport;\n generateRequestId;\n requestTimeout;\n turnTimeout;\n /** requestId → single-response waiter (create_session, get_session, ping, …). */\n pending = new Map();\n /** requestId → active streaming turn (send_message, and HITL resumes). */\n turns = new Map();\n /** Unsolicited-event listeners (keepalive, server-push). */\n listeners = new Set();\n unsubscribe = [];\n constructor(options) {\n this.transport =\n options.transport ??\n new WebSocketTransport(withConnectionToken(options.url, options.token), options.webSocketFactory);\n this.requestTimeout = options.requestTimeout ?? 30_000;\n this.turnTimeout = options.turnTimeout ?? 120_000;\n this.generateRequestId =\n options.generateRequestId ??\n (() => `req-${(globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2))}`);\n this.unsubscribe.push(this.transport.onMessage((data) => this.handleFrame(data)));\n this.unsubscribe.push(this.transport.onClose(() => this.failAll(new Error('Transport closed'))));\n }\n /** Open the underlying transport. */\n async connect() {\n await this.transport.connect();\n }\n /** Close the transport and reject all in-flight work. */\n disconnect(reason = 'client disconnect') {\n this.failAll(new Error(reason));\n for (const u of this.unsubscribe)\n u();\n this.unsubscribe = [];\n this.transport.close(1000, reason);\n }\n /** Subscribe to unsolicited / uncorrelated server events (e.g. keepalive). */\n onEvent(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n // ───────────────────────────── Actions ─────────────────────────────────\n /** Start a new conversation session. Resolves with the session descriptor. */\n async createConversationSession(req) {\n const event = await this.request({ action: 'create_conversation_session', ...req });\n return extractImmediateData(event);\n }\n /** Fetch a session snapshot by ID. */\n async getSession(req) {\n const event = await this.request({ action: 'get_session', ...req });\n return extractImmediateData(event);\n }\n /** Fetch a page of conversation messages. */\n async getMessages(req) {\n const event = await this.request({ action: 'get_conversation_messages', ...req });\n return extractImmediateData(event);\n }\n /** Keepalive ping. Resolves with the server timestamp from the `pong` event. */\n async ping() {\n const event = await this.request({ action: 'ping' });\n if (event.type === 'pong')\n return event.timestamp ?? event.data?.timestamp ?? Date.now();\n return Date.now();\n }\n /**\n * Submit a user message and return a {@link MessageTurn}: await it for the\n * terminal `eventual_response`, or async-iterate it for the streaming events.\n */\n sendMessage(req) {\n const requestId = this.generateRequestId();\n const turn = new MessageTurn(requestId, () => this.turns.delete(requestId), this.turnTimeout);\n this.turns.set(requestId, turn);\n try {\n this.transport.send(JSON.stringify({ action: 'send_message', requestId, ...req }));\n }\n catch (err) {\n this.turns.delete(requestId);\n turn.abort(err);\n }\n return turn;\n }\n /**\n * Approve or reject a pending tool write, resuming the paused turn identified\n * by `requestId`. The resumed streaming events flow back into the original\n * {@link MessageTurn} for that `requestId`.\n */\n confirmToolAction(req) {\n this.transport.send(JSON.stringify({ action: 'confirm_tool_action', ...req }));\n }\n /**\n * Submit an OTP code, resuming the paused turn identified by `requestId`.\n * The resumed streaming events flow back into the original {@link MessageTurn}.\n */\n verifyOtp(req) {\n this.transport.send(JSON.stringify({ action: 'verify_otp', ...req }));\n }\n // ─────────────────────────── Internals ─────────────────────────────────\n /** Send an action that expects a single correlated response event. */\n request(action) {\n const requestId = action.requestId ?? this.generateRequestId();\n const frame = { ...action, requestId };\n return new Promise((resolve, reject) => {\n const timer = this.requestTimeout > 0\n ? setTimeout(() => {\n this.pending.delete(requestId);\n reject(new RequestTimeoutError(requestId, this.requestTimeout));\n }, this.requestTimeout)\n : undefined;\n this.pending.set(requestId, { resolve, reject, timer });\n try {\n this.transport.send(JSON.stringify(frame));\n }\n catch (err) {\n if (timer)\n clearTimeout(timer);\n this.pending.delete(requestId);\n reject(err);\n }\n });\n }\n /** Parse and route an incoming frame to the right consumer. */\n handleFrame(data) {\n let frame;\n try {\n frame = JSON.parse(data);\n }\n catch {\n return; // ignore malformed frames\n }\n if (!isServerEvent(frame))\n return;\n const event = frame;\n const requestId = event.requestId;\n // 1. Streaming turn? Route every related event into it.\n if (requestId && this.turns.has(requestId)) {\n this.turns.get(requestId).push(event);\n return;\n }\n // 2. Single-response request awaiting resolution?\n if (requestId && this.pending.has(requestId)) {\n const pending = this.pending.get(requestId);\n this.pending.delete(requestId);\n if (pending.timer)\n clearTimeout(pending.timer);\n if (event.type === 'error') {\n const code = event.data?.error?.code ?? 'INTERNAL_ERROR';\n const message = event.data?.error?.message ?? 'Unknown protocol error';\n pending.reject(new ProtocolError(code, message, requestId));\n }\n else {\n pending.resolve(event);\n }\n return;\n }\n // 3. Unsolicited / uncorrelated event (keepalive, server push).\n for (const l of this.listeners)\n l(event);\n }\n failAll(err) {\n for (const [, p] of this.pending) {\n if (p.timer)\n clearTimeout(p.timer);\n p.reject(err);\n }\n this.pending.clear();\n for (const [, turn] of this.turns)\n turn.abort(err);\n this.turns.clear();\n }\n}\n/**\n * Merge a connection auth `token` into a WebSocket URL as a `?token=` query param,\n * preserving any existing query string. Returns `url` unchanged when no token is\n * given, so the no-token path is byte-for-byte identical to before. Uses `URL` /\n * `URLSearchParams` so an existing `?foo=bar` becomes `?foo=bar&token=…` (and the\n * value is properly percent-encoded) rather than a naive `?`/`&` string-concat.\n *\n * Falls back to manual concatenation if `url` is not absolute (so `URL` can't parse\n * it) — e.g. a relative or mock URL used in tests.\n */\nfunction withConnectionToken(url, token) {\n if (!token)\n return url;\n try {\n const parsed = new URL(url);\n parsed.searchParams.set('token', token);\n return parsed.toString();\n }\n catch {\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}token=${encodeURIComponent(token)}`;\n }\n}\n/** Pull the typed `data` payload out of an `immediate_response` event. */\nfunction extractImmediateData(event) {\n if (event.type === 'immediate_response')\n return event.data;\n // Some servers may answer a non-streaming action with the payload elsewhere;\n // fall back to `data` if present.\n if ('data' in event && event.data && typeof event.data === 'object')\n return event.data;\n throw new ProtocolError('UNEXPECTED_EVENT', `Expected immediate_response, got \"${event.type}\"`, event.requestId);\n}\n//# sourceMappingURL=client.js.map","/**\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 * 2. `send(text)` → `send_message`, streaming `stream_token` deltas into the\n * in-progress assistant message, then the terminal\n * `eventual_response`.\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 { ChatWidgetConfig } from './config.js';\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}\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}\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\nexport class ConversationController {\n private readonly config: ChatWidgetConfig;\n private readonly events: ConversationEvents;\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 /** Visitor identity, seeded from config and updated by the pre-chat form. */\n private identity: UserInfo;\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\n constructor(config: ChatWidgetConfig, events: ConversationEvents) {\n this.config = config;\n this.events = events;\n this.identity = { name: config.userName, email: config.userEmail, phone: config.userPhone };\n }\n\n get connectionStatus(): ConnectionStatus {\n return this.status;\n }\n\n /** Merge in visitor identity (from the pre-chat form). Applied on next connect. */\n setUserInfo(info: UserInfo): void {\n this.identity = { ...this.identity, ...info };\n }\n\n private setInterrupt(interrupt: Interrupt | null): void {\n this.interrupt = interrupt;\n this.events.onInterrupt?.(interrupt);\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 /** Open the transport and create a conversation session. Idempotent. */\n async connect(): Promise<void> {\n if (this.status === 'connecting' || this.status === 'ready') return;\n this.setStatus('connecting');\n try {\n this.client = new SmoothAgentClient({ url: this.config.endpoint });\n await this.client.connect();\n const session = await this.client.createConversationSession({\n agentId: this.config.agentId,\n userName: this.identity.name,\n userEmail: this.identity.email,\n // Phone has no first-class field yet; carry it in session metadata.\n ...(this.identity.phone ? { metadata: { userPhone: this.identity.phone } } : {}),\n });\n this.sessionId = session.sessionId;\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 /**\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 /** 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 this.setInterrupt(null);\n this.setStatus('closed');\n }\n}\n","/**\n * The Smooth logo, inlined as an SVG string so the full-page header can render\n * it without a separate network fetch (the IIFE bundle is self-contained).\n *\n * GENERATED from `assets/smooth-logo.svg` — do not edit by hand. Regenerate with:\n * node -e ... (see the commit that added this file)\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","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: block;\n position: relative;\n width: 100%;\n height: 100%;\n min-height: 100vh;`\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* { 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. */\n.panel.fullpage {\n width: 100%;\n height: 100%;\n min-height: 100vh;\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; }\n.avatar .logo { height: 22px; width: auto; display: block; }\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; }\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\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/* 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\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.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\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\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 type { ChatWidgetConfig, ChatWidgetMode, ChatWidgetTheme } from './config.js';\nimport { needsUserInfo, resolveConfig } from './config.js';\nimport { type ChatMessage, type Citation, type ConnectionStatus, ConversationController, type Interrupt } from './conversation.js';\nimport { SMOOTH_LOGO_SVG } from './logo.js';\nimport { buildStyles } from './styles.js';\n\nexport const ELEMENT_TAG = 'smooth-agent-chat';\n\nconst OBSERVED = ['endpoint', 'agent-id', 'agent-name', 'placeholder', 'greeting', 'start-open', 'mode'] 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/**\n * Return `url` only if it is a valid absolute `http(s)` URL, else `null`.\n *\n * SECURITY: citation URLs originate from indexed content (web / GitHub\n * connectors), which can be attacker-influenceable. Assigning an arbitrary\n * string to `<a>.href` allows `javascript:`/`data:`/`vbscript:` URLs that\n * execute on click — a stored-XSS vector. Only http(s) links are rendered as\n * anchors; anything else falls back to plain text.\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\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 /** Current mid-turn interrupt (OTP / tool-confirmation), or null. */\n private interrupt: Interrupt | null = null;\n private interruptEl: HTMLElement | null = null;\n\n // Cached DOM refs (populated in render()).\n private panelEl: HTMLElement | null = null;\n private launcherEl: HTMLElement | null = null;\n private messagesEl: HTMLElement | null = null;\n private statusEl: HTMLElement | null = null;\n private dotEl: HTMLElement | null = null;\n private inputEl: HTMLTextAreaElement | null = null;\n private sendBtn: HTMLButtonElement | null = null;\n\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.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 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 userName: this.overrides.userName,\n userEmail: this.overrides.userEmail,\n userPhone: this.overrides.userPhone,\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 examplePrompts: this.overrides.examplePrompts,\n requireName: this.overrides.requireName,\n requireEmail: this.overrides.requireEmail,\n requirePhone: this.overrides.requirePhone,\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 // (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.messages = messages;\n this.renderMessages(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 });\n if (resolved.startOpen) this.open = true;\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 Smooth 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.\n const monogram = escapeHtml((resolved.agentName.trim().charAt(0) || 'A').toUpperCase());\n const header = fullpage\n ? `<div class=\"header\">\n <div class=\"avatar\"><span class=\"logo-wrap\">${SMOOTH_LOGO_SVG}</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 <span class=\"powered\">powered by smooth-operator</span>\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 for the empty-state chips.\n this.examplePrompts = resolved.examplePrompts;\n\n // Gate the conversation behind a pre-chat identity form when required.\n const gating = needsUserInfo(resolved) && !this.userInfoSatisfied;\n const field = (name: string, type: string, label: string, autocomplete: string) =>\n `<label class=\"pc-field\"><span>${escapeHtml(label)}</span><input name=\"${name}\" type=\"${type}\" autocomplete=\"${autocomplete}\" required /></label>`;\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') : ''}\n ${resolved.requireEmail ? field('email', 'email', 'Email', 'email') : ''}\n ${resolved.requirePhone ? field('phone', 'tel', 'Phone', 'tel') : ''}\n <button type=\"submit\" class=\"pc-submit\">Start chat</button>\n </form>\n </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 <div class=\"footer\">powered by <b>smooth&#8209;operator</b></div>\n </div>`;\n\n const container = document.createElement('div');\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 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 // 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(resolved.greeting);\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 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 /** Collect identity 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 this.controller?.setUserInfo({ name: val('name'), email: val('email'), phone: val('phone') });\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 private renderMessages(greeting: string): void {\n if (!this.messagesEl) return;\n this.messagesEl.replaceChildren();\n\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 bubble.classList.add('cursor');\n bubble.textContent = msg.text;\n } else {\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.messagesEl.scrollTop = this.messagesEl.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';\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 const snip = document.createElement('span');\n snip.className = 'src-snippet';\n snip.textContent = c.snippet;\n li.appendChild(snip);\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\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case '&':\n return '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n default:\n return '&#39;';\n }\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 * Standalone IIFE entry. Bundled (with the protocol client inlined) into\n * `dist/chat-widget.global.js` for a plain `<script src=\"…\">` embed.\n *\n * On load it:\n * - registers the `<smooth-agent-chat>` custom element, and\n * - exposes the programmatic API on the IIFE global `SmoothAgentChat`\n * (`window.SmoothAgentChat.mount({ endpoint, agentId })`).\n *\n * A host page can then either drop the element in markup:\n * <smooth-agent-chat endpoint=\"wss://…/ws\" agent-id=\"…\"></smooth-agent-chat>\n * or mount it programmatically:\n * SmoothAgentChat.mount({ endpoint: 'wss://…/ws', agentId: '…' });\n */\nimport type { ChatWidgetConfig } from './config.js';\nimport { defineChatWidget, mountChatWidget, mountFullPageChat, SmoothAgentChatElement } from './element.js';\n\ndefineChatWidget();\n\nexport { defineChatWidget, mountChatWidget, mountFullPageChat, SmoothAgentChatElement };\n\n/** Convenience alias matching the global API surface (`SmoothAgentChat.mount`). */\nexport function mount(config: ChatWidgetConfig, target?: HTMLElement): SmoothAgentChatElement {\n return mountChatWidget(config, target);\n}\n\n/**\n * Full-page convenience alias (`SmoothAgentChat.mountFullPage`): mounts the chat\n * in `mode: \"fullpage\"` so it fills its container/viewport with no launcher.\n */\nexport function mountFullPage(config: Omit<ChatWidgetConfig, 'mode'>, target?: HTMLElement): SmoothAgentChatElement {\n return mountFullPageChat(config, target);\n}\n"],"x_google_ignoreList":[1,2,3],"mappings":";;;;CAgHA,SAAgB,cAAc,QAA0C;EACpE,MAAM,QAAQ,OAAO,SAAS,CAAC;EAC/B,MAAM,UAAU,MAAM,WAAW;EACjC,MAAM,cAAc,MAAM,eAAe;EAEzC,MAAM,kBAAkB,MAAM,qBAAqB,MAAM,mBAAmB;EAC5E,MAAM,sBAAsB,MAAM,yBAAyB,MAAM,uBAAuB;EACxF,MAAM,aAAa,MAAM,sBAAsB,MAAM,cAAc;EACnE,MAAM,iBAAiB,MAAM,0BAA0B,MAAM,kBAAkB;EAC/E,OAAO;GACH,UAAU,OAAO;GACjB,MAAM,OAAO,QAAQ;GACrB,SAAS,OAAO;GAChB,WAAW,OAAO,aAAa;GAC/B,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB,aAAa,OAAO,eAAe;GACnC,UAAU,OAAO,YAAY;GAC7B,wBAAwB,OAAO,0BAA0B;GACzD,WAAW,OAAO,aAAa;GAC/B,iBAAiB,OAAO,kBAAkB,CAAC,EAAA,CAAG,QAAQ,MAAM,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;GAC3F,aAAa,OAAO,eAAe;GACnC,cAAc,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I,CAAC,KAAK,WAAW,CAAC,KAAK,YAAY;GACvC,MAAM,OAAO,KAAK,QAAQ;GAC1B,IAAI,CAAC,KAAK,KAAK,GAAG;GAClB,KAAK,QAAQ,QAAQ;GACrB,KAAK,UAAU;GACf,KAAK,SAAS;GACd,KAAU,WAAW,KAAK,IAAI;EAClC;CACJ;CAEA,SAAS,WAAW,OAAuB;EACvC,OAAO,MAAM,QAAQ,aAAa,MAAM;GACpC,QAAQ,GAAR;IACI,KAAK,KACD,OAAO;IACX,KAAK,KACD,OAAO;IACX,KAAK,KACD,OAAO;IACX,KAAK,MACD,OAAO;IACX,SACI,OAAO;GACf;EACJ,CAAC;CACL;;CAGA,SAAgB,mBAAyB;EACrC,IAAI,OAAO,mBAAmB,eAAe,CAAC,eAAe,IAAA,mBAAe,GACxE,eAAe,OAAO,aAAa,sBAAsB;CAEjE;;;;;CAMA,SAAgB,gBAAgB,QAA0B,SAAsB,SAAS,MAA8B;EACnH,iBAAiB;EACjB,MAAM,KAAK,SAAS,cAAc,WAAW;EAC7C,GAAG,UAAU,MAAM;EACnB,OAAO,YAAY,EAAE;EACrB,OAAO;CACX;;;;;;;;;;;;;;;CAgBA,SAAgB,kBAAkB,QAAwC,SAAsB,SAAS,MAA8B;EACnI,OAAO,gBAAgB;GAAE,GAAG;GAAQ,MAAM;EAAW,GAAG,MAAM;CAClE;;;CC/oBA,iBAAiB;;CAKjB,SAAgB,MAAM,QAA0B,QAA8C;EAC1F,OAAO,gBAAgB,QAAQ,MAAM;CACzC;;;;;CAMA,SAAgB,cAAc,QAAwC,QAA8C;EAChH,OAAO,kBAAkB,QAAQ,MAAM;CAC3C"}
1
+ {"version":3,"file":"chat-widget.global.js","names":[],"sources":["../src/config.ts","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/transport.js","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/types.js","../node_modules/.pnpm/@smooai+smooth-operator@1.8.0/node_modules/@smooai/smooth-operator/dist/client.js","../src/fingerprint.ts","../node_modules/.pnpm/zustand@5.0.14/node_modules/zustand/esm/vanilla.mjs","../node_modules/.pnpm/zustand@5.0.14/node_modules/zustand/esm/middleware.mjs","../src/persistence.ts","../src/conversation.ts","../src/logo.ts","../src/markdown.ts","../src/styles.ts","../src/element.ts","../src/standalone.ts"],"sourcesContent":["/**\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 */\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 /** 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 * 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'>> & {\n theme: ResolvedTheme;\n userName?: string;\n userEmail?: string;\n userPhone?: string;\n authContext?: { userId: string; signature: string; timestamp: number };\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 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 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 * Transport abstraction for the client.\n *\n * The client is deliberately decoupled from any concrete WebSocket implementation\n * so it can be unit-tested with a mock and run on Node, the browser, or a custom\n * socket. A transport is anything that can send a string frame and surface\n * incoming string frames + lifecycle events.\n */\nconst WS_CONNECTING = 0;\nconst WS_OPEN = 1;\nconst WS_CLOSING = 2;\n/** Default connect timeout (ms) for the WebSocket transport. */\nconst DEFAULT_CONNECT_TIMEOUT = 30_000;\n/**\n * Default transport backed by a `WebSocket`-like object. By default it uses the\n * global `WebSocket`; pass a `factory` to inject one (e.g. the `ws` package on\n * Node, or a mock in tests).\n */\nexport class WebSocketTransport {\n socket = null;\n url;\n factory;\n connectTimeout;\n messageHandlers = new Set();\n closeHandlers = new Set();\n errorHandlers = new Set();\n constructor(url, factory, connectTimeout = DEFAULT_CONNECT_TIMEOUT) {\n this.url = url;\n this.connectTimeout = connectTimeout;\n if (factory) {\n this.factory = factory;\n }\n else {\n const G = globalThis;\n if (!G.WebSocket) {\n throw new Error('No global WebSocket available; pass a WebSocketFactory to WebSocketTransport.');\n }\n const Ctor = G.WebSocket;\n this.factory = (u) => new Ctor(u);\n }\n }\n get state() {\n if (!this.socket)\n return 'closed';\n switch (this.socket.readyState) {\n case WS_CONNECTING:\n return 'connecting';\n case WS_OPEN:\n return 'open';\n case WS_CLOSING:\n return 'closing';\n default:\n return 'closed';\n }\n }\n connect() {\n if (this.socket && this.socket.readyState === WS_OPEN)\n return Promise.resolve();\n // A prior socket that never reached OPEN (failed/half-open dial, or a closed\n // socket from a previous attempt) would otherwise be orphaned: its listeners\n // stay registered and keep dispatching into the shared handler sets, so a late\n // message/close from the dead socket double-fires. Close it and detach it\n // before dialing a fresh one. (WebSocketLike has no removeEventListener, so we\n // also guard every handler below with an identity check on `this.socket`.)\n if (this.socket && this.socket.readyState !== WS_OPEN) {\n const stale = this.socket;\n this.socket = null;\n try {\n stale.close();\n }\n catch {\n // ignore — best-effort teardown of a half-open socket\n }\n }\n return new Promise((resolve, reject) => {\n const socket = this.factory(this.url);\n this.socket = socket;\n let settled = false;\n const timer = this.connectTimeout > 0\n ? setTimeout(() => {\n if (settled)\n return;\n settled = true;\n // Tear down the half-open socket so it can't leak / fire later.\n if (this.socket === socket)\n this.socket = null;\n try {\n socket.close();\n }\n catch {\n // ignore\n }\n reject(new Error(`WebSocket connect to ${this.url} timed out after ${this.connectTimeout}ms`));\n }, this.connectTimeout)\n : undefined;\n socket.addEventListener('open', () => {\n // Ignore events from a socket we've already replaced/abandoned.\n if (this.socket !== socket)\n return;\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n resolve();\n });\n socket.addEventListener('error', (ev) => {\n if (this.socket !== socket)\n return;\n for (const h of this.errorHandlers)\n h(ev);\n if (!settled && this.state !== 'open') {\n settled = true;\n if (timer)\n clearTimeout(timer);\n if (this.socket === socket)\n this.socket = null;\n // Release the failed socket so it can't linger / fire later.\n try {\n socket.close();\n }\n catch {\n // ignore\n }\n reject(ev instanceof Error ? ev : new Error('WebSocket connection error'));\n }\n });\n socket.addEventListener('close', (ev) => {\n if (this.socket !== socket)\n return;\n if (timer)\n clearTimeout(timer);\n for (const h of this.closeHandlers)\n h({ code: ev.code, reason: ev.reason });\n });\n socket.addEventListener('message', (ev) => {\n if (this.socket !== socket)\n return;\n const data = typeof ev.data === 'string' ? ev.data : String(ev.data);\n for (const h of this.messageHandlers)\n h(data);\n });\n });\n }\n send(data) {\n if (!this.socket || this.socket.readyState !== WS_OPEN) {\n throw new Error(`Cannot send: transport is \"${this.state}\"`);\n }\n this.socket.send(data);\n }\n close(code, reason) {\n this.socket?.close(code, reason);\n }\n onMessage(handler) {\n this.messageHandlers.add(handler);\n return () => this.messageHandlers.delete(handler);\n }\n onClose(handler) {\n this.closeHandlers.add(handler);\n return () => this.closeHandlers.delete(handler);\n }\n onError(handler) {\n this.errorHandlers.add(handler);\n return () => this.errorHandlers.delete(handler);\n }\n}\n//# sourceMappingURL=transport.js.map","export * from './generated/types.js';\n// ───────────────────────────── Discriminators ──────────────────────────────\n/** Every client→server `action` discriminator value. */\nexport const ACTION_TYPES = [\n 'create_conversation_session',\n 'send_message',\n 'get_session',\n 'get_conversation_messages',\n 'confirm_tool_action',\n 'verify_otp',\n 'ping',\n];\n/** Every server→client `type` discriminator value. */\nexport const EVENT_TYPES = [\n 'immediate_response',\n 'eventual_response',\n 'stream_chunk',\n 'stream_token',\n 'keepalive',\n 'write_confirmation_required',\n 'otp_verification_required',\n 'otp_sent',\n 'otp_verified',\n 'otp_invalid',\n 'error',\n 'pong',\n];\n// ───────────────────────────── Type guards ─────────────────────────────────\n/** True if `frame` is a server event of the given `type`, narrowing accordingly. */\nexport function isEvent(frame, type) {\n return isServerEvent(frame) && frame.type === type;\n}\n/** True if `frame` looks like any server event (has a known `type` discriminator). */\nexport function isServerEvent(frame) {\n return (typeof frame === 'object' &&\n frame !== null &&\n 'type' in frame &&\n typeof frame.type === 'string' &&\n EVENT_TYPES.includes(frame.type));\n}\n/** True if `frame` looks like any client action (has a known `action` discriminator). */\nexport function isClientAction(frame) {\n return (typeof frame === 'object' &&\n frame !== null &&\n 'action' in frame &&\n typeof frame.action === 'string' &&\n ACTION_TYPES.includes(frame.action));\n}\n//# sourceMappingURL=types.js.map","/**\n * SmoothAgentClient — a minimal, idiomatic, transport-agnostic client for the\n * smooth-operator WebSocket protocol.\n *\n * Design goals\n * ------------\n * - **Transport-agnostic.** The client never touches a real socket directly; it\n * talks to an injectable {@link Transport}. The default ({@link WebSocketTransport})\n * uses the global `WebSocket`, but tests inject a mock and Node can inject `ws`.\n * - **Request/response correlation by `requestId`.** Every action gets a generated\n * `requestId`; the client routes incoming events back to the originating call.\n * - **Streaming as an async iterator.** `sendMessage` returns a {@link MessageTurn}\n * that is both awaitable (resolves with the terminal `eventual_response`) and\n * async-iterable (yields each `stream_token` / `stream_chunk` / HITL event in\n * order). This models the `stream_token`/`stream_chunk` → `eventual_response`\n * flow without forcing a callback style on the caller.\n * - **No live server required.** Correctness is fully unit-testable with a mock\n * transport (see `test/client.test.ts`).\n */\nimport { WebSocketTransport, } from './transport.js';\nimport { isServerEvent } from './types.js';\n/** Events that terminate a streaming turn (success or error). */\nconst TURN_TERMINAL = new Set(['eventual_response', 'error']);\n/** A timeout that yields no terminal event. */\nclass RequestTimeoutError extends Error {\n constructor(requestId, ms) {\n super(`Request ${requestId} timed out after ${ms}ms`);\n this.name = 'RequestTimeoutError';\n }\n}\n/**\n * A streaming turn that received no terminal `eventual_response` / `error` within the\n * configured {@link SmoothAgentClientOptions.turnTimeout}. The turn rejects with this\n * and its async iteration throws it, so a stuck server can never hang the caller.\n */\nexport class TurnTimeoutError extends Error {\n requestId;\n constructor(requestId, ms) {\n super(`Turn ${requestId} timed out after ${ms}ms without a terminal response`);\n this.name = 'TurnTimeoutError';\n this.requestId = requestId;\n }\n}\n/** A protocol-level error event surfaced as a throwable. */\nexport class ProtocolError extends Error {\n code;\n requestId;\n constructor(code, message, requestId) {\n super(message);\n this.name = 'ProtocolError';\n this.code = code;\n this.requestId = requestId;\n }\n}\n/**\n * A streaming message turn. Await it for the terminal {@link EventualResponse},\n * or async-iterate it to receive every intermediate event in arrival order.\n *\n * ```ts\n * const turn = client.sendMessage({ sessionId, message: 'hi' });\n * for await (const ev of turn) {\n * if (ev.type === 'stream_token') process.stdout.write(ev.token ?? '');\n * }\n * const final = await turn; // EventualResponse\n * ```\n */\nexport class MessageTurn {\n /** The requestId this turn is correlated on. */\n requestId;\n queue = [];\n waiter = null;\n done = false;\n finalEvent = null;\n error = null;\n settled;\n settle;\n fail;\n onClose;\n timeoutTimer;\n constructor(requestId, onClose, turnTimeout = 0) {\n this.requestId = requestId;\n this.onClose = onClose;\n this.settled = new Promise((resolve, reject) => {\n this.settle = resolve;\n this.fail = reject;\n });\n // Avoid unhandled-rejection noise if the caller only iterates and never awaits.\n this.settled.catch(() => { });\n // Bound the turn: a server that accepts the message but never emits a terminal\n // event must not hang the caller forever.\n if (turnTimeout > 0) {\n this.timeoutTimer = setTimeout(() => {\n this.finish(null, new TurnTimeoutError(this.requestId, turnTimeout));\n }, turnTimeout);\n }\n }\n /** Feed an event into the turn (called by the client's dispatcher). */\n push(event) {\n if (this.done)\n return;\n if (event.type === 'error') {\n const code = event.data?.error?.code ?? 'INTERNAL_ERROR';\n const message = event.data?.error?.message ?? 'Unknown protocol error';\n this.deliver(event);\n this.finish(null, new ProtocolError(code, message, this.requestId));\n return;\n }\n this.deliver(event);\n if (event.type === 'eventual_response') {\n this.finish(event, null);\n }\n }\n /** Force-close the turn (e.g. on disconnect) with an error. */\n abort(err) {\n if (this.done)\n return;\n this.finish(null, err);\n }\n deliver(event) {\n if (this.waiter) {\n const w = this.waiter;\n this.waiter = null;\n w.resolve({ value: event, done: false });\n }\n else {\n this.queue.push(event);\n }\n }\n finish(final, err) {\n if (this.done)\n return;\n this.done = true;\n this.finalEvent = final;\n this.error = err;\n if (this.timeoutTimer) {\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n }\n this.onClose();\n if (err)\n this.fail(err);\n else if (final)\n this.settle(final);\n // Release any pending iterator waiter now that the stream has ended. On error\n // the parked next() must *reject* (mirroring the queued-error path in next())\n // so a pure `for await` consumer sees the terminal error thrown instead of a\n // silent, indistinguishable `{ done: true }`.\n if (this.waiter) {\n const w = this.waiter;\n this.waiter = null;\n if (err) {\n w.reject(err);\n }\n else {\n w.resolve({ value: undefined, done: true });\n }\n }\n }\n [Symbol.asyncIterator]() {\n return {\n next: () => {\n if (this.queue.length > 0) {\n return Promise.resolve({ value: this.queue.shift(), done: false });\n }\n if (this.done) {\n if (this.error)\n return Promise.reject(this.error);\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n this.waiter = { resolve, reject };\n });\n },\n };\n }\n // PromiseLike — `await turn` resolves with the EventualResponse.\n then(onfulfilled, onrejected) {\n return this.settled.then(onfulfilled, onrejected);\n }\n}\nexport class SmoothAgentClient {\n transport;\n generateRequestId;\n requestTimeout;\n turnTimeout;\n /** requestId → single-response waiter (create_session, get_session, ping, …). */\n pending = new Map();\n /** requestId → active streaming turn (send_message, and HITL resumes). */\n turns = new Map();\n /** Unsolicited-event listeners (keepalive, server-push). */\n listeners = new Set();\n unsubscribe = [];\n constructor(options) {\n this.transport =\n options.transport ??\n new WebSocketTransport(withConnectionToken(options.url, options.token), options.webSocketFactory);\n this.requestTimeout = options.requestTimeout ?? 30_000;\n this.turnTimeout = options.turnTimeout ?? 120_000;\n this.generateRequestId =\n options.generateRequestId ??\n (() => `req-${(globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2))}`);\n this.unsubscribe.push(this.transport.onMessage((data) => this.handleFrame(data)));\n this.unsubscribe.push(this.transport.onClose(() => this.failAll(new Error('Transport closed'))));\n }\n /** Open the underlying transport. */\n async connect() {\n await this.transport.connect();\n }\n /** Close the transport and reject all in-flight work. */\n disconnect(reason = 'client disconnect') {\n this.failAll(new Error(reason));\n for (const u of this.unsubscribe)\n u();\n this.unsubscribe = [];\n this.transport.close(1000, reason);\n }\n /** Subscribe to unsolicited / uncorrelated server events (e.g. keepalive). */\n onEvent(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n // ───────────────────────────── Actions ─────────────────────────────────\n /** Start a new conversation session. Resolves with the session descriptor. */\n async createConversationSession(req) {\n const event = await this.request({ action: 'create_conversation_session', ...req });\n return extractImmediateData(event);\n }\n /** Fetch a session snapshot by ID. */\n async getSession(req) {\n const event = await this.request({ action: 'get_session', ...req });\n return extractImmediateData(event);\n }\n /** Fetch a page of conversation messages. */\n async getMessages(req) {\n const event = await this.request({ action: 'get_conversation_messages', ...req });\n return extractImmediateData(event);\n }\n /** Keepalive ping. Resolves with the server timestamp from the `pong` event. */\n async ping() {\n const event = await this.request({ action: 'ping' });\n if (event.type === 'pong')\n return event.timestamp ?? event.data?.timestamp ?? Date.now();\n return Date.now();\n }\n /**\n * Submit a user message and return a {@link MessageTurn}: await it for the\n * terminal `eventual_response`, or async-iterate it for the streaming events.\n */\n sendMessage(req) {\n const requestId = this.generateRequestId();\n const turn = new MessageTurn(requestId, () => this.turns.delete(requestId), this.turnTimeout);\n this.turns.set(requestId, turn);\n try {\n this.transport.send(JSON.stringify({ action: 'send_message', requestId, ...req }));\n }\n catch (err) {\n this.turns.delete(requestId);\n turn.abort(err);\n }\n return turn;\n }\n /**\n * Approve or reject a pending tool write, resuming the paused turn identified\n * by `requestId`. The resumed streaming events flow back into the original\n * {@link MessageTurn} for that `requestId`.\n */\n confirmToolAction(req) {\n this.transport.send(JSON.stringify({ action: 'confirm_tool_action', ...req }));\n }\n /**\n * Submit an OTP code, resuming the paused turn identified by `requestId`.\n * The resumed streaming events flow back into the original {@link MessageTurn}.\n */\n verifyOtp(req) {\n this.transport.send(JSON.stringify({ action: 'verify_otp', ...req }));\n }\n // ─────────────────────────── Internals ─────────────────────────────────\n /** Send an action that expects a single correlated response event. */\n request(action) {\n const requestId = action.requestId ?? this.generateRequestId();\n const frame = { ...action, requestId };\n return new Promise((resolve, reject) => {\n const timer = this.requestTimeout > 0\n ? setTimeout(() => {\n this.pending.delete(requestId);\n reject(new RequestTimeoutError(requestId, this.requestTimeout));\n }, this.requestTimeout)\n : undefined;\n this.pending.set(requestId, { resolve, reject, timer });\n try {\n this.transport.send(JSON.stringify(frame));\n }\n catch (err) {\n if (timer)\n clearTimeout(timer);\n this.pending.delete(requestId);\n reject(err);\n }\n });\n }\n /** Parse and route an incoming frame to the right consumer. */\n handleFrame(data) {\n let frame;\n try {\n frame = JSON.parse(data);\n }\n catch {\n return; // ignore malformed frames\n }\n if (!isServerEvent(frame))\n return;\n const event = frame;\n const requestId = event.requestId;\n // 1. Streaming turn? Route every related event into it.\n if (requestId && this.turns.has(requestId)) {\n this.turns.get(requestId).push(event);\n return;\n }\n // 2. Single-response request awaiting resolution?\n if (requestId && this.pending.has(requestId)) {\n const pending = this.pending.get(requestId);\n this.pending.delete(requestId);\n if (pending.timer)\n clearTimeout(pending.timer);\n if (event.type === 'error') {\n const code = event.data?.error?.code ?? 'INTERNAL_ERROR';\n const message = event.data?.error?.message ?? 'Unknown protocol error';\n pending.reject(new ProtocolError(code, message, requestId));\n }\n else {\n pending.resolve(event);\n }\n return;\n }\n // 3. Unsolicited / uncorrelated event (keepalive, server push).\n for (const l of this.listeners)\n l(event);\n }\n failAll(err) {\n for (const [, p] of this.pending) {\n if (p.timer)\n clearTimeout(p.timer);\n p.reject(err);\n }\n this.pending.clear();\n for (const [, turn] of this.turns)\n turn.abort(err);\n this.turns.clear();\n }\n}\n/**\n * Merge a connection auth `token` into a WebSocket URL as a `?token=` query param,\n * preserving any existing query string. Returns `url` unchanged when no token is\n * given, so the no-token path is byte-for-byte identical to before. Uses `URL` /\n * `URLSearchParams` so an existing `?foo=bar` becomes `?foo=bar&token=…` (and the\n * value is properly percent-encoded) rather than a naive `?`/`&` string-concat.\n *\n * Falls back to manual concatenation if `url` is not absolute (so `URL` can't parse\n * it) — e.g. a relative or mock URL used in tests.\n */\nfunction withConnectionToken(url, token) {\n if (!token)\n return url;\n try {\n const parsed = new URL(url);\n parsed.searchParams.set('token', token);\n return parsed.toString();\n }\n catch {\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}token=${encodeURIComponent(token)}`;\n }\n}\n/** Pull the typed `data` payload out of an `immediate_response` event. */\nfunction extractImmediateData(event) {\n if (event.type === 'immediate_response')\n return event.data;\n // Some servers may answer a non-streaming action with the payload elsewhere;\n // fall back to `data` if present.\n if ('data' in event && event.data && typeof event.data === 'object')\n return event.data;\n throw new ProtocolError('UNEXPECTED_EVENT', `Expected immediate_response, got \"${event.type}\"`, event.requestId);\n}\n//# sourceMappingURL=client.js.map","/**\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","const createStoreImpl = (createState) => {\n let state;\n const listeners = /* @__PURE__ */ new Set();\n const setState = (partial, replace) => {\n const nextState = typeof partial === \"function\" ? partial(state) : partial;\n if (!Object.is(nextState, state)) {\n const previousState = state;\n state = (replace != null ? replace : typeof nextState !== \"object\" || nextState === null) ? nextState : Object.assign({}, state, nextState);\n listeners.forEach((listener) => listener(state, previousState));\n }\n };\n const getState = () => state;\n const getInitialState = () => initialState;\n const subscribe = (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n const api = { setState, getState, getInitialState, subscribe };\n const initialState = state = createState(setState, getState, api);\n return api;\n};\nconst createStore = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);\n\nexport { createStore };\n","const reduxImpl = (reducer, initial) => (set, _get, api) => {\n api.dispatch = (action) => {\n set((state) => reducer(state, action), false, action);\n return action;\n };\n api.dispatchFromDevtools = true;\n return { dispatch: (...args) => api.dispatch(...args), ...initial };\n};\nconst redux = reduxImpl;\n\nconst shouldDispatchFromDevtools = (api) => !!api.dispatchFromDevtools && typeof api.dispatch === \"function\";\nconst trackedConnections = /* @__PURE__ */ new Map();\nconst getTrackedConnectionState = (name) => {\n const api = trackedConnections.get(name);\n if (!api) return {};\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])\n );\n};\nconst extractConnectionInformation = (store, extensionConnector, options) => {\n if (store === void 0) {\n return {\n type: \"untracked\",\n connection: extensionConnector.connect(options)\n };\n }\n const existingConnection = trackedConnections.get(options.name);\n if (existingConnection) {\n return { type: \"tracked\", store, ...existingConnection };\n }\n const newConnection = {\n connection: extensionConnector.connect(options),\n stores: {}\n };\n trackedConnections.set(options.name, newConnection);\n return { type: \"tracked\", store, ...newConnection };\n};\nconst removeStoreFromTrackedConnections = (name, store) => {\n if (store === void 0) return;\n const connectionInfo = trackedConnections.get(name);\n if (!connectionInfo) return;\n delete connectionInfo.stores[store];\n if (Object.keys(connectionInfo.stores).length === 0) {\n trackedConnections.delete(name);\n }\n};\nconst v8StackLineRe = /.+ (.+) .+/;\nconst geckoStackLineRe = /^([^@]+)@/;\nfunction findCallerName(stack) {\n var _a, _b, _c;\n if (!stack) return void 0;\n const traceLines = stack.split(\"\\n\");\n const apiSetStateLineIndex = traceLines.findIndex(\n (traceLine) => traceLine.includes(\"api.setState\")\n );\n if (apiSetStateLineIndex < 0) return void 0;\n const callerLine = ((_a = traceLines[apiSetStateLineIndex + 1]) == null ? void 0 : _a.trim()) || \"\";\n return ((_b = v8StackLineRe.exec(callerLine)) == null ? void 0 : _b[1]) || ((_c = geckoStackLineRe.exec(callerLine)) == null ? void 0 : _c[1]);\n}\nconst devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;\n let extensionConnector;\n try {\n extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") && window.__REDUX_DEVTOOLS_EXTENSION__;\n } catch (e) {\n }\n if (!extensionConnector) {\n return fn(set, get, api);\n }\n const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);\n let isRecording = true;\n api.setState = ((state, replace, nameOrAction) => {\n const r = set(state, replace);\n if (!isRecording) return r;\n const action = nameOrAction === void 0 ? {\n type: anonymousActionType || findCallerName(new Error().stack) || \"anonymous\"\n } : typeof nameOrAction === \"string\" ? { type: nameOrAction } : nameOrAction;\n if (store === void 0) {\n connection == null ? void 0 : connection.send(action, get());\n return r;\n }\n connection == null ? void 0 : connection.send(\n {\n ...action,\n type: `${store}/${action.type}`\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState()\n }\n );\n return r;\n });\n api.devtools = {\n cleanup: () => {\n if (connection && typeof connection.unsubscribe === \"function\") {\n connection.unsubscribe();\n }\n removeStoreFromTrackedConnections(options.name, store);\n }\n };\n const setStateFromDevtools = (...a) => {\n const originalIsRecording = isRecording;\n isRecording = false;\n set(...a);\n isRecording = originalIsRecording;\n };\n const initialState = fn(api.setState, get, api);\n if (connectionInformation.type === \"untracked\") {\n connection == null ? void 0 : connection.init(initialState);\n } else {\n connectionInformation.stores[connectionInformation.store] = api;\n connection == null ? void 0 : connection.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store2]) => [\n key,\n key === connectionInformation.store ? initialState : store2.getState()\n ])\n )\n );\n }\n if (shouldDispatchFromDevtools(api)) {\n let didWarnAboutReservedActionType = false;\n const originalDispatch = api.dispatch;\n api.dispatch = (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && args[0].type === \"__setState\" && !didWarnAboutReservedActionType) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved to set state from the devtools. Avoid using it.'\n );\n didWarnAboutReservedActionType = true;\n }\n originalDispatch(...args);\n };\n }\n connection.subscribe((message) => {\n var _a;\n switch (message.type) {\n case \"ACTION\":\n if (typeof message.payload !== \"string\") {\n console.error(\n \"[zustand devtools middleware] Unsupported action format\"\n );\n return;\n }\n return parseJsonThen(\n message.payload,\n (action) => {\n if (action.type === \"__setState\") {\n if (store === void 0) {\n setStateFromDevtools(action.state);\n return;\n }\n if (Object.keys(action.state).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format.\n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `\n );\n }\n const stateFromDevtools = action.state[store];\n if (stateFromDevtools === void 0 || stateFromDevtools === null) {\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {\n setStateFromDevtools(stateFromDevtools);\n }\n return;\n }\n if (shouldDispatchFromDevtools(api)) {\n api.dispatch(action);\n }\n }\n );\n case \"DISPATCH\":\n switch (message.payload.type) {\n case \"RESET\":\n setStateFromDevtools(initialState);\n if (store === void 0) {\n return connection == null ? void 0 : connection.init(api.getState());\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"COMMIT\":\n if (store === void 0) {\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"ROLLBACK\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n setStateFromDevtools(state[store]);\n connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n });\n case \"JUMP_TO_STATE\":\n case \"JUMP_TO_ACTION\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {\n setStateFromDevtools(state[store]);\n }\n });\n case \"IMPORT_STATE\": {\n const { nextLiftedState } = message.payload;\n const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;\n if (!lastComputedState) return;\n if (store === void 0) {\n setStateFromDevtools(lastComputedState);\n } else {\n setStateFromDevtools(lastComputedState[store]);\n }\n connection == null ? void 0 : connection.send(\n null,\n // FIXME no-any\n nextLiftedState\n );\n return;\n }\n case \"PAUSE_RECORDING\":\n return isRecording = !isRecording;\n }\n return;\n }\n });\n return initialState;\n};\nconst devtools = devtoolsImpl;\nconst parseJsonThen = (stringified, fn) => {\n let parsed;\n try {\n parsed = JSON.parse(stringified);\n } catch (e) {\n console.error(\n \"[zustand devtools middleware] Could not parse the received json\",\n e\n );\n }\n if (parsed !== void 0) fn(parsed);\n};\n\nconst subscribeWithSelectorImpl = (fn) => (set, get, api) => {\n const origSubscribe = api.subscribe;\n api.subscribe = ((selector, optListener, options) => {\n let listener = selector;\n if (optListener) {\n const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;\n let currentSlice = selector(api.getState());\n listener = (state) => {\n const nextSlice = selector(state);\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice;\n optListener(currentSlice = nextSlice, previousSlice);\n }\n };\n if (options == null ? void 0 : options.fireImmediately) {\n optListener(currentSlice, currentSlice);\n }\n }\n return origSubscribe(listener);\n });\n const initialState = fn(set, get, api);\n return initialState;\n};\nconst subscribeWithSelector = subscribeWithSelectorImpl;\n\nfunction combine(initialState, create) {\n return (...args) => Object.assign({}, initialState, create(...args));\n}\n\nfunction createJSONStorage(getStorage, options) {\n let storage;\n try {\n storage = getStorage();\n } catch (e) {\n return;\n }\n const persistStorage = {\n getItem: (name) => {\n var _a;\n const parse = (str2) => {\n if (str2 === null) {\n return null;\n }\n return JSON.parse(str2, options == null ? void 0 : options.reviver);\n };\n const str = (_a = storage.getItem(name)) != null ? _a : null;\n if (str instanceof Promise) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer)),\n removeItem: (name) => storage.removeItem(name)\n };\n return persistStorage;\n}\nconst toThenable = (fn) => (input) => {\n try {\n const result = fn(input);\n if (result instanceof Promise) {\n return result;\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result);\n },\n catch(_onRejected) {\n return this;\n }\n };\n } catch (e) {\n return {\n then(_onFulfilled) {\n return this;\n },\n catch(onRejected) {\n return toThenable(onRejected)(e);\n }\n };\n }\n};\nconst persistImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n storage: createJSONStorage(() => window.localStorage),\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n let hydrationVersion = 0;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage = options.storage;\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const setItem = () => {\n const state = options.partialize({ ...get() });\n return storage.setItem(options.name, {\n state,\n version: options.version\n });\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n return setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n return setItem();\n },\n get,\n api\n );\n api.getInitialState = () => configResult;\n let stateFromStorage;\n const hydrate = () => {\n var _a, _b;\n if (!storage) return;\n const currentVersion = ++hydrationVersion;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => {\n var _a2;\n return cb((_a2 = get()) != null ? _a2 : configResult);\n });\n const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n const migration = options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n if (migration instanceof Promise) {\n return migration.then((result) => [true, result]);\n }\n return [true, migration];\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return [false, deserializedStorageValue.state];\n }\n }\n return [false, void 0];\n }).then((migrationResult) => {\n var _a2;\n if (currentVersion !== hydrationVersion) {\n return;\n }\n const [migrated, migratedState] = migrationResult;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n if (migrated) {\n return setItem();\n }\n }).then(() => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(get(), void 0);\n stateFromStorage = get();\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.storage) {\n storage = newOptions.storage;\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n if (!options.skipHydration) {\n hydrate();\n }\n return stateFromStorage || configResult;\n};\nconst persist = persistImpl;\n\nfunction ssrSafe(config, isSSR = typeof window === \"undefined\") {\n return (set, get, api) => {\n if (!isSSR) {\n return config(set, get, api);\n }\n const ssrSet = () => {\n throw new Error(\"Cannot set state of Zustand store in SSR\");\n };\n api.setState = ssrSet;\n return config(ssrSet, get, api);\n };\n}\n\nexport { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector, ssrSafe as unstable_ssrSafe };\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, inlined as an SVG string so the full-page header can render\n * it without a separate network fetch (the IIFE bundle is self-contained).\n *\n * GENERATED from `assets/smooth-logo.svg` — do not edit by hand. Regenerate with:\n * node -e ... (see the commit that added this file)\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 * 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** — `![alt](src)` 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 '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n default:\n return '&#39;';\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: ![alt](src) — 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 `![alt](src)` 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 * `[![Logo](…)](…) # 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: [![alt](imgsrc)](href)\n s = s.replace(/^\\s*\\[!\\[[^\\]]*\\]\\([^)]*\\)\\]\\([^)]*\\)\\s*/, '');\n // Leading bare image: ![alt](src)\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","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: block;\n position: relative;\n width: 100%;\n height: 100%;\n min-height: 100vh;`\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* { 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. */\n.panel.fullpage {\n width: 100%;\n height: 100%;\n min-height: 100vh;\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; }\n.avatar .logo { height: 22px; width: auto; display: block; }\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; }\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\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\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.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 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_LOGO_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\nconst OBSERVED = ['endpoint', 'agent-id', 'agent-name', 'placeholder', 'greeting', 'start-open', 'mode'] 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 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 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 Smooth 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.\n const monogram = escapeHtml((resolved.agentName.trim().charAt(0) || 'A').toUpperCase());\n const header = fullpage\n ? `<div class=\"header\">\n <div class=\"avatar\"><span class=\"logo-wrap\">${SMOOTH_LOGO_SVG}</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 <span class=\"powered\">powered by smooth-operator</span>\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) =>\n `<label class=\"pc-field\"><span>${escapeHtml(label)}</span><input name=\"${name}\" type=\"${type}\" autocomplete=\"${autocomplete}\"${required ? ' required' : ''} /></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) : ''}\n ${consentHtml}\n <button type=\"submit\" class=\"pc-submit\">Start chat</button>\n </form>\n </div>`;\n const restoreLink = this.allowChatRestore ? ` · <button type=\"button\" class=\"restore-link\">Restore my chats</button>` : '';\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 <div class=\"footer\">powered by <b>smooth&#8209;operator</b>${restoreLink}</div>\n </div>`;\n\n const container = document.createElement('div');\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 // 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 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 /** 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 this.controller?.setUserInfo({\n name: val('name'),\n email: val('email'),\n phone: val('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 /** 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 * Standalone IIFE entry. Bundled (with the protocol client inlined) into\n * `dist/chat-widget.global.js` for a plain `<script src=\"…\">` embed.\n *\n * On load it:\n * - registers the `<smooth-agent-chat>` custom element, and\n * - exposes the programmatic API on the IIFE global `SmoothAgentChat`\n * (`window.SmoothAgentChat.mount({ endpoint, agentId })`).\n *\n * A host page can then either drop the element in markup:\n * <smooth-agent-chat endpoint=\"wss://…/ws\" agent-id=\"…\"></smooth-agent-chat>\n * or mount it programmatically:\n * SmoothAgentChat.mount({ endpoint: 'wss://…/ws', agentId: '…' });\n */\nimport type { ChatWidgetConfig } from './config.js';\nimport { defineChatWidget, mountChatWidget, mountFullPageChat, SmoothAgentChatElement } from './element.js';\n\ndefineChatWidget();\n\nexport { defineChatWidget, mountChatWidget, mountFullPageChat, SmoothAgentChatElement };\n\n/** Convenience alias matching the global API surface (`SmoothAgentChat.mount`). */\nexport function mount(config: ChatWidgetConfig, target?: HTMLElement): SmoothAgentChatElement {\n return mountChatWidget(config, target);\n}\n\n/**\n * Full-page convenience alias (`SmoothAgentChat.mountFullPage`): mounts the chat\n * in `mode: \"fullpage\"` so it fills its container/viewport with no launcher.\n */\nexport function mountFullPage(config: Omit<ChatWidgetConfig, 'mode'>, target?: HTMLElement): SmoothAgentChatElement {\n return mountFullPageChat(config, target);\n}\n"],"x_google_ignoreList":[1,2,3,5,6],"mappings":";;;;CA0IA,SAAgB,cAAc,QAA0C;EACpE,MAAM,QAAQ,OAAO,SAAS,CAAC;EAC/B,MAAM,UAAU,MAAM,WAAW;EACjC,MAAM,cAAc,MAAM,eAAe;EAEzC,MAAM,kBAAkB,MAAM,qBAAqB,MAAM,mBAAmB;EAC5E,MAAM,sBAAsB,MAAM,yBAAyB,MAAM,uBAAuB;EACxF,MAAM,aAAa,MAAM,sBAAsB,MAAM,cAAc;EACnE,MAAM,iBAAiB,MAAM,0BAA0B,MAAM,kBAAkB;EAC/E,OAAO;GACH,UAAU,OAAO;GACjB,MAAM,OAAO,QAAQ;GACrB,SAAS,OAAO;GAChB,WAAW,OAAO,aAAa;GAC/B,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB,aAAa,OAAO;GACpB,aAAa,OAAO,eAAe;GACnC,UAAU,OAAO,YAAY;GAC7B,wBAAwB,OAAO,0BAA0B;GACzD,WAAW,OAAO,aAAa;GAC/B,iBAAiB,OAAO,kBAAkB,CAAC,EAAA,CAAG,QAAQ,MAAM,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;GAC3F,aAAa,OAAO,eAAe;GACnC,cAAc,OAAO,gBAAgB;GACrC,cAAc,OA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