@smooai/chat-widget 0.5.2 → 0.6.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/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 /** 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","/**\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\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 { 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\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 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.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 });\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 + 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 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 // 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 // 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 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 /**\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],"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,OAAO,gBAAgB;GACrC,cAAc,OAAO,gBAAgB;GACrC,gBAAgB,OAAO,kBAAkB;GACzC,OAAO;IACH,MAAM,MAAM,QAAQ;IACpB,YAAY,MAAM,cAAc;IAChC;IACA;IACA,WAAW,MAAM,aAAa;IAC9B;IACA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