@cheerlyai/agentlib-react 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/AgentChat.tsx","../src/Chart.tsx","../src/identity.ts","../src/styles.ts"],"sourcesContent":["export { AgentChat, type AgentChatProps } from \"./AgentChat\";\nexport {\n getOrCreateVisitorId,\n identityHeaders,\n type EndUser,\n} from \"./identity\";\nexport { AGENT_CHAT_CSS, injectStyles } from \"./styles\";\n","\"use client\";\n\nimport { splitReply } from \"@cheerlyai/agentlib-protocol\";\nimport { useChat } from \"@ai-sdk/react\";\nimport { DefaultChatTransport } from \"ai\";\nimport type { UIMessage } from \"ai\";\nimport {\n type CSSProperties,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport { isValidElement, type ReactNode } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport rehypeSanitize from \"rehype-sanitize\";\nimport remarkGfm from \"remark-gfm\";\n\nimport Chart, { parseChartSpec } from \"./Chart\";\n\nimport {\n conversationStorageKey,\n identityHeaders,\n type EndUser,\n} from \"./identity\";\nimport { injectStyles } from \"./styles\";\n\nexport type AgentChatProps = {\n /** Your agentlib API origin, e.g. \"https://api.example.com\". */\n baseUrl: string;\n /** The agent to chat with — its id, shown on the console's View tab. */\n agentId: string;\n /** A publishable key (alk_pub_…) scoped to this agent. Safe in page source. */\n publishableKey: string;\n /** Verified end-user identity (id + HMAC signature from your backend).\n * Omit for anonymous visitors — a per-browser id is minted automatically. */\n user?: EndUser;\n /** Header title. Defaults to the agent's name, fetched from the API. */\n title?: string;\n placeholder?: string;\n welcomeTitle?: string;\n welcomeSubtitle?: string;\n /** Accent color for the user bubbles and send button. */\n accentColor?: string;\n /** Resume the identity's last conversation after a reload (default true). */\n persistConversation?: boolean;\n className?: string;\n};\n\nfunction readStored(key: string): string | null {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeStored(key: string, value: string | null): void {\n try {\n if (value === null) localStorage.removeItem(key);\n else localStorage.setItem(key, value);\n } catch {\n // Storage blocked: conversations just don't survive reloads.\n }\n}\n\nfunction messageText(message: UIMessage): string {\n return message.parts\n .map((p) => (p.type === \"text\" ? p.text : \"\"))\n .join(\"\");\n}\n\nfunction ThinkingDots() {\n return (\n <div className=\"alw-msg alw-msg-assistant\">\n <div className=\"alw-bubble alw-thinking\" aria-label=\"Thinking\">\n <span />\n <span />\n <span />\n </div>\n </div>\n );\n}\n\nfunction SendIcon() {\n return (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden>\n <path\n d=\"M12 19V5m0 0-6 6m6-6 6 6\"\n stroke=\"currentColor\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\n/** An embeddable chat thread with one agentlib agent.\n *\n * Talks directly to the platform's public embed API with a publishable key —\n * no proxy or backend route needed in the host app (the key is designed to\n * appear in page source; lock it to your domains in the console's Embed tab).\n * Conversations persist server-side per visitor/user and resume after\n * reloads. Styles are self-contained and injected on mount, working equally\n * inside a normal document or a Shadow Root.\n */\n/** The parsed spec of a ```chart fence, or null for any other code block. */\nfunction fencedChart(children: ReactNode) {\n if (!isValidElement(children)) return null;\n const props = children.props as { className?: string; children?: ReactNode };\n if (!props.className?.split(/\\s+/).includes(\"language-chart\")) return null;\n const source = typeof props.children === \"string\" ? props.children : null;\n return source ? parseChartSpec(source) : null;\n}\n\nexport function AgentChat({\n baseUrl,\n agentId,\n publishableKey,\n user,\n title,\n placeholder = \"Ask anything…\",\n welcomeTitle = \"How can I help?\",\n welcomeSubtitle = \"Replies stream in as the agent works.\",\n accentColor,\n persistConversation = true,\n className,\n}: AgentChatProps) {\n const api = `${baseUrl.replace(/\\/$/, \"\")}/v1/embed`;\n const headers = {\n Authorization: `Bearer ${publishableKey}`,\n ...identityHeaders(user),\n };\n const storageKey = conversationStorageKey(agentId, user);\n\n const rootRef = useRef<HTMLDivElement>(null);\n const scrollRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const stickToBottomRef = useRef(true);\n // The server-side conversation this thread continues; the first turn's\n // data-run-info part carries the minted id.\n const conversationIdRef = useRef<string | null>(\n persistConversation ? readStored(storageKey) : null,\n );\n\n const [prompt, setPrompt] = useState(\"\");\n const [agentName, setAgentName] = useState<string | null>(null);\n\n const { messages, sendMessage, status, error, setMessages, clearError, stop } =\n useChat({\n transport: new DefaultChatTransport({\n api: `${api}/agents/${encodeURIComponent(agentId)}/chat`,\n headers,\n prepareSendMessagesRequest: ({ api, id, messages, body, trigger, messageId }) => ({\n api: conversationIdRef.current\n ? `${api}?conversation_id=${conversationIdRef.current}`\n : api,\n body: { ...body, id, messages, trigger, messageId },\n }),\n }),\n onData: (part) => {\n if (part.type === \"data-run-info\") {\n const info = part.data as { conversation_id?: string | null };\n if (info.conversation_id) {\n conversationIdRef.current = info.conversation_id;\n if (persistConversation) writeStored(storageKey, info.conversation_id);\n }\n }\n },\n });\n\n // Styles live wherever this instance renders — document head or Shadow Root.\n useLayoutEffect(() => {\n injectStyles(rootRef.current?.getRootNode());\n }, []);\n\n // Default the header to the agent's real name.\n useEffect(() => {\n if (title) return;\n let cancelled = false;\n fetch(`${api}/agents/${encodeURIComponent(agentId)}`, { headers })\n .then((r) => (r.ok ? r.json() : null))\n .then((info) => {\n if (!cancelled && info?.name) setAgentName(info.name);\n })\n .catch(() => {});\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, baseUrl, title]);\n\n // Resume the stored conversation after a reload.\n useEffect(() => {\n const stored = conversationIdRef.current;\n if (!persistConversation || !stored) return;\n let cancelled = false;\n fetch(`${api}/conversations/${stored}/ui-messages`, { headers })\n .then((r) => (r.ok ? r.json() : null))\n .then((uiMessages: UIMessage[] | null) => {\n if (cancelled) return;\n if (uiMessages) setMessages(uiMessages);\n else {\n // Stale id (deleted, revoked scope, other browser profile…).\n conversationIdRef.current = null;\n writeStored(storageKey, null);\n }\n })\n .catch(() => {});\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n function onScroll() {\n const el = scrollRef.current;\n if (!el) return;\n stickToBottomRef.current =\n el.scrollHeight - el.scrollTop - el.clientHeight < 80;\n }\n\n useEffect(() => {\n const el = scrollRef.current;\n if (el && stickToBottomRef.current) el.scrollTop = el.scrollHeight;\n }, [messages, status]);\n\n const busy = status === \"submitted\" || status === \"streaming\";\n\n function autoGrow() {\n const el = inputRef.current;\n if (!el) return;\n el.style.height = \"auto\";\n el.style.height = `${Math.min(el.scrollHeight, 140)}px`;\n }\n\n function send() {\n const p = prompt.trim();\n if (!p || busy) return;\n setPrompt(\"\");\n requestAnimationFrame(autoGrow);\n void sendMessage({ text: p });\n }\n\n function reset() {\n stop();\n setMessages([]);\n clearError();\n conversationIdRef.current = null;\n writeStored(storageKey, null);\n inputRef.current?.focus();\n }\n\n return (\n <div\n ref={rootRef}\n className={className ? `alw-root ${className}` : \"alw-root\"}\n style={accentColor ? ({ \"--alw-accent\": accentColor } as CSSProperties) : undefined}\n >\n <div className=\"alw-header\">\n <p className=\"alw-title\">{title ?? agentName ?? \"Chat\"}</p>\n <button\n type=\"button\"\n className=\"alw-new\"\n onClick={reset}\n disabled={messages.length === 0 && !error}\n >\n New chat\n </button>\n </div>\n\n <div className=\"alw-scroll\" ref={scrollRef} onScroll={onScroll}>\n {messages.length === 0 && !busy ? (\n <div className=\"alw-empty\">\n <p className=\"alw-empty-title\">{welcomeTitle}</p>\n <p className=\"alw-empty-sub\">{welcomeSubtitle}</p>\n </div>\n ) : (\n <div className=\"alw-messages\">\n {messages.map((m) => {\n const text = messageText(m);\n if (!text && m.role === \"assistant\") return null;\n // A RAG agent is told to end its reply with a \"Sources:\"\n // section. Left in the prose it reads as a stray heading; split\n // out it becomes the citation block a reader can scan.\n const { body, sources } =\n m.role === \"assistant\"\n ? splitReply(text)\n : { body: text, sources: null };\n return (\n <div\n key={m.id}\n className={`alw-msg ${\n m.role === \"user\" ? \"alw-msg-user\" : \"alw-msg-assistant\"\n }`}\n >\n <div className=\"alw-bubble\">\n {m.role === \"assistant\" ? (\n <div className=\"alw-md\">\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n // Replies are model output rendered to the public, so\n // raw HTML is parsed only behind a sanitizer: without\n // rehype-raw a model's <details> block reaches the\n // visitor as literal tags, and without rehype-sanitize\n // a page the agent read could put a <script> on your\n // customer's site. Sanitize must follow raw.\n rehypePlugins={[rehypeRaw, rehypeSanitize]}\n components={{\n pre: ({ children }) => {\n const spec = fencedChart(children);\n return spec ? (\n <Chart spec={spec} />\n ) : (\n <pre>{children}</pre>\n );\n },\n }}\n >\n {body}\n </ReactMarkdown>\n {sources && (\n <div className=\"alw-sources\">\n <p className=\"alw-sources-label\">Sources</p>\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n rehypePlugins={[rehypeRaw, rehypeSanitize]}\n >\n {sources}\n </ReactMarkdown>\n </div>\n )}\n </div>\n ) : (\n text\n )}\n </div>\n </div>\n );\n })}\n {status === \"submitted\" && <ThinkingDots />}\n {error && (\n <p className=\"alw-error\">\n {error.message || \"Something went wrong.\"}\n <button type=\"button\" onClick={clearError}>\n Dismiss\n </button>\n </p>\n )}\n </div>\n )}\n </div>\n\n <div className=\"alw-composer\">\n <div className=\"alw-inputrow\">\n <textarea\n ref={inputRef}\n className=\"alw-input\"\n rows={1}\n value={prompt}\n placeholder={placeholder}\n onChange={(e) => {\n setPrompt(e.target.value);\n autoGrow();\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n send();\n }\n }}\n />\n <button\n type=\"button\"\n className=\"alw-send\"\n onClick={send}\n disabled={!prompt.trim() || busy}\n aria-label=\"Send\"\n >\n <SendIcon />\n </button>\n </div>\n <p className=\"alw-powered\">Powered by agentlib</p>\n </div>\n </div>\n );\n}\n","\"use client\";\n\nimport { type ChartSpec, parseChartSpec } from \"@cheerlyai/agentlib-protocol\";\nimport { useId, useState } from \"react\";\n\n/* The SVG renderer for a ```chart block. Parsing and validation live in\n * @cheerlyai/agentlib-protocol, so this file and web/components/Chart.tsx cannot drift\n * on what counts as a drawable chart.\n *\n * Hand-rolled rather than pulled from a library because this ships inside the\n * embeddable widget, where the bundle is the product's weight on someone\n * else's page — Chart.js and Recharts are ~6-7MB unpacked, Mermaid 83MB, for\n * four chart types on a fixed schema we control.\n *\n * Colours are the validated categorical palette, in fixed slot order and never\n * cycled: hue identifies a series, so a run of eight must not repaint slot 1.\n * Three light-mode hues sit below 3:1 against the surface, which obliges\n * relief — that is why the data table is built in rather than optional.\n */\n\n// Re-exported so `import Chart, { parseChartSpec } from \"./Chart\"` keeps\n// working for callers that already had it.\nexport { parseChartSpec, type ChartSpec };\n\n/** Palette slots. Matches the parser's series cap: past eight, hue stops\n * being an identity channel. */\nconst MAX_SERIES = 8;\n\n/* --- geometry ------------------------------------------------------------ */\n\nconst W = 720;\nconst H = 300;\nconst PAD = { top: 16, right: 16, bottom: 34, left: 52 };\nconst PLOT = { w: W - PAD.left - PAD.right, h: H - PAD.top - PAD.bottom };\n\n/** Axis ticks on 1/2/5 steps, so the reader gets 0 / 500 / 1,000 rather than\n * 0 / 437 / 874. */\nfunction ticks(min: number, max: number, count = 4): number[] {\n if (min === max) return [min];\n const raw = (max - min) / count;\n const mag = 10 ** Math.floor(Math.log10(raw));\n const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? mag * 10;\n const out: number[] = [];\n for (let t = Math.floor(min / step) * step; t <= max + step / 2; t += step) {\n out.push(Number(t.toFixed(10)));\n }\n return out;\n}\n\n/** A bar rounded only at its data end — square where it meets the baseline,\n * so it sits on the axis rather than floating above it. */\nfunction barPath(x: number, y: number, w: number, h: number, round: boolean) {\n const r = round ? Math.max(0, Math.min(4, w / 2, h)) : 0;\n if (r === 0) return `M${x},${y} h${w} v${h} h${-w} Z`;\n return (\n `M${x},${y + h} L${x},${y + r} Q${x},${y} ${x + r},${y} ` +\n `L${x + w - r},${y} Q${x + w},${y} ${x + w},${y + r} L${x + w},${y + h} Z`\n );\n}\n\nconst fmt = (n: number) =>\n Math.abs(n) >= 1000 ? n.toLocaleString(\"en-US\") : String(Number(n.toFixed(2)));\n\nexport default function Chart({ spec }: { spec: ChartSpec }) {\n const [showTable, setShowTable] = useState(false);\n const id = useId();\n const { type, x, series, unit, title } = spec;\n const stacked = type === \"stacked_bar\";\n const multi = series.length > 1;\n\n const totals = x.map((_, i) => series.reduce((sum, s) => sum + s.values[i], 0));\n const flat = series.flatMap((s) => s.values);\n const hi = Math.max(0, ...(stacked ? totals : flat));\n const lo = Math.min(0, ...(stacked ? totals : flat));\n const tickValues = ticks(lo, hi);\n const yMax = Math.max(...tickValues, hi);\n const yMin = Math.min(...tickValues, lo);\n const yOf = (v: number) =>\n PAD.top + PLOT.h - ((v - yMin) / (yMax - yMin || 1)) * PLOT.h;\n\n const band = PLOT.w / x.length;\n const centre = (i: number) => PAD.left + band * i + band / 2;\n const label = (i: number) => `var(--alx-s${(i % MAX_SERIES) + 1})`;\n\n return (\n <figure className=\"alx-chart my-3 first:mt-0 last:mb-0\">\n <style>{CSS}</style>\n {title ? <figcaption className=\"alx-chart-title\">{title}</figcaption> : null}\n\n <svg\n viewBox={`0 0 ${W} ${H}`}\n className=\"alx-chart-svg\"\n role=\"img\"\n aria-labelledby={`${id}-t`}\n preserveAspectRatio=\"xMidYMid meet\"\n >\n <title id={`${id}-t`}>\n {title ?? `${type} chart`}\n {multi ? ` — ${series.map((s) => s.label).join(\", \")}` : \"\"}\n </title>\n\n {/* Gridlines: hairline, solid, one step off the surface. */}\n {tickValues.map((t) => (\n <g key={t}>\n <line\n x1={PAD.left}\n x2={W - PAD.right}\n y1={yOf(t)}\n y2={yOf(t)}\n className=\"alx-grid\"\n />\n <text x={PAD.left - 8} y={yOf(t)} className=\"alx-tick\" textAnchor=\"end\">\n {fmt(t)}\n </text>\n </g>\n ))}\n\n {(type === \"bar\" || stacked) &&\n x.map((_, i) => {\n // ≤24px thick, and never the whole band — the leftover is air.\n const groupW = Math.min(band * 0.7, stacked ? 24 : 24 * series.length);\n const barW = stacked ? groupW : groupW / series.length;\n let stackTop = yOf(0);\n return (\n <g key={i}>\n {series.map((s, si) => {\n const v = s.values[i];\n if (stacked) {\n const h = Math.abs(yOf(v) - yOf(0));\n stackTop -= h;\n return (\n <path\n key={si}\n d={barPath(\n centre(i) - groupW / 2,\n // 2px surface gap does the separating, not a stroke.\n stackTop + (si > 0 ? 2 : 0),\n groupW,\n Math.max(0, h - (si > 0 ? 2 : 0)),\n si === series.length - 1,\n )}\n fill={label(si)}\n />\n );\n }\n const top = Math.min(yOf(v), yOf(0));\n return (\n <path\n key={si}\n d={barPath(\n centre(i) - groupW / 2 + si * barW + (si > 0 ? 1 : 0),\n top,\n Math.max(0, barW - (multi ? 2 : 0)),\n Math.abs(yOf(v) - yOf(0)),\n true,\n )}\n fill={label(si)}\n />\n );\n })}\n </g>\n );\n })}\n\n {(type === \"line\" || type === \"area\") &&\n series.map((s, si) => {\n const pts = s.values.map((v, i) => `${centre(i)},${yOf(v)}`).join(\" \");\n return (\n <g key={si}>\n {type === \"area\" && (\n <polygon\n points={`${centre(0)},${yOf(Math.max(0, yMin))} ${pts} ${centre(\n x.length - 1,\n )},${yOf(Math.max(0, yMin))}`}\n fill={label(si)}\n // A wash, never a saturated block.\n fillOpacity={0.1}\n />\n )}\n <polyline points={pts} className=\"alx-line\" stroke={label(si)} />\n {s.values.map((v, i) => (\n // 2px surface ring keeps markers legible where lines cross.\n <circle\n key={i}\n cx={centre(i)}\n cy={yOf(v)}\n r={4}\n fill={label(si)}\n className=\"alx-dot\"\n />\n ))}\n </g>\n );\n })}\n\n {x.map((lab, i) => (\n <text key={i} x={centre(i)} y={H - 12} className=\"alx-tick\" textAnchor=\"middle\">\n {lab.length > 12 ? `${lab.slice(0, 11)}…` : lab}\n </text>\n ))}\n </svg>\n\n {/* Always for two or more series; never for one — the title names it. */}\n {multi && (\n <ul className=\"alx-legend\">\n {series.map((s, si) => (\n <li key={si}>\n <span className=\"alx-swatch\" style={{ background: label(si) }} />\n {s.label || `Series ${si + 1}`}\n </li>\n ))}\n </ul>\n )}\n\n <button\n type=\"button\"\n className=\"alx-table-toggle\"\n onClick={() => setShowTable((v) => !v)}\n aria-expanded={showTable}\n >\n {showTable ? \"Hide data\" : \"Show data\"}\n </button>\n\n {showTable && (\n <div className=\"alx-table-wrap\">\n <table className=\"alx-table\">\n <thead>\n <tr>\n <th />\n {x.map((lab) => (\n <th key={lab}>{lab}</th>\n ))}\n </tr>\n </thead>\n <tbody>\n {series.map((s, si) => (\n <tr key={si}>\n <th scope=\"row\">\n <span className=\"alx-swatch\" style={{ background: label(si) }} />\n {s.label || `Series ${si + 1}`}\n </th>\n {s.values.map((v, i) => (\n <td key={i}>\n {fmt(v)}\n {unit ? ` ${unit}` : \"\"}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </figure>\n );\n}\n\n/* Roles, not raw hex, so light/dark swap in one place. The dark steps are the\n * same eight hues re-stepped for the dark surface and validated against it —\n * not an automatic flip of the light values. Declared under both the media\n * query and the data-theme scope so an explicit theme choice wins either way. */\nconst CSS = `\n.alx-chart{--alx-surface:#fcfcfb;--alx-ink:#0b0b0b;--alx-ink-2:#52514e;--alx-grid:#e7e7e4;\n--alx-s1:#2a78d6;--alx-s2:#eb6834;--alx-s3:#1baf7a;--alx-s4:#eda100;\n--alx-s5:#e87ba4;--alx-s6:#008300;--alx-s7:#4a3aa7;--alx-s8:#e34948;}\n@media (prefers-color-scheme:dark){:root:where(:not([data-theme=\"light\"])) .alx-chart{\n--alx-surface:#1a1a19;--alx-ink:#fff;--alx-ink-2:#c3c2b7;--alx-grid:#333331;\n--alx-s1:#3987e5;--alx-s2:#d95926;--alx-s3:#199e70;--alx-s4:#c98500;\n--alx-s5:#d55181;--alx-s6:#008300;--alx-s7:#9085e9;--alx-s8:#e66767;}}\n:root[data-theme=\"dark\"] .alx-chart{--alx-surface:#1a1a19;--alx-ink:#fff;--alx-ink-2:#c3c2b7;\n--alx-grid:#333331;--alx-s1:#3987e5;--alx-s2:#d95926;--alx-s3:#199e70;--alx-s4:#c98500;\n--alx-s5:#d55181;--alx-s6:#008300;--alx-s7:#9085e9;--alx-s8:#e66767;}\n.alx-chart-title{font-size:13px;font-weight:600;color:var(--alx-ink);margin:0 0 6px}\n.alx-chart-svg{width:100%;height:auto;display:block;overflow:visible}\n.alx-grid{stroke:var(--alx-grid);stroke-width:1}\n.alx-tick{font-size:11px;fill:var(--alx-ink-2);dominant-baseline:middle}\n.alx-line{fill:none;stroke-width:2;stroke-linejoin:round;stroke-linecap:round}\n.alx-dot{stroke:var(--alx-surface);stroke-width:2}\n.alx-legend{display:flex;flex-wrap:wrap;gap:4px 14px;list-style:none;margin:8px 0 0;padding:0;\nfont-size:12px;color:var(--alx-ink-2)}\n.alx-legend li{display:flex;align-items:center;gap:6px}\n.alx-swatch{width:9px;height:9px;border-radius:2px;display:inline-block;flex:none}\n.alx-table-toggle{margin-top:6px;font-size:11px;color:var(--alx-ink-2);background:none;\nborder:0;padding:0;cursor:pointer;text-decoration:underline;text-underline-offset:2px}\n.alx-table-wrap{overflow-x:auto;margin-top:6px}\n.alx-table{border-collapse:collapse;font-size:12px;color:var(--alx-ink)}\n.alx-table th,.alx-table td{border-bottom:1px solid var(--alx-grid);padding:3px 8px;text-align:right;\nwhite-space:nowrap}\n.alx-table th[scope=row]{text-align:left;font-weight:500;display:flex;align-items:center;gap:6px}\n.alx-table thead th{color:var(--alx-ink-2);font-weight:500}\n`;\n","/** Who is chatting, as the embed API's identity headers.\n *\n * Anonymous visitors get a random id minted once per browser and kept in\n * localStorage, so their conversations survive reloads without any backend\n * work from the embedding site. Identified users pass an id + HMAC signature\n * their backend computed with the key's signing secret (see the console's\n * Embed tab) — that keeps one user's threads consistent across devices and\n * unforgeable by other visitors, and can carry signed facts about them for\n * the agent to rely on.\n */\n\nexport type EndUser = {\n /** Your app's stable id for this user. */\n id: string;\n /** Hex HMAC-SHA256 of the signed payload, computed server-side with the\n * signing secret: of `id` alone, or of `` `${id}.${data}` `` when you send\n * attributes. */\n signature: string;\n /** Optional facts about this user for the agent to rely on — base64-encoded\n * JSON, e.g. `{\"name\":\"Marie\",\"plan\":\"pro\"}`, rendered into the run's\n * instructions rather than into the conversation.\n *\n * Produce this string on your **server**, in the same step that signs it,\n * and pass it through here untouched. The signature covers these exact\n * bytes, so re-encoding the object in the browser — a different key order is\n * enough — would invalidate it. Attributes are honoured only for a verified\n * user; a visitor sending them gets a 400. */\n data?: string;\n};\n\nconst VISITOR_STORAGE_KEY = \"agentlib:visitor\";\n\nfunction randomId(): string {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) {\n return crypto.randomUUID();\n }\n return `v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport function getOrCreateVisitorId(): string {\n try {\n const existing = localStorage.getItem(VISITOR_STORAGE_KEY);\n if (existing) return existing;\n const minted = randomId();\n localStorage.setItem(VISITOR_STORAGE_KEY, minted);\n return minted;\n } catch {\n // Storage blocked (private mode, sandboxed iframe): a per-page identity.\n return randomId();\n }\n}\n\nexport function identityHeaders(user: EndUser | undefined): Record<string, string> {\n if (user) {\n return {\n \"X-Agentlib-User\": user.id,\n \"X-Agentlib-User-Signature\": user.signature,\n ...(user.data ? { \"X-Agentlib-User-Data\": user.data } : {}),\n };\n }\n return { \"X-Agentlib-Visitor\": getOrCreateVisitorId() };\n}\n\n/** The localStorage slot remembering which conversation this identity has\n * open with this agent (per browser; resumed on reload). */\nexport function conversationStorageKey(\n agentId: string,\n user: EndUser | undefined,\n): string {\n return `agentlib:conversation:${agentId}:${user ? `u:${user.id}` : \"visitor\"}`;\n}\n","/** Self-contained styles, kept as a string so they can be injected into a\n * document head (React apps) or a Shadow Root (the script-tag widget) alike —\n * no CSS build plumbing required of the host. Everything is namespaced under\n * `alw-` (AgentLib Widget) and themed via `--alw-accent`. */\nexport const AGENT_CHAT_CSS = `\n.alw-root {\n --alw-accent: #171717;\n --alw-bg: #ffffff;\n --alw-border: #e5e5e5;\n --alw-text: #171717;\n --alw-muted: #737373;\n display: flex;\n flex-direction: column;\n height: 100%;\n min-height: 0;\n background: var(--alw-bg);\n color: var(--alw-text);\n font-family: ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto,\n \"Helvetica Neue\", Arial, sans-serif;\n font-size: 14px;\n line-height: 1.55;\n border: 1px solid var(--alw-border);\n border-radius: 14px;\n overflow: hidden;\n box-sizing: border-box;\n}\n.alw-root *, .alw-root *::before, .alw-root *::after { box-sizing: border-box; }\n\n.alw-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 10px 14px;\n border-bottom: 1px solid var(--alw-border);\n flex: none;\n}\n.alw-title { font-weight: 600; font-size: 14px; margin: 0; }\n.alw-new {\n border: 0;\n background: none;\n color: var(--alw-muted);\n font: inherit;\n font-size: 12px;\n cursor: pointer;\n padding: 4px 8px;\n border-radius: 8px;\n}\n.alw-new:hover { background: #f5f5f5; color: var(--alw-text); }\n.alw-new:disabled { opacity: 0; pointer-events: none; }\n\n.alw-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 14px; }\n.alw-empty { text-align: center; color: var(--alw-muted); padding: 40px 12px; }\n.alw-empty-title { color: var(--alw-text); font-weight: 500; font-size: 15px; margin: 0 0 4px; }\n.alw-empty-sub { font-size: 13px; margin: 0; }\n\n.alw-messages { display: flex; flex-direction: column; gap: 12px; }\n.alw-msg { display: flex; }\n.alw-msg-user { justify-content: flex-end; }\n.alw-bubble {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: 16px;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n.alw-msg-user .alw-bubble {\n background: var(--alw-accent);\n color: #fff;\n border-bottom-right-radius: 4px;\n}\n.alw-msg-assistant .alw-bubble {\n background: #f5f5f5;\n border-bottom-left-radius: 4px;\n white-space: normal;\n}\n.alw-md p { margin: 0 0 8px; }\n.alw-md p:last-child { margin-bottom: 0; }\n.alw-md pre {\n background: #171717;\n color: #f5f5f5;\n padding: 10px 12px;\n border-radius: 8px;\n overflow-x: auto;\n font-size: 12.5px;\n}\n.alw-md code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }\n.alw-md :not(pre) > code { background: #e8e8e8; padding: 1px 5px; border-radius: 4px; }\n.alw-md a { color: inherit; text-decoration: underline; }\n.alw-md ul, .alw-md ol { margin: 0 0 8px; padding-left: 20px; }\n.alw-md table { border-collapse: collapse; margin: 0 0 8px; display: block; overflow-x: auto; }\n.alw-md th, .alw-md td { border: 1px solid var(--alw-border); padding: 4px 8px; }\n\n.alw-thinking { display: inline-flex; gap: 4px; padding: 10px 12px; }\n.alw-thinking span {\n width: 6px; height: 6px; border-radius: 50%;\n background: var(--alw-muted);\n animation: alw-pulse 1.2s ease-in-out infinite;\n}\n.alw-thinking span:nth-child(2) { animation-delay: 0.15s; }\n.alw-thinking span:nth-child(3) { animation-delay: 0.3s; }\n@keyframes alw-pulse {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-3px); }\n}\n\n.alw-error { color: #dc2626; font-size: 13px; margin: 4px 0 0; }\n.alw-error button {\n border: 0; background: none; color: inherit; font: inherit;\n text-decoration: underline; cursor: pointer; padding: 0; margin-left: 4px;\n}\n\n.alw-composer { flex: none; padding: 10px 12px 12px; }\n.alw-inputrow {\n display: flex;\n align-items: flex-end;\n gap: 8px;\n border: 1px solid var(--alw-border);\n border-radius: 22px;\n padding: 6px 6px 6px 14px;\n background: var(--alw-bg);\n transition: border-color 0.15s;\n}\n.alw-inputrow:focus-within { border-color: #a3a3a3; }\n.alw-input {\n flex: 1;\n border: 0;\n outline: none;\n resize: none;\n background: none;\n font: inherit;\n color: inherit;\n max-height: 140px;\n padding: 4px 0;\n}\n.alw-send {\n flex: none;\n width: 32px; height: 32px;\n border: 0;\n border-radius: 50%;\n background: var(--alw-accent);\n color: #fff;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n}\n.alw-send:disabled { opacity: 0.35; cursor: default; }\n.alw-powered {\n text-align: center;\n font-size: 11px;\n color: var(--alw-muted);\n margin: 8px 0 0;\n}\n.alw-powered a { color: inherit; text-decoration: none; }\n`;\n\nconst STYLE_ATTR = \"data-agentlib-styles\";\n\n/** Idempotently install the stylesheet next to where the component renders —\n * the document head normally, or the containing Shadow Root when embedded via\n * the script-tag widget. */\nexport function injectStyles(root: Node | null | undefined): void {\n const target: Node =\n root instanceof ShadowRoot ? root : (root?.ownerDocument ?? document).head;\n const holder = target as ShadowRoot | HTMLHeadElement;\n if (holder.querySelector?.(`style[${STYLE_ATTR}]\n.alw-sources {\n margin-top: 10px;\n padding: 8px 11px;\n border: 1px solid var(--alw-border);\n border-radius: 9px;\n background: #f5f5f5;\n}\n.alw-sources-label {\n margin: 0 0 2px;\n font-size: 10px;\n font-weight: 600;\n letter-spacing: 0.06em;\n text-transform: uppercase;\n color: var(--alw-muted);\n}\n.alw-sources p,\n.alw-sources ul,\n.alw-sources ol {\n margin: 2px 0;\n font-size: 12.5px;\n line-height: 1.55;\n color: var(--alw-muted);\n}\n.alw-sources ul,\n.alw-sources ol {\n padding-left: 18px;\n}\n`)) return;\n const style = document.createElement(\"style\");\n style.setAttribute(STYLE_ATTR, \"\");\n style.textContent = AGENT_CHAT_CSS;\n holder.appendChild(style);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAAA,4BAA2B;AAC3B,IAAAC,gBAAwB;AACxB,gBAAqC;AAErC,IAAAA,gBAMO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,eAAe,CAAC,kBAAAC,SAAW,uBAAAC,OAAc;AAAA,wBAExC;AAAA;AAAA,oBACH;AAAA,qBACF;AAAA,mBAEJ,IAEA,MAEJ;AAAA;AAAA,cA7CK,EAAE;AAAA,YA8CT;AAAA,UAEJ,CAAC;AAAA,UACA,WAAW,eAAe,6CAAC,gBAAa;AAAA,UACxC,SACC,8CAAC,OAAE,WAAU,aACV;AAAA,kBAAM,WAAW;AAAA,YAClB,6CAAC,YAAO,MAAK,UAAS,SAAS,YAAY,qBAE3C;AAAA,aACF;AAAA,WAEJ,GAEJ;AAAA,QAEA,8CAAC,SAAI,WAAU,gBACb;AAAA,wDAAC,SAAI,WAAU,gBACb;AAAA;AAAA,cAAC;AAAA;AAAA,gBACC,KAAK;AAAA,gBACL,WAAU;AAAA,gBACV,MAAM;AAAA,gBACN,OAAO;AAAA,gBACP;AAAA,gBACA,UAAU,CAAC,MAAM;AACf,4BAAU,EAAE,OAAO,KAAK;AACxB,2BAAS;AAAA,gBACX;AAAA,gBACA,WAAW,CAAC,MAAM;AAChB,sBAAI,EAAE,QAAQ,WAAW,CAAC,EAAE,UAAU;AACpC,sBAAE,eAAe;AACjB,yBAAK;AAAA,kBACP;AAAA,gBACF;AAAA;AAAA,YACF;AAAA,YACA;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,WAAU;AAAA,gBACV,SAAS;AAAA,gBACT,UAAU,CAAC,OAAO,KAAK,KAAK;AAAA,gBAC5B,cAAW;AAAA,gBAEX,uDAAC,YAAS;AAAA;AAAA,YACZ;AAAA,aACF;AAAA,UACA,6CAAC,OAAE,WAAU,eAAc,iCAAmB;AAAA,WAChD;AAAA;AAAA;AAAA,EACF;AAEJ;","names":["import_agentlib_protocol","import_react","import_jsx_runtime","api","messages","ReactMarkdown","remarkGfm","rehypeRaw","rehypeSanitize"]}
@@ -0,0 +1,67 @@
1
+ import * as react from 'react';
2
+
3
+ /** Who is chatting, as the embed API's identity headers.
4
+ *
5
+ * Anonymous visitors get a random id minted once per browser and kept in
6
+ * localStorage, so their conversations survive reloads without any backend
7
+ * work from the embedding site. Identified users pass an id + HMAC signature
8
+ * their backend computed with the key's signing secret (see the console's
9
+ * Embed tab) — that keeps one user's threads consistent across devices and
10
+ * unforgeable by other visitors, and can carry signed facts about them for
11
+ * the agent to rely on.
12
+ */
13
+ type EndUser = {
14
+ /** Your app's stable id for this user. */
15
+ id: string;
16
+ /** Hex HMAC-SHA256 of the signed payload, computed server-side with the
17
+ * signing secret: of `id` alone, or of `` `${id}.${data}` `` when you send
18
+ * attributes. */
19
+ signature: string;
20
+ /** Optional facts about this user for the agent to rely on — base64-encoded
21
+ * JSON, e.g. `{"name":"Marie","plan":"pro"}`, rendered into the run's
22
+ * instructions rather than into the conversation.
23
+ *
24
+ * Produce this string on your **server**, in the same step that signs it,
25
+ * and pass it through here untouched. The signature covers these exact
26
+ * bytes, so re-encoding the object in the browser — a different key order is
27
+ * enough — would invalidate it. Attributes are honoured only for a verified
28
+ * user; a visitor sending them gets a 400. */
29
+ data?: string;
30
+ };
31
+ declare function getOrCreateVisitorId(): string;
32
+ declare function identityHeaders(user: EndUser | undefined): Record<string, string>;
33
+
34
+ type AgentChatProps = {
35
+ /** Your agentlib API origin, e.g. "https://api.example.com". */
36
+ baseUrl: string;
37
+ /** The agent to chat with — its id, shown on the console's View tab. */
38
+ agentId: string;
39
+ /** A publishable key (alk_pub_…) scoped to this agent. Safe in page source. */
40
+ publishableKey: string;
41
+ /** Verified end-user identity (id + HMAC signature from your backend).
42
+ * Omit for anonymous visitors — a per-browser id is minted automatically. */
43
+ user?: EndUser;
44
+ /** Header title. Defaults to the agent's name, fetched from the API. */
45
+ title?: string;
46
+ placeholder?: string;
47
+ welcomeTitle?: string;
48
+ welcomeSubtitle?: string;
49
+ /** Accent color for the user bubbles and send button. */
50
+ accentColor?: string;
51
+ /** Resume the identity's last conversation after a reload (default true). */
52
+ persistConversation?: boolean;
53
+ className?: string;
54
+ };
55
+ declare function AgentChat({ baseUrl, agentId, publishableKey, user, title, placeholder, welcomeTitle, welcomeSubtitle, accentColor, persistConversation, className, }: AgentChatProps): react.JSX.Element;
56
+
57
+ /** Self-contained styles, kept as a string so they can be injected into a
58
+ * document head (React apps) or a Shadow Root (the script-tag widget) alike —
59
+ * no CSS build plumbing required of the host. Everything is namespaced under
60
+ * `alw-` (AgentLib Widget) and themed via `--alw-accent`. */
61
+ declare const AGENT_CHAT_CSS = "\n.alw-root {\n --alw-accent: #171717;\n --alw-bg: #ffffff;\n --alw-border: #e5e5e5;\n --alw-text: #171717;\n --alw-muted: #737373;\n display: flex;\n flex-direction: column;\n height: 100%;\n min-height: 0;\n background: var(--alw-bg);\n color: var(--alw-text);\n font-family: ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto,\n \"Helvetica Neue\", Arial, sans-serif;\n font-size: 14px;\n line-height: 1.55;\n border: 1px solid var(--alw-border);\n border-radius: 14px;\n overflow: hidden;\n box-sizing: border-box;\n}\n.alw-root *, .alw-root *::before, .alw-root *::after { box-sizing: border-box; }\n\n.alw-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 10px 14px;\n border-bottom: 1px solid var(--alw-border);\n flex: none;\n}\n.alw-title { font-weight: 600; font-size: 14px; margin: 0; }\n.alw-new {\n border: 0;\n background: none;\n color: var(--alw-muted);\n font: inherit;\n font-size: 12px;\n cursor: pointer;\n padding: 4px 8px;\n border-radius: 8px;\n}\n.alw-new:hover { background: #f5f5f5; color: var(--alw-text); }\n.alw-new:disabled { opacity: 0; pointer-events: none; }\n\n.alw-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 14px; }\n.alw-empty { text-align: center; color: var(--alw-muted); padding: 40px 12px; }\n.alw-empty-title { color: var(--alw-text); font-weight: 500; font-size: 15px; margin: 0 0 4px; }\n.alw-empty-sub { font-size: 13px; margin: 0; }\n\n.alw-messages { display: flex; flex-direction: column; gap: 12px; }\n.alw-msg { display: flex; }\n.alw-msg-user { justify-content: flex-end; }\n.alw-bubble {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: 16px;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n.alw-msg-user .alw-bubble {\n background: var(--alw-accent);\n color: #fff;\n border-bottom-right-radius: 4px;\n}\n.alw-msg-assistant .alw-bubble {\n background: #f5f5f5;\n border-bottom-left-radius: 4px;\n white-space: normal;\n}\n.alw-md p { margin: 0 0 8px; }\n.alw-md p:last-child { margin-bottom: 0; }\n.alw-md pre {\n background: #171717;\n color: #f5f5f5;\n padding: 10px 12px;\n border-radius: 8px;\n overflow-x: auto;\n font-size: 12.5px;\n}\n.alw-md code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }\n.alw-md :not(pre) > code { background: #e8e8e8; padding: 1px 5px; border-radius: 4px; }\n.alw-md a { color: inherit; text-decoration: underline; }\n.alw-md ul, .alw-md ol { margin: 0 0 8px; padding-left: 20px; }\n.alw-md table { border-collapse: collapse; margin: 0 0 8px; display: block; overflow-x: auto; }\n.alw-md th, .alw-md td { border: 1px solid var(--alw-border); padding: 4px 8px; }\n\n.alw-thinking { display: inline-flex; gap: 4px; padding: 10px 12px; }\n.alw-thinking span {\n width: 6px; height: 6px; border-radius: 50%;\n background: var(--alw-muted);\n animation: alw-pulse 1.2s ease-in-out infinite;\n}\n.alw-thinking span:nth-child(2) { animation-delay: 0.15s; }\n.alw-thinking span:nth-child(3) { animation-delay: 0.3s; }\n@keyframes alw-pulse {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-3px); }\n}\n\n.alw-error { color: #dc2626; font-size: 13px; margin: 4px 0 0; }\n.alw-error button {\n border: 0; background: none; color: inherit; font: inherit;\n text-decoration: underline; cursor: pointer; padding: 0; margin-left: 4px;\n}\n\n.alw-composer { flex: none; padding: 10px 12px 12px; }\n.alw-inputrow {\n display: flex;\n align-items: flex-end;\n gap: 8px;\n border: 1px solid var(--alw-border);\n border-radius: 22px;\n padding: 6px 6px 6px 14px;\n background: var(--alw-bg);\n transition: border-color 0.15s;\n}\n.alw-inputrow:focus-within { border-color: #a3a3a3; }\n.alw-input {\n flex: 1;\n border: 0;\n outline: none;\n resize: none;\n background: none;\n font: inherit;\n color: inherit;\n max-height: 140px;\n padding: 4px 0;\n}\n.alw-send {\n flex: none;\n width: 32px; height: 32px;\n border: 0;\n border-radius: 50%;\n background: var(--alw-accent);\n color: #fff;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n}\n.alw-send:disabled { opacity: 0.35; cursor: default; }\n.alw-powered {\n text-align: center;\n font-size: 11px;\n color: var(--alw-muted);\n margin: 8px 0 0;\n}\n.alw-powered a { color: inherit; text-decoration: none; }\n";
62
+ /** Idempotently install the stylesheet next to where the component renders —
63
+ * the document head normally, or the containing Shadow Root when embedded via
64
+ * the script-tag widget. */
65
+ declare function injectStyles(root: Node | null | undefined): void;
66
+
67
+ export { AGENT_CHAT_CSS, AgentChat, type AgentChatProps, type EndUser, getOrCreateVisitorId, identityHeaders, injectStyles };
@@ -0,0 +1,67 @@
1
+ import * as react from 'react';
2
+
3
+ /** Who is chatting, as the embed API's identity headers.
4
+ *
5
+ * Anonymous visitors get a random id minted once per browser and kept in
6
+ * localStorage, so their conversations survive reloads without any backend
7
+ * work from the embedding site. Identified users pass an id + HMAC signature
8
+ * their backend computed with the key's signing secret (see the console's
9
+ * Embed tab) — that keeps one user's threads consistent across devices and
10
+ * unforgeable by other visitors, and can carry signed facts about them for
11
+ * the agent to rely on.
12
+ */
13
+ type EndUser = {
14
+ /** Your app's stable id for this user. */
15
+ id: string;
16
+ /** Hex HMAC-SHA256 of the signed payload, computed server-side with the
17
+ * signing secret: of `id` alone, or of `` `${id}.${data}` `` when you send
18
+ * attributes. */
19
+ signature: string;
20
+ /** Optional facts about this user for the agent to rely on — base64-encoded
21
+ * JSON, e.g. `{"name":"Marie","plan":"pro"}`, rendered into the run's
22
+ * instructions rather than into the conversation.
23
+ *
24
+ * Produce this string on your **server**, in the same step that signs it,
25
+ * and pass it through here untouched. The signature covers these exact
26
+ * bytes, so re-encoding the object in the browser — a different key order is
27
+ * enough — would invalidate it. Attributes are honoured only for a verified
28
+ * user; a visitor sending them gets a 400. */
29
+ data?: string;
30
+ };
31
+ declare function getOrCreateVisitorId(): string;
32
+ declare function identityHeaders(user: EndUser | undefined): Record<string, string>;
33
+
34
+ type AgentChatProps = {
35
+ /** Your agentlib API origin, e.g. "https://api.example.com". */
36
+ baseUrl: string;
37
+ /** The agent to chat with — its id, shown on the console's View tab. */
38
+ agentId: string;
39
+ /** A publishable key (alk_pub_…) scoped to this agent. Safe in page source. */
40
+ publishableKey: string;
41
+ /** Verified end-user identity (id + HMAC signature from your backend).
42
+ * Omit for anonymous visitors — a per-browser id is minted automatically. */
43
+ user?: EndUser;
44
+ /** Header title. Defaults to the agent's name, fetched from the API. */
45
+ title?: string;
46
+ placeholder?: string;
47
+ welcomeTitle?: string;
48
+ welcomeSubtitle?: string;
49
+ /** Accent color for the user bubbles and send button. */
50
+ accentColor?: string;
51
+ /** Resume the identity's last conversation after a reload (default true). */
52
+ persistConversation?: boolean;
53
+ className?: string;
54
+ };
55
+ declare function AgentChat({ baseUrl, agentId, publishableKey, user, title, placeholder, welcomeTitle, welcomeSubtitle, accentColor, persistConversation, className, }: AgentChatProps): react.JSX.Element;
56
+
57
+ /** Self-contained styles, kept as a string so they can be injected into a
58
+ * document head (React apps) or a Shadow Root (the script-tag widget) alike —
59
+ * no CSS build plumbing required of the host. Everything is namespaced under
60
+ * `alw-` (AgentLib Widget) and themed via `--alw-accent`. */
61
+ declare const AGENT_CHAT_CSS = "\n.alw-root {\n --alw-accent: #171717;\n --alw-bg: #ffffff;\n --alw-border: #e5e5e5;\n --alw-text: #171717;\n --alw-muted: #737373;\n display: flex;\n flex-direction: column;\n height: 100%;\n min-height: 0;\n background: var(--alw-bg);\n color: var(--alw-text);\n font-family: ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", Roboto,\n \"Helvetica Neue\", Arial, sans-serif;\n font-size: 14px;\n line-height: 1.55;\n border: 1px solid var(--alw-border);\n border-radius: 14px;\n overflow: hidden;\n box-sizing: border-box;\n}\n.alw-root *, .alw-root *::before, .alw-root *::after { box-sizing: border-box; }\n\n.alw-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 10px 14px;\n border-bottom: 1px solid var(--alw-border);\n flex: none;\n}\n.alw-title { font-weight: 600; font-size: 14px; margin: 0; }\n.alw-new {\n border: 0;\n background: none;\n color: var(--alw-muted);\n font: inherit;\n font-size: 12px;\n cursor: pointer;\n padding: 4px 8px;\n border-radius: 8px;\n}\n.alw-new:hover { background: #f5f5f5; color: var(--alw-text); }\n.alw-new:disabled { opacity: 0; pointer-events: none; }\n\n.alw-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 14px; }\n.alw-empty { text-align: center; color: var(--alw-muted); padding: 40px 12px; }\n.alw-empty-title { color: var(--alw-text); font-weight: 500; font-size: 15px; margin: 0 0 4px; }\n.alw-empty-sub { font-size: 13px; margin: 0; }\n\n.alw-messages { display: flex; flex-direction: column; gap: 12px; }\n.alw-msg { display: flex; }\n.alw-msg-user { justify-content: flex-end; }\n.alw-bubble {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: 16px;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n.alw-msg-user .alw-bubble {\n background: var(--alw-accent);\n color: #fff;\n border-bottom-right-radius: 4px;\n}\n.alw-msg-assistant .alw-bubble {\n background: #f5f5f5;\n border-bottom-left-radius: 4px;\n white-space: normal;\n}\n.alw-md p { margin: 0 0 8px; }\n.alw-md p:last-child { margin-bottom: 0; }\n.alw-md pre {\n background: #171717;\n color: #f5f5f5;\n padding: 10px 12px;\n border-radius: 8px;\n overflow-x: auto;\n font-size: 12.5px;\n}\n.alw-md code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }\n.alw-md :not(pre) > code { background: #e8e8e8; padding: 1px 5px; border-radius: 4px; }\n.alw-md a { color: inherit; text-decoration: underline; }\n.alw-md ul, .alw-md ol { margin: 0 0 8px; padding-left: 20px; }\n.alw-md table { border-collapse: collapse; margin: 0 0 8px; display: block; overflow-x: auto; }\n.alw-md th, .alw-md td { border: 1px solid var(--alw-border); padding: 4px 8px; }\n\n.alw-thinking { display: inline-flex; gap: 4px; padding: 10px 12px; }\n.alw-thinking span {\n width: 6px; height: 6px; border-radius: 50%;\n background: var(--alw-muted);\n animation: alw-pulse 1.2s ease-in-out infinite;\n}\n.alw-thinking span:nth-child(2) { animation-delay: 0.15s; }\n.alw-thinking span:nth-child(3) { animation-delay: 0.3s; }\n@keyframes alw-pulse {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-3px); }\n}\n\n.alw-error { color: #dc2626; font-size: 13px; margin: 4px 0 0; }\n.alw-error button {\n border: 0; background: none; color: inherit; font: inherit;\n text-decoration: underline; cursor: pointer; padding: 0; margin-left: 4px;\n}\n\n.alw-composer { flex: none; padding: 10px 12px 12px; }\n.alw-inputrow {\n display: flex;\n align-items: flex-end;\n gap: 8px;\n border: 1px solid var(--alw-border);\n border-radius: 22px;\n padding: 6px 6px 6px 14px;\n background: var(--alw-bg);\n transition: border-color 0.15s;\n}\n.alw-inputrow:focus-within { border-color: #a3a3a3; }\n.alw-input {\n flex: 1;\n border: 0;\n outline: none;\n resize: none;\n background: none;\n font: inherit;\n color: inherit;\n max-height: 140px;\n padding: 4px 0;\n}\n.alw-send {\n flex: none;\n width: 32px; height: 32px;\n border: 0;\n border-radius: 50%;\n background: var(--alw-accent);\n color: #fff;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n}\n.alw-send:disabled { opacity: 0.35; cursor: default; }\n.alw-powered {\n text-align: center;\n font-size: 11px;\n color: var(--alw-muted);\n margin: 8px 0 0;\n}\n.alw-powered a { color: inherit; text-decoration: none; }\n";
62
+ /** Idempotently install the stylesheet next to where the component renders —
63
+ * the document head normally, or the containing Shadow Root when embedded via
64
+ * the script-tag widget. */
65
+ declare function injectStyles(root: Node | null | undefined): void;
66
+
67
+ export { AGENT_CHAT_CSS, AgentChat, type AgentChatProps, type EndUser, getOrCreateVisitorId, identityHeaders, injectStyles };